clang 20.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
329void
331 Expr *DefaultArg) {
332 if (!param || !DefaultArg)
333 return;
334
335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
336 UnparsedDefaultArgLocs.erase(Param);
337
338 // Default arguments are only permitted in C++
339 if (!getLangOpts().CPlusPlus) {
340 Diag(EqualLoc, diag::err_param_default_argument)
341 << DefaultArg->getSourceRange();
342 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
343 }
344
345 // Check for unexpanded parameter packs.
347 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
348
349 // C++11 [dcl.fct.default]p3
350 // A default argument expression [...] shall not be specified for a
351 // parameter pack.
352 if (Param->isParameterPack()) {
353 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
354 << DefaultArg->getSourceRange();
355 // Recover by discarding the default argument.
356 Param->setDefaultArg(nullptr);
357 return;
358 }
359
360 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
361 if (Result.isInvalid())
362 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
363
364 DefaultArg = Result.getAs<Expr>();
365
366 // Check that the default argument is well-formed
367 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
368 if (DefaultArgChecker.Visit(DefaultArg))
369 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
370
371 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
372}
373
375 SourceLocation EqualLoc,
376 SourceLocation ArgLoc) {
377 if (!param)
378 return;
379
380 ParmVarDecl *Param = cast<ParmVarDecl>(param);
381 Param->setUnparsedDefaultArg();
382 UnparsedDefaultArgLocs[Param] = ArgLoc;
383}
384
386 Expr *DefaultArg) {
387 if (!param)
388 return;
389
390 ParmVarDecl *Param = cast<ParmVarDecl>(param);
391 Param->setInvalidDecl();
392 UnparsedDefaultArgLocs.erase(Param);
393 ExprResult RE;
394 if (DefaultArg) {
395 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
396 Param->getType().getNonReferenceType());
397 } else {
398 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
399 Param->getType().getNonReferenceType());
400 }
401 Param->setDefaultArg(RE.get());
402}
403
405 // C++ [dcl.fct.default]p3
406 // A default argument expression shall be specified only in the
407 // parameter-declaration-clause of a function declaration or in a
408 // template-parameter (14.1). It shall not be specified for a
409 // parameter pack. If it is specified in a
410 // parameter-declaration-clause, it shall not occur within a
411 // declarator or abstract-declarator of a parameter-declaration.
412 bool MightBeFunction = D.isFunctionDeclarationContext();
413 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
414 DeclaratorChunk &chunk = D.getTypeObject(i);
415 if (chunk.Kind == DeclaratorChunk::Function) {
416 if (MightBeFunction) {
417 // This is a function declaration. It can have default arguments, but
418 // keep looking in case its return type is a function type with default
419 // arguments.
420 MightBeFunction = false;
421 continue;
422 }
423 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
424 ++argIdx) {
425 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
426 if (Param->hasUnparsedDefaultArg()) {
427 std::unique_ptr<CachedTokens> Toks =
428 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
429 SourceRange SR;
430 if (Toks->size() > 1)
431 SR = SourceRange((*Toks)[1].getLocation(),
432 Toks->back().getLocation());
433 else
434 SR = UnparsedDefaultArgLocs[Param];
435 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
436 << SR;
437 } else if (Param->getDefaultArg()) {
438 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
439 << Param->getDefaultArg()->getSourceRange();
440 Param->setDefaultArg(nullptr);
441 }
442 }
443 } else if (chunk.Kind != DeclaratorChunk::Paren) {
444 MightBeFunction = false;
445 }
446 }
447}
448
450 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
451 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
452 });
453}
454
456 Scope *S) {
457 bool Invalid = false;
458
459 // The declaration context corresponding to the scope is the semantic
460 // parent, unless this is a local function declaration, in which case
461 // it is that surrounding function.
462 DeclContext *ScopeDC = New->isLocalExternDecl()
463 ? New->getLexicalDeclContext()
464 : New->getDeclContext();
465
466 // Find the previous declaration for the purpose of default arguments.
467 FunctionDecl *PrevForDefaultArgs = Old;
468 for (/**/; PrevForDefaultArgs;
469 // Don't bother looking back past the latest decl if this is a local
470 // extern declaration; nothing else could work.
471 PrevForDefaultArgs = New->isLocalExternDecl()
472 ? nullptr
473 : PrevForDefaultArgs->getPreviousDecl()) {
474 // Ignore hidden declarations.
475 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
476 continue;
477
478 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
479 !New->isCXXClassMember()) {
480 // Ignore default arguments of old decl if they are not in
481 // the same scope and this is not an out-of-line definition of
482 // a member function.
483 continue;
484 }
485
486 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
487 // If only one of these is a local function declaration, then they are
488 // declared in different scopes, even though isDeclInScope may think
489 // they're in the same scope. (If both are local, the scope check is
490 // sufficient, and if neither is local, then they are in the same scope.)
491 continue;
492 }
493
494 // We found the right previous declaration.
495 break;
496 }
497
498 // C++ [dcl.fct.default]p4:
499 // For non-template functions, default arguments can be added in
500 // later declarations of a function in the same
501 // scope. Declarations in different scopes have completely
502 // distinct sets of default arguments. That is, declarations in
503 // inner scopes do not acquire default arguments from
504 // declarations in outer scopes, and vice versa. In a given
505 // function declaration, all parameters subsequent to a
506 // parameter with a default argument shall have default
507 // arguments supplied in this or previous declarations. A
508 // default argument shall not be redefined by a later
509 // declaration (not even to the same value).
510 //
511 // C++ [dcl.fct.default]p6:
512 // Except for member functions of class templates, the default arguments
513 // in a member function definition that appears outside of the class
514 // definition are added to the set of default arguments provided by the
515 // member function declaration in the class definition.
516 for (unsigned p = 0, NumParams = PrevForDefaultArgs
517 ? PrevForDefaultArgs->getNumParams()
518 : 0;
519 p < NumParams; ++p) {
520 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
521 ParmVarDecl *NewParam = New->getParamDecl(p);
522
523 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
524 bool NewParamHasDfl = NewParam->hasDefaultArg();
525
526 if (OldParamHasDfl && NewParamHasDfl) {
527 unsigned DiagDefaultParamID =
528 diag::err_param_default_argument_redefinition;
529
530 // MSVC accepts that default parameters be redefined for member functions
531 // of template class. The new default parameter's value is ignored.
532 Invalid = true;
533 if (getLangOpts().MicrosoftExt) {
534 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
535 if (MD && MD->getParent()->getDescribedClassTemplate()) {
536 // Merge the old default argument into the new parameter.
537 NewParam->setHasInheritedDefaultArg();
538 if (OldParam->hasUninstantiatedDefaultArg())
540 OldParam->getUninstantiatedDefaultArg());
541 else
542 NewParam->setDefaultArg(OldParam->getInit());
543 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
544 Invalid = false;
545 }
546 }
547
548 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
549 // hint here. Alternatively, we could walk the type-source information
550 // for NewParam to find the last source location in the type... but it
551 // isn't worth the effort right now. This is the kind of test case that
552 // is hard to get right:
553 // int f(int);
554 // void g(int (*fp)(int) = f);
555 // void g(int (*fp)(int) = &f);
556 Diag(NewParam->getLocation(), DiagDefaultParamID)
557 << NewParam->getDefaultArgRange();
558
559 // Look for the function declaration where the default argument was
560 // actually written, which may be a declaration prior to Old.
561 for (auto Older = PrevForDefaultArgs;
562 OldParam->hasInheritedDefaultArg(); /**/) {
563 Older = Older->getPreviousDecl();
564 OldParam = Older->getParamDecl(p);
565 }
566
567 Diag(OldParam->getLocation(), diag::note_previous_definition)
568 << OldParam->getDefaultArgRange();
569 } else if (OldParamHasDfl) {
570 // Merge the old default argument into the new parameter unless the new
571 // function is a friend declaration in a template class. In the latter
572 // case the default arguments will be inherited when the friend
573 // declaration will be instantiated.
574 if (New->getFriendObjectKind() == Decl::FOK_None ||
576 // It's important to use getInit() here; getDefaultArg()
577 // strips off any top-level ExprWithCleanups.
578 NewParam->setHasInheritedDefaultArg();
579 if (OldParam->hasUnparsedDefaultArg())
580 NewParam->setUnparsedDefaultArg();
581 else if (OldParam->hasUninstantiatedDefaultArg())
583 OldParam->getUninstantiatedDefaultArg());
584 else
585 NewParam->setDefaultArg(OldParam->getInit());
586 }
587 } else if (NewParamHasDfl) {
588 if (New->getDescribedFunctionTemplate()) {
589 // Paragraph 4, quoted above, only applies to non-template functions.
590 Diag(NewParam->getLocation(),
591 diag::err_param_default_argument_template_redecl)
592 << NewParam->getDefaultArgRange();
593 Diag(PrevForDefaultArgs->getLocation(),
594 diag::note_template_prev_declaration)
595 << false;
596 } else if (New->getTemplateSpecializationKind()
599 // C++ [temp.expr.spec]p21:
600 // Default function arguments shall not be specified in a declaration
601 // or a definition for one of the following explicit specializations:
602 // - the explicit specialization of a function template;
603 // - the explicit specialization of a member function template;
604 // - the explicit specialization of a member function of a class
605 // template where the class template specialization to which the
606 // member function specialization belongs is implicitly
607 // instantiated.
608 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
610 << New->getDeclName()
611 << NewParam->getDefaultArgRange();
612 } else if (New->getDeclContext()->isDependentContext()) {
613 // C++ [dcl.fct.default]p6 (DR217):
614 // Default arguments for a member function of a class template shall
615 // be specified on the initial declaration of the member function
616 // within the class template.
617 //
618 // Reading the tea leaves a bit in DR217 and its reference to DR205
619 // leads me to the conclusion that one cannot add default function
620 // arguments for an out-of-line definition of a member function of a
621 // dependent type.
622 int WhichKind = 2;
624 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
625 if (Record->getDescribedClassTemplate())
626 WhichKind = 0;
627 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
628 WhichKind = 1;
629 else
630 WhichKind = 2;
631 }
632
633 Diag(NewParam->getLocation(),
634 diag::err_param_default_argument_member_template_redecl)
635 << WhichKind
636 << NewParam->getDefaultArgRange();
637 }
638 }
639 }
640
641 // DR1344: If a default argument is added outside a class definition and that
642 // default argument makes the function a special member function, the program
643 // is ill-formed. This can only happen for constructors.
644 if (isa<CXXConstructorDecl>(New) &&
646 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
647 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
648 if (NewSM != OldSM) {
649 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
650 assert(NewParam->hasDefaultArg());
651 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
652 << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
653 Diag(Old->getLocation(), diag::note_previous_declaration);
654 }
655 }
656
657 const FunctionDecl *Def;
658 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
659 // template has a constexpr specifier then all its declarations shall
660 // contain the constexpr specifier.
661 if (New->getConstexprKind() != Old->getConstexprKind()) {
662 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
663 << New << static_cast<int>(New->getConstexprKind())
664 << static_cast<int>(Old->getConstexprKind());
665 Diag(Old->getLocation(), diag::note_previous_declaration);
666 Invalid = true;
667 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
668 Old->isDefined(Def) &&
669 // If a friend function is inlined but does not have 'inline'
670 // specifier, it is a definition. Do not report attribute conflict
671 // in this case, redefinition will be diagnosed later.
672 (New->isInlineSpecified() ||
674 // C++11 [dcl.fcn.spec]p4:
675 // If the definition of a function appears in a translation unit before its
676 // first declaration as inline, the program is ill-formed.
677 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
678 Diag(Def->getLocation(), diag::note_previous_definition);
679 Invalid = true;
680 }
681
682 // C++17 [temp.deduct.guide]p3:
683 // Two deduction guide declarations in the same translation unit
684 // for the same class template shall not have equivalent
685 // parameter-declaration-clauses.
686 if (isa<CXXDeductionGuideDecl>(New) &&
688 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
689 Diag(Old->getLocation(), diag::note_previous_declaration);
690 }
691
692 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
693 // argument expression, that declaration shall be a definition and shall be
694 // the only declaration of the function or function template in the
695 // translation unit.
698 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
699 Diag(Old->getLocation(), diag::note_previous_declaration);
700 Invalid = true;
701 }
702
703 // C++11 [temp.friend]p4 (DR329):
704 // When a function is defined in a friend function declaration in a class
705 // template, the function is instantiated when the function is odr-used.
706 // The same restrictions on multiple declarations and definitions that
707 // apply to non-template function declarations and definitions also apply
708 // to these implicit definitions.
709 const FunctionDecl *OldDefinition = nullptr;
711 Old->isDefined(OldDefinition, true))
712 CheckForFunctionRedefinition(New, OldDefinition);
713
714 return Invalid;
715}
716
719 ? diag::warn_cxx23_placeholder_var_definition
720 : diag::ext_placeholder_var_definition);
721}
722
723NamedDecl *
725 MultiTemplateParamsArg TemplateParamLists) {
726 assert(D.isDecompositionDeclarator());
727 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
728
729 // The syntax only allows a decomposition declarator as a simple-declaration,
730 // a for-range-declaration, or a condition in Clang, but we parse it in more
731 // cases than that.
732 if (!D.mayHaveDecompositionDeclarator()) {
733 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
734 << Decomp.getSourceRange();
735 return nullptr;
736 }
737
738 if (!TemplateParamLists.empty()) {
739 // FIXME: There's no rule against this, but there are also no rules that
740 // would actually make it usable, so we reject it for now.
741 Diag(TemplateParamLists.front()->getTemplateLoc(),
742 diag::err_decomp_decl_template);
743 return nullptr;
744 }
745
746 Diag(Decomp.getLSquareLoc(),
748 ? diag::ext_decomp_decl
749 : D.getContext() == DeclaratorContext::Condition
750 ? diag::ext_decomp_decl_cond
751 : diag::warn_cxx14_compat_decomp_decl)
752 << Decomp.getSourceRange();
753
754 // The semantic context is always just the current context.
755 DeclContext *const DC = CurContext;
756
757 // C++17 [dcl.dcl]/8:
758 // The decl-specifier-seq shall contain only the type-specifier auto
759 // and cv-qualifiers.
760 // C++20 [dcl.dcl]/8:
761 // If decl-specifier-seq contains any decl-specifier other than static,
762 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
763 // C++23 [dcl.pre]/6:
764 // Each decl-specifier in the decl-specifier-seq shall be static,
765 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
766 auto &DS = D.getDeclSpec();
767 {
768 // Note: While constrained-auto needs to be checked, we do so separately so
769 // we can emit a better diagnostic.
770 SmallVector<StringRef, 8> BadSpecifiers;
771 SmallVector<SourceLocation, 8> BadSpecifierLocs;
772 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
773 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
774 if (auto SCS = DS.getStorageClassSpec()) {
775 if (SCS == DeclSpec::SCS_static) {
776 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
777 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
778 } else {
779 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
780 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
781 }
782 }
783 if (auto TSCS = DS.getThreadStorageClassSpec()) {
784 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
785 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
786 }
787 if (DS.hasConstexprSpecifier()) {
788 BadSpecifiers.push_back(
789 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
790 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
791 }
792 if (DS.isInlineSpecified()) {
793 BadSpecifiers.push_back("inline");
794 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
795 }
796
797 if (!BadSpecifiers.empty()) {
798 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
799 Err << (int)BadSpecifiers.size()
800 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
801 // Don't add FixItHints to remove the specifiers; we do still respect
802 // them when building the underlying variable.
803 for (auto Loc : BadSpecifierLocs)
804 Err << SourceRange(Loc, Loc);
805 } else if (!CPlusPlus20Specifiers.empty()) {
806 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
808 ? diag::warn_cxx17_compat_decomp_decl_spec
809 : diag::ext_decomp_decl_spec);
810 Warn << (int)CPlusPlus20Specifiers.size()
811 << llvm::join(CPlusPlus20Specifiers.begin(),
812 CPlusPlus20Specifiers.end(), " ");
813 for (auto Loc : CPlusPlus20SpecifierLocs)
814 Warn << SourceRange(Loc, Loc);
815 }
816 // We can't recover from it being declared as a typedef.
817 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
818 return nullptr;
819 }
820
821 // C++2a [dcl.struct.bind]p1:
822 // A cv that includes volatile is deprecated
823 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
825 Diag(DS.getVolatileSpecLoc(),
826 diag::warn_deprecated_volatile_structured_binding);
827
829 QualType R = TInfo->getType();
830
831 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
833 D.setInvalidType();
834
835 // The syntax only allows a single ref-qualifier prior to the decomposition
836 // declarator. No other declarator chunks are permitted. Also check the type
837 // specifier here.
838 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
839 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
840 (D.getNumTypeObjects() == 1 &&
841 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
842 Diag(Decomp.getLSquareLoc(),
843 (D.hasGroupingParens() ||
844 (D.getNumTypeObjects() &&
845 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
846 ? diag::err_decomp_decl_parens
847 : diag::err_decomp_decl_type)
848 << R;
849
850 // In most cases, there's no actual problem with an explicitly-specified
851 // type, but a function type won't work here, and ActOnVariableDeclarator
852 // shouldn't be called for such a type.
853 if (R->isFunctionType())
854 D.setInvalidType();
855 }
856
857 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
858 if (DS.isConstrainedAuto()) {
859 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
860 assert(TemplRep->Kind == TNK_Concept_template &&
861 "No other template kind should be possible for a constrained auto");
862
863 SourceRange TemplRange{TemplRep->TemplateNameLoc,
864 TemplRep->RAngleLoc.isValid()
865 ? TemplRep->RAngleLoc
866 : TemplRep->TemplateNameLoc};
867 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
868 << TemplRange << FixItHint::CreateRemoval(TemplRange);
869 }
870
871 // Build the BindingDecls.
873
874 // Build the BindingDecls.
875 for (auto &B : D.getDecompositionDeclarator().bindings()) {
876 // Check for name conflicts.
877 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
878 IdentifierInfo *VarName = B.Name;
879 assert(VarName && "Cannot have an unnamed binding declaration");
880
882 RedeclarationKind::ForVisibleRedeclaration);
884 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
885
886 // It's not permitted to shadow a template parameter name.
887 if (Previous.isSingleResult() &&
888 Previous.getFoundDecl()->isTemplateParameter()) {
889 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
890 Previous.getFoundDecl());
891 Previous.clear();
892 }
893
894 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
895
896 ProcessDeclAttributeList(S, BD, *B.Attrs);
897
898 // Find the shadowed declaration before filtering for scope.
899 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
901 : nullptr;
902
903 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
904 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
905 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
906 /*AllowInlineNamespace*/false);
907
908 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
909 DC->isFunctionOrMethod() && VarName->isPlaceholder();
910 if (!Previous.empty()) {
911 if (IsPlaceholder) {
912 bool sameDC = (Previous.end() - 1)
913 ->getDeclContext()
914 ->getRedeclContext()
915 ->Equals(DC->getRedeclContext());
916 if (sameDC &&
917 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
918 Previous.clear();
920 }
921 } else {
922 auto *Old = Previous.getRepresentativeDecl();
923 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
924 Diag(Old->getLocation(), diag::note_previous_definition);
925 }
926 } else if (ShadowedDecl && !D.isRedeclaration()) {
927 CheckShadow(BD, ShadowedDecl, Previous);
928 }
929 PushOnScopeChains(BD, S, true);
930 Bindings.push_back(BD);
931 ParsingInitForAutoVars.insert(BD);
932 }
933
934 // There are no prior lookup results for the variable itself, because it
935 // is unnamed.
936 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
937 Decomp.getLSquareLoc());
939 RedeclarationKind::ForVisibleRedeclaration);
940
941 // Build the variable that holds the non-decomposed object.
942 bool AddToScope = true;
943 NamedDecl *New =
944 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
945 MultiTemplateParamsArg(), AddToScope, Bindings);
946 if (AddToScope) {
947 S->AddDecl(New);
949 }
950
951 if (OpenMP().isInOpenMPDeclareTargetContext())
953
954 return New;
955}
956
959 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
960 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
961 if ((int64_t)Bindings.size() != NumElems) {
962 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
963 << DecompType << (unsigned)Bindings.size()
964 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
965 << toString(NumElems, 10) << (NumElems < Bindings.size());
966 return true;
967 }
968
969 unsigned I = 0;
970 for (auto *B : Bindings) {
971 SourceLocation Loc = B->getLocation();
972 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
973 if (E.isInvalid())
974 return true;
975 E = GetInit(Loc, E.get(), I++);
976 if (E.isInvalid())
977 return true;
978 B->setBinding(ElemType, E.get());
979 }
980
981 return false;
982}
983
986 ValueDecl *Src, QualType DecompType,
987 const llvm::APSInt &NumElems,
988 QualType ElemType) {
990 S, Bindings, Src, DecompType, NumElems, ElemType,
991 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
993 if (E.isInvalid())
994 return ExprError();
995 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
996 });
997}
998
1000 ValueDecl *Src, QualType DecompType,
1001 const ConstantArrayType *CAT) {
1002 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1003 llvm::APSInt(CAT->getSize()),
1004 CAT->getElementType());
1005}
1006
1008 ValueDecl *Src, QualType DecompType,
1009 const VectorType *VT) {
1011 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1013 DecompType.getQualifiers()));
1014}
1015
1018 ValueDecl *Src, QualType DecompType,
1019 const ComplexType *CT) {
1021 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1023 DecompType.getQualifiers()),
1024 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1025 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1026 });
1027}
1028
1031 const TemplateParameterList *Params) {
1033 llvm::raw_svector_ostream OS(SS);
1034 bool First = true;
1035 unsigned I = 0;
1036 for (auto &Arg : Args.arguments()) {
1037 if (!First)
1038 OS << ", ";
1039 Arg.getArgument().print(PrintingPolicy, OS,
1041 PrintingPolicy, Params, I));
1042 First = false;
1043 I++;
1044 }
1045 return std::string(OS.str());
1046}
1047
1048static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1049 SourceLocation Loc, StringRef Trait,
1051 unsigned DiagID) {
1052 auto DiagnoseMissing = [&] {
1053 if (DiagID)
1055 Args, /*Params*/ nullptr);
1056 return true;
1057 };
1058
1059 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1061 if (!Std)
1062 return DiagnoseMissing();
1063
1064 // Look up the trait itself, within namespace std. We can diagnose various
1065 // problems with this lookup even if we've been asked to not diagnose a
1066 // missing specialization, because this can only fail if the user has been
1067 // declaring their own names in namespace std or we don't support the
1068 // standard library implementation in use.
1072 return DiagnoseMissing();
1073 if (Result.isAmbiguous())
1074 return true;
1075
1076 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1077 if (!TraitTD) {
1078 Result.suppressDiagnostics();
1079 NamedDecl *Found = *Result.begin();
1080 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1081 S.Diag(Found->getLocation(), diag::note_declared_at);
1082 return true;
1083 }
1084
1085 // Build the template-id.
1086 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1087 if (TraitTy.isNull())
1088 return true;
1089 if (!S.isCompleteType(Loc, TraitTy)) {
1090 if (DiagID)
1092 Loc, TraitTy, DiagID,
1094 TraitTD->getTemplateParameters()));
1095 return true;
1096 }
1097
1098 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1099 assert(RD && "specialization of class template is not a class?");
1100
1101 // Look up the member of the trait type.
1102 S.LookupQualifiedName(TraitMemberLookup, RD);
1103 return TraitMemberLookup.isAmbiguous();
1104}
1105
1108 uint64_t I) {
1110 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1111}
1112
1116}
1117
1118namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1119
1121 llvm::APSInt &Size) {
1124
1127
1128 // Form template argument list for tuple_size<T>.
1131
1132 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1133 // it's not tuple-like.
1134 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1135 R.empty())
1136 return IsTupleLike::NotTupleLike;
1137
1138 // If we get this far, we've committed to the tuple interpretation, but
1139 // we can still fail if there actually isn't a usable ::value.
1140
1141 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1142 LookupResult &R;
1144 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1145 : R(R), Args(Args) {}
1146 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1147 SourceLocation Loc) override {
1148 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1150 /*Params*/ nullptr);
1151 }
1152 } Diagnoser(R, Args);
1153
1154 ExprResult E =
1155 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1156 if (E.isInvalid())
1157 return IsTupleLike::Error;
1158
1159 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1160 if (E.isInvalid())
1161 return IsTupleLike::Error;
1162
1163 return IsTupleLike::TupleLike;
1164}
1165
1166/// \return std::tuple_element<I, T>::type.
1168 unsigned I, QualType T) {
1169 // Form template argument list for tuple_element<I, T>.
1171 Args.addArgument(
1174
1175 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1178 S, R, Loc, "tuple_element", Args,
1179 diag::err_decomp_decl_std_tuple_element_not_specialized))
1180 return QualType();
1181
1182 auto *TD = R.getAsSingle<TypeDecl>();
1183 if (!TD) {
1185 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1187 /*Params*/ nullptr);
1188 if (!R.empty())
1189 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1190 return QualType();
1191 }
1192
1193 return S.Context.getTypeDeclType(TD);
1194}
1195
1196namespace {
1197struct InitializingBinding {
1198 Sema &S;
1199 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1203 Ctx.Entity = BD;
1205 }
1206 ~InitializingBinding() {
1208 }
1209};
1210}
1211
1214 VarDecl *Src, QualType DecompType,
1215 const llvm::APSInt &TupleSize) {
1216 if ((int64_t)Bindings.size() != TupleSize) {
1217 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1218 << DecompType << (unsigned)Bindings.size()
1219 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1220 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1221 return true;
1222 }
1223
1224 if (Bindings.empty())
1225 return false;
1226
1227 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1228
1229 // [dcl.decomp]p3:
1230 // The unqualified-id get is looked up in the scope of E by class member
1231 // access lookup ...
1232 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1233 bool UseMemberGet = false;
1234 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1235 if (auto *RD = DecompType->getAsCXXRecordDecl())
1236 S.LookupQualifiedName(MemberGet, RD);
1237 if (MemberGet.isAmbiguous())
1238 return true;
1239 // ... and if that finds at least one declaration that is a function
1240 // template whose first template parameter is a non-type parameter ...
1241 for (NamedDecl *D : MemberGet) {
1242 if (FunctionTemplateDecl *FTD =
1243 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1244 TemplateParameterList *TPL = FTD->getTemplateParameters();
1245 if (TPL->size() != 0 &&
1246 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1247 // ... the initializer is e.get<i>().
1248 UseMemberGet = true;
1249 break;
1250 }
1251 }
1252 }
1253 }
1254
1255 unsigned I = 0;
1256 for (auto *B : Bindings) {
1257 InitializingBinding InitContext(S, B);
1258 SourceLocation Loc = B->getLocation();
1259
1260 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1261 if (E.isInvalid())
1262 return true;
1263
1264 // e is an lvalue if the type of the entity is an lvalue reference and
1265 // an xvalue otherwise
1266 if (!Src->getType()->isLValueReferenceType())
1267 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1268 E.get(), nullptr, VK_XValue,
1270
1272 Args.addArgument(
1274
1275 if (UseMemberGet) {
1276 // if [lookup of member get] finds at least one declaration, the
1277 // initializer is e.get<i-1>().
1278 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1279 CXXScopeSpec(), SourceLocation(), nullptr,
1280 MemberGet, &Args, nullptr);
1281 if (E.isInvalid())
1282 return true;
1283
1284 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1285 } else {
1286 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1287 // in the associated namespaces.
1290 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1292 /*KnownDependent=*/false);
1293
1294 Expr *Arg = E.get();
1295 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1296 }
1297 if (E.isInvalid())
1298 return true;
1299 Expr *Init = E.get();
1300
1301 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1302 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1303 if (T.isNull())
1304 return true;
1305
1306 // each vi is a variable of type "reference to T" initialized with the
1307 // initializer, where the reference is an lvalue reference if the
1308 // initializer is an lvalue and an rvalue reference otherwise
1309 QualType RefType =
1310 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1311 if (RefType.isNull())
1312 return true;
1313 auto *RefVD = VarDecl::Create(
1314 S.Context, Src->getDeclContext(), Loc, Loc,
1315 B->getDeclName().getAsIdentifierInfo(), RefType,
1317 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1318 RefVD->setTSCSpec(Src->getTSCSpec());
1319 RefVD->setImplicit();
1320 if (Src->isInlineSpecified())
1321 RefVD->setInlineSpecified();
1322 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1323
1326 InitializationSequence Seq(S, Entity, Kind, Init);
1327 E = Seq.Perform(S, Entity, Kind, Init);
1328 if (E.isInvalid())
1329 return true;
1330 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1331 if (E.isInvalid())
1332 return true;
1333 RefVD->setInit(E.get());
1335
1337 DeclarationNameInfo(B->getDeclName(), Loc),
1338 RefVD);
1339 if (E.isInvalid())
1340 return true;
1341
1342 B->setBinding(T, E.get());
1343 I++;
1344 }
1345
1346 return false;
1347}
1348
1349/// Find the base class to decompose in a built-in decomposition of a class type.
1350/// This base class search is, unfortunately, not quite like any other that we
1351/// perform anywhere else in C++.
1353 const CXXRecordDecl *RD,
1354 CXXCastPath &BasePath) {
1355 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1356 CXXBasePath &Path) {
1357 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1358 };
1359
1360 const CXXRecordDecl *ClassWithFields = nullptr;
1362 if (RD->hasDirectFields())
1363 // [dcl.decomp]p4:
1364 // Otherwise, all of E's non-static data members shall be public direct
1365 // members of E ...
1366 ClassWithFields = RD;
1367 else {
1368 // ... or of ...
1369 CXXBasePaths Paths;
1370 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1371 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1372 // If no classes have fields, just decompose RD itself. (This will work
1373 // if and only if zero bindings were provided.)
1374 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1375 }
1376
1377 CXXBasePath *BestPath = nullptr;
1378 for (auto &P : Paths) {
1379 if (!BestPath)
1380 BestPath = &P;
1381 else if (!S.Context.hasSameType(P.back().Base->getType(),
1382 BestPath->back().Base->getType())) {
1383 // ... the same ...
1384 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1385 << false << RD << BestPath->back().Base->getType()
1386 << P.back().Base->getType();
1387 return DeclAccessPair();
1388 } else if (P.Access < BestPath->Access) {
1389 BestPath = &P;
1390 }
1391 }
1392
1393 // ... unambiguous ...
1394 QualType BaseType = BestPath->back().Base->getType();
1395 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1396 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1397 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1398 return DeclAccessPair();
1399 }
1400
1401 // ... [accessible, implied by other rules] base class of E.
1402 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1403 *BestPath, diag::err_decomp_decl_inaccessible_base);
1404 AS = BestPath->Access;
1405
1406 ClassWithFields = BaseType->getAsCXXRecordDecl();
1407 S.BuildBasePathArray(Paths, BasePath);
1408 }
1409
1410 // The above search did not check whether the selected class itself has base
1411 // classes with fields, so check that now.
1412 CXXBasePaths Paths;
1413 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1414 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1415 << (ClassWithFields == RD) << RD << ClassWithFields
1416 << Paths.front().back().Base->getType();
1417 return DeclAccessPair();
1418 }
1419
1420 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1421}
1422
1424 ValueDecl *Src, QualType DecompType,
1425 const CXXRecordDecl *OrigRD) {
1426 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1427 diag::err_incomplete_type))
1428 return true;
1429
1430 CXXCastPath BasePath;
1431 DeclAccessPair BasePair =
1432 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1433 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1434 if (!RD)
1435 return true;
1437 DecompType.getQualifiers());
1438
1439 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1440 unsigned NumFields = llvm::count_if(
1441 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1442 assert(Bindings.size() != NumFields);
1443 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1444 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1445 << (NumFields < Bindings.size());
1446 return true;
1447 };
1448
1449 // all of E's non-static data members shall be [...] well-formed
1450 // when named as e.name in the context of the structured binding,
1451 // E shall not have an anonymous union member, ...
1452 unsigned I = 0;
1453 for (auto *FD : RD->fields()) {
1454 if (FD->isUnnamedBitField())
1455 continue;
1456
1457 // All the non-static data members are required to be nameable, so they
1458 // must all have names.
1459 if (!FD->getDeclName()) {
1460 if (RD->isLambda()) {
1461 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1462 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1463 return true;
1464 }
1465
1466 if (FD->isAnonymousStructOrUnion()) {
1467 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1468 << DecompType << FD->getType()->isUnionType();
1469 S.Diag(FD->getLocation(), diag::note_declared_at);
1470 return true;
1471 }
1472
1473 // FIXME: Are there any other ways we could have an anonymous member?
1474 }
1475
1476 // We have a real field to bind.
1477 if (I >= Bindings.size())
1478 return DiagnoseBadNumberOfBindings();
1479 auto *B = Bindings[I++];
1480 SourceLocation Loc = B->getLocation();
1481
1482 // The field must be accessible in the context of the structured binding.
1483 // We already checked that the base class is accessible.
1484 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1485 // const_cast here.
1487 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1489 BasePair.getAccess(), FD->getAccess())));
1490
1491 // Initialize the binding to Src.FD.
1492 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1493 if (E.isInvalid())
1494 return true;
1495 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1496 VK_LValue, &BasePath);
1497 if (E.isInvalid())
1498 return true;
1499 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1500 CXXScopeSpec(), FD,
1501 DeclAccessPair::make(FD, FD->getAccess()),
1502 DeclarationNameInfo(FD->getDeclName(), Loc));
1503 if (E.isInvalid())
1504 return true;
1505
1506 // If the type of the member is T, the referenced type is cv T, where cv is
1507 // the cv-qualification of the decomposition expression.
1508 //
1509 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1510 // 'const' to the type of the field.
1511 Qualifiers Q = DecompType.getQualifiers();
1512 if (FD->isMutable())
1513 Q.removeConst();
1514 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1515 }
1516
1517 if (I != Bindings.size())
1518 return DiagnoseBadNumberOfBindings();
1519
1520 return false;
1521}
1522
1524 QualType DecompType = DD->getType();
1525
1526 // If the type of the decomposition is dependent, then so is the type of
1527 // each binding.
1528 if (DecompType->isDependentType()) {
1529 for (auto *B : DD->bindings())
1530 B->setType(Context.DependentTy);
1531 return;
1532 }
1533
1534 DecompType = DecompType.getNonReferenceType();
1536
1537 // C++1z [dcl.decomp]/2:
1538 // If E is an array type [...]
1539 // As an extension, we also support decomposition of built-in complex and
1540 // vector types.
1541 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1542 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1543 DD->setInvalidDecl();
1544 return;
1545 }
1546 if (auto *VT = DecompType->getAs<VectorType>()) {
1547 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1548 DD->setInvalidDecl();
1549 return;
1550 }
1551 if (auto *CT = DecompType->getAs<ComplexType>()) {
1552 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1553 DD->setInvalidDecl();
1554 return;
1555 }
1556
1557 // C++1z [dcl.decomp]/3:
1558 // if the expression std::tuple_size<E>::value is a well-formed integral
1559 // constant expression, [...]
1560 llvm::APSInt TupleSize(32);
1561 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1562 case IsTupleLike::Error:
1563 DD->setInvalidDecl();
1564 return;
1565
1566 case IsTupleLike::TupleLike:
1567 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1568 DD->setInvalidDecl();
1569 return;
1570
1571 case IsTupleLike::NotTupleLike:
1572 break;
1573 }
1574
1575 // C++1z [dcl.dcl]/8:
1576 // [E shall be of array or non-union class type]
1577 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1578 if (!RD || RD->isUnion()) {
1579 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1580 << DD << !RD << DecompType;
1581 DD->setInvalidDecl();
1582 return;
1583 }
1584
1585 // C++1z [dcl.decomp]/4:
1586 // all of E's non-static data members shall be [...] direct members of
1587 // E or of the same unambiguous public base class of E, ...
1588 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1589 DD->setInvalidDecl();
1590}
1591
1593 // Shortcut if exceptions are disabled.
1594 if (!getLangOpts().CXXExceptions)
1595 return;
1596
1597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1598 "Should only be called if types are otherwise the same.");
1599
1600 QualType NewType = New->getType();
1601 QualType OldType = Old->getType();
1602
1603 // We're only interested in pointers and references to functions, as well
1604 // as pointers to member functions.
1605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1606 NewType = R->getPointeeType();
1607 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1609 NewType = P->getPointeeType();
1610 OldType = OldType->castAs<PointerType>()->getPointeeType();
1611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1612 NewType = M->getPointeeType();
1613 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1614 }
1615
1616 if (!NewType->isFunctionProtoType())
1617 return;
1618
1619 // There's lots of special cases for functions. For function pointers, system
1620 // libraries are hopefully not as broken so that we don't need these
1621 // workarounds.
1623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1625 New->setInvalidDecl();
1626 }
1627}
1628
1629/// CheckCXXDefaultArguments - Verify that the default arguments for a
1630/// function declaration are well-formed according to C++
1631/// [dcl.fct.default].
1633 // This checking doesn't make sense for explicit specializations; their
1634 // default arguments are determined by the declaration we're specializing,
1635 // not by FD.
1637 return;
1638 if (auto *FTD = FD->getDescribedFunctionTemplate())
1639 if (FTD->isMemberSpecialization())
1640 return;
1641
1642 unsigned NumParams = FD->getNumParams();
1643 unsigned ParamIdx = 0;
1644
1645 // Find first parameter with a default argument
1646 for (; ParamIdx < NumParams; ++ParamIdx) {
1647 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1648 if (Param->hasDefaultArg())
1649 break;
1650 }
1651
1652 // C++20 [dcl.fct.default]p4:
1653 // In a given function declaration, each parameter subsequent to a parameter
1654 // with a default argument shall have a default argument supplied in this or
1655 // a previous declaration, unless the parameter was expanded from a
1656 // parameter pack, or shall be a function parameter pack.
1657 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1658 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1659 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1662 continue;
1663 if (Param->isInvalidDecl())
1664 /* We already complained about this parameter. */;
1665 else if (Param->getIdentifier())
1666 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1667 << Param->getIdentifier();
1668 else
1669 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1670 }
1671}
1672
1673/// Check that the given type is a literal type. Issue a diagnostic if not,
1674/// if Kind is Diagnose.
1675/// \return \c true if a problem has been found (and optionally diagnosed).
1676template <typename... Ts>
1678 SourceLocation Loc, QualType T, unsigned DiagID,
1679 Ts &&...DiagArgs) {
1680 if (T->isDependentType())
1681 return false;
1682
1683 switch (Kind) {
1685 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1686 std::forward<Ts>(DiagArgs)...);
1687
1689 return !T->isLiteralType(SemaRef.Context);
1690 }
1691
1692 llvm_unreachable("unknown CheckConstexprKind");
1693}
1694
1695/// Determine whether a destructor cannot be constexpr due to
1697 const CXXDestructorDecl *DD,
1699 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1700 "this check is obsolete for C++23");
1701 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1702 const CXXRecordDecl *RD =
1704 if (!RD || RD->hasConstexprDestructor())
1705 return true;
1706
1708 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1709 << static_cast<int>(DD->getConstexprKind()) << !FD
1710 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1711 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1712 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1713 }
1714 return false;
1715 };
1716
1717 const CXXRecordDecl *RD = DD->getParent();
1718 for (const CXXBaseSpecifier &B : RD->bases())
1719 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1720 return false;
1721 for (const FieldDecl *FD : RD->fields())
1722 if (!Check(FD->getLocation(), FD->getType(), FD))
1723 return false;
1724 return true;
1725}
1726
1727/// Check whether a function's parameter types are all literal types. If so,
1728/// return true. If not, produce a suitable diagnostic and return false.
1730 const FunctionDecl *FD,
1732 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1733 "this check is obsolete for C++23");
1734 unsigned ArgIndex = 0;
1735 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1736 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1737 e = FT->param_type_end();
1738 i != e; ++i, ++ArgIndex) {
1739 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1740 assert(PD && "null in a parameter list");
1741 SourceLocation ParamLoc = PD->getLocation();
1742 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1743 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1744 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1745 FD->isConsteval()))
1746 return false;
1747 }
1748 return true;
1749}
1750
1751/// Check whether a function's return type is a literal type. If so, return
1752/// true. If not, produce a suitable diagnostic and return false.
1755 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1756 "this check is obsolete for C++23");
1757 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1758 diag::err_constexpr_non_literal_return,
1759 FD->isConsteval()))
1760 return false;
1761 return true;
1762}
1763
1764/// Get diagnostic %select index for tag kind for
1765/// record diagnostic message.
1766/// WARNING: Indexes apply to particular diagnostics only!
1767///
1768/// \returns diagnostic %select index.
1770 switch (Tag) {
1772 return 0;
1774 return 1;
1775 case TagTypeKind::Class:
1776 return 2;
1777 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1778 }
1779}
1780
1781static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1782 Stmt *Body,
1784static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1785
1787 CheckConstexprKind Kind) {
1788 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1789 if (MD && MD->isInstance()) {
1790 // C++11 [dcl.constexpr]p4:
1791 // The definition of a constexpr constructor shall satisfy the following
1792 // constraints:
1793 // - the class shall not have any virtual base classes;
1794 //
1795 // FIXME: This only applies to constructors and destructors, not arbitrary
1796 // member functions.
1797 const CXXRecordDecl *RD = MD->getParent();
1798 if (RD->getNumVBases()) {
1800 return false;
1801
1802 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1803 << isa<CXXConstructorDecl>(NewFD)
1805 for (const auto &I : RD->vbases())
1806 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1807 << I.getSourceRange();
1808 return false;
1809 }
1810 }
1811
1812 if (!isa<CXXConstructorDecl>(NewFD)) {
1813 // C++11 [dcl.constexpr]p3:
1814 // The definition of a constexpr function shall satisfy the following
1815 // constraints:
1816 // - it shall not be virtual; (removed in C++20)
1817 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1818 if (Method && Method->isVirtual()) {
1819 if (getLangOpts().CPlusPlus20) {
1820 if (Kind == CheckConstexprKind::Diagnose)
1821 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1822 } else {
1824 return false;
1825
1826 Method = Method->getCanonicalDecl();
1827 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1828
1829 // If it's not obvious why this function is virtual, find an overridden
1830 // function which uses the 'virtual' keyword.
1831 const CXXMethodDecl *WrittenVirtual = Method;
1832 while (!WrittenVirtual->isVirtualAsWritten())
1833 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1834 if (WrittenVirtual != Method)
1835 Diag(WrittenVirtual->getLocation(),
1836 diag::note_overridden_virtual_function);
1837 return false;
1838 }
1839 }
1840
1841 // - its return type shall be a literal type; (removed in C++23)
1842 if (!getLangOpts().CPlusPlus23 &&
1843 !CheckConstexprReturnType(*this, NewFD, Kind))
1844 return false;
1845 }
1846
1847 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1848 // A destructor can be constexpr only if the defaulted destructor could be;
1849 // we don't need to check the members and bases if we already know they all
1850 // have constexpr destructors. (removed in C++23)
1851 if (!getLangOpts().CPlusPlus23 &&
1852 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1854 return false;
1855 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1856 return false;
1857 }
1858 }
1859
1860 // - each of its parameter types shall be a literal type; (removed in C++23)
1861 if (!getLangOpts().CPlusPlus23 &&
1862 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1863 return false;
1864
1865 Stmt *Body = NewFD->getBody();
1866 assert(Body &&
1867 "CheckConstexprFunctionDefinition called on function with no body");
1868 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1869}
1870
1871/// Check the given declaration statement is legal within a constexpr function
1872/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1873///
1874/// \return true if the body is OK (maybe only as an extension), false if we
1875/// have diagnosed a problem.
1877 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1879 // C++11 [dcl.constexpr]p3 and p4:
1880 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1881 // contain only
1882 for (const auto *DclIt : DS->decls()) {
1883 switch (DclIt->getKind()) {
1884 case Decl::StaticAssert:
1885 case Decl::Using:
1886 case Decl::UsingShadow:
1887 case Decl::UsingDirective:
1888 case Decl::UnresolvedUsingTypename:
1889 case Decl::UnresolvedUsingValue:
1890 case Decl::UsingEnum:
1891 // - static_assert-declarations
1892 // - using-declarations,
1893 // - using-directives,
1894 // - using-enum-declaration
1895 continue;
1896
1897 case Decl::Typedef:
1898 case Decl::TypeAlias: {
1899 // - typedef declarations and alias-declarations that do not define
1900 // classes or enumerations,
1901 const auto *TN = cast<TypedefNameDecl>(DclIt);
1902 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1903 // Don't allow variably-modified types in constexpr functions.
1905 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1906 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1907 << TL.getSourceRange() << TL.getType()
1908 << isa<CXXConstructorDecl>(Dcl);
1909 }
1910 return false;
1911 }
1912 continue;
1913 }
1914
1915 case Decl::Enum:
1916 case Decl::CXXRecord:
1917 // C++1y allows types to be defined, not just declared.
1918 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1920 SemaRef.Diag(DS->getBeginLoc(),
1921 SemaRef.getLangOpts().CPlusPlus14
1922 ? diag::warn_cxx11_compat_constexpr_type_definition
1923 : diag::ext_constexpr_type_definition)
1924 << isa<CXXConstructorDecl>(Dcl);
1925 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1926 return false;
1927 }
1928 }
1929 continue;
1930
1931 case Decl::EnumConstant:
1932 case Decl::IndirectField:
1933 case Decl::ParmVar:
1934 // These can only appear with other declarations which are banned in
1935 // C++11 and permitted in C++1y, so ignore them.
1936 continue;
1937
1938 case Decl::Var:
1939 case Decl::Decomposition: {
1940 // C++1y [dcl.constexpr]p3 allows anything except:
1941 // a definition of a variable of non-literal type or of static or
1942 // thread storage duration or [before C++2a] for which no
1943 // initialization is performed.
1944 const auto *VD = cast<VarDecl>(DclIt);
1945 if (VD->isThisDeclarationADefinition()) {
1946 if (VD->isStaticLocal()) {
1948 SemaRef.Diag(VD->getLocation(),
1949 SemaRef.getLangOpts().CPlusPlus23
1950 ? diag::warn_cxx20_compat_constexpr_var
1951 : diag::ext_constexpr_static_var)
1952 << isa<CXXConstructorDecl>(Dcl)
1953 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1954 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1955 return false;
1956 }
1957 }
1958 if (SemaRef.LangOpts.CPlusPlus23) {
1959 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1960 diag::warn_cxx20_compat_constexpr_var,
1961 isa<CXXConstructorDecl>(Dcl),
1962 /*variable of non-literal type*/ 2);
1963 } else if (CheckLiteralType(
1964 SemaRef, Kind, VD->getLocation(), VD->getType(),
1965 diag::err_constexpr_local_var_non_literal_type,
1966 isa<CXXConstructorDecl>(Dcl))) {
1967 return false;
1968 }
1969 if (!VD->getType()->isDependentType() &&
1970 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1972 SemaRef.Diag(
1973 VD->getLocation(),
1974 SemaRef.getLangOpts().CPlusPlus20
1975 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1976 : diag::ext_constexpr_local_var_no_init)
1977 << isa<CXXConstructorDecl>(Dcl);
1978 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1979 return false;
1980 }
1981 continue;
1982 }
1983 }
1985 SemaRef.Diag(VD->getLocation(),
1986 SemaRef.getLangOpts().CPlusPlus14
1987 ? diag::warn_cxx11_compat_constexpr_local_var
1988 : diag::ext_constexpr_local_var)
1989 << isa<CXXConstructorDecl>(Dcl);
1990 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1991 return false;
1992 }
1993 continue;
1994 }
1995
1996 case Decl::NamespaceAlias:
1997 case Decl::Function:
1998 // These are disallowed in C++11 and permitted in C++1y. Allow them
1999 // everywhere as an extension.
2000 if (!Cxx1yLoc.isValid())
2001 Cxx1yLoc = DS->getBeginLoc();
2002 continue;
2003
2004 default:
2006 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2007 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2008 }
2009 return false;
2010 }
2011 }
2012
2013 return true;
2014}
2015
2016/// Check that the given field is initialized within a constexpr constructor.
2017///
2018/// \param Dcl The constexpr constructor being checked.
2019/// \param Field The field being checked. This may be a member of an anonymous
2020/// struct or union nested within the class being checked.
2021/// \param Inits All declarations, including anonymous struct/union members and
2022/// indirect members, for which any initialization was provided.
2023/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2024/// multiple notes for different members to the same error.
2025/// \param Kind Whether we're diagnosing a constructor as written or determining
2026/// whether the formal requirements are satisfied.
2027/// \return \c false if we're checking for validity and the constructor does
2028/// not satisfy the requirements on a constexpr constructor.
2030 const FunctionDecl *Dcl,
2031 FieldDecl *Field,
2032 llvm::SmallSet<Decl*, 16> &Inits,
2033 bool &Diagnosed,
2035 // In C++20 onwards, there's nothing to check for validity.
2037 SemaRef.getLangOpts().CPlusPlus20)
2038 return true;
2039
2040 if (Field->isInvalidDecl())
2041 return true;
2042
2043 if (Field->isUnnamedBitField())
2044 return true;
2045
2046 // Anonymous unions with no variant members and empty anonymous structs do not
2047 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2048 // indirect fields don't need initializing.
2049 if (Field->isAnonymousStructOrUnion() &&
2050 (Field->getType()->isUnionType()
2051 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2052 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2053 return true;
2054
2055 if (!Inits.count(Field)) {
2057 if (!Diagnosed) {
2058 SemaRef.Diag(Dcl->getLocation(),
2059 SemaRef.getLangOpts().CPlusPlus20
2060 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2061 : diag::ext_constexpr_ctor_missing_init);
2062 Diagnosed = true;
2063 }
2064 SemaRef.Diag(Field->getLocation(),
2065 diag::note_constexpr_ctor_missing_init);
2066 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2067 return false;
2068 }
2069 } else if (Field->isAnonymousStructOrUnion()) {
2070 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2071 for (auto *I : RD->fields())
2072 // If an anonymous union contains an anonymous struct of which any member
2073 // is initialized, all members must be initialized.
2074 if (!RD->isUnion() || Inits.count(I))
2075 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2076 Kind))
2077 return false;
2078 }
2079 return true;
2080}
2081
2082/// Check the provided statement is allowed in a constexpr function
2083/// definition.
2084static bool
2087 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2088 SourceLocation &Cxx2bLoc,
2090 // - its function-body shall be [...] a compound-statement that contains only
2091 switch (S->getStmtClass()) {
2092 case Stmt::NullStmtClass:
2093 // - null statements,
2094 return true;
2095
2096 case Stmt::DeclStmtClass:
2097 // - static_assert-declarations
2098 // - using-declarations,
2099 // - using-directives,
2100 // - typedef declarations and alias-declarations that do not define
2101 // classes or enumerations,
2102 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2103 return false;
2104 return true;
2105
2106 case Stmt::ReturnStmtClass:
2107 // - and exactly one return statement;
2108 if (isa<CXXConstructorDecl>(Dcl)) {
2109 // C++1y allows return statements in constexpr constructors.
2110 if (!Cxx1yLoc.isValid())
2111 Cxx1yLoc = S->getBeginLoc();
2112 return true;
2113 }
2114
2115 ReturnStmts.push_back(S->getBeginLoc());
2116 return true;
2117
2118 case Stmt::AttributedStmtClass:
2119 // Attributes on a statement don't affect its formal kind and hence don't
2120 // affect its validity in a constexpr function.
2122 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2123 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2124
2125 case Stmt::CompoundStmtClass: {
2126 // C++1y allows compound-statements.
2127 if (!Cxx1yLoc.isValid())
2128 Cxx1yLoc = S->getBeginLoc();
2129
2130 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2131 for (auto *BodyIt : CompStmt->body()) {
2132 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2133 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2134 return false;
2135 }
2136 return true;
2137 }
2138
2139 case Stmt::IfStmtClass: {
2140 // C++1y allows if-statements.
2141 if (!Cxx1yLoc.isValid())
2142 Cxx1yLoc = S->getBeginLoc();
2143
2144 IfStmt *If = cast<IfStmt>(S);
2145 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2146 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2147 return false;
2148 if (If->getElse() &&
2149 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2150 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2151 return false;
2152 return true;
2153 }
2154
2155 case Stmt::WhileStmtClass:
2156 case Stmt::DoStmtClass:
2157 case Stmt::ForStmtClass:
2158 case Stmt::CXXForRangeStmtClass:
2159 case Stmt::ContinueStmtClass:
2160 // C++1y allows all of these. We don't allow them as extensions in C++11,
2161 // because they don't make sense without variable mutation.
2162 if (!SemaRef.getLangOpts().CPlusPlus14)
2163 break;
2164 if (!Cxx1yLoc.isValid())
2165 Cxx1yLoc = S->getBeginLoc();
2166 for (Stmt *SubStmt : S->children()) {
2167 if (SubStmt &&
2168 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2169 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2170 return false;
2171 }
2172 return true;
2173
2174 case Stmt::SwitchStmtClass:
2175 case Stmt::CaseStmtClass:
2176 case Stmt::DefaultStmtClass:
2177 case Stmt::BreakStmtClass:
2178 // C++1y allows switch-statements, and since they don't need variable
2179 // mutation, we can reasonably allow them in C++11 as an extension.
2180 if (!Cxx1yLoc.isValid())
2181 Cxx1yLoc = S->getBeginLoc();
2182 for (Stmt *SubStmt : S->children()) {
2183 if (SubStmt &&
2184 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2185 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2186 return false;
2187 }
2188 return true;
2189
2190 case Stmt::LabelStmtClass:
2191 case Stmt::GotoStmtClass:
2192 if (Cxx2bLoc.isInvalid())
2193 Cxx2bLoc = S->getBeginLoc();
2194 for (Stmt *SubStmt : S->children()) {
2195 if (SubStmt &&
2196 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2197 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2198 return false;
2199 }
2200 return true;
2201
2202 case Stmt::GCCAsmStmtClass:
2203 case Stmt::MSAsmStmtClass:
2204 // C++2a allows inline assembly statements.
2205 case Stmt::CXXTryStmtClass:
2206 if (Cxx2aLoc.isInvalid())
2207 Cxx2aLoc = S->getBeginLoc();
2208 for (Stmt *SubStmt : S->children()) {
2209 if (SubStmt &&
2210 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2211 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2212 return false;
2213 }
2214 return true;
2215
2216 case Stmt::CXXCatchStmtClass:
2217 // Do not bother checking the language mode (already covered by the
2218 // try block check).
2220 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2221 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2222 return false;
2223 return true;
2224
2225 default:
2226 if (!isa<Expr>(S))
2227 break;
2228
2229 // C++1y allows expression-statements.
2230 if (!Cxx1yLoc.isValid())
2231 Cxx1yLoc = S->getBeginLoc();
2232 return true;
2233 }
2234
2236 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2237 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2238 }
2239 return false;
2240}
2241
2242/// Check the body for the given constexpr function declaration only contains
2243/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2244///
2245/// \return true if the body is OK, false if we have found or diagnosed a
2246/// problem.
2248 Stmt *Body,
2251
2252 if (isa<CXXTryStmt>(Body)) {
2253 // C++11 [dcl.constexpr]p3:
2254 // The definition of a constexpr function shall satisfy the following
2255 // constraints: [...]
2256 // - its function-body shall be = delete, = default, or a
2257 // compound-statement
2258 //
2259 // C++11 [dcl.constexpr]p4:
2260 // In the definition of a constexpr constructor, [...]
2261 // - its function-body shall not be a function-try-block;
2262 //
2263 // This restriction is lifted in C++2a, as long as inner statements also
2264 // apply the general constexpr rules.
2265 switch (Kind) {
2267 if (!SemaRef.getLangOpts().CPlusPlus20)
2268 return false;
2269 break;
2270
2272 SemaRef.Diag(Body->getBeginLoc(),
2273 !SemaRef.getLangOpts().CPlusPlus20
2274 ? diag::ext_constexpr_function_try_block_cxx20
2275 : diag::warn_cxx17_compat_constexpr_function_try_block)
2276 << isa<CXXConstructorDecl>(Dcl);
2277 break;
2278 }
2279 }
2280
2281 // - its function-body shall be [...] a compound-statement that contains only
2282 // [... list of cases ...]
2283 //
2284 // Note that walking the children here is enough to properly check for
2285 // CompoundStmt and CXXTryStmt body.
2286 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2287 for (Stmt *SubStmt : Body->children()) {
2288 if (SubStmt &&
2289 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2290 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2291 return false;
2292 }
2293
2295 // If this is only valid as an extension, report that we don't satisfy the
2296 // constraints of the current language.
2297 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2298 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2299 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2300 return false;
2301 } else if (Cxx2bLoc.isValid()) {
2302 SemaRef.Diag(Cxx2bLoc,
2303 SemaRef.getLangOpts().CPlusPlus23
2304 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2305 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2306 << isa<CXXConstructorDecl>(Dcl);
2307 } else if (Cxx2aLoc.isValid()) {
2308 SemaRef.Diag(Cxx2aLoc,
2309 SemaRef.getLangOpts().CPlusPlus20
2310 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2311 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2312 << isa<CXXConstructorDecl>(Dcl);
2313 } else if (Cxx1yLoc.isValid()) {
2314 SemaRef.Diag(Cxx1yLoc,
2315 SemaRef.getLangOpts().CPlusPlus14
2316 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2317 : diag::ext_constexpr_body_invalid_stmt)
2318 << isa<CXXConstructorDecl>(Dcl);
2319 }
2320
2321 if (const CXXConstructorDecl *Constructor
2322 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2323 const CXXRecordDecl *RD = Constructor->getParent();
2324 // DR1359:
2325 // - every non-variant non-static data member and base class sub-object
2326 // shall be initialized;
2327 // DR1460:
2328 // - if the class is a union having variant members, exactly one of them
2329 // shall be initialized;
2330 if (RD->isUnion()) {
2331 if (Constructor->getNumCtorInitializers() == 0 &&
2332 RD->hasVariantMembers()) {
2334 SemaRef.Diag(
2335 Dcl->getLocation(),
2336 SemaRef.getLangOpts().CPlusPlus20
2337 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2338 : diag::ext_constexpr_union_ctor_no_init);
2339 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2340 return false;
2341 }
2342 }
2343 } else if (!Constructor->isDependentContext() &&
2344 !Constructor->isDelegatingConstructor()) {
2345 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2346
2347 // Skip detailed checking if we have enough initializers, and we would
2348 // allow at most one initializer per member.
2349 bool AnyAnonStructUnionMembers = false;
2350 unsigned Fields = 0;
2352 E = RD->field_end(); I != E; ++I, ++Fields) {
2353 if (I->isAnonymousStructOrUnion()) {
2354 AnyAnonStructUnionMembers = true;
2355 break;
2356 }
2357 }
2358 // DR1460:
2359 // - if the class is a union-like class, but is not a union, for each of
2360 // its anonymous union members having variant members, exactly one of
2361 // them shall be initialized;
2362 if (AnyAnonStructUnionMembers ||
2363 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2364 // Check initialization of non-static data members. Base classes are
2365 // always initialized so do not need to be checked. Dependent bases
2366 // might not have initializers in the member initializer list.
2367 llvm::SmallSet<Decl*, 16> Inits;
2368 for (const auto *I: Constructor->inits()) {
2369 if (FieldDecl *FD = I->getMember())
2370 Inits.insert(FD);
2371 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2372 Inits.insert(ID->chain_begin(), ID->chain_end());
2373 }
2374
2375 bool Diagnosed = false;
2376 for (auto *I : RD->fields())
2377 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2378 Kind))
2379 return false;
2380 }
2381 }
2382 } else {
2383 if (ReturnStmts.empty()) {
2384 switch (Kind) {
2387 return false;
2388 break;
2389
2391 // The formal requirements don't include this rule in C++14, even
2392 // though the "must be able to produce a constant expression" rules
2393 // still imply it in some cases.
2394 if (!SemaRef.getLangOpts().CPlusPlus14)
2395 return false;
2396 break;
2397 }
2398 } else if (ReturnStmts.size() > 1) {
2399 switch (Kind) {
2401 SemaRef.Diag(
2402 ReturnStmts.back(),
2403 SemaRef.getLangOpts().CPlusPlus14
2404 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2405 : diag::ext_constexpr_body_multiple_return);
2406 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2407 SemaRef.Diag(ReturnStmts[I],
2408 diag::note_constexpr_body_previous_return);
2409 break;
2410
2412 if (!SemaRef.getLangOpts().CPlusPlus14)
2413 return false;
2414 break;
2415 }
2416 }
2417 }
2418
2419 // C++11 [dcl.constexpr]p5:
2420 // if no function argument values exist such that the function invocation
2421 // substitution would produce a constant expression, the program is
2422 // ill-formed; no diagnostic required.
2423 // C++11 [dcl.constexpr]p3:
2424 // - every constructor call and implicit conversion used in initializing the
2425 // return value shall be one of those allowed in a constant expression.
2426 // C++11 [dcl.constexpr]p4:
2427 // - every constructor involved in initializing non-static data members and
2428 // base class sub-objects shall be a constexpr constructor.
2429 //
2430 // Note that this rule is distinct from the "requirements for a constexpr
2431 // function", so is not checked in CheckValid mode. Because the check for
2432 // constexpr potential is expensive, skip the check if the diagnostic is
2433 // disabled, the function is declared in a system header, or we're in C++23
2434 // or later mode (see https://wg21.link/P2448).
2435 bool SkipCheck =
2436 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2439 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2441 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2443 SemaRef.Diag(Dcl->getLocation(),
2444 diag::ext_constexpr_function_never_constant_expr)
2445 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2446 << Dcl->getNameInfo().getSourceRange();
2447 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2448 SemaRef.Diag(Diags[I].first, Diags[I].second);
2449 // Don't return false here: we allow this for compatibility in
2450 // system headers.
2451 }
2452
2453 return true;
2454}
2455
2457 const FunctionDecl *Dcl) {
2458 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2460 // Skip emitting a missing return error diagnostic for non-void functions
2461 // since C++23 no longer mandates constexpr functions to yield constant
2462 // expressions.
2463 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2464 return true;
2465
2466 // C++14 doesn't require constexpr functions to contain a 'return'
2467 // statement. We still do, unless the return type might be void, because
2468 // otherwise if there's no return statement, the function cannot
2469 // be used in a core constant expression.
2470 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2471 SemaRef.Diag(Dcl->getLocation(),
2472 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2473 : diag::err_constexpr_body_no_return)
2474 << Dcl->isConsteval();
2475 return OK;
2476}
2477
2479 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2481 return true;
2485 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2486 if (it != UndefinedButUsed.end()) {
2487 Diag(it->second, diag::err_immediate_function_used_before_definition)
2488 << it->first;
2489 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2490 if (FD->isImmediateFunction() && !FD->isConsteval())
2492 return false;
2493 }
2494 }
2495 return true;
2496}
2497
2499 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2500 "expected an immediate function");
2501 assert(FD->hasBody() && "expected the function to have a body");
2502 struct ImmediateEscalatingExpressionsVisitor
2503 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2504
2506 Sema &SemaRef;
2507
2508 const FunctionDecl *ImmediateFn;
2509 bool ImmediateFnIsConstructor;
2510 CXXConstructorDecl *CurrentConstructor = nullptr;
2511 CXXCtorInitializer *CurrentInit = nullptr;
2512
2513 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2514 : SemaRef(SemaRef), ImmediateFn(FD),
2515 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2516
2517 bool shouldVisitImplicitCode() const { return true; }
2518 bool shouldVisitLambdaBody() const { return false; }
2519
2520 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2523 if (CurrentConstructor && CurrentInit) {
2524 Loc = CurrentConstructor->getLocation();
2525 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2526 : SourceRange();
2527 }
2528
2529 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2530
2531 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2532 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2533 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2534 << (InitializedField != nullptr)
2535 << (CurrentInit && !CurrentInit->isWritten())
2536 << InitializedField << Range;
2537 }
2538 bool TraverseCallExpr(CallExpr *E) {
2539 if (const auto *DR =
2540 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2541 DR && DR->isImmediateEscalating()) {
2542 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2543 return false;
2544 }
2545
2546 for (Expr *A : E->arguments())
2547 if (!getDerived().TraverseStmt(A))
2548 return false;
2549
2550 return true;
2551 }
2552
2553 bool VisitDeclRefExpr(DeclRefExpr *E) {
2554 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2555 ReferencedFn && E->isImmediateEscalating()) {
2556 Diag(E, ReferencedFn, /*IsCall=*/false);
2557 return false;
2558 }
2559
2560 return true;
2561 }
2562
2563 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2564 CXXConstructorDecl *D = E->getConstructor();
2565 if (E->isImmediateEscalating()) {
2566 Diag(E, D, /*IsCall=*/true);
2567 return false;
2568 }
2569 return true;
2570 }
2571
2572 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2573 llvm::SaveAndRestore RAII(CurrentInit, Init);
2574 return Base::TraverseConstructorInitializer(Init);
2575 }
2576
2577 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2578 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2579 return Base::TraverseCXXConstructorDecl(Ctr);
2580 }
2581
2582 bool TraverseType(QualType T) { return true; }
2583 bool VisitBlockExpr(BlockExpr *T) { return true; }
2584
2585 } Visitor(*this, FD);
2586 Visitor.TraverseDecl(FD);
2587}
2588
2590 assert(getLangOpts().CPlusPlus && "No class names in C!");
2591
2592 if (SS && SS->isInvalid())
2593 return nullptr;
2594
2595 if (SS && SS->isNotEmpty()) {
2596 DeclContext *DC = computeDeclContext(*SS, true);
2597 return dyn_cast_or_null<CXXRecordDecl>(DC);
2598 }
2599
2600 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2601}
2602
2604 const CXXScopeSpec *SS) {
2605 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2606 return CurDecl && &II == CurDecl->getIdentifier();
2607}
2608
2610 assert(getLangOpts().CPlusPlus && "No class names in C!");
2611
2612 if (!getLangOpts().SpellChecking)
2613 return false;
2614
2615 CXXRecordDecl *CurDecl;
2616 if (SS && SS->isSet() && !SS->isInvalid()) {
2617 DeclContext *DC = computeDeclContext(*SS, true);
2618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2619 } else
2620 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2621
2622 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2623 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2624 < II->getLength()) {
2625 II = CurDecl->getIdentifier();
2626 return true;
2627 }
2628
2629 return false;
2630}
2631
2633 SourceRange SpecifierRange,
2634 bool Virtual, AccessSpecifier Access,
2635 TypeSourceInfo *TInfo,
2636 SourceLocation EllipsisLoc) {
2637 QualType BaseType = TInfo->getType();
2638 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2639 if (BaseType->containsErrors()) {
2640 // Already emitted a diagnostic when parsing the error type.
2641 return nullptr;
2642 }
2643
2644 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2645 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2646 << TInfo->getTypeLoc().getSourceRange();
2647 EllipsisLoc = SourceLocation();
2648 }
2649
2650 auto *BaseDecl =
2651 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2652 // C++ [class.derived.general]p2:
2653 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2654 // that is not an incompletely defined class; any cv-qualifiers are
2655 // ignored.
2656 if (BaseDecl) {
2657 // C++ [class.union.general]p4:
2658 // [...] A union shall not be used as a base class.
2659 if (BaseDecl->isUnion()) {
2660 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2661 return nullptr;
2662 }
2663
2664 // For the MS ABI, propagate DLL attributes to base class templates.
2666 Context.getTargetInfo().getTriple().isPS()) {
2667 if (Attr *ClassAttr = getDLLAttr(Class)) {
2668 if (auto *BaseSpec =
2669 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2670 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2671 BaseLoc);
2672 }
2673 }
2674 }
2675
2676 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2677 SpecifierRange)) {
2678 Class->setInvalidDecl();
2679 return nullptr;
2680 }
2681
2682 BaseDecl = BaseDecl->getDefinition();
2683 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2684
2685 // Microsoft docs say:
2686 // "If a base-class has a code_seg attribute, derived classes must have the
2687 // same attribute."
2688 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2689 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2690 if ((DerivedCSA || BaseCSA) &&
2691 (!BaseCSA || !DerivedCSA ||
2692 BaseCSA->getName() != DerivedCSA->getName())) {
2693 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2694 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2695 << BaseDecl;
2696 return nullptr;
2697 }
2698
2699 // A class which contains a flexible array member is not suitable for use as
2700 // a base class:
2701 // - If the layout determines that a base comes before another base,
2702 // the flexible array member would index into the subsequent base.
2703 // - If the layout determines that base comes before the derived class,
2704 // the flexible array member would index into the derived class.
2705 if (BaseDecl->hasFlexibleArrayMember()) {
2706 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2707 << BaseDecl->getDeclName();
2708 return nullptr;
2709 }
2710
2711 // C++ [class]p3:
2712 // If a class is marked final and it appears as a base-type-specifier in
2713 // base-clause, the program is ill-formed.
2714 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2715 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2716 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2717 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2718 << BaseDecl->getDeclName() << FA->getRange();
2719 return nullptr;
2720 }
2721
2722 // If the base class is invalid the derived class is as well.
2723 if (BaseDecl->isInvalidDecl())
2724 Class->setInvalidDecl();
2725 } else if (BaseType->isDependentType()) {
2726 // Make sure that we don't make an ill-formed AST where the type of the
2727 // Class is non-dependent and its attached base class specifier is an
2728 // dependent type, which violates invariants in many clang code paths (e.g.
2729 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2730 // explicitly mark the Class decl invalid. The diagnostic was already
2731 // emitted.
2732 if (!Class->isDependentContext())
2733 Class->setInvalidDecl();
2734 } else {
2735 // The base class is some non-dependent non-class type.
2736 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2737 return nullptr;
2738 }
2739
2740 // In HLSL, unspecified class access is public rather than private.
2741 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2742 Access == AS_none)
2743 Access = AS_public;
2744
2745 // Create the base specifier.
2746 return new (Context) CXXBaseSpecifier(
2747 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2748 Access, TInfo, EllipsisLoc);
2749}
2750
2752 const ParsedAttributesView &Attributes,
2753 bool Virtual, AccessSpecifier Access,
2754 ParsedType basetype, SourceLocation BaseLoc,
2755 SourceLocation EllipsisLoc) {
2756 if (!classdecl)
2757 return true;
2758
2759 AdjustDeclIfTemplate(classdecl);
2760 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2761 if (!Class)
2762 return true;
2763
2764 // We haven't yet attached the base specifiers.
2765 Class->setIsParsingBaseSpecifiers();
2766
2767 // We do not support any C++11 attributes on base-specifiers yet.
2768 // Diagnose any attributes we see.
2769 for (const ParsedAttr &AL : Attributes) {
2770 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2771 continue;
2772 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2773 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2774 << AL << AL.getRange();
2775 else
2776 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2777 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2778 }
2779
2780 TypeSourceInfo *TInfo = nullptr;
2781 GetTypeFromParser(basetype, &TInfo);
2782
2783 if (EllipsisLoc.isInvalid() &&
2784 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2786 return true;
2787
2788 // C++ [class.union.general]p4:
2789 // [...] A union shall not have base classes.
2790 if (Class->isUnion()) {
2791 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2792 << SpecifierRange;
2793 return true;
2794 }
2795
2796 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2797 Virtual, Access, TInfo,
2798 EllipsisLoc))
2799 return BaseSpec;
2800
2801 Class->setInvalidDecl();
2802 return true;
2803}
2804
2805/// Use small set to collect indirect bases. As this is only used
2806/// locally, there's no need to abstract the small size parameter.
2808
2809/// Recursively add the bases of Type. Don't add Type itself.
2810static void
2812 const QualType &Type)
2813{
2814 // Even though the incoming type is a base, it might not be
2815 // a class -- it could be a template parm, for instance.
2816 if (auto Rec = Type->getAs<RecordType>()) {
2817 auto Decl = Rec->getAsCXXRecordDecl();
2818
2819 // Iterate over its bases.
2820 for (const auto &BaseSpec : Decl->bases()) {
2821 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2823 if (Set.insert(Base).second)
2824 // If we've not already seen it, recurse.
2826 }
2827 }
2828}
2829
2832 if (Bases.empty())
2833 return false;
2834
2835 // Used to keep track of which base types we have already seen, so
2836 // that we can properly diagnose redundant direct base types. Note
2837 // that the key is always the unqualified canonical type of the base
2838 // class.
2839 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2840
2841 // Used to track indirect bases so we can see if a direct base is
2842 // ambiguous.
2843 IndirectBaseSet IndirectBaseTypes;
2844
2845 // Copy non-redundant base specifiers into permanent storage.
2846 unsigned NumGoodBases = 0;
2847 bool Invalid = false;
2848 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2849 QualType NewBaseType
2850 = Context.getCanonicalType(Bases[idx]->getType());
2851 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2852
2853 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2854 if (KnownBase) {
2855 // C++ [class.mi]p3:
2856 // A class shall not be specified as a direct base class of a
2857 // derived class more than once.
2858 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2859 << KnownBase->getType() << Bases[idx]->getSourceRange();
2860
2861 // Delete the duplicate base class specifier; we're going to
2862 // overwrite its pointer later.
2863 Context.Deallocate(Bases[idx]);
2864
2865 Invalid = true;
2866 } else {
2867 // Okay, add this new base class.
2868 KnownBase = Bases[idx];
2869 Bases[NumGoodBases++] = Bases[idx];
2870
2871 if (NewBaseType->isDependentType())
2872 continue;
2873 // Note this base's direct & indirect bases, if there could be ambiguity.
2874 if (Bases.size() > 1)
2875 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2876
2877 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2878 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2879 if (Class->isInterface() &&
2880 (!RD->isInterfaceLike() ||
2881 KnownBase->getAccessSpecifier() != AS_public)) {
2882 // The Microsoft extension __interface does not permit bases that
2883 // are not themselves public interfaces.
2884 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2885 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2886 << RD->getSourceRange();
2887 Invalid = true;
2888 }
2889 if (RD->hasAttr<WeakAttr>())
2890 Class->addAttr(WeakAttr::CreateImplicit(Context));
2891 }
2892 }
2893 }
2894
2895 // Attach the remaining base class specifiers to the derived class.
2896 Class->setBases(Bases.data(), NumGoodBases);
2897
2898 // Check that the only base classes that are duplicate are virtual.
2899 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2900 // Check whether this direct base is inaccessible due to ambiguity.
2901 QualType BaseType = Bases[idx]->getType();
2902
2903 // Skip all dependent types in templates being used as base specifiers.
2904 // Checks below assume that the base specifier is a CXXRecord.
2905 if (BaseType->isDependentType())
2906 continue;
2907
2908 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2910
2911 if (IndirectBaseTypes.count(CanonicalBase)) {
2912 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2913 /*DetectVirtual=*/true);
2914 bool found
2915 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2916 assert(found);
2917 (void)found;
2918
2919 if (Paths.isAmbiguous(CanonicalBase))
2920 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2921 << BaseType << getAmbiguousPathsDisplayString(Paths)
2922 << Bases[idx]->getSourceRange();
2923 else
2924 assert(Bases[idx]->isVirtual());
2925 }
2926
2927 // Delete the base class specifier, since its data has been copied
2928 // into the CXXRecordDecl.
2929 Context.Deallocate(Bases[idx]);
2930 }
2931
2932 return Invalid;
2933}
2934
2937 if (!ClassDecl || Bases.empty())
2938 return;
2939
2940 AdjustDeclIfTemplate(ClassDecl);
2941 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2942}
2943
2945 if (!getLangOpts().CPlusPlus)
2946 return false;
2947
2948 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2949 if (!DerivedRD)
2950 return false;
2951
2952 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2953 if (!BaseRD)
2954 return false;
2955
2956 // If either the base or the derived type is invalid, don't try to
2957 // check whether one is derived from the other.
2958 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2959 return false;
2960
2961 // FIXME: In a modules build, do we need the entire path to be visible for us
2962 // to be able to use the inheritance relationship?
2963 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2964 return false;
2965
2966 return DerivedRD->isDerivedFrom(BaseRD);
2967}
2968
2970 CXXBasePaths &Paths) {
2971 if (!getLangOpts().CPlusPlus)
2972 return false;
2973
2974 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2975 if (!DerivedRD)
2976 return false;
2977
2978 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2979 if (!BaseRD)
2980 return false;
2981
2982 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2983 return false;
2984
2985 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2986}
2987
2989 CXXCastPath &BasePathArray) {
2990 // We first go backward and check if we have a virtual base.
2991 // FIXME: It would be better if CXXBasePath had the base specifier for
2992 // the nearest virtual base.
2993 unsigned Start = 0;
2994 for (unsigned I = Path.size(); I != 0; --I) {
2995 if (Path[I - 1].Base->isVirtual()) {
2996 Start = I - 1;
2997 break;
2998 }
2999 }
3000
3001 // Now add all bases.
3002 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3003 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3004}
3005
3006
3008 CXXCastPath &BasePathArray) {
3009 assert(BasePathArray.empty() && "Base path array must be empty!");
3010 assert(Paths.isRecordingPaths() && "Must record paths!");
3011 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3012}
3013
3014bool
3016 unsigned InaccessibleBaseID,
3017 unsigned AmbiguousBaseConvID,
3019 DeclarationName Name,
3020 CXXCastPath *BasePath,
3021 bool IgnoreAccess) {
3022 // First, determine whether the path from Derived to Base is
3023 // ambiguous. This is slightly more expensive than checking whether
3024 // the Derived to Base conversion exists, because here we need to
3025 // explore multiple paths to determine if there is an ambiguity.
3026 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3027 /*DetectVirtual=*/false);
3028 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3029 if (!DerivationOkay)
3030 return true;
3031
3032 const CXXBasePath *Path = nullptr;
3033 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3034 Path = &Paths.front();
3035
3036 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3037 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3038 // user to access such bases.
3039 if (!Path && getLangOpts().MSVCCompat) {
3040 for (const CXXBasePath &PossiblePath : Paths) {
3041 if (PossiblePath.size() == 1) {
3042 Path = &PossiblePath;
3043 if (AmbiguousBaseConvID)
3044 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3045 << Base << Derived << Range;
3046 break;
3047 }
3048 }
3049 }
3050
3051 if (Path) {
3052 if (!IgnoreAccess) {
3053 // Check that the base class can be accessed.
3054 switch (
3055 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3056 case AR_inaccessible:
3057 return true;
3058 case AR_accessible:
3059 case AR_dependent:
3060 case AR_delayed:
3061 break;
3062 }
3063 }
3064
3065 // Build a base path if necessary.
3066 if (BasePath)
3067 ::BuildBasePathArray(*Path, *BasePath);
3068 return false;
3069 }
3070
3071 if (AmbiguousBaseConvID) {
3072 // We know that the derived-to-base conversion is ambiguous, and
3073 // we're going to produce a diagnostic. Perform the derived-to-base
3074 // search just one more time to compute all of the possible paths so
3075 // that we can print them out. This is more expensive than any of
3076 // the previous derived-to-base checks we've done, but at this point
3077 // performance isn't as much of an issue.
3078 Paths.clear();
3079 Paths.setRecordingPaths(true);
3080 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3081 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3082 (void)StillOkay;
3083
3084 // Build up a textual representation of the ambiguous paths, e.g.,
3085 // D -> B -> A, that will be used to illustrate the ambiguous
3086 // conversions in the diagnostic. We only print one of the paths
3087 // to each base class subobject.
3088 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3089
3090 Diag(Loc, AmbiguousBaseConvID)
3091 << Derived << Base << PathDisplayStr << Range << Name;
3092 }
3093 return true;
3094}
3095
3096bool
3099 CXXCastPath *BasePath,
3100 bool IgnoreAccess) {
3102 Derived, Base, diag::err_upcast_to_inaccessible_base,
3103 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3104 BasePath, IgnoreAccess);
3105}
3106
3108 std::string PathDisplayStr;
3109 std::set<unsigned> DisplayedPaths;
3110 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3111 Path != Paths.end(); ++Path) {
3112 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3113 // We haven't displayed a path to this particular base
3114 // class subobject yet.
3115 PathDisplayStr += "\n ";
3116 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3117 for (CXXBasePath::const_iterator Element = Path->begin();
3118 Element != Path->end(); ++Element)
3119 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3120 }
3121 }
3122
3123 return PathDisplayStr;
3124}
3125
3126//===----------------------------------------------------------------------===//
3127// C++ class member Handling
3128//===----------------------------------------------------------------------===//
3129
3131 SourceLocation ColonLoc,
3132 const ParsedAttributesView &Attrs) {
3133 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3135 ASLoc, ColonLoc);
3136 CurContext->addHiddenDecl(ASDecl);
3137 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3138}
3139
3141 if (D->isInvalidDecl())
3142 return;
3143
3144 // We only care about "override" and "final" declarations.
3145 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3146 return;
3147
3148 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3149
3150 // We can't check dependent instance methods.
3151 if (MD && MD->isInstance() &&
3152 (MD->getParent()->hasAnyDependentBases() ||
3153 MD->getType()->isDependentType()))
3154 return;
3155
3156 if (MD && !MD->isVirtual()) {
3157 // If we have a non-virtual method, check if it hides a virtual method.
3158 // (In that case, it's most likely the method has the wrong type.)
3159 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3160 FindHiddenVirtualMethods(MD, OverloadedMethods);
3161
3162 if (!OverloadedMethods.empty()) {
3163 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3164 Diag(OA->getLocation(),
3165 diag::override_keyword_hides_virtual_member_function)
3166 << "override" << (OverloadedMethods.size() > 1);
3167 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3168 Diag(FA->getLocation(),
3169 diag::override_keyword_hides_virtual_member_function)
3170 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3171 << (OverloadedMethods.size() > 1);
3172 }
3173 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3174 MD->setInvalidDecl();
3175 return;
3176 }
3177 // Fall through into the general case diagnostic.
3178 // FIXME: We might want to attempt typo correction here.
3179 }
3180
3181 if (!MD || !MD->isVirtual()) {
3182 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3183 Diag(OA->getLocation(),
3184 diag::override_keyword_only_allowed_on_virtual_member_functions)
3185 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3186 D->dropAttr<OverrideAttr>();
3187 }
3188 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3189 Diag(FA->getLocation(),
3190 diag::override_keyword_only_allowed_on_virtual_member_functions)
3191 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3192 << FixItHint::CreateRemoval(FA->getLocation());
3193 D->dropAttr<FinalAttr>();
3194 }
3195 return;
3196 }
3197
3198 // C++11 [class.virtual]p5:
3199 // If a function is marked with the virt-specifier override and
3200 // does not override a member function of a base class, the program is
3201 // ill-formed.
3202 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3203 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3204 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3205 << MD->getDeclName();
3206}
3207
3209 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3210 return;
3211 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3212 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3213 return;
3214
3216 SourceLocation SpellingLoc = Loc;
3217 if (getSourceManager().isMacroArgExpansion(Loc))
3219 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3220 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3221 return;
3222
3223 if (MD->size_overridden_methods() > 0) {
3224 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3225 unsigned DiagID =
3226 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3227 ? DiagInconsistent
3228 : DiagSuggest;
3229 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3230 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3231 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3232 };
3233 if (isa<CXXDestructorDecl>(MD))
3234 EmitDiag(
3235 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3236 diag::warn_suggest_destructor_marked_not_override_overriding);
3237 else
3238 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3239 diag::warn_suggest_function_marked_not_override_overriding);
3240 }
3241}
3242
3244 const CXXMethodDecl *Old) {
3245 FinalAttr *FA = Old->getAttr<FinalAttr>();
3246 if (!FA)
3247 return false;
3248
3249 Diag(New->getLocation(), diag::err_final_function_overridden)
3250 << New->getDeclName()
3251 << FA->isSpelledAsSealed();
3252 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3253 return true;
3254}
3255
3257 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3258 // FIXME: Destruction of ObjC lifetime types has side-effects.
3259 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3260 return !RD->isCompleteDefinition() ||
3261 !RD->hasTrivialDefaultConstructor() ||
3262 !RD->hasTrivialDestructor();
3263 return false;
3264}
3265
3266void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3267 DeclarationName FieldName,
3268 const CXXRecordDecl *RD,
3269 bool DeclIsField) {
3270 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3271 return;
3272
3273 // To record a shadowed field in a base
3274 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3275 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3276 CXXBasePath &Path) {
3277 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3278 // Record an ambiguous path directly
3279 if (Bases.find(Base) != Bases.end())
3280 return true;
3281 for (const auto Field : Base->lookup(FieldName)) {
3282 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3283 Field->getAccess() != AS_private) {
3284 assert(Field->getAccess() != AS_none);
3285 assert(Bases.find(Base) == Bases.end());
3286 Bases[Base] = Field;
3287 return true;
3288 }
3289 }
3290 return false;
3291 };
3292
3293 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3294 /*DetectVirtual=*/true);
3295 if (!RD->lookupInBases(FieldShadowed, Paths))
3296 return;
3297
3298 for (const auto &P : Paths) {
3299 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3300 auto It = Bases.find(Base);
3301 // Skip duplicated bases
3302 if (It == Bases.end())
3303 continue;
3304 auto BaseField = It->second;
3305 assert(BaseField->getAccess() != AS_private);
3306 if (AS_none !=
3307 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3308 Diag(Loc, diag::warn_shadow_field)
3309 << FieldName << RD << Base << DeclIsField;
3310 Diag(BaseField->getLocation(), diag::note_shadow_field);
3311 Bases.erase(It);
3312 }
3313 }
3314}
3315
3316NamedDecl *
3318 MultiTemplateParamsArg TemplateParameterLists,
3319 Expr *BW, const VirtSpecifiers &VS,
3320 InClassInitStyle InitStyle) {
3321 const DeclSpec &DS = D.getDeclSpec();
3323 DeclarationName Name = NameInfo.getName();
3324 SourceLocation Loc = NameInfo.getLoc();
3325
3326 // For anonymous bitfields, the location should point to the type.
3327 if (Loc.isInvalid())
3328 Loc = D.getBeginLoc();
3329
3330 Expr *BitWidth = static_cast<Expr*>(BW);
3331
3332 assert(isa<CXXRecordDecl>(CurContext));
3333 assert(!DS.isFriendSpecified());
3334
3335 bool isFunc = D.isDeclarationOfFunction();
3336 const ParsedAttr *MSPropertyAttr =
3337 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3338
3339 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3340 // The Microsoft extension __interface only permits public member functions
3341 // and prohibits constructors, destructors, operators, non-public member
3342 // functions, static methods and data members.
3343 unsigned InvalidDecl;
3344 bool ShowDeclName = true;
3345 if (!isFunc &&
3346 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3347 InvalidDecl = 0;
3348 else if (!isFunc)
3349 InvalidDecl = 1;
3350 else if (AS != AS_public)
3351 InvalidDecl = 2;
3353 InvalidDecl = 3;
3354 else switch (Name.getNameKind()) {
3356 InvalidDecl = 4;
3357 ShowDeclName = false;
3358 break;
3359
3361 InvalidDecl = 5;
3362 ShowDeclName = false;
3363 break;
3364
3367 InvalidDecl = 6;
3368 break;
3369
3370 default:
3371 InvalidDecl = 0;
3372 break;
3373 }
3374
3375 if (InvalidDecl) {
3376 if (ShowDeclName)
3377 Diag(Loc, diag::err_invalid_member_in_interface)
3378 << (InvalidDecl-1) << Name;
3379 else
3380 Diag(Loc, diag::err_invalid_member_in_interface)
3381 << (InvalidDecl-1) << "";
3382 return nullptr;
3383 }
3384 }
3385
3386 // C++ 9.2p6: A member shall not be declared to have automatic storage
3387 // duration (auto, register) or with the extern storage-class-specifier.
3388 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3389 // data members and cannot be applied to names declared const or static,
3390 // and cannot be applied to reference members.
3391 switch (DS.getStorageClassSpec()) {
3395 break;
3397 if (isFunc) {
3398 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3399
3400 // FIXME: It would be nicer if the keyword was ignored only for this
3401 // declarator. Otherwise we could get follow-up errors.
3402 D.getMutableDeclSpec().ClearStorageClassSpecs();
3403 }
3404 break;
3405 default:
3407 diag::err_storageclass_invalid_for_member);
3408 D.getMutableDeclSpec().ClearStorageClassSpecs();
3409 break;
3410 }
3411
3412 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3414 !isFunc && TemplateParameterLists.empty();
3415
3416 if (DS.hasConstexprSpecifier() && isInstField) {
3418 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3419 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3420 if (InitStyle == ICIS_NoInit) {
3421 B << 0 << 0;
3422 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3423 B << FixItHint::CreateRemoval(ConstexprLoc);
3424 else {
3425 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3426 D.getMutableDeclSpec().ClearConstexprSpec();
3427 const char *PrevSpec;
3428 unsigned DiagID;
3429 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3430 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3431 (void)Failed;
3432 assert(!Failed && "Making a constexpr member const shouldn't fail");
3433 }
3434 } else {
3435 B << 1;
3436 const char *PrevSpec;
3437 unsigned DiagID;
3438 if (D.getMutableDeclSpec().SetStorageClassSpec(
3439 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3442 "This is the only DeclSpec that should fail to be applied");
3443 B << 1;
3444 } else {
3445 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3446 isInstField = false;
3447 }
3448 }
3449 }
3450
3452 if (isInstField) {
3453 CXXScopeSpec &SS = D.getCXXScopeSpec();
3454
3455 // Data members must have identifiers for names.
3456 if (!Name.isIdentifier()) {
3457 Diag(Loc, diag::err_bad_variable_name)
3458 << Name;
3459 return nullptr;
3460 }
3461
3462 IdentifierInfo *II = Name.getAsIdentifierInfo();
3463 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3464 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3465 << II
3466 << SourceRange(D.getName().TemplateId->LAngleLoc,
3467 D.getName().TemplateId->RAngleLoc)
3468 << D.getName().TemplateId->LAngleLoc;
3469 D.SetIdentifier(II, Loc);
3470 }
3471
3472 if (SS.isSet() && !SS.isInvalid()) {
3473 // The user provided a superfluous scope specifier inside a class
3474 // definition:
3475 //
3476 // class X {
3477 // int X::member;
3478 // };
3479 if (DeclContext *DC = computeDeclContext(SS, false)) {
3480 TemplateIdAnnotation *TemplateId =
3482 ? D.getName().TemplateId
3483 : nullptr;
3484 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3485 TemplateId,
3486 /*IsMemberSpecialization=*/false);
3487 } else {
3488 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3489 << Name << SS.getRange();
3490 }
3491 SS.clear();
3492 }
3493
3494 if (MSPropertyAttr) {
3495 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3496 BitWidth, InitStyle, AS, *MSPropertyAttr);
3497 if (!Member)
3498 return nullptr;
3499 isInstField = false;
3500 } else {
3501 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3502 BitWidth, InitStyle, AS);
3503 if (!Member)
3504 return nullptr;
3505 }
3506
3507 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3508 } else {
3509 Member = HandleDeclarator(S, D, TemplateParameterLists);
3510 if (!Member)
3511 return nullptr;
3512
3513 // Non-instance-fields can't have a bitfield.
3514 if (BitWidth) {
3515 if (Member->isInvalidDecl()) {
3516 // don't emit another diagnostic.
3517 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3518 // C++ 9.6p3: A bit-field shall not be a static member.
3519 // "static member 'A' cannot be a bit-field"
3520 Diag(Loc, diag::err_static_not_bitfield)
3521 << Name << BitWidth->getSourceRange();
3522 } else if (isa<TypedefDecl>(Member)) {
3523 // "typedef member 'x' cannot be a bit-field"
3524 Diag(Loc, diag::err_typedef_not_bitfield)
3525 << Name << BitWidth->getSourceRange();
3526 } else {
3527 // A function typedef ("typedef int f(); f a;").
3528 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3529 Diag(Loc, diag::err_not_integral_type_bitfield)
3530 << Name << cast<ValueDecl>(Member)->getType()
3531 << BitWidth->getSourceRange();
3532 }
3533
3534 BitWidth = nullptr;
3535 Member->setInvalidDecl();
3536 }
3537
3538 NamedDecl *NonTemplateMember = Member;
3539 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3540 NonTemplateMember = FunTmpl->getTemplatedDecl();
3541 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3542 NonTemplateMember = VarTmpl->getTemplatedDecl();
3543
3544 Member->setAccess(AS);
3545
3546 // If we have declared a member function template or static data member
3547 // template, set the access of the templated declaration as well.
3548 if (NonTemplateMember != Member)
3549 NonTemplateMember->setAccess(AS);
3550
3551 // C++ [temp.deduct.guide]p3:
3552 // A deduction guide [...] for a member class template [shall be
3553 // declared] with the same access [as the template].
3554 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3555 auto *TD = DG->getDeducedTemplate();
3556 // Access specifiers are only meaningful if both the template and the
3557 // deduction guide are from the same scope.
3558 if (AS != TD->getAccess() &&
3559 TD->getDeclContext()->getRedeclContext()->Equals(
3560 DG->getDeclContext()->getRedeclContext())) {
3561 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3562 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3563 << TD->getAccess();
3564 const AccessSpecDecl *LastAccessSpec = nullptr;
3565 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3566 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3567 LastAccessSpec = AccessSpec;
3568 }
3569 assert(LastAccessSpec && "differing access with no access specifier");
3570 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3571 << AS;
3572 }
3573 }
3574 }
3575
3576 if (VS.isOverrideSpecified())
3577 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3578 if (VS.isFinalSpecified())
3579 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3581 ? FinalAttr::Keyword_sealed
3582 : FinalAttr::Keyword_final));
3583
3584 if (VS.getLastLocation().isValid()) {
3585 // Update the end location of a method that has a virt-specifiers.
3586 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3587 MD->setRangeEnd(VS.getLastLocation());
3588 }
3589
3591
3592 assert((Name || isInstField) && "No identifier for non-field ?");
3593
3594 if (isInstField) {
3595 FieldDecl *FD = cast<FieldDecl>(Member);
3596 FieldCollector->Add(FD);
3597
3598 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3599 // Remember all explicit private FieldDecls that have a name, no side
3600 // effects and are not part of a dependent type declaration.
3601
3602 auto DeclHasUnusedAttr = [](const QualType &T) {
3603 if (const TagDecl *TD = T->getAsTagDecl())
3604 return TD->hasAttr<UnusedAttr>();
3605 if (const TypedefType *TDT = T->getAs<TypedefType>())
3606 return TDT->getDecl()->hasAttr<UnusedAttr>();
3607 return false;
3608 };
3609
3610 if (!FD->isImplicit() && FD->getDeclName() &&
3611 FD->getAccess() == AS_private &&
3612 !FD->hasAttr<UnusedAttr>() &&
3613 !FD->getParent()->isDependentContext() &&
3614 !DeclHasUnusedAttr(FD->getType()) &&
3616 UnusedPrivateFields.insert(FD);
3617 }
3618 }
3619
3620 return Member;
3621}
3622
3623namespace {
3624 class UninitializedFieldVisitor
3625 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3626 Sema &S;
3627 // List of Decls to generate a warning on. Also remove Decls that become
3628 // initialized.
3629 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3630 // List of base classes of the record. Classes are removed after their
3631 // initializers.
3632 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3633 // Vector of decls to be removed from the Decl set prior to visiting the
3634 // nodes. These Decls may have been initialized in the prior initializer.
3636 // If non-null, add a note to the warning pointing back to the constructor.
3637 const CXXConstructorDecl *Constructor;
3638 // Variables to hold state when processing an initializer list. When
3639 // InitList is true, special case initialization of FieldDecls matching
3640 // InitListFieldDecl.
3641 bool InitList;
3642 FieldDecl *InitListFieldDecl;
3643 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3644
3645 public:
3647 UninitializedFieldVisitor(Sema &S,
3648 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3649 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3650 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3651 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3652
3653 // Returns true if the use of ME is not an uninitialized use.
3654 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3655 bool CheckReferenceOnly) {
3657 bool ReferenceField = false;
3658 while (ME) {
3659 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3660 if (!FD)
3661 return false;
3662 Fields.push_back(FD);
3663 if (FD->getType()->isReferenceType())
3664 ReferenceField = true;
3665 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3666 }
3667
3668 // Binding a reference to an uninitialized field is not an
3669 // uninitialized use.
3670 if (CheckReferenceOnly && !ReferenceField)
3671 return true;
3672
3673 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3674 // Discard the first field since it is the field decl that is being
3675 // initialized.
3676 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3677 UsedFieldIndex.push_back(FD->getFieldIndex());
3678
3679 for (auto UsedIter = UsedFieldIndex.begin(),
3680 UsedEnd = UsedFieldIndex.end(),
3681 OrigIter = InitFieldIndex.begin(),
3682 OrigEnd = InitFieldIndex.end();
3683 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3684 if (*UsedIter < *OrigIter)
3685 return true;
3686 if (*UsedIter > *OrigIter)
3687 break;
3688 }
3689
3690 return false;
3691 }
3692
3693 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3694 bool AddressOf) {
3695 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3696 return;
3697
3698 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3699 // or union.
3700 MemberExpr *FieldME = ME;
3701
3702 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3703
3704 Expr *Base = ME;
3705 while (MemberExpr *SubME =
3706 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3707
3708 if (isa<VarDecl>(SubME->getMemberDecl()))
3709 return;
3710
3711 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3712 if (!FD->isAnonymousStructOrUnion())
3713 FieldME = SubME;
3714
3715 if (!FieldME->getType().isPODType(S.Context))
3716 AllPODFields = false;
3717
3718 Base = SubME->getBase();
3719 }
3720
3721 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3722 Visit(Base);
3723 return;
3724 }
3725
3726 if (AddressOf && AllPODFields)
3727 return;
3728
3729 ValueDecl* FoundVD = FieldME->getMemberDecl();
3730
3731 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3732 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3733 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3734 }
3735
3736 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3737 QualType T = BaseCast->getType();
3738 if (T->isPointerType() &&
3739 BaseClasses.count(T->getPointeeType())) {
3740 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3741 << T->getPointeeType() << FoundVD;
3742 }
3743 }
3744 }
3745
3746 if (!Decls.count(FoundVD))
3747 return;
3748
3749 const bool IsReference = FoundVD->getType()->isReferenceType();
3750
3751 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3752 // Special checking for initializer lists.
3753 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3754 return;
3755 }
3756 } else {
3757 // Prevent double warnings on use of unbounded references.
3758 if (CheckReferenceOnly && !IsReference)
3759 return;
3760 }
3761
3762 unsigned diag = IsReference
3763 ? diag::warn_reference_field_is_uninit
3764 : diag::warn_field_is_uninit;
3765 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3766 if (Constructor)
3767 S.Diag(Constructor->getLocation(),
3768 diag::note_uninit_in_this_constructor)
3769 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3770
3771 }
3772
3773 void HandleValue(Expr *E, bool AddressOf) {
3774 E = E->IgnoreParens();
3775
3776 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3777 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3778 AddressOf /*AddressOf*/);
3779 return;
3780 }
3781
3782 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3783 Visit(CO->getCond());
3784 HandleValue(CO->getTrueExpr(), AddressOf);
3785 HandleValue(CO->getFalseExpr(), AddressOf);
3786 return;
3787 }
3788
3789 if (BinaryConditionalOperator *BCO =
3790 dyn_cast<BinaryConditionalOperator>(E)) {
3791 Visit(BCO->getCond());
3792 HandleValue(BCO->getFalseExpr(), AddressOf);
3793 return;
3794 }
3795
3796 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3797 HandleValue(OVE->getSourceExpr(), AddressOf);
3798 return;
3799 }
3800
3801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3802 switch (BO->getOpcode()) {
3803 default:
3804 break;
3805 case(BO_PtrMemD):
3806 case(BO_PtrMemI):
3807 HandleValue(BO->getLHS(), AddressOf);
3808 Visit(BO->getRHS());
3809 return;
3810 case(BO_Comma):
3811 Visit(BO->getLHS());
3812 HandleValue(BO->getRHS(), AddressOf);
3813 return;
3814 }
3815 }
3816
3817 Visit(E);
3818 }
3819
3820 void CheckInitListExpr(InitListExpr *ILE) {
3821 InitFieldIndex.push_back(0);
3822 for (auto *Child : ILE->children()) {
3823 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3824 CheckInitListExpr(SubList);
3825 } else {
3826 Visit(Child);
3827 }
3828 ++InitFieldIndex.back();
3829 }
3830 InitFieldIndex.pop_back();
3831 }
3832
3833 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3834 FieldDecl *Field, const Type *BaseClass) {
3835 // Remove Decls that may have been initialized in the previous
3836 // initializer.
3837 for (ValueDecl* VD : DeclsToRemove)
3838 Decls.erase(VD);
3839 DeclsToRemove.clear();
3840
3841 Constructor = FieldConstructor;
3842 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3843
3844 if (ILE && Field) {
3845 InitList = true;
3846 InitListFieldDecl = Field;
3847 InitFieldIndex.clear();
3848 CheckInitListExpr(ILE);
3849 } else {
3850 InitList = false;
3851 Visit(E);
3852 }
3853
3854 if (Field)
3855 Decls.erase(Field);
3856 if (BaseClass)
3857 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3858 }
3859
3860 void VisitMemberExpr(MemberExpr *ME) {
3861 // All uses of unbounded reference fields will warn.
3862 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3863 }
3864
3865 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3866 if (E->getCastKind() == CK_LValueToRValue) {
3867 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3868 return;
3869 }
3870
3871 Inherited::VisitImplicitCastExpr(E);
3872 }
3873
3874 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3875 if (E->getConstructor()->isCopyConstructor()) {
3876 Expr *ArgExpr = E->getArg(0);
3877 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3878 if (ILE->getNumInits() == 1)
3879 ArgExpr = ILE->getInit(0);
3880 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3881 if (ICE->getCastKind() == CK_NoOp)
3882 ArgExpr = ICE->getSubExpr();
3883 HandleValue(ArgExpr, false /*AddressOf*/);
3884 return;
3885 }
3886 Inherited::VisitCXXConstructExpr(E);
3887 }
3888
3889 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3890 Expr *Callee = E->getCallee();
3891 if (isa<MemberExpr>(Callee)) {
3892 HandleValue(Callee, false /*AddressOf*/);
3893 for (auto *Arg : E->arguments())
3894 Visit(Arg);
3895 return;
3896 }
3897
3898 Inherited::VisitCXXMemberCallExpr(E);
3899 }
3900
3901 void VisitCallExpr(CallExpr *E) {
3902 // Treat std::move as a use.
3903 if (E->isCallToStdMove()) {
3904 HandleValue(E->getArg(0), /*AddressOf=*/false);
3905 return;
3906 }
3907
3908 Inherited::VisitCallExpr(E);
3909 }
3910
3911 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3912 Expr *Callee = E->getCallee();
3913
3914 if (isa<UnresolvedLookupExpr>(Callee))
3915 return Inherited::VisitCXXOperatorCallExpr(E);
3916
3917 Visit(Callee);
3918 for (auto *Arg : E->arguments())
3919 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3920 }
3921
3922 void VisitBinaryOperator(BinaryOperator *E) {
3923 // If a field assignment is detected, remove the field from the
3924 // uninitiailized field set.
3925 if (E->getOpcode() == BO_Assign)
3926 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3927 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3928 if (!FD->getType()->isReferenceType())
3929 DeclsToRemove.push_back(FD);
3930
3931 if (E->isCompoundAssignmentOp()) {
3932 HandleValue(E->getLHS(), false /*AddressOf*/);
3933 Visit(E->getRHS());
3934 return;
3935 }
3936
3937 Inherited::VisitBinaryOperator(E);
3938 }
3939
3940 void VisitUnaryOperator(UnaryOperator *E) {
3941 if (E->isIncrementDecrementOp()) {
3942 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3943 return;
3944 }
3945 if (E->getOpcode() == UO_AddrOf) {
3946 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3947 HandleValue(ME->getBase(), true /*AddressOf*/);
3948 return;
3949 }
3950 }
3951
3952 Inherited::VisitUnaryOperator(E);
3953 }
3954 };
3955
3956 // Diagnose value-uses of fields to initialize themselves, e.g.
3957 // foo(foo)
3958 // where foo is not also a parameter to the constructor.
3959 // Also diagnose across field uninitialized use such as
3960 // x(y), y(x)
3961 // TODO: implement -Wuninitialized and fold this into that framework.
3962 static void DiagnoseUninitializedFields(
3963 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3964
3965 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3966 Constructor->getLocation())) {
3967 return;
3968 }
3969
3970 if (Constructor->isInvalidDecl())
3971 return;
3972
3973 const CXXRecordDecl *RD = Constructor->getParent();
3974
3975 if (RD->isDependentContext())
3976 return;
3977
3978 // Holds fields that are uninitialized.
3979 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3980
3981 // At the beginning, all fields are uninitialized.
3982 for (auto *I : RD->decls()) {
3983 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3984 UninitializedFields.insert(FD);
3985 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3986 UninitializedFields.insert(IFD->getAnonField());
3987 }
3988 }
3989
3990 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3991 for (const auto &I : RD->bases())
3992 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3993
3994 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3995 return;
3996
3997 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3998 UninitializedFields,
3999 UninitializedBaseClasses);
4000
4001 for (const auto *FieldInit : Constructor->inits()) {
4002 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4003 break;
4004
4005 Expr *InitExpr = FieldInit->getInit();
4006 if (!InitExpr)
4007 continue;
4008
4010 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4011 InitExpr = Default->getExpr();
4012 if (!InitExpr)
4013 continue;
4014 // In class initializers will point to the constructor.
4015 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4016 FieldInit->getAnyMember(),
4017 FieldInit->getBaseClass());
4018 } else {
4019 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4020 FieldInit->getAnyMember(),
4021 FieldInit->getBaseClass());
4022 }
4023 }
4024 }
4025} // namespace
4026
4028 // Create a synthetic function scope to represent the call to the constructor
4029 // that notionally surrounds a use of this initializer.
4031}
4032
4034 if (!D.isFunctionDeclarator())
4035 return;
4036 auto &FTI = D.getFunctionTypeInfo();
4037 if (!FTI.Params)
4038 return;
4039 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4040 FTI.NumParams)) {
4041 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4042 if (ParamDecl->getDeclName())
4043 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4044 }
4045}
4046
4048 return ActOnRequiresClause(ConstraintExpr);
4049}
4050
4052 if (ConstraintExpr.isInvalid())
4053 return ExprError();
4054
4055 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4056 if (ConstraintExpr.isInvalid())
4057 return ExprError();
4058
4059 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4061 return ExprError();
4062
4063 return ConstraintExpr;
4064}
4065
4067 Expr *InitExpr,
4068 SourceLocation InitLoc) {
4069 InitializedEntity Entity =
4071 InitializationKind Kind =
4074 InitExpr->getBeginLoc(),
4075 InitExpr->getEndLoc())
4076 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4077 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4078 return Seq.Perform(*this, Entity, Kind, InitExpr);
4079}
4080
4082 SourceLocation InitLoc,
4083 Expr *InitExpr) {
4084 // Pop the notional constructor scope we created earlier.
4085 PopFunctionScopeInfo(nullptr, D);
4086
4087 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4088 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4089 "must set init style when field is created");
4090
4091 if (!InitExpr) {
4092 D->setInvalidDecl();
4093 if (FD)
4095 return;
4096 }
4097
4099 FD->setInvalidDecl();
4101 return;
4102 }
4103
4104 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4105 /*RecoverUncorrectedTypos=*/true);
4106 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4107 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4108 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4109 // C++11 [class.base.init]p7:
4110 // The initialization of each base and member constitutes a
4111 // full-expression.
4112 if (!Init.isInvalid())
4113 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4114 if (Init.isInvalid()) {
4115 FD->setInvalidDecl();
4116 return;
4117 }
4118 }
4119
4120 FD->setInClassInitializer(Init.get());
4121}
4122
4123/// Find the direct and/or virtual base specifiers that
4124/// correspond to the given base type, for use in base initialization
4125/// within a constructor.
4127 CXXRecordDecl *ClassDecl,
4128 QualType BaseType,
4129 const CXXBaseSpecifier *&DirectBaseSpec,
4130 const CXXBaseSpecifier *&VirtualBaseSpec) {
4131 // First, check for a direct base class.
4132 DirectBaseSpec = nullptr;
4133 for (const auto &Base : ClassDecl->bases()) {
4134 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4135 // We found a direct base of this type. That's what we're
4136 // initializing.
4137 DirectBaseSpec = &Base;
4138 break;
4139 }
4140 }
4141
4142 // Check for a virtual base class.
4143 // FIXME: We might be able to short-circuit this if we know in advance that
4144 // there are no virtual bases.
4145 VirtualBaseSpec = nullptr;
4146 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4147 // We haven't found a base yet; search the class hierarchy for a
4148 // virtual base class.
4149 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4150 /*DetectVirtual=*/false);
4151 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4152 SemaRef.Context.getTypeDeclType(ClassDecl),
4153 BaseType, Paths)) {
4154 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4155 Path != Paths.end(); ++Path) {
4156 if (Path->back().Base->isVirtual()) {
4157 VirtualBaseSpec = Path->back().Base;
4158 break;
4159 }
4160 }
4161 }
4162 }
4163
4164 return DirectBaseSpec || VirtualBaseSpec;
4165}
4166
4169 Scope *S,
4170 CXXScopeSpec &SS,
4171 IdentifierInfo *MemberOrBase,
4172 ParsedType TemplateTypeTy,
4173 const DeclSpec &DS,
4174 SourceLocation IdLoc,
4175 Expr *InitList,
4176 SourceLocation EllipsisLoc) {
4177 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4178 DS, IdLoc, InitList,
4179 EllipsisLoc);
4180}
4181
4184 Scope *S,
4185 CXXScopeSpec &SS,
4186 IdentifierInfo *MemberOrBase,
4187 ParsedType TemplateTypeTy,
4188 const DeclSpec &DS,
4189 SourceLocation IdLoc,
4190 SourceLocation LParenLoc,
4191 ArrayRef<Expr *> Args,
4192 SourceLocation RParenLoc,
4193 SourceLocation EllipsisLoc) {
4194 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4195 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4196 DS, IdLoc, List, EllipsisLoc);
4197}
4198
4199namespace {
4200
4201// Callback to only accept typo corrections that can be a valid C++ member
4202// initializer: either a non-static field member or a base class.
4203class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4204public:
4205 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4206 : ClassDecl(ClassDecl) {}
4207
4208 bool ValidateCandidate(const TypoCorrection &candidate) override {
4209 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4210 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4211 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4212 return isa<TypeDecl>(ND);
4213 }
4214 return false;
4215 }
4216
4217 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4218 return std::make_unique<MemInitializerValidatorCCC>(*this);
4219 }
4220
4221private:
4222 CXXRecordDecl *ClassDecl;
4223};
4224
4225}
4226
4228 RecordDecl *ClassDecl,
4229 const IdentifierInfo *Name) {
4230 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4232 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4233 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4235 });
4236 // We did not find a placeholder variable
4237 if (Found == Result.end())
4238 return false;
4239 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4240 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4241 const NamedDecl *ND = *It;
4242 if (ND->getDeclContext() != ND->getDeclContext())
4243 break;
4244 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4246 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4247 }
4248 return true;
4249}
4250
4251ValueDecl *
4253 const IdentifierInfo *MemberOrBase) {
4254 ValueDecl *ND = nullptr;
4255 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4256 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4257 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4258 if (ND) {
4259 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4260 return nullptr;
4261 break;
4262 }
4263 if (!IsPlaceholder)
4264 return cast<ValueDecl>(D);
4265 ND = cast<ValueDecl>(D);
4266 }
4267 }
4268 return ND;
4269}
4270
4272 CXXScopeSpec &SS,
4273 ParsedType TemplateTypeTy,
4274 IdentifierInfo *MemberOrBase) {
4275 if (SS.getScopeRep() || TemplateTypeTy)
4276 return nullptr;
4277 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4278}
4279
4282 Scope *S,
4283 CXXScopeSpec &SS,
4284 IdentifierInfo *MemberOrBase,
4285 ParsedType TemplateTypeTy,
4286 const DeclSpec &DS,
4287 SourceLocation IdLoc,
4288 Expr *Init,
4289 SourceLocation EllipsisLoc) {
4290 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4291 /*RecoverUncorrectedTypos=*/true);
4292 if (!Res.isUsable())
4293 return true;
4294 Init = Res.get();
4295
4296 if (!ConstructorD)
4297 return true;
4298
4299 AdjustDeclIfTemplate(ConstructorD);
4300
4301 CXXConstructorDecl *Constructor
4302 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4303 if (!Constructor) {
4304 // The user wrote a constructor initializer on a function that is
4305 // not a C++ constructor. Ignore the error for now, because we may
4306 // have more member initializers coming; we'll diagnose it just
4307 // once in ActOnMemInitializers.
4308 return true;
4309 }
4310
4311 CXXRecordDecl *ClassDecl = Constructor->getParent();
4312
4313 // C++ [class.base.init]p2:
4314 // Names in a mem-initializer-id are looked up in the scope of the
4315 // constructor's class and, if not found in that scope, are looked
4316 // up in the scope containing the constructor's definition.
4317 // [Note: if the constructor's class contains a member with the
4318 // same name as a direct or virtual base class of the class, a
4319 // mem-initializer-id naming the member or base class and composed
4320 // of a single identifier refers to the class member. A
4321 // mem-initializer-id for the hidden base class may be specified
4322 // using a qualified name. ]
4323
4324 // Look for a member, first.
4326 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4327 if (EllipsisLoc.isValid())
4328 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4329 << MemberOrBase
4330 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4331
4332 return BuildMemberInitializer(Member, Init, IdLoc);
4333 }
4334 // It didn't name a member, so see if it names a class.
4335 QualType BaseType;
4336 TypeSourceInfo *TInfo = nullptr;
4337
4338 if (TemplateTypeTy) {
4339 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4340 if (BaseType.isNull())
4341 return true;
4342 } else if (DS.getTypeSpecType() == TST_decltype) {
4343 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4344 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4345 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4346 return true;
4347 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4348 BaseType =
4350 DS.getBeginLoc(), DS.getEllipsisLoc());
4351 } else {
4352 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4353 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4354
4355 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4356 if (!TyD) {
4357 if (R.isAmbiguous()) return true;
4358
4359 // We don't want access-control diagnostics here.
4361
4362 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4363 bool NotUnknownSpecialization = false;
4364 DeclContext *DC = computeDeclContext(SS, false);
4365 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4366 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4367
4368 if (!NotUnknownSpecialization) {
4369 // When the scope specifier can refer to a member of an unknown
4370 // specialization, we take it as a type name.
4371 BaseType = CheckTypenameType(
4373 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4374 if (BaseType.isNull())
4375 return true;
4376
4377 TInfo = Context.CreateTypeSourceInfo(BaseType);
4380 if (!TL.isNull()) {
4381 TL.setNameLoc(IdLoc);
4384 }
4385
4386 R.clear();
4387 R.setLookupName(MemberOrBase);
4388 }
4389 }
4390
4391 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4392 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4393 auto *TempSpec = cast<TemplateSpecializationType>(
4394 UnqualifiedBase->getInjectedClassNameSpecialization());
4395 TemplateName TN = TempSpec->getTemplateName();
4396 for (auto const &Base : ClassDecl->bases()) {
4397 auto BaseTemplate =
4398 Base.getType()->getAs<TemplateSpecializationType>();
4399 if (BaseTemplate && Context.hasSameTemplateName(
4400 BaseTemplate->getTemplateName(), TN)) {
4401 Diag(IdLoc, diag::ext_unqualified_base_class)
4402 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4403 BaseType = Base.getType();
4404 break;
4405 }
4406 }
4407 }
4408 }
4409
4410 // If no results were found, try to correct typos.
4411 TypoCorrection Corr;
4412 MemInitializerValidatorCCC CCC(ClassDecl);
4413 if (R.empty() && BaseType.isNull() &&
4414 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4415 CCC, CTK_ErrorRecovery, ClassDecl))) {
4417 // We have found a non-static data member with a similar
4418 // name to what was typed; complain and initialize that
4419 // member.
4420 diagnoseTypo(Corr,
4421 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4422 << MemberOrBase << true);
4423 return BuildMemberInitializer(Member, Init, IdLoc);
4424 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4425 const CXXBaseSpecifier *DirectBaseSpec;
4426 const CXXBaseSpecifier *VirtualBaseSpec;
4427 if (FindBaseInitializer(*this, ClassDecl,
4429 DirectBaseSpec, VirtualBaseSpec)) {
4430 // We have found a direct or virtual base class with a
4431 // similar name to what was typed; complain and initialize
4432 // that base class.
4433 diagnoseTypo(Corr,
4434 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4435 << MemberOrBase << false,
4436 PDiag() /*Suppress note, we provide our own.*/);
4437
4438 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4439 : VirtualBaseSpec;
4440 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4441 << BaseSpec->getType() << BaseSpec->getSourceRange();
4442
4443 TyD = Type;
4444 }
4445 }
4446 }
4447
4448 if (!TyD && BaseType.isNull()) {
4449 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4450 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4451 return true;
4452 }
4453 }
4454
4455 if (BaseType.isNull()) {
4458 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4459 TInfo = Context.CreateTypeSourceInfo(BaseType);
4461 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4464 }
4465 }
4466
4467 if (!TInfo)
4468 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4469
4470 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4471}
4472
4475 SourceLocation IdLoc) {
4476 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4477 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4478 assert((DirectMember || IndirectMember) &&
4479 "Member must be a FieldDecl or IndirectFieldDecl");
4480
4482 return true;
4483
4484 if (Member->isInvalidDecl())
4485 return true;
4486
4487 MultiExprArg Args;
4488 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4489 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4490 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4491 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4492 } else {
4493 // Template instantiation doesn't reconstruct ParenListExprs for us.
4494 Args = Init;
4495 }
4496
4497 SourceRange InitRange = Init->getSourceRange();
4498
4499 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4500 // Can't check initialization for a member of dependent type or when
4501 // any of the arguments are type-dependent expressions.
4503 } else {
4504 bool InitList = false;
4505 if (isa<InitListExpr>(Init)) {
4506 InitList = true;
4507 Args = Init;
4508 }
4509
4510 // Initialize the member.
4511 InitializedEntity MemberEntity =
4512 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4513 : InitializedEntity::InitializeMember(IndirectMember,
4514 nullptr);
4515 InitializationKind Kind =
4517 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4518 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4519 InitRange.getEnd());
4520
4521 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4522 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4523 nullptr);
4524 if (!MemberInit.isInvalid()) {
4525 // C++11 [class.base.init]p7:
4526 // The initialization of each base and member constitutes a
4527 // full-expression.
4528 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4529 /*DiscardedValue*/ false);
4530 }
4531
4532 if (MemberInit.isInvalid()) {
4533 // Args were sensible expressions but we couldn't initialize the member
4534 // from them. Preserve them in a RecoveryExpr instead.
4535 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4536 Member->getType())
4537 .get();
4538 if (!Init)
4539 return true;
4540 } else {
4541 Init = MemberInit.get();
4542 }
4543 }
4544
4545 if (DirectMember) {
4546 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4547 InitRange.getBegin(), Init,
4548 InitRange.getEnd());
4549 } else {
4550 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4551 InitRange.getBegin(), Init,
4552 InitRange.getEnd());
4553 }
4554}
4555
4558 CXXRecordDecl *ClassDecl) {
4559 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4560 if (!LangOpts.CPlusPlus11)
4561 return Diag(NameLoc, diag::err_delegating_ctor)
4562 << TInfo->getTypeLoc().getSourceRange();
4563 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4564
4565 bool InitList = true;
4566 MultiExprArg Args = Init;
4567 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4568 InitList = false;
4569 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4570 }
4571
4572 SourceRange InitRange = Init->getSourceRange();
4573 // Initialize the object.
4575 QualType(ClassDecl->getTypeForDecl(), 0));
4576 InitializationKind Kind =
4578 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4579 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4580 InitRange.getEnd());
4581 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4582 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4583 Args, nullptr);
4584 if (!DelegationInit.isInvalid()) {
4585 assert((DelegationInit.get()->containsErrors() ||
4586 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4587 "Delegating constructor with no target?");
4588
4589 // C++11 [class.base.init]p7:
4590 // The initialization of each base and member constitutes a
4591 // full-expression.
4592 DelegationInit = ActOnFinishFullExpr(
4593 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4594 }
4595
4596 if (DelegationInit.isInvalid()) {
4597 DelegationInit =
4598 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4599 QualType(ClassDecl->getTypeForDecl(), 0));
4600 if (DelegationInit.isInvalid())
4601 return true;
4602 } else {
4603 // If we are in a dependent context, template instantiation will
4604 // perform this type-checking again. Just save the arguments that we
4605 // received in a ParenListExpr.
4606 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4607 // of the information that we have about the base
4608 // initializer. However, deconstructing the ASTs is a dicey process,
4609 // and this approach is far more likely to get the corner cases right.
4611 DelegationInit = Init;
4612 }
4613
4614 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4615 DelegationInit.getAs<Expr>(),
4616 InitRange.getEnd());
4617}
4618
4621 Expr *Init, CXXRecordDecl *ClassDecl,
4622 SourceLocation EllipsisLoc) {
4623 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4624
4625 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4626 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4627 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4628
4629 // C++ [class.base.init]p2:
4630 // [...] Unless the mem-initializer-id names a nonstatic data
4631 // member of the constructor's class or a direct or virtual base
4632 // of that class, the mem-initializer is ill-formed. A
4633 // mem-initializer-list can initialize a base class using any
4634 // name that denotes that base class type.
4635
4636 // We can store the initializers in "as-written" form and delay analysis until
4637 // instantiation if the constructor is dependent. But not for dependent
4638 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4640 (BaseType->isDependentType() || Init->isTypeDependent());
4641
4642 SourceRange InitRange = Init->getSourceRange();
4643 if (EllipsisLoc.isValid()) {
4644 // This is a pack expansion.
4645 if (!BaseType->containsUnexpandedParameterPack()) {
4646 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4647 << SourceRange(BaseLoc, InitRange.getEnd());
4648
4649 EllipsisLoc = SourceLocation();
4650 }
4651 } else {
4652 // Check for any unexpanded parameter packs.
4653 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4654 return true;
4655
4657 return true;
4658 }
4659
4660 // Check for direct and virtual base classes.
4661 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4662 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4663 if (!Dependent) {
4665 BaseType))
4666 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4667
4668 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4669 VirtualBaseSpec);
4670
4671 // C++ [base.class.init]p2:
4672 // Unless the mem-initializer-id names a nonstatic data member of the
4673 // constructor's class or a direct or virtual base of that class, the
4674 // mem-initializer is ill-formed.
4675 if (!DirectBaseSpec && !VirtualBaseSpec) {
4676 // If the class has any dependent bases, then it's possible that
4677 // one of those types will resolve to the same type as
4678 // BaseType. Therefore, just treat this as a dependent base
4679 // class initialization. FIXME: Should we try to check the
4680 // initialization anyway? It seems odd.
4681 if (ClassDecl->hasAnyDependentBases())
4682 Dependent = true;
4683 else
4684 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4685 << BaseType << Context.getTypeDeclType(ClassDecl)
4686 << BaseTInfo->getTypeLoc().getSourceRange();
4687 }
4688 }
4689
4690 if (Dependent) {
4692
4693 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4694 /*IsVirtual=*/false,
4695 InitRange.getBegin(), Init,
4696 InitRange.getEnd(), EllipsisLoc);
4697 }
4698
4699 // C++ [base.class.init]p2:
4700 // If a mem-initializer-id is ambiguous because it designates both
4701 // a direct non-virtual base class and an inherited virtual base
4702 // class, the mem-initializer is ill-formed.
4703 if (DirectBaseSpec && VirtualBaseSpec)
4704 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4705 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4706
4707 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4708 if (!BaseSpec)
4709 BaseSpec = VirtualBaseSpec;
4710
4711 // Initialize the base.
4712 bool InitList = true;
4713 MultiExprArg Args = Init;
4714 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4715 InitList = false;
4716 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4717 }
4718
4719 InitializedEntity BaseEntity =
4720 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4721 InitializationKind Kind =
4722 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4723 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4724 InitRange.getEnd());
4725 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4726 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4727 if (!BaseInit.isInvalid()) {
4728 // C++11 [class.base.init]p7:
4729 // The initialization of each base and member constitutes a
4730 // full-expression.
4731 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4732 /*DiscardedValue*/ false);
4733 }
4734
4735 if (BaseInit.isInvalid()) {
4736 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4737 Args, BaseType);
4738 if (BaseInit.isInvalid())
4739 return true;
4740 } else {
4741 // If we are in a dependent context, template instantiation will
4742 // perform this type-checking again. Just save the arguments that we
4743 // received in a ParenListExpr.
4744 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4745 // of the information that we have about the base
4746 // initializer. However, deconstructing the ASTs is a dicey process,
4747 // and this approach is far more likely to get the corner cases right.
4749 BaseInit = Init;
4750 }
4751
4752 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4753 BaseSpec->isVirtual(),
4754 InitRange.getBegin(),
4755 BaseInit.getAs<Expr>(),
4756 InitRange.getEnd(), EllipsisLoc);
4757}
4758
4759// Create a static_cast<T&&>(expr).
4761 QualType TargetType =
4762 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4764 SourceLocation ExprLoc = E->getBeginLoc();
4766 TargetType, ExprLoc);
4767
4768 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4769 SourceRange(ExprLoc, ExprLoc),
4770 E->getSourceRange()).get();
4771}
4772
4773/// ImplicitInitializerKind - How an implicit base or member initializer should
4774/// initialize its base or member.
4781
4782static bool
4784 ImplicitInitializerKind ImplicitInitKind,
4785 CXXBaseSpecifier *BaseSpec,
4786 bool IsInheritedVirtualBase,
4787 CXXCtorInitializer *&CXXBaseInit) {
4788 InitializedEntity InitEntity
4790 IsInheritedVirtualBase);
4791
4792 ExprResult BaseInit;
4793
4794 switch (ImplicitInitKind) {
4795 case IIK_Inherit:
4796 case IIK_Default: {
4797 InitializationKind InitKind
4798 = InitializationKind::CreateDefault(Constructor->getLocation());
4799 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4800 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4801 break;
4802 }
4803
4804 case IIK_Move:
4805 case IIK_Copy: {
4806 bool Moving = ImplicitInitKind == IIK_Move;
4807 ParmVarDecl *Param = Constructor->getParamDecl(0);
4808 QualType ParamType = Param->getType().getNonReferenceType();
4809
4810 Expr *CopyCtorArg =
4812 SourceLocation(), Param, false,
4813 Constructor->getLocation(), ParamType,
4814 VK_LValue, nullptr);
4815
4816 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4817
4818 // Cast to the base class to avoid ambiguities.
4819 QualType ArgTy =
4821 ParamType.getQualifiers());
4822
4823 if (Moving) {
4824 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4825 }
4826
4827 CXXCastPath BasePath;
4828 BasePath.push_back(BaseSpec);
4829 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4830 CK_UncheckedDerivedToBase,
4831 Moving ? VK_XValue : VK_LValue,
4832 &BasePath).get();
4833
4834 InitializationKind InitKind
4835 = InitializationKind::CreateDirect(Constructor->getLocation(),
4837 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4838 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4839 break;
4840 }
4841 }
4842
4843 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4844 if (BaseInit.isInvalid())
4845 return true;
4846
4847 CXXBaseInit =
4850 SourceLocation()),
4851 BaseSpec->isVirtual(),
4853 BaseInit.getAs<Expr>(),
4855 SourceLocation());
4856
4857 return false;
4858}
4859
4860static bool RefersToRValueRef(Expr *MemRef) {
4861 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4862 return Referenced->getType()->isRValueReferenceType();
4863}
4864
4865static bool
4867 ImplicitInitializerKind ImplicitInitKind,
4869 CXXCtorInitializer *&CXXMemberInit) {
4870 if (Field->isInvalidDecl())
4871 return true;
4872
4873 SourceLocation Loc = Constructor->getLocation();
4874
4875 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4876 bool Moving = ImplicitInitKind == IIK_Move;
4877 ParmVarDecl *Param = Constructor->getParamDecl(0);
4878 QualType ParamType = Param->getType().getNonReferenceType();
4879
4880 // Suppress copying zero-width bitfields.
4881 if (Field->isZeroLengthBitField(SemaRef.Context))
4882 return false;
4883
4884 Expr *MemberExprBase =
4886 SourceLocation(), Param, false,
4887 Loc, ParamType, VK_LValue, nullptr);
4888
4889 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4890
4891 if (Moving) {
4892 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4893 }
4894
4895 // Build a reference to this field within the parameter.
4896 CXXScopeSpec SS;
4897 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4899 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4900 : cast<ValueDecl>(Field), AS_public);
4901 MemberLookup.resolveKind();
4902 ExprResult CtorArg
4903 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4904 ParamType, Loc,
4905 /*IsArrow=*/false,
4906 SS,
4907 /*TemplateKWLoc=*/SourceLocation(),
4908 /*FirstQualifierInScope=*/nullptr,
4909 MemberLookup,
4910 /*TemplateArgs=*/nullptr,
4911 /*S*/nullptr);
4912 if (CtorArg.isInvalid())
4913 return true;
4914
4915 // C++11 [class.copy]p15:
4916 // - if a member m has rvalue reference type T&&, it is direct-initialized
4917 // with static_cast<T&&>(x.m);
4918 if (RefersToRValueRef(CtorArg.get())) {
4919 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4920 }
4921
4922 InitializedEntity Entity =
4924 /*Implicit*/ true)
4925 : InitializedEntity::InitializeMember(Field, nullptr,
4926 /*Implicit*/ true);
4927
4928 // Direct-initialize to use the copy constructor.
4929 InitializationKind InitKind =
4931
4932 Expr *CtorArgE = CtorArg.getAs<Expr>();
4933 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4934 ExprResult MemberInit =
4935 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4936 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4937 if (MemberInit.isInvalid())
4938 return true;
4939
4940 if (Indirect)
4941 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4942 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4943 else
4944 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4945 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4946 return false;
4947 }
4948
4949 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4950 "Unhandled implicit init kind!");
4951
4952 QualType FieldBaseElementType =
4953 SemaRef.Context.getBaseElementType(Field->getType());
4954
4955 if (FieldBaseElementType->isRecordType()) {
4956 InitializedEntity InitEntity =
4958 /*Implicit*/ true)
4959 : InitializedEntity::InitializeMember(Field, nullptr,
4960 /*Implicit*/ true);
4961 InitializationKind InitKind =
4963
4964 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4965 ExprResult MemberInit =
4966 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4967
4968 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4969 if (MemberInit.isInvalid())
4970 return true;
4971
4972 if (Indirect)
4973 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4974 Indirect, Loc,
4975 Loc,
4976 MemberInit.get(),
4977 Loc);
4978 else
4979 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4980 Field, Loc, Loc,
4981 MemberInit.get(),
4982 Loc);
4983 return false;
4984 }
4985
4986 if (!Field->getParent()->isUnion()) {
4987 if (FieldBaseElementType->isReferenceType()) {
4988 SemaRef.Diag(Constructor->getLocation(),
4989 diag::err_uninitialized_member_in_ctor)
4990 << (int)Constructor->isImplicit()
4991 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4992 << 0 << Field->getDeclName();
4993 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4994 return true;
4995 }
4996
4997 if (FieldBaseElementType.isConstQualified()) {
4998 SemaRef.Diag(Constructor->getLocation(),
4999 diag::err_uninitialized_member_in_ctor)
5000 << (int)Constructor->isImplicit()
5001 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5002 << 1 << Field->getDeclName();
5003 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5004 return true;
5005 }
5006 }
5007
5008 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5009 // ARC and Weak:
5010 // Default-initialize Objective-C pointers to NULL.
5011 CXXMemberInit
5013 Loc, Loc,
5014 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5015 Loc);
5016 return false;
5017 }
5018
5019 // Nothing to initialize.
5020 CXXMemberInit = nullptr;
5021 return false;
5022}
5023
5024namespace {
5025struct BaseAndFieldInfo {
5026 Sema &S;
5027 CXXConstructorDecl *Ctor;
5028 bool AnyErrorsInInits;
5030 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5032 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5033
5034 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5035 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5036 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5037 if (Ctor->getInheritedConstructor())
5038 IIK = IIK_Inherit;
5039 else if (Generated && Ctor->isCopyConstructor())
5040 IIK = IIK_Copy;
5041 else if (Generated && Ctor->isMoveConstructor())
5042 IIK = IIK_Move;
5043 else
5044 IIK = IIK_Default;
5045 }
5046
5047 bool isImplicitCopyOrMove() const {
5048 switch (IIK) {
5049 case IIK_Copy:
5050 case IIK_Move:
5051 return true;
5052
5053 case IIK_Default:
5054 case IIK_Inherit:
5055 return false;
5056 }
5057
5058 llvm_unreachable("Invalid ImplicitInitializerKind!");
5059 }
5060
5061 bool addFieldInitializer(CXXCtorInitializer *Init) {
5062 AllToInit.push_back(Init);
5063
5064 // Check whether this initializer makes the field "used".
5065 if (Init->getInit()->HasSideEffects(S.Context))
5066 S.UnusedPrivateFields.remove(Init->getAnyMember());
5067
5068 return false;
5069 }
5070
5071 bool isInactiveUnionMember(FieldDecl *Field) {
5072 RecordDecl *Record = Field->getParent();
5073 if (!Record->isUnion())
5074 return false;
5075
5076 if (FieldDecl *Active =
5077 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5078 return Active != Field->getCanonicalDecl();
5079
5080 // In an implicit copy or move constructor, ignore any in-class initializer.
5081 if (isImplicitCopyOrMove())
5082 return true;
5083
5084 // If there's no explicit initialization, the field is active only if it
5085 // has an in-class initializer...
5086 if (Field->hasInClassInitializer())
5087 return false;
5088 // ... or it's an anonymous struct or union whose class has an in-class
5089 // initializer.
5090 if (!Field->isAnonymousStructOrUnion())
5091 return true;
5092 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5093 return !FieldRD->hasInClassInitializer();
5094 }
5095
5096 /// Determine whether the given field is, or is within, a union member
5097 /// that is inactive (because there was an initializer given for a different
5098 /// member of the union, or because the union was not initialized at all).
5099 bool isWithinInactiveUnionMember(FieldDecl *Field,
5101 if (!Indirect)
5102 return isInactiveUnionMember(Field);
5103
5104 for (auto *C : Indirect->chain()) {
5105 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5106 if (Field && isInactiveUnionMember(Field))
5107 return true;
5108 }
5109 return false;
5110 }
5111};
5112}
5113
5114/// Determine whether the given type is an incomplete or zero-lenfgth
5115/// array type.
5117 if (T->isIncompleteArrayType())
5118 return true;
5119
5120 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5121 if (ArrayT->isZeroSize())
5122 return true;
5123
5124 T = ArrayT->getElementType();
5125 }
5126
5127 return false;
5128}
5129
5130static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5131 FieldDecl *Field,
5132 IndirectFieldDecl *Indirect = nullptr) {
5133 if (Field->isInvalidDecl())
5134 return false;
5135
5136 // Overwhelmingly common case: we have a direct initializer for this field.
5138 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5139 return Info.addFieldInitializer(Init);
5140
5141 // C++11 [class.base.init]p8:
5142 // if the entity is a non-static data member that has a
5143 // brace-or-equal-initializer and either
5144 // -- the constructor's class is a union and no other variant member of that
5145 // union is designated by a mem-initializer-id or
5146 // -- the constructor's class is not a union, and, if the entity is a member
5147 // of an anonymous union, no other member of that union is designated by
5148 // a mem-initializer-id,
5149 // the entity is initialized as specified in [dcl.init].
5150 //
5151 // We also apply the same rules to handle anonymous structs within anonymous
5152 // unions.
5153 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5154 return false;
5155
5156 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5157 ExprResult DIE =
5158 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5159 if (DIE.isInvalid())
5160 return true;
5161
5162 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5163 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5164
5166 if (Indirect)
5167 Init = new (SemaRef.Context)
5169 SourceLocation(), DIE.get(), SourceLocation());
5170 else
5171 Init = new (SemaRef.Context)
5173 SourceLocation(), DIE.get(), SourceLocation());
5174 return Info.addFieldInitializer(Init);
5175 }
5176
5177 // Don't initialize incomplete or zero-length arrays.
5178 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5179 return false;
5180
5181 // Don't try to build an implicit initializer if there were semantic
5182 // errors in any of the initializers (and therefore we might be
5183 // missing some that the user actually wrote).
5184 if (Info.AnyErrorsInInits)
5185 return false;
5186
5187 CXXCtorInitializer *Init = nullptr;
5188 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5189 Indirect, Init))
5190 return true;
5191
5192 if (!Init)
5193 return false;
5194
5195 return Info.addFieldInitializer(Init);
5196}
5197
5198bool
5201 assert(Initializer->isDelegatingInitializer());
5202 Constructor->setNumCtorInitializers(1);
5203 CXXCtorInitializer **initializer =
5204 new (Context) CXXCtorInitializer*[1];
5205 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5206 Constructor->setCtorInitializers(initializer);
5207
5208 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5209 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5210 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5211 }
5212
5213 DelegatingCtorDecls.push_back(Constructor);
5214
5215 DiagnoseUninitializedFields(*this, Constructor);
5216
5217 return false;
5218}
5219
5220bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5221 ArrayRef<CXXCtorInitializer *> Initializers) {
5222 if (Constructor->isDependentContext()) {
5223 // Just store the initializers as written, they will be checked during
5224 // instantiation.
5225 if (!Initializers.empty()) {
5226 Constructor->setNumCtorInitializers(Initializers.size());
5227 CXXCtorInitializer **baseOrMemberInitializers =
5228 new (Context) CXXCtorInitializer*[Initializers.size()];
5229 memcpy(baseOrMemberInitializers, Initializers.data(),
5230 Initializers.size() * sizeof(CXXCtorInitializer*));
5231 Constructor->setCtorInitializers(baseOrMemberInitializers);
5232 }
5233
5234 // Let template instantiation know whether we had errors.
5235 if (AnyErrors)
5236 Constructor->setInvalidDecl();
5237
5238 return false;
5239 }
5240
5241 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5242
5243 // We need to build the initializer AST according to order of construction
5244 // and not what user specified in the Initializers list.
5245 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5246 if (!ClassDecl)
5247 return true;
5248
5249 bool HadError = false;
5250
5251 for (unsigned i = 0; i < Initializers.size(); i++) {
5252 CXXCtorInitializer *Member = Initializers[i];
5253
5254 if (Member->isBaseInitializer())
5255 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5256 else {
5257 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5258
5259 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5260 for (auto *C : F->chain()) {
5261 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5262 if (FD && FD->getParent()->isUnion())
5263 Info.ActiveUnionMember.insert(std::make_pair(
5265 }
5266 } else if (FieldDecl *FD = Member->getMember()) {
5267 if (FD->getParent()->isUnion())
5268 Info.ActiveUnionMember.insert(std::make_pair(
5270 }
5271 }
5272 }
5273
5274 // Keep track of the direct virtual bases.
5276 for (auto &I : ClassDecl->bases()) {
5277 if (I.isVirtual())
5278 DirectVBases.insert(&I);
5279 }
5280
5281 // Push virtual bases before others.
5282 for (auto &VBase : ClassDecl->vbases()) {
5284 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5285 // [class.base.init]p7, per DR257:
5286 // A mem-initializer where the mem-initializer-id names a virtual base
5287 // class is ignored during execution of a constructor of any class that
5288 // is not the most derived class.
5289 if (ClassDecl->isAbstract()) {
5290 // FIXME: Provide a fixit to remove the base specifier. This requires
5291 // tracking the location of the associated comma for a base specifier.
5292 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5293 << VBase.getType() << ClassDecl;
5294 DiagnoseAbstractType(ClassDecl);
5295 }
5296
5297 Info.AllToInit.push_back(Value);
5298 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5299 // [class.base.init]p8, per DR257:
5300 // If a given [...] base class is not named by a mem-initializer-id
5301 // [...] and the entity is not a virtual base class of an abstract
5302 // class, then [...] the entity is default-initialized.
5303 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5304 CXXCtorInitializer *CXXBaseInit;
5305 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5306 &VBase, IsInheritedVirtualBase,
5307 CXXBaseInit)) {
5308 HadError = true;
5309 continue;
5310 }
5311
5312 Info.AllToInit.push_back(CXXBaseInit);
5313 }
5314 }
5315
5316 // Non-virtual bases.
5317 for (auto &Base : ClassDecl->bases()) {
5318 // Virtuals are in the virtual base list and already constructed.
5319 if (Base.isVirtual())
5320 continue;
5321
5323 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5324 Info.AllToInit.push_back(Value);
5325 } else if (!AnyErrors) {
5326 CXXCtorInitializer *CXXBaseInit;
5327 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5328 &Base, /*IsInheritedVirtualBase=*/false,
5329 CXXBaseInit)) {
5330 HadError = true;
5331 continue;
5332 }
5333
5334 Info.AllToInit.push_back(CXXBaseInit);
5335 }
5336 }
5337
5338 // Fields.
5339 for (auto *Mem : ClassDecl->decls()) {
5340 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5341 // C++ [class.bit]p2:
5342 // A declaration for a bit-field that omits the identifier declares an
5343 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5344 // initialized.
5345 if (F->isUnnamedBitField())
5346 continue;
5347
5348 // If we're not generating the implicit copy/move constructor, then we'll
5349 // handle anonymous struct/union fields based on their individual
5350 // indirect fields.
5351 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5352 continue;
5353
5354 if (CollectFieldInitializer(*this, Info, F))
5355 HadError = true;
5356 continue;
5357 }
5358
5359 // Beyond this point, we only consider default initialization.
5360 if (Info.isImplicitCopyOrMove())
5361 continue;
5362
5363 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5364 if (F->getType()->isIncompleteArrayType()) {
5365 assert(ClassDecl->hasFlexibleArrayMember() &&
5366 "Incomplete array type is not valid");
5367 continue;
5368 }
5369
5370 // Initialize each field of an anonymous struct individually.
5371 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5372 HadError = true;
5373
5374 continue;
5375 }
5376 }
5377
5378 unsigned NumInitializers = Info.AllToInit.size();
5379 if (NumInitializers > 0) {
5380 Constructor->setNumCtorInitializers(NumInitializers);
5381 CXXCtorInitializer **baseOrMemberInitializers =
5382 new (Context) CXXCtorInitializer*[NumInitializers];
5383 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5384 NumInitializers * sizeof(CXXCtorInitializer*));
5385 Constructor->setCtorInitializers(baseOrMemberInitializers);
5386
5387 // Constructors implicitly reference the base and member
5388 // destructors.
5389 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5390 Constructor->getParent());
5391 }
5392
5393 return HadError;
5394}
5395
5397 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5398 const RecordDecl *RD = RT->getDecl();
5399 if (RD->isAnonymousStructOrUnion()) {
5400 for (auto *Field : RD->fields())
5401 PopulateKeysForFields(Field, IdealInits);
5402 return;
5403 }
5404 }
5405 IdealInits.push_back(Field->getCanonicalDecl());
5406}
5407
5408static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5409 return Context.getCanonicalType(BaseType).getTypePtr();
5410}
5411
5414 if (!Member->isAnyMemberInitializer())
5415 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5416
5417 return Member->getAnyMember()->getCanonicalDecl();
5418}
5419
5422 const CXXCtorInitializer *Current) {
5423 if (Previous->isAnyMemberInitializer())
5424 Diag << 0 << Previous->getAnyMember();
5425 else
5426 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5427
5428 if (Current->isAnyMemberInitializer())
5429 Diag << 0 << Current->getAnyMember();
5430 else
5431 Diag << 1 << Current->getTypeSourceInfo()->getType();
5432}
5433
5435 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5437 if (Constructor->getDeclContext()->isDependentContext())
5438 return;
5439
5440 // Don't check initializers order unless the warning is enabled at the
5441 // location of at least one initializer.
5442 bool ShouldCheckOrder = false;
5443 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5444 CXXCtorInitializer *Init = Inits[InitIndex];
5445 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5446 Init->getSourceLocation())) {
5447 ShouldCheckOrder = true;
5448 break;
5449 }
5450 }
5451 if (!ShouldCheckOrder)
5452 return;
5453
5454 // Build the list of bases and members in the order that they'll
5455 // actually be initialized. The explicit initializers should be in
5456 // this same order but may be missing things.
5457 SmallVector<const void*, 32> IdealInitKeys;
5458
5459 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5460
5461 // 1. Virtual bases.
5462 for (const auto &VBase : ClassDecl->vbases())
5463 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5464
5465 // 2. Non-virtual bases.
5466 for (const auto &Base : ClassDecl->bases()) {
5467 if (Base.isVirtual())
5468 continue;
5469 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5470 }
5471
5472 // 3. Direct fields.
5473 for (auto *Field : ClassDecl->fields()) {
5474 if (Field->isUnnamedBitField())
5475 continue;
5476
5477 PopulateKeysForFields(Field, IdealInitKeys);
5478 }
5479
5480 unsigned NumIdealInits = IdealInitKeys.size();
5481 unsigned IdealIndex = 0;
5482
5483 // Track initializers that are in an incorrect order for either a warning or
5484 // note if multiple ones occur.
5485 SmallVector<unsigned> WarnIndexes;
5486 // Correlates the index of an initializer in the init-list to the index of
5487 // the field/base in the class.
5488 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5489
5490 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5491 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5492
5493 // Scan forward to try to find this initializer in the idealized
5494 // initializers list.
5495 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5496 if (InitKey == IdealInitKeys[IdealIndex])
5497 break;
5498
5499 // If we didn't find this initializer, it must be because we
5500 // scanned past it on a previous iteration. That can only
5501 // happen if we're out of order; emit a warning.
5502 if (IdealIndex == NumIdealInits && InitIndex) {
5503 WarnIndexes.push_back(InitIndex);
5504
5505 // Move back to the initializer's location in the ideal list.
5506 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5507 if (InitKey == IdealInitKeys[IdealIndex])
5508 break;
5509
5510 assert(IdealIndex < NumIdealInits &&
5511 "initializer not found in initializer list");
5512 }
5513 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5514 }
5515
5516 if (WarnIndexes.empty())
5517 return;
5518
5519 // Sort based on the ideal order, first in the pair.
5520 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5521
5522 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5523 // emit the diagnostic before we can try adding notes.
5524 {
5526 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5527 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5528 : diag::warn_some_initializers_out_of_order);
5529
5530 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5531 if (CorrelatedInitOrder[I].second == I)
5532 continue;
5533 // Ideally we would be using InsertFromRange here, but clang doesn't
5534 // appear to handle InsertFromRange correctly when the source range is
5535 // modified by another fix-it.
5537 Inits[I]->getSourceRange(),
5540 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5542 }
5543
5544 // If there is only 1 item out of order, the warning expects the name and
5545 // type of each being added to it.
5546 if (WarnIndexes.size() == 1) {
5547 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5548 Inits[WarnIndexes.front()]);
5549 return;
5550 }
5551 }
5552 // More than 1 item to warn, create notes letting the user know which ones
5553 // are bad.
5554 for (unsigned WarnIndex : WarnIndexes) {
5555 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5556 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5557 diag::note_initializer_out_of_order);
5558 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5559 D << PrevInit->getSourceRange();
5560 }
5561}
5562
5563namespace {
5564bool CheckRedundantInit(Sema &S,
5566 CXXCtorInitializer *&PrevInit) {
5567 if (!PrevInit) {
5568 PrevInit = Init;
5569 return false;
5570 }
5571
5572 if (FieldDecl *Field = Init->getAnyMember())
5573 S.Diag(Init->getSourceLocation(),
5574 diag::err_multiple_mem_initialization)
5575 << Field->getDeclName()
5576 << Init->getSourceRange();
5577 else {
5578 const Type *BaseClass = Init->getBaseClass();
5579 assert(BaseClass && "neither field nor base");
5580 S.Diag(Init->getSourceLocation(),
5581 diag::err_multiple_base_initialization)
5582 << QualType(BaseClass, 0)
5583 << Init->getSourceRange();
5584 }
5585 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5586 << 0 << PrevInit->getSourceRange();
5587
5588 return true;
5589}
5590
5591typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5592typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5593
5594bool CheckRedundantUnionInit(Sema &S,
5596 RedundantUnionMap &Unions) {
5597 FieldDecl *Field = Init->getAnyMember();
5598 RecordDecl *Parent = Field->getParent();
5599 NamedDecl *Child = Field;
5600
5601 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5602 if (Parent->isUnion()) {
5603 UnionEntry &En = Unions[Parent];
5604 if (En.first && En.first != Child) {
5605 S.Diag(Init->getSourceLocation(),
5606 diag::err_multiple_mem_union_initialization)
5607 << Field->getDeclName()
5608 << Init->getSourceRange();
5609 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5610 << 0 << En.second->getSourceRange();
5611 return true;
5612 }
5613 if (!En.first) {
5614 En.first = Child;
5615 En.second = Init;
5616 }
5617 if (!Parent->isAnonymousStructOrUnion())
5618 return false;
5619 }
5620
5621 Child = Parent;
5622 Parent = cast<RecordDecl>(Parent->getDeclContext());
5623 }
5624
5625 return false;
5626}
5627} // namespace
5628
5629void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5630 SourceLocation ColonLoc,
5632 bool AnyErrors) {
5633 if (!ConstructorDecl)
5634 return;
5635
5636 AdjustDeclIfTemplate(ConstructorDecl);
5637
5638 CXXConstructorDecl *Constructor
5639 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5640
5641 if (!Constructor) {
5642 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5643 return;
5644 }
5645
5646 // Mapping for the duplicate initializers check.
5647 // For member initializers, this is keyed with a FieldDecl*.
5648 // For base initializers, this is keyed with a Type*.
5649 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5650
5651 // Mapping for the inconsistent anonymous-union initializers check.
5652 RedundantUnionMap MemberUnions;
5653
5654 bool HadError = false;
5655 for (unsigned i = 0; i < MemInits.size(); i++) {
5656 CXXCtorInitializer *Init = MemInits[i];
5657
5658 // Set the source order index.
5659 Init->setSourceOrder(i);
5660
5661 if (Init->isAnyMemberInitializer()) {
5662 const void *Key = GetKeyForMember(Context, Init);
5663 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5664 CheckRedundantUnionInit(*this, Init, MemberUnions))
5665 HadError = true;
5666 } else if (Init->isBaseInitializer()) {
5667 const void *Key = GetKeyForMember(Context, Init);
5668 if (CheckRedundantInit(*this, Init, Members[Key]))
5669 HadError = true;
5670 } else {
5671 assert(Init->isDelegatingInitializer());
5672 // This must be the only initializer
5673 if (MemInits.size() != 1) {
5674 Diag(Init->getSourceLocation(),
5675 diag::err_delegating_initializer_alone)
5676 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5677 // We will treat this as being the only initializer.
5678 }
5679 SetDelegatingInitializer(Constructor, MemInits[i]);
5680 // Return immediately as the initializer is set.
5681 return;
5682 }
5683 }
5684
5685 if (HadError)
5686 return;
5687
5688 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5689
5690 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5691
5692 DiagnoseUninitializedFields(*this, Constructor);
5693}
5694
5695void
5697 CXXRecordDecl *ClassDecl) {
5698 // Ignore dependent contexts. Also ignore unions, since their members never
5699 // have destructors implicitly called.
5700 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5701 return;
5702
5703 // FIXME: all the access-control diagnostics are positioned on the
5704 // field/base declaration. That's probably good; that said, the
5705 // user might reasonably want to know why the destructor is being
5706 // emitted, and we currently don't say.
5707
5708 // Non-static data members.
5709 for (auto *Field : ClassDecl->fields()) {
5710 if (Field->isInvalidDecl())
5711 continue;
5712
5713 // Don't destroy incomplete or zero-length arrays.
5714 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5715 continue;
5716
5717 QualType FieldType = Context.getBaseElementType(Field->getType());
5718
5719 const RecordType* RT = FieldType->getAs<RecordType>();
5720 if (!RT)
5721 continue;
5722
5723 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5724 if (FieldClassDecl->isInvalidDecl())
5725 continue;
5726 if (FieldClassDecl->hasIrrelevantDestructor())
5727 continue;
5728 // The destructor for an implicit anonymous union member is never invoked.
5729 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5730 continue;
5731
5732 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5733 // Dtor might still be missing, e.g because it's invalid.
5734 if (!Dtor)
5735 continue;
5736 CheckDestructorAccess(Field->getLocation(), Dtor,
5737 PDiag(diag::err_access_dtor_field)
5738 << Field->getDeclName()
5739 << FieldType);
5740
5741 MarkFunctionReferenced(Location, Dtor);
5742 DiagnoseUseOfDecl(Dtor, Location);
5743 }
5744
5745 // We only potentially invoke the destructors of potentially constructed
5746 // subobjects.
5747 bool VisitVirtualBases = !ClassDecl->isAbstract();
5748
5749 // If the destructor exists and has already been marked used in the MS ABI,
5750 // then virtual base destructors have already been checked and marked used.
5751 // Skip checking them again to avoid duplicate diagnostics.
5753 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5754 if (Dtor && Dtor->isUsed())
5755 VisitVirtualBases = false;
5756 }
5757
5759
5760 // Bases.
5761 for (const auto &Base : ClassDecl->bases()) {
5762 const RecordType *RT = Base.getType()->getAs<RecordType>();
5763 if (!RT)
5764 continue;
5765
5766 // Remember direct virtual bases.
5767 if (Base.isVirtual()) {
5768 if (!VisitVirtualBases)
5769 continue;
5770 DirectVirtualBases.insert(RT);
5771 }
5772
5773 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5774 // If our base class is invalid, we probably can't get its dtor anyway.
5775 if (BaseClassDecl->isInvalidDecl())
5776 continue;
5777 if (BaseClassDecl->hasIrrelevantDestructor())
5778 continue;
5779
5780 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5781 // Dtor might still be missing, e.g because it's invalid.
5782 if (!Dtor)
5783 continue;
5784
5785 // FIXME: caret should be on the start of the class name
5786 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5787 PDiag(diag::err_access_dtor_base)
5788 << Base.getType() << Base.getSourceRange(),
5789 Context.getTypeDeclType(ClassDecl));
5790
5791 MarkFunctionReferenced(Location, Dtor);
5792 DiagnoseUseOfDecl(Dtor, Location);
5793 }
5794
5795 if (VisitVirtualBases)
5796 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5797 &DirectVirtualBases);
5798}
5799
5801 SourceLocation Location, CXXRecordDecl *ClassDecl,
5802 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5803 // Virtual bases.
5804 for (const auto &VBase : ClassDecl->vbases()) {
5805 // Bases are always records in a well-formed non-dependent class.
5806 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5807
5808 // Ignore already visited direct virtual bases.
5809 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5810 continue;
5811
5812 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5813 // If our base class is invalid, we probably can't get its dtor anyway.
5814 if (BaseClassDecl->isInvalidDecl())
5815 continue;
5816 if (BaseClassDecl->hasIrrelevantDestructor())
5817 continue;
5818
5819 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5820 // Dtor might still be missing, e.g because it's invalid.
5821 if (!Dtor)
5822 continue;
5824 ClassDecl->getLocation(), Dtor,
5825 PDiag(diag::err_access_dtor_vbase)
5826 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5827 Context.getTypeDeclType(ClassDecl)) ==
5828 AR_accessible) {
5830 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5831 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5832 SourceRange(), DeclarationName(), nullptr);
5833 }
5834
5835 MarkFunctionReferenced(Location, Dtor);
5836 DiagnoseUseOfDecl(Dtor, Location);
5837 }
5838}
5839
5841 if (!CDtorDecl)
5842 return;
5843
5844 if (CXXConstructorDecl *Constructor
5845 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5846 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5847 !ClassDecl || ClassDecl->isInvalidDecl()) {
5848 return;
5849 }
5850 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5851 DiagnoseUninitializedFields(*this, Constructor);
5852 }
5853}
5854
5856 if (!getLangOpts().CPlusPlus)
5857 return false;
5858
5859 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5860 if (!RD)
5861 return false;
5862
5863 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5864 // class template specialization here, but doing so breaks a lot of code.
5865
5866 // We can't answer whether something is abstract until it has a
5867 // definition. If it's currently being defined, we'll walk back
5868 // over all the declarations when we have a full definition.
5869 const CXXRecordDecl *Def = RD->getDefinition();
5870 if (!Def || Def->isBeingDefined())
5871 return false;
5872
5873 return RD->isAbstract();
5874}
5875
5877 TypeDiagnoser &Diagnoser) {
5878 if (!isAbstractType(Loc, T))
5879 return false;
5880
5882 Diagnoser.diagnose(*this, Loc, T);
5884 return true;
5885}
5886
5888 // Check if we've already emitted the list of pure virtual functions
5889 // for this class.
5891 return;
5892
5893 // If the diagnostic is suppressed, don't emit the notes. We're only
5894 // going to emit them once, so try to attach them to a diagnostic we're
5895 // actually going to show.
5897 return;
5898
5899 CXXFinalOverriderMap FinalOverriders;
5900 RD->getFinalOverriders(FinalOverriders);
5901
5902 // Keep a set of seen pure methods so we won't diagnose the same method
5903 // more than once.
5905
5906 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5907 MEnd = FinalOverriders.end();
5908 M != MEnd;
5909 ++M) {
5910 for (OverridingMethods::iterator SO = M->second.begin(),
5911 SOEnd = M->second.end();
5912 SO != SOEnd; ++SO) {
5913 // C++ [class.abstract]p4:
5914 // A class is abstract if it contains or inherits at least one
5915 // pure virtual function for which the final overrider is pure
5916 // virtual.
5917
5918 //
5919 if (SO->second.size() != 1)
5920 continue;
5921
5922 if (!SO->second.front().Method->isPureVirtual())
5923 continue;
5924
5925 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5926 continue;
5927
5928 Diag(SO->second.front().Method->getLocation(),
5929 diag::note_pure_virtual_function)
5930 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5931 }
5932 }
5933
5936 PureVirtualClassDiagSet->insert(RD);
5937}
5938
5939namespace {
5940struct AbstractUsageInfo {
5941 Sema &S;
5943 CanQualType AbstractType;
5944 bool Invalid;
5945
5946 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5947 : S(S), Record(Record),
5948 AbstractType(S.Context.getCanonicalType(
5949 S.Context.getTypeDeclType(Record))),
5950 Invalid(false) {}
5951
5952 void DiagnoseAbstractType() {
5953 if (Invalid) return;
5955 Invalid = true;
5956 }
5957
5958 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5959};
5960
5961struct CheckAbstractUsage {
5962 AbstractUsageInfo &Info;
5963 const NamedDecl *Ctx;
5964
5965 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5966 : Info(Info), Ctx(Ctx) {}
5967
5968 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5969 switch (TL.getTypeLocClass()) {
5970#define ABSTRACT_TYPELOC(CLASS, PARENT)
5971#define TYPELOC(CLASS, PARENT) \
5972 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5973#include "clang/AST/TypeLocNodes.def"
5974 }
5975 }
5976
5977 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5979 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5980 if (!TL.getParam(I))
5981 continue;
5982
5984 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5985 }
5986 }
5987
5988 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5990 }
5991
5993 // Visit the type parameters from a permissive context.
5994 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5995 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5997 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5998 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5999 // TODO: other template argument types?
6000 }
6001 }
6002
6003 // Visit pointee types from a permissive context.
6004#define CheckPolymorphic(Type) \
6005 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6006 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6007 }
6013
6014 /// Handle all the types we haven't given a more specific
6015 /// implementation for above.
6016 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6017 // Every other kind of type that we haven't called out already
6018 // that has an inner type is either (1) sugar or (2) contains that
6019 // inner type in some way as a subobject.
6020 if (TypeLoc Next = TL.getNextTypeLoc())
6021 return Visit(Next, Sel);
6022
6023 // If there's no inner type and we're in a permissive context,
6024 // don't diagnose.
6025 if (Sel == Sema::AbstractNone) return;
6026
6027 // Check whether the type matches the abstract type.
6028 QualType T = TL.getType();
6029 if (T->isArrayType()) {
6031 T = Info.S.Context.getBaseElementType(T);
6032 }
6034 if (CT != Info.AbstractType) return;
6035
6036 // It matched; do some magic.
6037 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6038 if (Sel == Sema::AbstractArrayType) {
6039 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6040 << T << TL.getSourceRange();
6041 } else {
6042 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6043 << Sel << T << TL.getSourceRange();
6044 }
6045 Info.DiagnoseAbstractType();
6046 }
6047};
6048
6049void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6051 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6052}
6053
6054}
6055
6056/// Check for invalid uses of an abstract type in a function declaration.
6057static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6058 FunctionDecl *FD) {
6059 // Only definitions are required to refer to complete and
6060 // non-abstract types.
6062 return;
6063
6064 // For safety's sake, just ignore it if we don't have type source
6065 // information. This should never happen for non-implicit methods,
6066 // but...
6067 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6068 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6069}
6070
6071/// Check for invalid uses of an abstract type in a variable0 declaration.
6072static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6073 VarDecl *VD) {
6074 // No need to do the check on definitions, which require that
6075 // the type is complete.
6077 return;
6078
6079 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6081}
6082
6083/// Check for invalid uses of an abstract type within a class definition.
6084static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6085 CXXRecordDecl *RD) {
6086 for (auto *D : RD->decls()) {
6087 if (D->isImplicit()) continue;
6088
6089 // Step through friends to the befriended declaration.
6090 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6091 D = FD->getFriendDecl();
6092 if (!D) continue;
6093 }
6094
6095 // Functions and function templates.
6096 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6097 CheckAbstractClassUsage(Info, FD);
6098 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6099 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6100
6101 // Fields and static variables.
6102 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6103 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6104 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6105 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6106 CheckAbstractClassUsage(Info, VD);
6107 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6108 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6109
6110 // Nested classes and class templates.
6111 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6112 CheckAbstractClassUsage(Info, RD);
6113 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6114 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6115 }
6116 }
6117}
6118
6120 Attr *ClassAttr = getDLLAttr(Class);
6121 if (!ClassAttr)
6122 return;
6123
6124 assert(ClassAttr->getKind() == attr::DLLExport);
6125
6126 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6127
6129 // Don't go any further if this is just an explicit instantiation
6130 // declaration.
6131 return;
6132
6133 // Add a context note to explain how we got to any diagnostics produced below.
6134 struct MarkingClassDllexported {
6135 Sema &S;
6136 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6137 SourceLocation AttrLoc)
6138 : S(S) {
6141 Ctx.PointOfInstantiation = AttrLoc;
6142 Ctx.Entity = Class;
6144 }
6145 ~MarkingClassDllexported() {
6147 }
6148 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6149
6150 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6151 S.MarkVTableUsed(Class->getLocation(), Class, true);
6152
6153 for (Decl *Member : Class->decls()) {
6154 // Skip members that were not marked exported.
6155 if (!Member->hasAttr<DLLExportAttr>())
6156 continue;
6157
6158 // Defined static variables that are members of an exported base
6159 // class must be marked export too.
6160 auto *VD = dyn_cast<VarDecl>(Member);
6161 if (VD && VD->getStorageClass() == SC_Static &&
6163 S.MarkVariableReferenced(VD->getLocation(), VD);
6164
6165 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6166 if (!MD)
6167 continue;
6168
6169 if (MD->isUserProvided()) {
6170 // Instantiate non-default class member functions ...
6171
6172 // .. except for certain kinds of template specializations.
6173 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6174 continue;
6175
6176 // If this is an MS ABI dllexport default constructor, instantiate any
6177 // default arguments.
6179 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6180 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6182 }
6183 }
6184
6185 S.MarkFunctionReferenced(Class->getLocation(), MD);
6186
6187 // The function will be passed to the consumer when its definition is
6188 // encountered.
6189 } else if (MD->isExplicitlyDefaulted()) {
6190 // Synthesize and instantiate explicitly defaulted methods.
6191 S.MarkFunctionReferenced(Class->getLocation(), MD);
6192
6194 // Except for explicit instantiation defs, we will not see the
6195 // definition again later, so pass it to the consumer now.
6197 }
6198 } else if (!MD->isTrivial() ||
6199 MD->isCopyAssignmentOperator() ||
6200 MD->isMoveAssignmentOperator()) {
6201 // Synthesize and instantiate non-trivial implicit methods, and the copy
6202 // and move assignment operators. The latter are exported even if they
6203 // are trivial, because the address of an operator can be taken and
6204 // should compare equal across libraries.
6205 S.MarkFunctionReferenced(Class->getLocation(), MD);
6206
6207 // There is no later point when we will see the definition of this
6208 // function, so pass it to the consumer now.
6210 }
6211 }
6212}
6213
6216 // Only the MS ABI has default constructor closures, so we don't need to do
6217 // this semantic checking anywhere else.
6219 return;
6220
6221 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6222 for (Decl *Member : Class->decls()) {
6223 // Look for exported default constructors.
6224 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6225 if (!CD || !CD->isDefaultConstructor())
6226 continue;
6227 auto *Attr = CD->getAttr<DLLExportAttr>();
6228 if (!Attr)
6229 continue;
6230
6231 // If the class is non-dependent, mark the default arguments as ODR-used so
6232 // that we can properly codegen the constructor closure.
6233 if (!Class->isDependentContext()) {
6234 for (ParmVarDecl *PD : CD->parameters()) {
6235 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6237 }
6238 }
6239
6240 if (LastExportedDefaultCtor) {
6241 S.Diag(LastExportedDefaultCtor->getLocation(),
6242 diag::err_attribute_dll_ambiguous_default_ctor)
6243 << Class;
6244 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6245 << CD->getDeclName();
6246 return;
6247 }
6248 LastExportedDefaultCtor = CD;
6249 }
6250}
6251
6254 bool ErrorReported = false;
6255 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6256 ClassTemplateDecl *TD) {
6257 if (ErrorReported)
6258 return;
6259 S.Diag(TD->getLocation(),
6260 diag::err_cuda_device_builtin_surftex_cls_template)
6261 << /*surface*/ 0 << TD;
6262 ErrorReported = true;
6263 };
6264
6265 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6266 if (!TD) {
6267 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6268 if (!SD) {
6269 S.Diag(Class->getLocation(),
6270 diag::err_cuda_device_builtin_surftex_ref_decl)
6271 << /*surface*/ 0 << Class;
6272 S.Diag(Class->getLocation(),
6273 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6274 << Class;
6275 return;
6276 }
6277 TD = SD->getSpecializedTemplate();
6278 }
6279
6281 unsigned N = Params->size();
6282
6283 if (N != 2) {
6284 reportIllegalClassTemplate(S, TD);
6285 S.Diag(TD->getLocation(),
6286 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6287 << TD << 2;
6288 }
6289 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6290 reportIllegalClassTemplate(S, TD);
6291 S.Diag(TD->getLocation(),
6292 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6293 << TD << /*1st*/ 0 << /*type*/ 0;
6294 }
6295 if (N > 1) {
6296 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6297 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6298 reportIllegalClassTemplate(S, TD);
6299 S.Diag(TD->getLocation(),
6300 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6301 << TD << /*2nd*/ 1 << /*integer*/ 1;
6302 }
6303 }
6304}
6305
6308 bool ErrorReported = false;
6309 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6310 ClassTemplateDecl *TD) {
6311 if (ErrorReported)
6312 return;
6313 S.Diag(TD->getLocation(),
6314 diag::err_cuda_device_builtin_surftex_cls_template)
6315 << /*texture*/ 1 << TD;
6316 ErrorReported = true;
6317 };
6318
6319 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6320 if (!TD) {
6321 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6322 if (!SD) {
6323 S.Diag(Class->getLocation(),
6324 diag::err_cuda_device_builtin_surftex_ref_decl)
6325 << /*texture*/ 1 << Class;
6326 S.Diag(Class->getLocation(),
6327 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6328 << Class;
6329 return;
6330 }
6331 TD = SD->getSpecializedTemplate();
6332 }
6333
6335 unsigned N = Params->size();
6336
6337 if (N != 3) {
6338 reportIllegalClassTemplate(S, TD);
6339 S.Diag(TD->getLocation(),
6340 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6341 << TD << 3;
6342 }
6343 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6344 reportIllegalClassTemplate(S, TD);
6345 S.Diag(TD->getLocation(),
6346 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6347 << TD << /*1st*/ 0 << /*type*/ 0;
6348 }
6349 if (N > 1) {
6350 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6351 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6352 reportIllegalClassTemplate(S, TD);
6353 S.Diag(TD->getLocation(),
6354 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6355 << TD << /*2nd*/ 1 << /*integer*/ 1;
6356 }
6357 }
6358 if (N > 2) {
6359 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6360 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6361 reportIllegalClassTemplate(S, TD);
6362 S.Diag(TD->getLocation(),
6363 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6364 << TD << /*3rd*/ 2 << /*integer*/ 1;
6365 }
6366 }
6367}
6368
6370 // Mark any compiler-generated routines with the implicit code_seg attribute.
6371 for (auto *Method : Class->methods()) {
6372 if (Method->isUserProvided())
6373 continue;
6374 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6375 Method->addAttr(A);
6376 }
6377}
6378
6380 Attr *ClassAttr = getDLLAttr(Class);
6381
6382 // MSVC inherits DLL attributes to partial class template specializations.
6383 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6384 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6385 if (Attr *TemplateAttr =
6386 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6387 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6388 A->setInherited(true);
6389 ClassAttr = A;
6390 }
6391 }
6392 }
6393
6394 if (!ClassAttr)
6395 return;
6396
6397 // MSVC allows imported or exported template classes that have UniqueExternal
6398 // linkage. This occurs when the template class has been instantiated with
6399 // a template parameter which itself has internal linkage.
6400 // We drop the attribute to avoid exporting or importing any members.
6402 Context.getTargetInfo().getTriple().isPS()) &&
6403 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6404 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6405 return;
6406 }
6407
6408 if (!Class->isExternallyVisible()) {
6409 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6410 << Class << ClassAttr;
6411 return;
6412 }
6413
6415 !ClassAttr->isInherited()) {
6416 // Diagnose dll attributes on members of class with dll attribute.
6417 for (Decl *Member : Class->decls()) {
6418 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6419 continue;
6420 InheritableAttr *MemberAttr = getDLLAttr(Member);
6421 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6422 continue;
6423
6424 Diag(MemberAttr->getLocation(),
6425 diag::err_attribute_dll_member_of_dll_class)
6426 << MemberAttr << ClassAttr;
6427 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6428 Member->setInvalidDecl();
6429 }
6430 }
6431
6432 if (Class->getDescribedClassTemplate())
6433 // Don't inherit dll attribute until the template is instantiated.
6434 return;
6435
6436 // The class is either imported or exported.
6437 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6438
6439 // Check if this was a dllimport attribute propagated from a derived class to
6440 // a base class template specialization. We don't apply these attributes to
6441 // static data members.
6442 const bool PropagatedImport =
6443 !ClassExported &&
6444 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6445
6446 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6447
6448 // Ignore explicit dllexport on explicit class template instantiation
6449 // declarations, except in MinGW mode.
6450 if (ClassExported && !ClassAttr->isInherited() &&
6452 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6453 Class->dropAttr<DLLExportAttr>();
6454 return;
6455 }
6456
6457 // Force declaration of implicit members so they can inherit the attribute.
6459
6460 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6461 // seem to be true in practice?
6462
6463 for (Decl *Member : Class->decls()) {
6464 VarDecl *VD = dyn_cast<VarDecl>(Member);
6465 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6466
6467 // Only methods and static fields inherit the attributes.
6468 if (!VD && !MD)
6469 continue;
6470
6471 if (MD) {
6472 // Don't process deleted methods.
6473 if (MD->isDeleted())
6474 continue;
6475
6476 if (MD->isInlined()) {
6477 // MinGW does not import or export inline methods. But do it for
6478 // template instantiations.
6482 continue;
6483
6484 // MSVC versions before 2015 don't export the move assignment operators
6485 // and move constructor, so don't attempt to import/export them if
6486 // we have a definition.
6487 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6488 if ((MD->isMoveAssignmentOperator() ||
6489 (Ctor && Ctor->isMoveConstructor())) &&
6490 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6491 continue;
6492
6493 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6494 // operator is exported anyway.
6495 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6496 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6497 continue;
6498 }
6499 }
6500
6501 // Don't apply dllimport attributes to static data members of class template
6502 // instantiations when the attribute is propagated from a derived class.
6503 if (VD && PropagatedImport)
6504 continue;
6505
6506 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6507 continue;
6508
6509 if (!getDLLAttr(Member)) {
6510 InheritableAttr *NewAttr = nullptr;
6511
6512 // Do not export/import inline function when -fno-dllexport-inlines is
6513 // passed. But add attribute for later local static var check.
6514 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6517 if (ClassExported) {
6518 NewAttr = ::new (getASTContext())
6519 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6520 } else {
6521 NewAttr = ::new (getASTContext())
6522 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6523 }
6524 } else {
6525 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6526 }
6527
6528 NewAttr->setInherited(true);
6529 Member->addAttr(NewAttr);
6530
6531 if (MD) {
6532 // Propagate DLLAttr to friend re-declarations of MD that have already
6533 // been constructed.
6534 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6535 FD = FD->getPreviousDecl()) {
6537 continue;
6538 assert(!getDLLAttr(FD) &&
6539 "friend re-decl should not already have a DLLAttr");
6540 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6541 NewAttr->setInherited(true);
6542 FD->addAttr(NewAttr);
6543 }
6544 }
6545 }
6546 }
6547
6548 if (ClassExported)
6549 DelayedDllExportClasses.push_back(Class);
6550}
6551
6553 CXXRecordDecl *Class, Attr *ClassAttr,
6554 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6555 if (getDLLAttr(
6556 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6557 // If the base class template has a DLL attribute, don't try to change it.
6558 return;
6559 }
6560
6561 auto TSK = BaseTemplateSpec->getSpecializationKind();
6562 if (!getDLLAttr(BaseTemplateSpec) &&
6564 TSK == TSK_ImplicitInstantiation)) {
6565 // The template hasn't been instantiated yet (or it has, but only as an
6566 // explicit instantiation declaration or implicit instantiation, which means
6567 // we haven't codegenned any members yet), so propagate the attribute.
6568 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6569 NewAttr->setInherited(true);
6570 BaseTemplateSpec->addAttr(NewAttr);
6571
6572 // If this was an import, mark that we propagated it from a derived class to
6573 // a base class template specialization.
6574 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6575 ImportAttr->setPropagatedToBaseTemplate();
6576
6577 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6578 // needs to be run again to work see the new attribute. Otherwise this will
6579 // get run whenever the template is instantiated.
6580 if (TSK != TSK_Undeclared)
6581 checkClassLevelDLLAttribute(BaseTemplateSpec);
6582
6583 return;
6584 }
6585
6586 if (getDLLAttr(BaseTemplateSpec)) {
6587 // The template has already been specialized or instantiated with an
6588 // attribute, explicitly or through propagation. We should not try to change
6589 // it.
6590 return;
6591 }
6592
6593 // The template was previously instantiated or explicitly specialized without
6594 // a dll attribute, It's too late for us to add an attribute, so warn that
6595 // this is unsupported.
6596 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6597 << BaseTemplateSpec->isExplicitSpecialization();
6598 Diag(ClassAttr->getLocation(), diag::note_attribute);
6599 if (BaseTemplateSpec->isExplicitSpecialization()) {
6600 Diag(BaseTemplateSpec->getLocation(),
6601 diag::note_template_class_explicit_specialization_was_here)
6602 << BaseTemplateSpec;
6603 } else {
6604 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6605 diag::note_template_class_instantiation_was_here)
6606 << BaseTemplateSpec;
6607 }
6608}
6609
6612 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6613 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6614 if (Ctor->isDefaultConstructor())
6616
6617 if (Ctor->isCopyConstructor())
6619
6620 if (Ctor->isMoveConstructor())
6622 }
6623
6624 if (MD->isCopyAssignmentOperator())
6626
6627 if (MD->isMoveAssignmentOperator())
6629
6630 if (isa<CXXDestructorDecl>(FD))
6632 }
6633
6634 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6635 case OO_EqualEqual:
6637
6638 case OO_ExclaimEqual:
6640
6641 case OO_Spaceship:
6642 // No point allowing this if <=> doesn't exist in the current language mode.
6643 if (!getLangOpts().CPlusPlus20)
6644 break;
6646
6647 case OO_Less:
6648 case OO_LessEqual:
6649 case OO_Greater:
6650 case OO_GreaterEqual:
6651 // No point allowing this if <=> doesn't exist in the current language mode.
6652 if (!getLangOpts().CPlusPlus20)
6653 break;
6655
6656 default:
6657 break;
6658 }
6659
6660 // Not defaultable.
6661 return DefaultedFunctionKind();
6662}
6663
6665 SourceLocation DefaultLoc) {
6667 if (DFK.isComparison())
6668 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6669
6670 switch (DFK.asSpecialMember()) {
6673 cast<CXXConstructorDecl>(FD));
6674 break;
6676 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6677 break;
6679 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6680 break;
6682 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6683 break;
6685 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6686 break;
6688 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6689 break;
6691 llvm_unreachable("Invalid special member.");
6692 }
6693}
6694
6695/// Determine whether a type is permitted to be passed or returned in
6696/// registers, per C++ [class.temporary]p3.
6699 if (D->isDependentType() || D->isInvalidDecl())
6700 return false;
6701
6702 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6703 // The PS4 platform ABI follows the behavior of Clang 3.2.
6705 return !D->hasNonTrivialDestructorForCall() &&
6706 !D->hasNonTrivialCopyConstructorForCall();
6707
6708 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6709 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6710 bool DtorIsTrivialForCall = false;
6711
6712 // If a class has at least one eligible, trivial copy constructor, it
6713 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6714 //
6715 // Note: This permits classes with non-trivial copy or move ctors to be
6716 // passed in registers, so long as they *also* have a trivial copy ctor,
6717 // which is non-conforming.
6718 if (D->needsImplicitCopyConstructor()) {
6719 if (!D->defaultedCopyConstructorIsDeleted()) {
6720 if (D->hasTrivialCopyConstructor())
6721 CopyCtorIsTrivial = true;
6722 if (D->hasTrivialCopyConstructorForCall())
6723 CopyCtorIsTrivialForCall = true;
6724 }
6725 } else {
6726 for (const CXXConstructorDecl *CD : D->ctors()) {
6727 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6728 !CD->isIneligibleOrNotSelected()) {
6729 if (CD->isTrivial())
6730 CopyCtorIsTrivial = true;
6731 if (CD->isTrivialForCall())
6732 CopyCtorIsTrivialForCall = true;
6733 }
6734 }
6735 }
6736
6737 if (D->needsImplicitDestructor()) {
6738 if (!D->defaultedDestructorIsDeleted() &&
6739 D->hasTrivialDestructorForCall())
6740 DtorIsTrivialForCall = true;
6741 } else if (const auto *DD = D->getDestructor()) {
6742 if (!DD->isDeleted() && DD->isTrivialForCall())
6743 DtorIsTrivialForCall = true;
6744 }
6745
6746 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6747 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6748 return true;
6749
6750 // If a class has a destructor, we'd really like to pass it indirectly
6751 // because it allows us to elide copies. Unfortunately, MSVC makes that
6752 // impossible for small types, which it will pass in a single register or
6753 // stack slot. Most objects with dtors are large-ish, so handle that early.
6754 // We can't call out all large objects as being indirect because there are
6755 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6756 // how we pass large POD types.
6757
6758 // Note: This permits small classes with nontrivial destructors to be
6759 // passed in registers, which is non-conforming.
6760 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6761 uint64_t TypeSize = isAArch64 ? 128 : 64;
6762
6763 if (CopyCtorIsTrivial &&
6764 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6765 return true;
6766 return false;
6767 }
6768
6769 // Per C++ [class.temporary]p3, the relevant condition is:
6770 // each copy constructor, move constructor, and destructor of X is
6771 // either trivial or deleted, and X has at least one non-deleted copy
6772 // or move constructor
6773 bool HasNonDeletedCopyOrMove = false;
6774
6775 if (D->needsImplicitCopyConstructor() &&
6776 !D->defaultedCopyConstructorIsDeleted()) {
6777 if (!D->hasTrivialCopyConstructorForCall())
6778 return false;
6779 HasNonDeletedCopyOrMove = true;
6780 }
6781
6782 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6783 !D->defaultedMoveConstructorIsDeleted()) {
6784 if (!D->hasTrivialMoveConstructorForCall())
6785 return false;
6786 HasNonDeletedCopyOrMove = true;
6787 }
6788
6789 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6790 !D->hasTrivialDestructorForCall())
6791 return false;
6792
6793 for (const CXXMethodDecl *MD : D->methods()) {
6794 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6795 continue;
6796
6797 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6798 if (CD && CD->isCopyOrMoveConstructor())
6799 HasNonDeletedCopyOrMove = true;
6800 else if (!isa<CXXDestructorDecl>(MD))
6801 continue;
6802
6803 if (!MD->isTrivialForCall())
6804 return false;
6805 }
6806
6807 return HasNonDeletedCopyOrMove;
6808}
6809
6810/// Report an error regarding overriding, along with any relevant
6811/// overridden methods.
6812///
6813/// \param DiagID the primary error to report.
6814/// \param MD the overriding method.
6815static bool
6816ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6817 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6818 bool IssuedDiagnostic = false;
6819 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6820 if (Report(O)) {
6821 if (!IssuedDiagnostic) {
6822 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6823 IssuedDiagnostic = true;
6824 }
6825 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6826 }
6827 }
6828 return IssuedDiagnostic;
6829}
6830
6832 if (!Record)
6833 return;
6834
6835 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6836 AbstractUsageInfo Info(*this, Record);
6838 }
6839
6840 // If this is not an aggregate type and has no user-declared constructor,
6841 // complain about any non-static data members of reference or const scalar
6842 // type, since they will never get initializers.
6843 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6844 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6845 !Record->isLambda()) {
6846 bool Complained = false;
6847 for (const auto *F : Record->fields()) {
6848 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6849 continue;
6850
6851 if (F->getType()->isReferenceType() ||
6852 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6853 if (!Complained) {
6854 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6855 << llvm::to_underlying(Record->getTagKind()) << Record;
6856 Complained = true;
6857 }
6858
6859 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6860 << F->getType()->isReferenceType()
6861 << F->getDeclName();
6862 }
6863 }
6864 }
6865
6866 if (Record->getIdentifier()) {
6867 // C++ [class.mem]p13:
6868 // If T is the name of a class, then each of the following shall have a
6869 // name different from T:
6870 // - every member of every anonymous union that is a member of class T.
6871 //
6872 // C++ [class.mem]p14:
6873 // In addition, if class T has a user-declared constructor (12.1), every
6874 // non-static data member of class T shall have a name different from T.
6875 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6876 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6877 ++I) {
6878 NamedDecl *D = (*I)->getUnderlyingDecl();
6879 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6880 Record->hasUserDeclaredConstructor()) ||
6881 isa<IndirectFieldDecl>(D)) {
6882 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6883 << D->getDeclName();
6884 break;
6885 }
6886 }
6887 }
6888
6889 // Warn if the class has virtual methods but non-virtual public destructor.
6890 if (Record->isPolymorphic() && !Record->isDependentType()) {
6891 CXXDestructorDecl *dtor = Record->getDestructor();
6892 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6893 !Record->hasAttr<FinalAttr>())
6894 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6895 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6896 }
6897
6898 if (Record->isAbstract()) {
6899 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6900 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6901 << FA->isSpelledAsSealed();
6903 }
6904 }
6905
6906 // Warn if the class has a final destructor but is not itself marked final.
6907 if (!Record->hasAttr<FinalAttr>()) {
6908 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6909 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6910 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6911 << FA->isSpelledAsSealed()
6913 getLocForEndOfToken(Record->getLocation()),
6914 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6915 Diag(Record->getLocation(),
6916 diag::note_final_dtor_non_final_class_silence)
6917 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6918 }
6919 }
6920 }
6921
6922 // See if trivial_abi has to be dropped.
6923 if (Record->hasAttr<TrivialABIAttr>())
6925
6926 // Set HasTrivialSpecialMemberForCall if the record has attribute
6927 // "trivial_abi".
6928 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6929
6930 if (HasTrivialABI)
6931 Record->setHasTrivialSpecialMemberForCall();
6932
6933 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6934 // We check these last because they can depend on the properties of the
6935 // primary comparison functions (==, <=>).
6936 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6937
6938 // Perform checks that can't be done until we know all the properties of a
6939 // member function (whether it's defaulted, deleted, virtual, overriding,
6940 // ...).
6941 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6942 // A static function cannot override anything.
6943 if (MD->getStorageClass() == SC_Static) {
6944 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6945 [](const CXXMethodDecl *) { return true; }))
6946 return;
6947 }
6948
6949 // A deleted function cannot override a non-deleted function and vice
6950 // versa.
6951 if (ReportOverrides(*this,
6952 MD->isDeleted() ? diag::err_deleted_override
6953 : diag::err_non_deleted_override,
6954 MD, [&](const CXXMethodDecl *V) {
6955 return MD->isDeleted() != V->isDeleted();
6956 })) {
6957 if (MD->isDefaulted() && MD->isDeleted())
6958 // Explain why this defaulted function was deleted.
6960 return;
6961 }
6962
6963 // A consteval function cannot override a non-consteval function and vice
6964 // versa.
6965 if (ReportOverrides(*this,
6966 MD->isConsteval() ? diag::err_consteval_override
6967 : diag::err_non_consteval_override,
6968 MD, [&](const CXXMethodDecl *V) {
6969 return MD->isConsteval() != V->isConsteval();
6970 })) {
6971 if (MD->isDefaulted() && MD->isDeleted())
6972 // Explain why this defaulted function was deleted.
6974 return;
6975 }
6976 };
6977
6978 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6979 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6980 return false;
6981
6985 DefaultedSecondaryComparisons.push_back(FD);
6986 return true;
6987 }
6988
6990 return false;
6991 };
6992
6993 if (!Record->isInvalidDecl() &&
6994 Record->hasAttr<VTablePointerAuthenticationAttr>())
6996
6997 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6998 // Check whether the explicitly-defaulted members are valid.
6999 bool Incomplete = CheckForDefaultedFunction(M);
7000
7001 // Skip the rest of the checks for a member of a dependent class.
7002 if (Record->isDependentType())
7003 return;
7004
7005 // For an explicitly defaulted or deleted special member, we defer
7006 // determining triviality until the class is complete. That time is now!
7008 if (!M->isImplicit() && !M->isUserProvided()) {
7009 if (CSM != CXXSpecialMemberKind::Invalid) {
7010 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7011 // Inform the class that we've finished declaring this member.
7012 Record->finishedDefaultedOrDeletedMember(M);
7013 M->setTrivialForCall(
7014 HasTrivialABI ||
7016 Record->setTrivialForCallFlags(M);
7017 }
7018 }
7019
7020 // Set triviality for the purpose of calls if this is a user-provided
7021 // copy/move constructor or destructor.
7025 M->isUserProvided()) {
7026 M->setTrivialForCall(HasTrivialABI);
7027 Record->setTrivialForCallFlags(M);
7028 }
7029
7030 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7031 M->hasAttr<DLLExportAttr>()) {
7032 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7033 M->isTrivial() &&
7037 M->dropAttr<DLLExportAttr>();
7038
7039 if (M->hasAttr<DLLExportAttr>()) {
7040 // Define after any fields with in-class initializers have been parsed.
7042 }
7043 }
7044
7045 // Define defaulted constexpr virtual functions that override a base class
7046 // function right away.
7047 // FIXME: We can defer doing this until the vtable is marked as used.
7048 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7049 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
7050 DefineDefaultedFunction(*this, M, M->getLocation());
7051
7052 if (!Incomplete)
7053 CheckCompletedMemberFunction(M);
7054 };
7055
7056 // Check the destructor before any other member function. We need to
7057 // determine whether it's trivial in order to determine whether the claas
7058 // type is a literal type, which is a prerequisite for determining whether
7059 // other special member functions are valid and whether they're implicitly
7060 // 'constexpr'.
7061 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7062 CompleteMemberFunction(Dtor);
7063
7064 bool HasMethodWithOverrideControl = false,
7065 HasOverridingMethodWithoutOverrideControl = false;
7066 for (auto *D : Record->decls()) {
7067 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7068 // FIXME: We could do this check for dependent types with non-dependent
7069 // bases.
7070 if (!Record->isDependentType()) {
7071 // See if a method overloads virtual methods in a base
7072 // class without overriding any.
7073 if (!M->isStatic())
7075 if (M->hasAttr<OverrideAttr>())
7076 HasMethodWithOverrideControl = true;
7077 else if (M->size_overridden_methods() > 0)
7078 HasOverridingMethodWithoutOverrideControl = true;
7079 }
7080
7081 if (!isa<CXXDestructorDecl>(M))
7082 CompleteMemberFunction(M);
7083 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7084 CheckForDefaultedFunction(
7085 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7086 }
7087 }
7088
7089 if (HasOverridingMethodWithoutOverrideControl) {
7090 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7091 for (auto *M : Record->methods())
7092 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7093 }
7094
7095 // Check the defaulted secondary comparisons after any other member functions.
7096 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7098
7099 // If this is a member function, we deferred checking it until now.
7100 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7101 CheckCompletedMemberFunction(MD);
7102 }
7103
7104 // ms_struct is a request to use the same ABI rules as MSVC. Check
7105 // whether this class uses any C++ features that are implemented
7106 // completely differently in MSVC, and if so, emit a diagnostic.
7107 // That diagnostic defaults to an error, but we allow projects to
7108 // map it down to a warning (or ignore it). It's a fairly common
7109 // practice among users of the ms_struct pragma to mass-annotate
7110 // headers, sweeping up a bunch of types that the project doesn't
7111 // really rely on MSVC-compatible layout for. We must therefore
7112 // support "ms_struct except for C++ stuff" as a secondary ABI.
7113 // Don't emit this diagnostic if the feature was enabled as a
7114 // language option (as opposed to via a pragma or attribute), as
7115 // the option -mms-bitfields otherwise essentially makes it impossible
7116 // to build C++ code, unless this diagnostic is turned off.
7117 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7118 (Record->isPolymorphic() || Record->getNumBases())) {
7119 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7120 }
7121
7124
7125 bool ClangABICompat4 =
7126 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7128 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7129 bool CanPass = canPassInRegisters(*this, Record, CCK);
7130
7131 // Do not change ArgPassingRestrictions if it has already been set to
7132 // RecordArgPassingKind::CanNeverPassInRegs.
7133 if (Record->getArgPassingRestrictions() !=
7135 Record->setArgPassingRestrictions(
7138
7139 // If canPassInRegisters returns true despite the record having a non-trivial
7140 // destructor, the record is destructed in the callee. This happens only when
7141 // the record or one of its subobjects has a field annotated with trivial_abi
7142 // or a field qualified with ObjC __strong/__weak.
7144 Record->setParamDestroyedInCallee(true);
7145 else if (Record->hasNonTrivialDestructor())
7146 Record->setParamDestroyedInCallee(CanPass);
7147
7148 if (getLangOpts().ForceEmitVTables) {
7149 // If we want to emit all the vtables, we need to mark it as used. This
7150 // is especially required for cases like vtable assumption loads.
7151 MarkVTableUsed(Record->getInnerLocStart(), Record);
7152 }
7153
7154 if (getLangOpts().CUDA) {
7155 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7157 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7159 }
7160}
7161
7162/// Look up the special member function that would be called by a special
7163/// member function for a subobject of class type.
7164///
7165/// \param Class The class type of the subobject.
7166/// \param CSM The kind of special member function.
7167/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7168/// \param ConstRHS True if this is a copy operation with a const object
7169/// on its RHS, that is, if the argument to the outer special member
7170/// function is 'const' and this is not a field marked 'mutable'.
7173 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7174 bool ConstRHS) {
7175 unsigned LHSQuals = 0;
7178 LHSQuals = FieldQuals;
7179
7180 unsigned RHSQuals = FieldQuals;
7183 RHSQuals = 0;
7184 else if (ConstRHS)
7185 RHSQuals |= Qualifiers::Const;
7186
7187 return S.LookupSpecialMember(Class, CSM,
7188 RHSQuals & Qualifiers::Const,
7189 RHSQuals & Qualifiers::Volatile,
7190 false,
7191 LHSQuals & Qualifiers::Const,
7192 LHSQuals & Qualifiers::Volatile);
7193}
7194
7196 Sema &S;
7197 SourceLocation UseLoc;
7198
7199 /// A mapping from the base classes through which the constructor was
7200 /// inherited to the using shadow declaration in that base class (or a null
7201 /// pointer if the constructor was declared in that base class).
7202 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7203 InheritedFromBases;
7204
7205public:
7208 : S(S), UseLoc(UseLoc) {
7209 bool DiagnosedMultipleConstructedBases = false;
7210 CXXRecordDecl *ConstructedBase = nullptr;
7211 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7212
7213 // Find the set of such base class subobjects and check that there's a
7214 // unique constructed subobject.
7215 for (auto *D : Shadow->redecls()) {
7216 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7217 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7218 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7219
7220 InheritedFromBases.insert(
7221 std::make_pair(DNominatedBase->getCanonicalDecl(),
7222 DShadow->getNominatedBaseClassShadowDecl()));
7223 if (DShadow->constructsVirtualBase())
7224 InheritedFromBases.insert(
7225 std::make_pair(DConstructedBase->getCanonicalDecl(),
7226 DShadow->getConstructedBaseClassShadowDecl()));
7227 else
7228 assert(DNominatedBase == DConstructedBase);
7229
7230 // [class.inhctor.init]p2:
7231 // If the constructor was inherited from multiple base class subobjects
7232 // of type B, the program is ill-formed.
7233 if (!ConstructedBase) {
7234 ConstructedBase = DConstructedBase;
7235 ConstructedBaseIntroducer = D->getIntroducer();
7236 } else if (ConstructedBase != DConstructedBase &&
7237 !Shadow->isInvalidDecl()) {
7238 if (!DiagnosedMultipleConstructedBases) {
7239 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7240 << Shadow->getTargetDecl();
7241 S.Diag(ConstructedBaseIntroducer->getLocation(),
7242 diag::note_ambiguous_inherited_constructor_using)
7243 << ConstructedBase;
7244 DiagnosedMultipleConstructedBases = true;
7245 }
7246 S.Diag(D->getIntroducer()->getLocation(),
7247 diag::note_ambiguous_inherited_constructor_using)
7248 << DConstructedBase;
7249 }
7250 }
7251
7252 if (DiagnosedMultipleConstructedBases)
7253 Shadow->setInvalidDecl();
7254 }
7255
7256 /// Find the constructor to use for inherited construction of a base class,
7257 /// and whether that base class constructor inherits the constructor from a
7258 /// virtual base class (in which case it won't actually invoke it).
7259 std::pair<CXXConstructorDecl *, bool>
7261 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7262 if (It == InheritedFromBases.end())
7263 return std::make_pair(nullptr, false);
7264
7265 // This is an intermediary class.
7266 if (It->second)
7267 return std::make_pair(
7268 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7269 It->second->constructsVirtualBase());
7270
7271 // This is the base class from which the constructor was inherited.
7272 return std::make_pair(Ctor, false);
7273 }
7274};
7275
7276/// Is the special member function which would be selected to perform the
7277/// specified operation on the specified class type a constexpr constructor?
7279 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7280 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7281 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7282 // Suppress duplicate constraint checking here, in case a constraint check
7283 // caused us to decide to do this. Any truely recursive checks will get
7284 // caught during these checks anyway.
7286
7287 // If we're inheriting a constructor, see if we need to call it for this base
7288 // class.
7289 if (InheritedCtor) {
7291 auto BaseCtor =
7292 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7293 if (BaseCtor)
7294 return BaseCtor->isConstexpr();
7295 }
7296
7298 return ClassDecl->hasConstexprDefaultConstructor();
7300 return ClassDecl->hasConstexprDestructor();
7301
7303 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7304 if (!SMOR.getMethod())
7305 // A constructor we wouldn't select can't be "involved in initializing"
7306 // anything.
7307 return true;
7308 return SMOR.getMethod()->isConstexpr();
7309}
7310
7311/// Determine whether the specified special member function would be constexpr
7312/// if it were implicitly defined.
7314 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7315 CXXConstructorDecl *InheritedCtor = nullptr,
7316 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7317 if (!S.getLangOpts().CPlusPlus11)
7318 return false;
7319
7320 // C++11 [dcl.constexpr]p4:
7321 // In the definition of a constexpr constructor [...]
7322 bool Ctor = true;
7323 switch (CSM) {
7325 if (Inherited)
7326 break;
7327 // Since default constructor lookup is essentially trivial (and cannot
7328 // involve, for instance, template instantiation), we compute whether a
7329 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7330 //
7331 // This is important for performance; we need to know whether the default
7332 // constructor is constexpr to determine whether the type is a literal type.
7333 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7334
7337 // For copy or move constructors, we need to perform overload resolution.
7338 break;
7339
7342 if (!S.getLangOpts().CPlusPlus14)
7343 return false;
7344 // In C++1y, we need to perform overload resolution.
7345 Ctor = false;
7346 break;
7347
7349 return ClassDecl->defaultedDestructorIsConstexpr();
7350
7352 return false;
7353 }
7354
7355 // -- if the class is a non-empty union, or for each non-empty anonymous
7356 // union member of a non-union class, exactly one non-static data member
7357 // shall be initialized; [DR1359]
7358 //
7359 // If we squint, this is guaranteed, since exactly one non-static data member
7360 // will be initialized (if the constructor isn't deleted), we just don't know
7361 // which one.
7362 if (Ctor && ClassDecl->isUnion())
7364 ? ClassDecl->hasInClassInitializer() ||
7365 !ClassDecl->hasVariantMembers()
7366 : true;
7367
7368 // -- the class shall not have any virtual base classes;
7369 if (Ctor && ClassDecl->getNumVBases())
7370 return false;
7371
7372 // C++1y [class.copy]p26:
7373 // -- [the class] is a literal type, and
7374 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7375 return false;
7376
7377 // -- every constructor involved in initializing [...] base class
7378 // sub-objects shall be a constexpr constructor;
7379 // -- the assignment operator selected to copy/move each direct base
7380 // class is a constexpr function, and
7381 if (!S.getLangOpts().CPlusPlus23) {
7382 for (const auto &B : ClassDecl->bases()) {
7383 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7384 if (!BaseType)
7385 continue;
7386 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7387 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7388 InheritedCtor, Inherited))
7389 return false;
7390 }
7391 }
7392
7393 // -- every constructor involved in initializing non-static data members
7394 // [...] shall be a constexpr constructor;
7395 // -- every non-static data member and base class sub-object shall be
7396 // initialized
7397 // -- for each non-static data member of X that is of class type (or array
7398 // thereof), the assignment operator selected to copy/move that member is
7399 // a constexpr function
7400 if (!S.getLangOpts().CPlusPlus23) {
7401 for (const auto *F : ClassDecl->fields()) {
7402 if (F->isInvalidDecl())
7403 continue;
7405 F->hasInClassInitializer())
7406 continue;
7407 QualType BaseType = S.Context.getBaseElementType(F->getType());
7408 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7409 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7410 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7411 BaseType.getCVRQualifiers(),
7412 ConstArg && !F->isMutable()))
7413 return false;
7414 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7415 return false;
7416 }
7417 }
7418 }
7419
7420 // All OK, it's constexpr!
7421 return true;
7422}
7423
7424namespace {
7425/// RAII object to register a defaulted function as having its exception
7426/// specification computed.
7427struct ComputingExceptionSpec {
7428 Sema &S;
7429
7430 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7431 : S(S) {
7435 Ctx.Entity = FD;
7437 }
7438 ~ComputingExceptionSpec() {
7440 }
7441};
7442}
7443
7446 CXXMethodDecl *MD,
7449
7452 FunctionDecl *FD,
7454
7457 auto DFK = S.getDefaultedFunctionKind(FD);
7458 if (DFK.isSpecialMember())
7460 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7461 if (DFK.isComparison())
7463 DFK.asComparison());
7464
7465 auto *CD = cast<CXXConstructorDecl>(FD);
7466 assert(CD->getInheritedConstructor() &&
7467 "only defaulted functions and inherited constructors have implicit "
7468 "exception specs");
7470 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7473}
7474
7476 CXXMethodDecl *MD) {
7478
7479 // Build an exception specification pointing back at this member.
7481 EPI.ExceptionSpec.SourceDecl = MD;
7482
7483 // Set the calling convention to the default for C++ instance methods.
7485 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7486 /*IsCXXMethod=*/true));
7487 return EPI;
7488}
7489
7491 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7493 return;
7494
7495 // Evaluate the exception specification.
7496 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7497 auto ESI = IES.getExceptionSpec();
7498
7499 // Update the type of the special member to use it.
7500 UpdateExceptionSpec(FD, ESI);
7501}
7502
7504 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7505
7507 if (!DefKind) {
7508 assert(FD->getDeclContext()->isDependentContext());
7509 return;
7510 }
7511
7512 if (DefKind.isComparison())
7513 UnusedPrivateFields.clear();
7514
7515 if (DefKind.isSpecialMember()
7516 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7517 DefKind.asSpecialMember(),
7518 FD->getDefaultLoc())
7520 FD->setInvalidDecl();
7521}
7522
7525 SourceLocation DefaultLoc) {
7526 CXXRecordDecl *RD = MD->getParent();
7527
7529 "not an explicitly-defaulted special member");
7530
7531 // Defer all checking for special members of a dependent type.
7532 if (RD->isDependentType())
7533 return false;
7534
7535 // Whether this was the first-declared instance of the constructor.
7536 // This affects whether we implicitly add an exception spec and constexpr.
7537 bool First = MD == MD->getCanonicalDecl();
7538
7539 bool HadError = false;
7540
7541 // C++11 [dcl.fct.def.default]p1:
7542 // A function that is explicitly defaulted shall
7543 // -- be a special member function [...] (checked elsewhere),
7544 // -- have the same type (except for ref-qualifiers, and except that a
7545 // copy operation can take a non-const reference) as an implicit
7546 // declaration, and
7547 // -- not have default arguments.
7548 // C++2a changes the second bullet to instead delete the function if it's
7549 // defaulted on its first declaration, unless it's "an assignment operator,
7550 // and its return type differs or its parameter type is not a reference".
7551 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7552 bool ShouldDeleteForTypeMismatch = false;
7553 unsigned ExpectedParams = 1;
7556 ExpectedParams = 0;
7557 if (MD->getNumExplicitParams() != ExpectedParams) {
7558 // This checks for default arguments: a copy or move constructor with a
7559 // default argument is classified as a default constructor, and assignment
7560 // operations and destructors can't have default arguments.
7561 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7562 << llvm::to_underlying(CSM) << MD->getSourceRange();
7563 HadError = true;
7564 } else if (MD->isVariadic()) {
7565 if (DeleteOnTypeMismatch)
7566 ShouldDeleteForTypeMismatch = true;
7567 else {
7568 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7569 << llvm::to_underlying(CSM) << MD->getSourceRange();
7570 HadError = true;
7571 }
7572 }
7573
7575
7576 bool CanHaveConstParam = false;
7578 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7580 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7581
7582 QualType ReturnType = Context.VoidTy;
7585 // Check for return type matching.
7586 ReturnType = Type->getReturnType();
7588
7589 QualType DeclType = Context.getTypeDeclType(RD);
7591 DeclType, nullptr);
7592 DeclType = Context.getAddrSpaceQualType(
7593 DeclType, ThisType.getQualifiers().getAddressSpace());
7594 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7595
7596 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7597 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7599 << ExpectedReturnType;
7600 HadError = true;
7601 }
7602
7603 // A defaulted special member cannot have cv-qualifiers.
7604 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7605 if (DeleteOnTypeMismatch)
7606 ShouldDeleteForTypeMismatch = true;
7607 else {
7608 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7610 << getLangOpts().CPlusPlus14;
7611 HadError = true;
7612 }
7613 }
7614 // [C++23][dcl.fct.def.default]/p2.2
7615 // if F2 has an implicit object parameter of type “reference to C”,
7616 // F1 may be an explicit object member function whose explicit object
7617 // parameter is of (possibly different) type “reference to C”,
7618 // in which case the type of F1 would differ from the type of F2
7619 // in that the type of F1 has an additional parameter;
7620 if (!Context.hasSameType(
7622 Context.getRecordType(RD))) {
7623 if (DeleteOnTypeMismatch)
7624 ShouldDeleteForTypeMismatch = true;
7625 else {
7626 Diag(MD->getLocation(),
7627 diag::err_defaulted_special_member_explicit_object_mismatch)
7628 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7629 << MD->getSourceRange();
7630 HadError = true;
7631 }
7632 }
7633 }
7634
7635 // Check for parameter type matching.
7636 QualType ArgType =
7637 ExpectedParams
7638 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7639 : QualType();
7640 bool HasConstParam = false;
7641 if (ExpectedParams && ArgType->isReferenceType()) {
7642 // Argument must be reference to possibly-const T.
7643 QualType ReferentType = ArgType->getPointeeType();
7644 HasConstParam = ReferentType.isConstQualified();
7645
7646 if (ReferentType.isVolatileQualified()) {
7647 if (DeleteOnTypeMismatch)
7648 ShouldDeleteForTypeMismatch = true;
7649 else {
7650 Diag(MD->getLocation(),
7651 diag::err_defaulted_special_member_volatile_param)
7652 << llvm::to_underlying(CSM);
7653 HadError = true;
7654 }
7655 }
7656
7657 if (HasConstParam && !CanHaveConstParam) {
7658 if (DeleteOnTypeMismatch)
7659 ShouldDeleteForTypeMismatch = true;
7660 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7662 Diag(MD->getLocation(),
7663 diag::err_defaulted_special_member_copy_const_param)
7665 // FIXME: Explain why this special member can't be const.
7666 HadError = true;
7667 } else {
7668 Diag(MD->getLocation(),
7669 diag::err_defaulted_special_member_move_const_param)
7671 HadError = true;
7672 }
7673 }
7674 } else if (ExpectedParams) {
7675 // A copy assignment operator can take its argument by value, but a
7676 // defaulted one cannot.
7678 "unexpected non-ref argument");
7679 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7680 HadError = true;
7681 }
7682
7683 // C++11 [dcl.fct.def.default]p2:
7684 // An explicitly-defaulted function may be declared constexpr only if it
7685 // would have been implicitly declared as constexpr,
7686 // Do not apply this rule to members of class templates, since core issue 1358
7687 // makes such functions always instantiate to constexpr functions. For
7688 // functions which cannot be constexpr (for non-constructors in C++11 and for
7689 // destructors in C++14 and C++17), this is checked elsewhere.
7690 //
7691 // FIXME: This should not apply if the member is deleted.
7692 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7693 HasConstParam);
7694
7695 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7696 // If the instantiated template specialization of a constexpr function
7697 // template or member function of a class template would fail to satisfy
7698 // the requirements for a constexpr function or constexpr constructor, that
7699 // specialization is still a constexpr function or constexpr constructor,
7700 // even though a call to such a function cannot appear in a constant
7701 // expression.
7702 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7703 Constexpr = true;
7704
7705 if ((getLangOpts().CPlusPlus20 ||
7706 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7707 : isa<CXXConstructorDecl>(MD))) &&
7708 MD->isConstexpr() && !Constexpr &&
7710 if (!MD->isConsteval() && RD->getNumVBases()) {
7711 Diag(MD->getBeginLoc(),
7712 diag::err_incorrect_defaulted_constexpr_with_vb)
7713 << llvm::to_underlying(CSM);
7714 for (const auto &I : RD->vbases())
7715 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7716 } else {
7717 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7718 << llvm::to_underlying(CSM) << MD->isConsteval();
7719 }
7720 HadError = true;
7721 // FIXME: Explain why the special member can't be constexpr.
7722 }
7723
7724 if (First) {
7725 // C++2a [dcl.fct.def.default]p3:
7726 // If a function is explicitly defaulted on its first declaration, it is
7727 // implicitly considered to be constexpr if the implicit declaration
7728 // would be.
7733
7734 if (!Type->hasExceptionSpec()) {
7735 // C++2a [except.spec]p3:
7736 // If a declaration of a function does not have a noexcept-specifier
7737 // [and] is defaulted on its first declaration, [...] the exception
7738 // specification is as specified below
7739 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7741 EPI.ExceptionSpec.SourceDecl = MD;
7742 MD->setType(
7743 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7744 }
7745 }
7746
7747 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7748 if (First) {
7749 SetDeclDeleted(MD, MD->getLocation());
7750 if (!inTemplateInstantiation() && !HadError) {
7751 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7752 << llvm::to_underlying(CSM);
7753 if (ShouldDeleteForTypeMismatch) {
7754 Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7755 << llvm::to_underlying(CSM);
7756 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7757 /*Diagnose*/ true) &&
7758 DefaultLoc.isValid()) {
7759 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7760 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7761 }
7762 }
7763 if (ShouldDeleteForTypeMismatch && !HadError) {
7764 Diag(MD->getLocation(),
7765 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7766 << llvm::to_underlying(CSM);
7767 }
7768 } else {
7769 // C++11 [dcl.fct.def.default]p4:
7770 // [For a] user-provided explicitly-defaulted function [...] if such a
7771 // function is implicitly defined as deleted, the program is ill-formed.
7772 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7773 << llvm::to_underlying(CSM);
7774 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7775 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7776 HadError = true;
7777 }
7778 }
7779
7780 return HadError;
7781}
7782
7783namespace {
7784/// Helper class for building and checking a defaulted comparison.
7785///
7786/// Defaulted functions are built in two phases:
7787///
7788/// * First, the set of operations that the function will perform are
7789/// identified, and some of them are checked. If any of the checked
7790/// operations is invalid in certain ways, the comparison function is
7791/// defined as deleted and no body is built.
7792/// * Then, if the function is not defined as deleted, the body is built.
7793///
7794/// This is accomplished by performing two visitation steps over the eventual
7795/// body of the function.
7796template<typename Derived, typename ResultList, typename Result,
7797 typename Subobject>
7798class DefaultedComparisonVisitor {
7799public:
7800 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7801
7802 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7803 DefaultedComparisonKind DCK)
7804 : S(S), RD(RD), FD(FD), DCK(DCK) {
7805 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7806 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7807 // UnresolvedSet to avoid this copy.
7808 Fns.assign(Info->getUnqualifiedLookups().begin(),
7809 Info->getUnqualifiedLookups().end());
7810 }
7811 }
7812
7813 ResultList visit() {
7814 // The type of an lvalue naming a parameter of this function.
7815 QualType ParamLvalType =
7817
7818 ResultList Results;
7819
7820 switch (DCK) {
7821 case DefaultedComparisonKind::None:
7822 llvm_unreachable("not a defaulted comparison");
7823
7824 case DefaultedComparisonKind::Equal:
7825 case DefaultedComparisonKind::ThreeWay:
7826 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7827 return Results;
7828
7829 case DefaultedComparisonKind::NotEqual:
7830 case DefaultedComparisonKind::Relational:
7831 Results.add(getDerived().visitExpandedSubobject(
7832 ParamLvalType, getDerived().getCompleteObject()));
7833 return Results;
7834 }
7835 llvm_unreachable("");
7836 }
7837
7838protected:
7839 Derived &getDerived() { return static_cast<Derived&>(*this); }
7840
7841 /// Visit the expanded list of subobjects of the given type, as specified in
7842 /// C++2a [class.compare.default].
7843 ///
7844 /// \return \c true if the ResultList object said we're done, \c false if not.
7845 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7846 Qualifiers Quals) {
7847 // C++2a [class.compare.default]p4:
7848 // The direct base class subobjects of C
7849 for (CXXBaseSpecifier &Base : Record->bases())
7850 if (Results.add(getDerived().visitSubobject(
7851 S.Context.getQualifiedType(Base.getType(), Quals),
7852 getDerived().getBase(&Base))))
7853 return true;
7854
7855 // followed by the non-static data members of C
7856 for (FieldDecl *Field : Record->fields()) {
7857 // C++23 [class.bit]p2:
7858 // Unnamed bit-fields are not members ...
7859 if (Field->isUnnamedBitField())
7860 continue;
7861 // Recursively expand anonymous structs.
7862 if (Field->isAnonymousStructOrUnion()) {
7863 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7864 Quals))
7865 return true;
7866 continue;
7867 }
7868
7869 // Figure out the type of an lvalue denoting this field.
7870 Qualifiers FieldQuals = Quals;
7871 if (Field->isMutable())
7872 FieldQuals.removeConst();
7873 QualType FieldType =
7874 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7875
7876 if (Results.add(getDerived().visitSubobject(
7877 FieldType, getDerived().getField(Field))))
7878 return true;
7879 }
7880
7881 // form a list of subobjects.
7882 return false;
7883 }
7884
7885 Result visitSubobject(QualType Type, Subobject Subobj) {
7886 // In that list, any subobject of array type is recursively expanded
7887 const ArrayType *AT = S.Context.getAsArrayType(Type);
7888 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7889 return getDerived().visitSubobjectArray(CAT->getElementType(),
7890 CAT->getSize(), Subobj);
7891 return getDerived().visitExpandedSubobject(Type, Subobj);
7892 }
7893
7894 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7895 Subobject Subobj) {
7896 return getDerived().visitSubobject(Type, Subobj);
7897 }
7898
7899protected:
7900 Sema &S;
7901 CXXRecordDecl *RD;
7902 FunctionDecl *FD;
7903 DefaultedComparisonKind DCK;
7905};
7906
7907/// Information about a defaulted comparison, as determined by
7908/// DefaultedComparisonAnalyzer.
7909struct DefaultedComparisonInfo {
7910 bool Deleted = false;
7911 bool Constexpr = true;
7912 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7913
7914 static DefaultedComparisonInfo deleted() {
7915 DefaultedComparisonInfo Deleted;
7916 Deleted.Deleted = true;
7917 return Deleted;
7918 }
7919
7920 bool add(const DefaultedComparisonInfo &R) {
7921 Deleted |= R.Deleted;
7922 Constexpr &= R.Constexpr;
7923 Category = commonComparisonType(Category, R.Category);
7924 return Deleted;
7925 }
7926};
7927
7928/// An element in the expanded list of subobjects of a defaulted comparison, as
7929/// specified in C++2a [class.compare.default]p4.
7930struct DefaultedComparisonSubobject {
7931 enum { CompleteObject, Member, Base } Kind;
7932 NamedDecl *Decl;
7934};
7935
7936/// A visitor over the notional body of a defaulted comparison that determines
7937/// whether that body would be deleted or constexpr.
7938class DefaultedComparisonAnalyzer
7939 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7940 DefaultedComparisonInfo,
7941 DefaultedComparisonInfo,
7942 DefaultedComparisonSubobject> {
7943public:
7944 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7945
7946private:
7947 DiagnosticKind Diagnose;
7948
7949public:
7950 using Base = DefaultedComparisonVisitor;
7951 using Result = DefaultedComparisonInfo;
7952 using Subobject = DefaultedComparisonSubobject;
7953
7954 friend Base;
7955
7956 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7957 DefaultedComparisonKind DCK,
7958 DiagnosticKind Diagnose = NoDiagnostics)
7959 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7960
7961 Result visit() {
7962 if ((DCK == DefaultedComparisonKind::Equal ||
7963 DCK == DefaultedComparisonKind::ThreeWay) &&
7964 RD->hasVariantMembers()) {
7965 // C++2a [class.compare.default]p2 [P2002R0]:
7966 // A defaulted comparison operator function for class C is defined as
7967 // deleted if [...] C has variant members.
7968 if (Diagnose == ExplainDeleted) {
7969 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7970 << FD << RD->isUnion() << RD;
7971 }
7972 return Result::deleted();
7973 }
7974
7975 return Base::visit();
7976 }
7977
7978private:
7979 Subobject getCompleteObject() {
7980 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7981 }
7982
7983 Subobject getBase(CXXBaseSpecifier *Base) {
7984 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7985 Base->getBaseTypeLoc()};
7986 }
7987
7988 Subobject getField(FieldDecl *Field) {
7989 return Subobject{Subobject::Member, Field, Field->getLocation()};
7990 }
7991
7992 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7993 // C++2a [class.compare.default]p2 [P2002R0]:
7994 // A defaulted <=> or == operator function for class C is defined as
7995 // deleted if any non-static data member of C is of reference type
7996 if (Type->isReferenceType()) {
7997 if (Diagnose == ExplainDeleted) {
7998 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7999 << FD << RD;
8000 }
8001 return Result::deleted();
8002 }
8003
8004 // [...] Let xi be an lvalue denoting the ith element [...]
8006 Expr *Args[] = {&Xi, &Xi};
8007
8008 // All operators start by trying to apply that same operator recursively.
8010 assert(OO != OO_None && "not an overloaded operator!");
8011 return visitBinaryOperator(OO, Args, Subobj);
8012 }
8013
8014 Result
8015 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8016 Subobject Subobj,
8017 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8018 // Note that there is no need to consider rewritten candidates here if
8019 // we've already found there is no viable 'operator<=>' candidate (and are
8020 // considering synthesizing a '<=>' from '==' and '<').
8021 OverloadCandidateSet CandidateSet(
8024 OO, FD->getLocation(),
8025 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8026
8027 /// C++2a [class.compare.default]p1 [P2002R0]:
8028 /// [...] the defaulted function itself is never a candidate for overload
8029 /// resolution [...]
8030 CandidateSet.exclude(FD);
8031
8032 if (Args[0]->getType()->isOverloadableType())
8033 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8034 else
8035 // FIXME: We determine whether this is a valid expression by checking to
8036 // see if there's a viable builtin operator candidate for it. That isn't
8037 // really what the rules ask us to do, but should give the right results.
8038 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8039
8040 Result R;
8041
8043 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8044 case OR_Success: {
8045 // C++2a [class.compare.secondary]p2 [P2002R0]:
8046 // The operator function [...] is defined as deleted if [...] the
8047 // candidate selected by overload resolution is not a rewritten
8048 // candidate.
8049 if ((DCK == DefaultedComparisonKind::NotEqual ||
8050 DCK == DefaultedComparisonKind::Relational) &&
8051 !Best->RewriteKind) {
8052 if (Diagnose == ExplainDeleted) {
8053 if (Best->Function) {
8054 S.Diag(Best->Function->getLocation(),
8055 diag::note_defaulted_comparison_not_rewritten_callee)
8056 << FD;
8057 } else {
8058 assert(Best->Conversions.size() == 2 &&
8059 Best->Conversions[0].isUserDefined() &&
8060 "non-user-defined conversion from class to built-in "
8061 "comparison");
8062 S.Diag(Best->Conversions[0]
8063 .UserDefined.FoundConversionFunction.getDecl()
8064 ->getLocation(),
8065 diag::note_defaulted_comparison_not_rewritten_conversion)
8066 << FD;
8067 }
8068 }
8069 return Result::deleted();
8070 }
8071
8072 // Throughout C++2a [class.compare]: if overload resolution does not
8073 // result in a usable function, the candidate function is defined as
8074 // deleted. This requires that we selected an accessible function.
8075 //
8076 // Note that this only considers the access of the function when named
8077 // within the type of the subobject, and not the access path for any
8078 // derived-to-base conversion.
8079 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8080 if (ArgClass && Best->FoundDecl.getDecl() &&
8081 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8082 QualType ObjectType = Subobj.Kind == Subobject::Member
8083 ? Args[0]->getType()
8084 : S.Context.getRecordType(RD);
8086 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8087 Diagnose == ExplainDeleted
8088 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8089 << FD << Subobj.Kind << Subobj.Decl
8090 : S.PDiag()))
8091 return Result::deleted();
8092 }
8093
8094 bool NeedsDeducing =
8095 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8096
8097 if (FunctionDecl *BestFD = Best->Function) {
8098 // C++2a [class.compare.default]p3 [P2002R0]:
8099 // A defaulted comparison function is constexpr-compatible if
8100 // [...] no overlod resolution performed [...] results in a
8101 // non-constexpr function.
8102 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8103 // If it's not constexpr, explain why not.
8104 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8105 if (Subobj.Kind != Subobject::CompleteObject)
8106 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8107 << Subobj.Kind << Subobj.Decl;
8108 S.Diag(BestFD->getLocation(),
8109 diag::note_defaulted_comparison_not_constexpr_here);
8110 // Bail out after explaining; we don't want any more notes.
8111 return Result::deleted();
8112 }
8113 R.Constexpr &= BestFD->isConstexpr();
8114
8115 if (NeedsDeducing) {
8116 // If any callee has an undeduced return type, deduce it now.
8117 // FIXME: It's not clear how a failure here should be handled. For
8118 // now, we produce an eager diagnostic, because that is forward
8119 // compatible with most (all?) other reasonable options.
8120 if (BestFD->getReturnType()->isUndeducedType() &&
8121 S.DeduceReturnType(BestFD, FD->getLocation(),
8122 /*Diagnose=*/false)) {
8123 // Don't produce a duplicate error when asked to explain why the
8124 // comparison is deleted: we diagnosed that when initially checking
8125 // the defaulted operator.
8126 if (Diagnose == NoDiagnostics) {
8127 S.Diag(
8128 FD->getLocation(),
8129 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8130 << Subobj.Kind << Subobj.Decl;
8131 S.Diag(
8132 Subobj.Loc,
8133 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8134 << Subobj.Kind << Subobj.Decl;
8135 S.Diag(BestFD->getLocation(),
8136 diag::note_defaulted_comparison_cannot_deduce_callee)
8137 << Subobj.Kind << Subobj.Decl;
8138 }
8139 return Result::deleted();
8140 }
8142 BestFD->getCallResultType());
8143 if (!Info) {
8144 if (Diagnose == ExplainDeleted) {
8145 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8146 << Subobj.Kind << Subobj.Decl
8147 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8148 S.Diag(BestFD->getLocation(),
8149 diag::note_defaulted_comparison_cannot_deduce_callee)
8150 << Subobj.Kind << Subobj.Decl;
8151 }
8152 return Result::deleted();
8153 }
8154 R.Category = Info->Kind;
8155 }
8156 } else {
8157 QualType T = Best->BuiltinParamTypes[0];
8158 assert(T == Best->BuiltinParamTypes[1] &&
8159 "builtin comparison for different types?");
8160 assert(Best->BuiltinParamTypes[2].isNull() &&
8161 "invalid builtin comparison");
8162
8163 if (NeedsDeducing) {
8164 std::optional<ComparisonCategoryType> Cat =
8166 assert(Cat && "no category for builtin comparison?");
8167 R.Category = *Cat;
8168 }
8169 }
8170
8171 // Note that we might be rewriting to a different operator. That call is
8172 // not considered until we come to actually build the comparison function.
8173 break;
8174 }
8175
8176 case OR_Ambiguous:
8177 if (Diagnose == ExplainDeleted) {
8178 unsigned Kind = 0;
8179 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8180 Kind = OO == OO_EqualEqual ? 1 : 2;
8181 CandidateSet.NoteCandidates(
8183 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8184 << FD << Kind << Subobj.Kind << Subobj.Decl),
8185 S, OCD_AmbiguousCandidates, Args);
8186 }
8187 R = Result::deleted();
8188 break;
8189
8190 case OR_Deleted:
8191 if (Diagnose == ExplainDeleted) {
8192 if ((DCK == DefaultedComparisonKind::NotEqual ||
8193 DCK == DefaultedComparisonKind::Relational) &&
8194 !Best->RewriteKind) {
8195 S.Diag(Best->Function->getLocation(),
8196 diag::note_defaulted_comparison_not_rewritten_callee)
8197 << FD;
8198 } else {
8199 S.Diag(Subobj.Loc,
8200 diag::note_defaulted_comparison_calls_deleted)
8201 << FD << Subobj.Kind << Subobj.Decl;
8202 S.NoteDeletedFunction(Best->Function);
8203 }
8204 }
8205 R = Result::deleted();
8206 break;
8207
8209 // If there's no usable candidate, we're done unless we can rewrite a
8210 // '<=>' in terms of '==' and '<'.
8211 if (OO == OO_Spaceship &&
8213 // For any kind of comparison category return type, we need a usable
8214 // '==' and a usable '<'.
8215 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8216 &CandidateSet)))
8217 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8218 break;
8219 }
8220
8221 if (Diagnose == ExplainDeleted) {
8222 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8223 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8224 << Subobj.Kind << Subobj.Decl;
8225
8226 // For a three-way comparison, list both the candidates for the
8227 // original operator and the candidates for the synthesized operator.
8228 if (SpaceshipCandidates) {
8229 SpaceshipCandidates->NoteCandidates(
8230 S, Args,
8231 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8232 Args, FD->getLocation()));
8233 S.Diag(Subobj.Loc,
8234 diag::note_defaulted_comparison_no_viable_function_synthesized)
8235 << (OO == OO_EqualEqual ? 0 : 1);
8236 }
8237
8238 CandidateSet.NoteCandidates(
8239 S, Args,
8240 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8241 FD->getLocation()));
8242 }
8243 R = Result::deleted();
8244 break;
8245 }
8246
8247 return R;
8248 }
8249};
8250
8251/// A list of statements.
8252struct StmtListResult {
8253 bool IsInvalid = false;
8255
8256 bool add(const StmtResult &S) {
8257 IsInvalid |= S.isInvalid();
8258 if (IsInvalid)
8259 return true;
8260 Stmts.push_back(S.get());
8261 return false;
8262 }
8263};
8264
8265/// A visitor over the notional body of a defaulted comparison that synthesizes
8266/// the actual body.
8267class DefaultedComparisonSynthesizer
8268 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8269 StmtListResult, StmtResult,
8270 std::pair<ExprResult, ExprResult>> {
8272 unsigned ArrayDepth = 0;
8273
8274public:
8275 using Base = DefaultedComparisonVisitor;
8276 using ExprPair = std::pair<ExprResult, ExprResult>;
8277
8278 friend Base;
8279
8280 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8281 DefaultedComparisonKind DCK,
8282 SourceLocation BodyLoc)
8283 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8284
8285 /// Build a suitable function body for this defaulted comparison operator.
8286 StmtResult build() {
8287 Sema::CompoundScopeRAII CompoundScope(S);
8288
8289 StmtListResult Stmts = visit();
8290 if (Stmts.IsInvalid)
8291 return StmtError();
8292
8293 ExprResult RetVal;
8294 switch (DCK) {
8295 case DefaultedComparisonKind::None:
8296 llvm_unreachable("not a defaulted comparison");
8297
8298 case DefaultedComparisonKind::Equal: {
8299 // C++2a [class.eq]p3:
8300 // [...] compar[e] the corresponding elements [...] until the first
8301 // index i where xi == yi yields [...] false. If no such index exists,
8302 // V is true. Otherwise, V is false.
8303 //
8304 // Join the comparisons with '&&'s and return the result. Use a right
8305 // fold (traversing the conditions right-to-left), because that
8306 // short-circuits more naturally.
8307 auto OldStmts = std::move(Stmts.Stmts);
8308 Stmts.Stmts.clear();
8309 ExprResult CmpSoFar;
8310 // Finish a particular comparison chain.
8311 auto FinishCmp = [&] {
8312 if (Expr *Prior = CmpSoFar.get()) {
8313 // Convert the last expression to 'return ...;'
8314 if (RetVal.isUnset() && Stmts.Stmts.empty())
8315 RetVal = CmpSoFar;
8316 // Convert any prior comparison to 'if (!(...)) return false;'
8317 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8318 return true;
8319 CmpSoFar = ExprResult();
8320 }
8321 return false;
8322 };
8323 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8324 Expr *E = dyn_cast<Expr>(EAsStmt);
8325 if (!E) {
8326 // Found an array comparison.
8327 if (FinishCmp() || Stmts.add(EAsStmt))
8328 return StmtError();
8329 continue;
8330 }
8331
8332 if (CmpSoFar.isUnset()) {
8333 CmpSoFar = E;
8334 continue;
8335 }
8336 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8337 if (CmpSoFar.isInvalid())
8338 return StmtError();
8339 }
8340 if (FinishCmp())
8341 return StmtError();
8342 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8343 // If no such index exists, V is true.
8344 if (RetVal.isUnset())
8345 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8346 break;
8347 }
8348
8349 case DefaultedComparisonKind::ThreeWay: {
8350 // Per C++2a [class.spaceship]p3, as a fallback add:
8351 // return static_cast<R>(std::strong_ordering::equal);
8353 ComparisonCategoryType::StrongOrdering, Loc,
8354 Sema::ComparisonCategoryUsage::DefaultedOperator);
8355 if (StrongOrdering.isNull())
8356 return StmtError();
8358 .getValueInfo(ComparisonCategoryResult::Equal)
8359 ->VD;
8360 RetVal = getDecl(EqualVD);
8361 if (RetVal.isInvalid())
8362 return StmtError();
8363 RetVal = buildStaticCastToR(RetVal.get());
8364 break;
8365 }
8366
8367 case DefaultedComparisonKind::NotEqual:
8368 case DefaultedComparisonKind::Relational:
8369 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8370 break;
8371 }
8372
8373 // Build the final return statement.
8374 if (RetVal.isInvalid())
8375 return StmtError();
8377 if (ReturnStmt.isInvalid())
8378 return StmtError();
8379 Stmts.Stmts.push_back(ReturnStmt.get());
8380
8381 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8382 }
8383
8384private:
8385 ExprResult getDecl(ValueDecl *VD) {
8386 return S.BuildDeclarationNameExpr(
8388 }
8389
8390 ExprResult getParam(unsigned I) {
8391 ParmVarDecl *PD = FD->getParamDecl(I);
8392 return getDecl(PD);
8393 }
8394
8395 ExprPair getCompleteObject() {
8396 unsigned Param = 0;
8397 ExprResult LHS;
8398 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8399 MD && MD->isImplicitObjectMemberFunction()) {
8400 // LHS is '*this'.
8401 LHS = S.ActOnCXXThis(Loc);
8402 if (!LHS.isInvalid())
8403 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8404 } else {
8405 LHS = getParam(Param++);
8406 }
8407 ExprResult RHS = getParam(Param++);
8408 assert(Param == FD->getNumParams());
8409 return {LHS, RHS};
8410 }
8411
8412 ExprPair getBase(CXXBaseSpecifier *Base) {
8413 ExprPair Obj = getCompleteObject();
8414 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8415 return {ExprError(), ExprError()};
8416 CXXCastPath Path = {Base};
8417 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8418 CK_DerivedToBase, VK_LValue, &Path),
8419 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8420 CK_DerivedToBase, VK_LValue, &Path)};
8421 }
8422
8423 ExprPair getField(FieldDecl *Field) {
8424 ExprPair Obj = getCompleteObject();
8425 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8426 return {ExprError(), ExprError()};
8427
8428 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8429 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8430 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8431 CXXScopeSpec(), Field, Found, NameInfo),
8432 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8433 CXXScopeSpec(), Field, Found, NameInfo)};
8434 }
8435
8436 // FIXME: When expanding a subobject, register a note in the code synthesis
8437 // stack to say which subobject we're comparing.
8438
8439 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8440 if (Cond.isInvalid())
8441 return StmtError();
8442
8443 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8444 if (NotCond.isInvalid())
8445 return StmtError();
8446
8447 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8448 assert(!False.isInvalid() && "should never fail");
8449 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8450 if (ReturnFalse.isInvalid())
8451 return StmtError();
8452
8453 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8454 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8455 Sema::ConditionKind::Boolean),
8456 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8457 }
8458
8459 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8460 ExprPair Subobj) {
8461 QualType SizeType = S.Context.getSizeType();
8462 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8463
8464 // Build 'size_t i$n = 0'.
8465 IdentifierInfo *IterationVarName = nullptr;
8466 {
8467 SmallString<8> Str;
8468 llvm::raw_svector_ostream OS(Str);
8469 OS << "i" << ArrayDepth;
8470 IterationVarName = &S.Context.Idents.get(OS.str());
8471 }
8472 VarDecl *IterationVar = VarDecl::Create(
8473 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8475 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8476 IterationVar->setInit(
8477 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8478 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8479
8480 auto IterRef = [&] {
8482 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8483 IterationVar);
8484 assert(!Ref.isInvalid() && "can't reference our own variable?");
8485 return Ref.get();
8486 };
8487
8488 // Build 'i$n != Size'.
8490 Loc, BO_NE, IterRef(),
8491 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8492 assert(!Cond.isInvalid() && "should never fail");
8493
8494 // Build '++i$n'.
8495 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8496 assert(!Inc.isInvalid() && "should never fail");
8497
8498 // Build 'a[i$n]' and 'b[i$n]'.
8499 auto Index = [&](ExprResult E) {
8500 if (E.isInvalid())
8501 return ExprError();
8502 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8503 };
8504 Subobj.first = Index(Subobj.first);
8505 Subobj.second = Index(Subobj.second);
8506
8507 // Compare the array elements.
8508 ++ArrayDepth;
8509 StmtResult Substmt = visitSubobject(Type, Subobj);
8510 --ArrayDepth;
8511
8512 if (Substmt.isInvalid())
8513 return StmtError();
8514
8515 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8516 // For outer levels or for an 'operator<=>' we already have a suitable
8517 // statement that returns as necessary.
8518 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8519 assert(DCK == DefaultedComparisonKind::Equal &&
8520 "should have non-expression statement");
8521 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8522 if (Substmt.isInvalid())
8523 return StmtError();
8524 }
8525
8526 // Build 'for (...) ...'
8527 return S.ActOnForStmt(Loc, Loc, Init,
8528 S.ActOnCondition(nullptr, Loc, Cond.get(),
8529 Sema::ConditionKind::Boolean),
8531 Substmt.get());
8532 }
8533
8534 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8535 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8536 return StmtError();
8537
8540 ExprResult Op;
8541 if (Type->isOverloadableType())
8542 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8543 Obj.second.get(), /*PerformADL=*/true,
8544 /*AllowRewrittenCandidates=*/true, FD);
8545 else
8546 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8547 if (Op.isInvalid())
8548 return StmtError();
8549
8550 switch (DCK) {
8551 case DefaultedComparisonKind::None:
8552 llvm_unreachable("not a defaulted comparison");
8553
8554 case DefaultedComparisonKind::Equal:
8555 // Per C++2a [class.eq]p2, each comparison is individually contextually
8556 // converted to bool.
8558 if (Op.isInvalid())
8559 return StmtError();
8560 return Op.get();
8561
8562 case DefaultedComparisonKind::ThreeWay: {
8563 // Per C++2a [class.spaceship]p3, form:
8564 // if (R cmp = static_cast<R>(op); cmp != 0)
8565 // return cmp;
8566 QualType R = FD->getReturnType();
8567 Op = buildStaticCastToR(Op.get());
8568 if (Op.isInvalid())
8569 return StmtError();
8570
8571 // R cmp = ...;
8572 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8573 VarDecl *VD =
8574 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8576 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8577 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8578
8579 // cmp != 0
8580 ExprResult VDRef = getDecl(VD);
8581 if (VDRef.isInvalid())
8582 return StmtError();
8583 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8584 Expr *Zero =
8587 if (VDRef.get()->getType()->isOverloadableType())
8588 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8589 true, FD);
8590 else
8591 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8592 if (Comp.isInvalid())
8593 return StmtError();
8595 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8596 if (Cond.isInvalid())
8597 return StmtError();
8598
8599 // return cmp;
8600 VDRef = getDecl(VD);
8601 if (VDRef.isInvalid())
8602 return StmtError();
8604 if (ReturnStmt.isInvalid())
8605 return StmtError();
8606
8607 // if (...)
8608 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8609 Loc, ReturnStmt.get(),
8610 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8611 }
8612
8613 case DefaultedComparisonKind::NotEqual:
8614 case DefaultedComparisonKind::Relational:
8615 // C++2a [class.compare.secondary]p2:
8616 // Otherwise, the operator function yields x @ y.
8617 return Op.get();
8618 }
8619 llvm_unreachable("");
8620 }
8621
8622 /// Build "static_cast<R>(E)".
8623 ExprResult buildStaticCastToR(Expr *E) {
8624 QualType R = FD->getReturnType();
8625 assert(!R->isUndeducedType() && "type should have been deduced already");
8626
8627 // Don't bother forming a no-op cast in the common case.
8628 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8629 return E;
8630 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8633 }
8634};
8635}
8636
8637/// Perform the unqualified lookups that might be needed to form a defaulted
8638/// comparison function for the given operator.
8640 UnresolvedSetImpl &Operators,
8642 auto Lookup = [&](OverloadedOperatorKind OO) {
8643 Self.LookupOverloadedOperatorName(OO, S, Operators);
8644 };
8645
8646 // Every defaulted operator looks up itself.
8647 Lookup(Op);
8648 // ... and the rewritten form of itself, if any.
8650 Lookup(ExtraOp);
8651
8652 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8653 // synthesize a three-way comparison from '<' and '=='. In a dependent
8654 // context, we also need to look up '==' in case we implicitly declare a
8655 // defaulted 'operator=='.
8656 if (Op == OO_Spaceship) {
8657 Lookup(OO_ExclaimEqual);
8658 Lookup(OO_Less);
8659 Lookup(OO_EqualEqual);
8660 }
8661}
8662
8665 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8666
8667 // Perform any unqualified lookups we're going to need to default this
8668 // function.
8669 if (S) {
8670 UnresolvedSet<32> Operators;
8671 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8672 FD->getOverloadedOperator());
8675 Context, Operators.pairs()));
8676 }
8677
8678 // C++2a [class.compare.default]p1:
8679 // A defaulted comparison operator function for some class C shall be a
8680 // non-template function declared in the member-specification of C that is
8681 // -- a non-static const non-volatile member of C having one parameter of
8682 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8683 // -- a friend of C having two parameters of type const C& or two
8684 // parameters of type C.
8685
8686 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8687 bool IsMethod = isa<CXXMethodDecl>(FD);
8688 if (IsMethod) {
8689 auto *MD = cast<CXXMethodDecl>(FD);
8690 assert(!MD->isStatic() && "comparison function cannot be a static member");
8691
8692 if (MD->getRefQualifier() == RQ_RValue) {
8693 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8694
8695 // Remove the ref qualifier to recover.
8696 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8697 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8698 EPI.RefQualifier = RQ_None;
8699 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8700 FPT->getParamTypes(), EPI));
8701 }
8702
8703 // If we're out-of-class, this is the class we're comparing.
8704 if (!RD)
8705 RD = MD->getParent();
8707 if (!T.isConstQualified()) {
8708 SourceLocation Loc, InsertLoc;
8710 Loc = MD->getParamDecl(0)->getBeginLoc();
8711 InsertLoc = getLocForEndOfToken(
8713 } else {
8714 Loc = MD->getLocation();
8716 InsertLoc = Loc.getRParenLoc();
8717 }
8718 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8719 // corresponding defaulted 'operator<=>' already.
8720 if (!MD->isImplicit()) {
8721 Diag(Loc, diag::err_defaulted_comparison_non_const)
8722 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8723 }
8724
8725 // Add the 'const' to the type to recover.
8726 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8727 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8728 EPI.TypeQuals.addConst();
8729 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8730 FPT->getParamTypes(), EPI));
8731 }
8732
8733 if (MD->isVolatile()) {
8734 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8735
8736 // Remove the 'volatile' from the type to recover.
8737 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8738 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8740 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8741 FPT->getParamTypes(), EPI));
8742 }
8743 }
8744
8745 if ((FD->getNumParams() -
8746 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8747 (IsMethod ? 1 : 2)) {
8748 // Let's not worry about using a variadic template pack here -- who would do
8749 // such a thing?
8750 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8751 << int(IsMethod) << int(DCK);
8752 return true;
8753 }
8754
8755 const ParmVarDecl *KnownParm = nullptr;
8756 for (const ParmVarDecl *Param : FD->parameters()) {
8757 if (Param->isExplicitObjectParameter())
8758 continue;
8759 QualType ParmTy = Param->getType();
8760
8761 if (!KnownParm) {
8762 auto CTy = ParmTy;
8763 // Is it `T const &`?
8764 bool Ok = !IsMethod;
8765 QualType ExpectedTy;
8766 if (RD)
8767 ExpectedTy = Context.getRecordType(RD);
8768 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8769 CTy = Ref->getPointeeType();
8770 if (RD)
8771 ExpectedTy.addConst();
8772 Ok = true;
8773 }
8774
8775 // Is T a class?
8776 if (!Ok) {
8777 } else if (RD) {
8778 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8779 Ok = false;
8780 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8781 RD = cast<CXXRecordDecl>(CRD);
8782 } else {
8783 Ok = false;
8784 }
8785
8786 if (Ok) {
8787 KnownParm = Param;
8788 } else {
8789 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8790 // corresponding defaulted 'operator<=>' already.
8791 if (!FD->isImplicit()) {
8792 if (RD) {
8793 QualType PlainTy = Context.getRecordType(RD);
8794 QualType RefTy =
8796 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8797 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8798 << Param->getSourceRange();
8799 } else {
8800 assert(!IsMethod && "should know expected type for method");
8801 Diag(FD->getLocation(),
8802 diag::err_defaulted_comparison_param_unknown)
8803 << int(DCK) << ParmTy << Param->getSourceRange();
8804 }
8805 }
8806 return true;
8807 }
8808 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8809 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8810 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8811 << ParmTy << Param->getSourceRange();
8812 return true;
8813 }
8814 }
8815
8816 assert(RD && "must have determined class");
8817 if (IsMethod) {
8818 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8819 // In-class, must be a friend decl.
8820 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8821 } else {
8822 // Out of class, require the defaulted comparison to be a friend (of a
8823 // complete type).
8825 diag::err_defaulted_comparison_not_friend, int(DCK),
8826 int(1)))
8827 return true;
8828
8829 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8830 return FD->getCanonicalDecl() ==
8831 F->getFriendDecl()->getCanonicalDecl();
8832 })) {
8833 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8834 << int(DCK) << int(0) << RD;
8835 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8836 return true;
8837 }
8838 }
8839
8840 // C++2a [class.eq]p1, [class.rel]p1:
8841 // A [defaulted comparison other than <=>] shall have a declared return
8842 // type bool.
8846 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8847 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8848 << FD->getReturnTypeSourceRange();
8849 return true;
8850 }
8851 // C++2a [class.spaceship]p2 [P2002R0]:
8852 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8853 // R shall not contain a placeholder type.
8854 if (QualType RT = FD->getDeclaredReturnType();
8856 RT->getContainedDeducedType() &&
8858 RT->getContainedAutoType()->isConstrained())) {
8859 Diag(FD->getLocation(),
8860 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8861 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8862 << FD->getReturnTypeSourceRange();
8863 return true;
8864 }
8865
8866 // For a defaulted function in a dependent class, defer all remaining checks
8867 // until instantiation.
8868 if (RD->isDependentType())
8869 return false;
8870
8871 // Determine whether the function should be defined as deleted.
8872 DefaultedComparisonInfo Info =
8873 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8874
8875 bool First = FD == FD->getCanonicalDecl();
8876
8877 if (!First) {
8878 if (Info.Deleted) {
8879 // C++11 [dcl.fct.def.default]p4:
8880 // [For a] user-provided explicitly-defaulted function [...] if such a
8881 // function is implicitly defined as deleted, the program is ill-formed.
8882 //
8883 // This is really just a consequence of the general rule that you can
8884 // only delete a function on its first declaration.
8885 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8886 << FD->isImplicit() << (int)DCK;
8887 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8888 DefaultedComparisonAnalyzer::ExplainDeleted)
8889 .visit();
8890 return true;
8891 }
8892 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8893 // C++20 [class.compare.default]p1:
8894 // [...] A definition of a comparison operator as defaulted that appears
8895 // in a class shall be the first declaration of that function.
8896 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8897 << (int)DCK;
8899 diag::note_previous_declaration);
8900 return true;
8901 }
8902 }
8903
8904 // If we want to delete the function, then do so; there's nothing else to
8905 // check in that case.
8906 if (Info.Deleted) {
8907 SetDeclDeleted(FD, FD->getLocation());
8908 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8909 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8910 << (int)DCK;
8911 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8912 DefaultedComparisonAnalyzer::ExplainDeleted)
8913 .visit();
8914 if (FD->getDefaultLoc().isValid())
8915 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8916 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8917 }
8918 return false;
8919 }
8920
8921 // C++2a [class.spaceship]p2:
8922 // The return type is deduced as the common comparison type of R0, R1, ...
8926 if (RetLoc.isInvalid())
8927 RetLoc = FD->getBeginLoc();
8928 // FIXME: Should we really care whether we have the complete type and the
8929 // 'enumerator' constants here? A forward declaration seems sufficient.
8931 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8932 if (Cat.isNull())
8933 return true;
8935 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8936 }
8937
8938 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8939 // An explicitly-defaulted function that is not defined as deleted may be
8940 // declared constexpr or consteval only if it is constexpr-compatible.
8941 // C++2a [class.compare.default]p3 [P2002R0]:
8942 // A defaulted comparison function is constexpr-compatible if it satisfies
8943 // the requirements for a constexpr function [...]
8944 // The only relevant requirements are that the parameter and return types are
8945 // literal types. The remaining conditions are checked by the analyzer.
8946 //
8947 // We support P2448R2 in language modes earlier than C++23 as an extension.
8948 // The concept of constexpr-compatible was removed.
8949 // C++23 [dcl.fct.def.default]p3 [P2448R2]
8950 // A function explicitly defaulted on its first declaration is implicitly
8951 // inline, and is implicitly constexpr if it is constexpr-suitable.
8952 // C++23 [dcl.constexpr]p3
8953 // A function is constexpr-suitable if
8954 // - it is not a coroutine, and
8955 // - if the function is a constructor or destructor, its class does not
8956 // have any virtual base classes.
8957 if (FD->isConstexpr()) {
8958 if (!getLangOpts().CPlusPlus23 &&
8961 !Info.Constexpr) {
8962 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
8963 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8964 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8965 DefaultedComparisonAnalyzer::ExplainConstexpr)
8966 .visit();
8967 }
8968 }
8969
8970 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8971 // If a constexpr-compatible function is explicitly defaulted on its first
8972 // declaration, it is implicitly considered to be constexpr.
8973 // FIXME: Only applying this to the first declaration seems problematic, as
8974 // simple reorderings can affect the meaning of the program.
8975 if (First && !FD->isConstexpr() && Info.Constexpr)
8977
8978 // C++2a [except.spec]p3:
8979 // If a declaration of a function does not have a noexcept-specifier
8980 // [and] is defaulted on its first declaration, [...] the exception
8981 // specification is as specified below
8982 if (FD->getExceptionSpecType() == EST_None) {
8983 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8984 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8986 EPI.ExceptionSpec.SourceDecl = FD;
8987 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8988 FPT->getParamTypes(), EPI));
8989 }
8990
8991 return false;
8992}
8993
8995 FunctionDecl *Spaceship) {
8998 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8999 Ctx.Entity = Spaceship;
9001
9002 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9003 EqualEqual->setImplicit();
9004
9006}
9007
9010 assert(FD->isDefaulted() && !FD->isDeleted() &&
9012 if (FD->willHaveBody() || FD->isInvalidDecl())
9013 return;
9014
9016
9017 // Add a context note for diagnostics produced after this point.
9018 Scope.addContextNote(UseLoc);
9019
9020 {
9021 // Build and set up the function body.
9022 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9023 // the type of the class being compared.
9024 auto PT = FD->getParamDecl(0)->getType();
9025 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9026 SourceLocation BodyLoc =
9027 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9028 StmtResult Body =
9029 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9030 if (Body.isInvalid()) {
9031 FD->setInvalidDecl();
9032 return;
9033 }
9034 FD->setBody(Body.get());
9035 FD->markUsed(Context);
9036 }
9037
9038 // The exception specification is needed because we are defining the
9039 // function. Note that this will reuse the body we just built.
9041
9043 L->CompletedImplicitDefinition(FD);
9044}
9045
9048 FunctionDecl *FD,
9050 ComputingExceptionSpec CES(S, FD, Loc);
9052
9053 if (FD->isInvalidDecl())
9054 return ExceptSpec;
9055
9056 // The common case is that we just defined the comparison function. In that
9057 // case, just look at whether the body can throw.
9058 if (FD->hasBody()) {
9059 ExceptSpec.CalledStmt(FD->getBody());
9060 } else {
9061 // Otherwise, build a body so we can check it. This should ideally only
9062 // happen when we're not actually marking the function referenced. (This is
9063 // only really important for efficiency: we don't want to build and throw
9064 // away bodies for comparison functions more than we strictly need to.)
9065
9066 // Pretend to synthesize the function body in an unevaluated context.
9067 // Note that we can't actually just go ahead and define the function here:
9068 // we are not permitted to mark its callees as referenced.
9072
9073 CXXRecordDecl *RD =
9074 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9075 ? FD->getDeclContext()
9076 : FD->getLexicalDeclContext());
9077 SourceLocation BodyLoc =
9078 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9079 StmtResult Body =
9080 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9081 if (!Body.isInvalid())
9082 ExceptSpec.CalledStmt(Body.get());
9083
9084 // FIXME: Can we hold onto this body and just transform it to potentially
9085 // evaluated when we're asked to define the function rather than rebuilding
9086 // it? Either that, or we should only build the bits of the body that we
9087 // need (the expressions, not the statements).
9088 }
9089
9090 return ExceptSpec;
9091}
9092
9094 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9096
9097 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9099
9100 // Perform any deferred checking of exception specifications for virtual
9101 // destructors.
9102 for (auto &Check : Overriding)
9103 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9104
9105 // Perform any deferred checking of exception specifications for befriended
9106 // special members.
9107 for (auto &Check : Equivalent)
9108 CheckEquivalentExceptionSpec(Check.second, Check.first);
9109}
9110
9111namespace {
9112/// CRTP base class for visiting operations performed by a special member
9113/// function (or inherited constructor).
9114template<typename Derived>
9115struct SpecialMemberVisitor {
9116 Sema &S;
9117 CXXMethodDecl *MD;
9120
9121 // Properties of the special member, computed for convenience.
9122 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9123
9124 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9126 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9127 switch (CSM) {
9128 case CXXSpecialMemberKind::DefaultConstructor:
9129 case CXXSpecialMemberKind::CopyConstructor:
9130 case CXXSpecialMemberKind::MoveConstructor:
9131 IsConstructor = true;
9132 break;
9133 case CXXSpecialMemberKind::CopyAssignment:
9134 case CXXSpecialMemberKind::MoveAssignment:
9135 IsAssignment = true;
9136 break;
9137 case CXXSpecialMemberKind::Destructor:
9138 break;
9139 case CXXSpecialMemberKind::Invalid:
9140 llvm_unreachable("invalid special member kind");
9141 }
9142
9143 if (MD->getNumExplicitParams()) {
9144 if (const ReferenceType *RT =
9146 ConstArg = RT->getPointeeType().isConstQualified();
9147 }
9148 }
9149
9150 Derived &getDerived() { return static_cast<Derived&>(*this); }
9151
9152 /// Is this a "move" special member?
9153 bool isMove() const {
9154 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9155 CSM == CXXSpecialMemberKind::MoveAssignment;
9156 }
9157
9158 /// Look up the corresponding special member in the given class.
9160 unsigned Quals, bool IsMutable) {
9161 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9162 ConstArg && !IsMutable);
9163 }
9164
9165 /// Look up the constructor for the specified base class to see if it's
9166 /// overridden due to this being an inherited constructor.
9167 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9168 if (!ICI)
9169 return {};
9170 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9171 auto *BaseCtor =
9172 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9173 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9174 return MD;
9175 return {};
9176 }
9177
9178 /// A base or member subobject.
9179 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9180
9181 /// Get the location to use for a subobject in diagnostics.
9182 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9183 // FIXME: For an indirect virtual base, the direct base leading to
9184 // the indirect virtual base would be a more useful choice.
9185 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9186 return B->getBaseTypeLoc();
9187 else
9188 return Subobj.get<FieldDecl*>()->getLocation();
9189 }
9190
9191 enum BasesToVisit {
9192 /// Visit all non-virtual (direct) bases.
9193 VisitNonVirtualBases,
9194 /// Visit all direct bases, virtual or not.
9195 VisitDirectBases,
9196 /// Visit all non-virtual bases, and all virtual bases if the class
9197 /// is not abstract.
9198 VisitPotentiallyConstructedBases,
9199 /// Visit all direct or virtual bases.
9200 VisitAllBases
9201 };
9202
9203 // Visit the bases and members of the class.
9204 bool visit(BasesToVisit Bases) {
9205 CXXRecordDecl *RD = MD->getParent();
9206
9207 if (Bases == VisitPotentiallyConstructedBases)
9208 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9209
9210 for (auto &B : RD->bases())
9211 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9212 getDerived().visitBase(&B))
9213 return true;
9214
9215 if (Bases == VisitAllBases)
9216 for (auto &B : RD->vbases())
9217 if (getDerived().visitBase(&B))
9218 return true;
9219
9220 for (auto *F : RD->fields())
9221 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9222 getDerived().visitField(F))
9223 return true;
9224
9225 return false;
9226 }
9227};
9228}
9229
9230namespace {
9231struct SpecialMemberDeletionInfo
9232 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9233 bool Diagnose;
9234
9236
9237 bool AllFieldsAreConst;
9238
9239 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9241 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9242 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9243 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9244
9245 bool inUnion() const { return MD->getParent()->isUnion(); }
9246
9247 CXXSpecialMemberKind getEffectiveCSM() {
9248 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9249 }
9250
9251 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9252
9253 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9254 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9255
9256 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9257 bool shouldDeleteForField(FieldDecl *FD);
9258 bool shouldDeleteForAllConstMembers();
9259
9260 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9261 unsigned Quals);
9262 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9264 bool IsDtorCallInCtor);
9265
9266 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9267};
9268}
9269
9270/// Is the given special member inaccessible when used on the given
9271/// sub-object.
9272bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9273 CXXMethodDecl *target) {
9274 /// If we're operating on a base class, the object type is the
9275 /// type of this special member.
9276 QualType objectTy;
9277 AccessSpecifier access = target->getAccess();
9278 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9279 objectTy = S.Context.getTypeDeclType(MD->getParent());
9280 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9281
9282 // If we're operating on a field, the object type is the type of the field.
9283 } else {
9284 objectTy = S.Context.getTypeDeclType(target->getParent());
9285 }
9286
9288 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9289}
9290
9291/// Check whether we should delete a special member due to the implicit
9292/// definition containing a call to a special member of a subobject.
9293bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9294 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9295 bool IsDtorCallInCtor) {
9296 CXXMethodDecl *Decl = SMOR.getMethod();
9297 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9298
9299 int DiagKind = -1;
9300
9302 DiagKind = !Decl ? 0 : 1;
9304 DiagKind = 2;
9305 else if (!isAccessible(Subobj, Decl))
9306 DiagKind = 3;
9307 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9308 !Decl->isTrivial()) {
9309 // A member of a union must have a trivial corresponding special member.
9310 // As a weird special case, a destructor call from a union's constructor
9311 // must be accessible and non-deleted, but need not be trivial. Such a
9312 // destructor is never actually called, but is semantically checked as
9313 // if it were.
9315 // [class.default.ctor]p2:
9316 // A defaulted default constructor for class X is defined as deleted if
9317 // - X is a union that has a variant member with a non-trivial default
9318 // constructor and no variant member of X has a default member
9319 // initializer
9320 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9321 if (!RD->hasInClassInitializer())
9322 DiagKind = 4;
9323 } else {
9324 DiagKind = 4;
9325 }
9326 }
9327
9328 if (DiagKind == -1)
9329 return false;
9330
9331 if (Diagnose) {
9332 if (Field) {
9333 S.Diag(Field->getLocation(),
9334 diag::note_deleted_special_member_class_subobject)
9335 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9336 << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9337 << /*IsObjCPtr*/ false;
9338 } else {
9339 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9340 S.Diag(Base->getBeginLoc(),
9341 diag::note_deleted_special_member_class_subobject)
9342 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9343 << /*IsField*/ false << Base->getType() << DiagKind
9344 << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9345 }
9346
9347 if (DiagKind == 1)
9349 // FIXME: Explain inaccessibility if DiagKind == 3.
9350 }
9351
9352 return true;
9353}
9354
9355/// Check whether we should delete a special member function due to having a
9356/// direct or virtual base class or non-static data member of class type M.
9357bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9358 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9359 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9360 bool IsMutable = Field && Field->isMutable();
9361
9362 // C++11 [class.ctor]p5:
9363 // -- any direct or virtual base class, or non-static data member with no
9364 // brace-or-equal-initializer, has class type M (or array thereof) and
9365 // either M has no default constructor or overload resolution as applied
9366 // to M's default constructor results in an ambiguity or in a function
9367 // that is deleted or inaccessible
9368 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9369 // -- a direct or virtual base class B that cannot be copied/moved because
9370 // overload resolution, as applied to B's corresponding special member,
9371 // results in an ambiguity or a function that is deleted or inaccessible
9372 // from the defaulted special member
9373 // C++11 [class.dtor]p5:
9374 // -- any direct or virtual base class [...] has a type with a destructor
9375 // that is deleted or inaccessible
9376 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9377 Field->hasInClassInitializer()) &&
9378 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9379 false))
9380 return true;
9381
9382 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9383 // -- any direct or virtual base class or non-static data member has a
9384 // type with a destructor that is deleted or inaccessible
9385 if (IsConstructor) {
9388 false, false, false, false);
9389 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9390 return true;
9391 }
9392
9393 return false;
9394}
9395
9396bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9397 FieldDecl *FD, QualType FieldType) {
9398 // The defaulted special functions are defined as deleted if this is a variant
9399 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9400 // type under ARC.
9401 if (!FieldType.hasNonTrivialObjCLifetime())
9402 return false;
9403
9404 // Don't make the defaulted default constructor defined as deleted if the
9405 // member has an in-class initializer.
9408 return false;
9409
9410 if (Diagnose) {
9411 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9412 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9413 << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9414 << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9415 << /*IsObjCPtr*/ true;
9416 }
9417
9418 return true;
9419}
9420
9421/// Check whether we should delete a special member function due to the class
9422/// having a particular direct or virtual base class.
9423bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9424 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9425 // If program is correct, BaseClass cannot be null, but if it is, the error
9426 // must be reported elsewhere.
9427 if (!BaseClass)
9428 return false;
9429 // If we have an inheriting constructor, check whether we're calling an
9430 // inherited constructor instead of a default constructor.
9431 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9432 if (auto *BaseCtor = SMOR.getMethod()) {
9433 // Note that we do not check access along this path; other than that,
9434 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9435 // FIXME: Check that the base has a usable destructor! Sink this into
9436 // shouldDeleteForClassSubobject.
9437 if (BaseCtor->isDeleted() && Diagnose) {
9438 S.Diag(Base->getBeginLoc(),
9439 diag::note_deleted_special_member_class_subobject)
9440 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9441 << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9442 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9443 S.NoteDeletedFunction(BaseCtor);
9444 }
9445 return BaseCtor->isDeleted();
9446 }
9447 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9448}
9449
9450/// Check whether we should delete a special member function due to the class
9451/// having a particular non-static data member.
9452bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9453 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9454 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9455
9456 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9457 return true;
9458
9460 // For a default constructor, all references must be initialized in-class
9461 // and, if a union, it must have a non-const member.
9462 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9463 if (Diagnose)
9464 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9465 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9466 return true;
9467 }
9468 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9469 // data member of const-qualified type (or array thereof) with no
9470 // brace-or-equal-initializer is not const-default-constructible.
9471 if (!inUnion() && FieldType.isConstQualified() &&
9472 !FD->hasInClassInitializer() &&
9473 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9474 if (Diagnose)
9475 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9476 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9477 return true;
9478 }
9479
9480 if (inUnion() && !FieldType.isConstQualified())
9481 AllFieldsAreConst = false;
9482 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9483 // For a copy constructor, data members must not be of rvalue reference
9484 // type.
9485 if (FieldType->isRValueReferenceType()) {
9486 if (Diagnose)
9487 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9488 << MD->getParent() << FD << FieldType;
9489 return true;
9490 }
9491 } else if (IsAssignment) {
9492 // For an assignment operator, data members must not be of reference type.
9493 if (FieldType->isReferenceType()) {
9494 if (Diagnose)
9495 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9496 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9497 return true;
9498 }
9499 if (!FieldRecord && FieldType.isConstQualified()) {
9500 // C++11 [class.copy]p23:
9501 // -- a non-static data member of const non-class type (or array thereof)
9502 if (Diagnose)
9503 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9504 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9505 return true;
9506 }
9507 }
9508
9509 if (FieldRecord) {
9510 // Some additional restrictions exist on the variant members.
9511 if (!inUnion() && FieldRecord->isUnion() &&
9512 FieldRecord->isAnonymousStructOrUnion()) {
9513 bool AllVariantFieldsAreConst = true;
9514
9515 // FIXME: Handle anonymous unions declared within anonymous unions.
9516 for (auto *UI : FieldRecord->fields()) {
9517 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9518
9519 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9520 return true;
9521
9522 if (!UnionFieldType.isConstQualified())
9523 AllVariantFieldsAreConst = false;
9524
9525 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9526 if (UnionFieldRecord &&
9527 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9528 UnionFieldType.getCVRQualifiers()))
9529 return true;
9530 }
9531
9532 // At least one member in each anonymous union must be non-const
9534 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9535 if (Diagnose)
9536 S.Diag(FieldRecord->getLocation(),
9537 diag::note_deleted_default_ctor_all_const)
9538 << !!ICI << MD->getParent() << /*anonymous union*/1;
9539 return true;
9540 }
9541
9542 // Don't check the implicit member of the anonymous union type.
9543 // This is technically non-conformant but supported, and we have a
9544 // diagnostic for this elsewhere.
9545 return false;
9546 }
9547
9548 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9549 FieldType.getCVRQualifiers()))
9550 return true;
9551 }
9552
9553 return false;
9554}
9555
9556/// C++11 [class.ctor] p5:
9557/// A defaulted default constructor for a class X is defined as deleted if
9558/// X is a union and all of its variant members are of const-qualified type.
9559bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9560 // This is a silly definition, because it gives an empty union a deleted
9561 // default constructor. Don't do that.
9562 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9563 AllFieldsAreConst) {
9564 bool AnyFields = false;
9565 for (auto *F : MD->getParent()->fields())
9566 if ((AnyFields = !F->isUnnamedBitField()))
9567 break;
9568 if (!AnyFields)
9569 return false;
9570 if (Diagnose)
9571 S.Diag(MD->getParent()->getLocation(),
9572 diag::note_deleted_default_ctor_all_const)
9573 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9574 return true;
9575 }
9576 return false;
9577}
9578
9579/// Determine whether a defaulted special member function should be defined as
9580/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9581/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9585 bool Diagnose) {
9586 if (MD->isInvalidDecl())
9587 return false;
9588 CXXRecordDecl *RD = MD->getParent();
9589 assert(!RD->isDependentType() && "do deletion after instantiation");
9590 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9591 RD->isInvalidDecl())
9592 return false;
9593
9594 // C++11 [expr.lambda.prim]p19:
9595 // The closure type associated with a lambda-expression has a
9596 // deleted (8.4.3) default constructor and a deleted copy
9597 // assignment operator.
9598 // C++2a adds back these operators if the lambda has no lambda-capture.
9602 if (Diagnose)
9603 Diag(RD->getLocation(), diag::note_lambda_decl);
9604 return true;
9605 }
9606
9607 // For an anonymous struct or union, the copy and assignment special members
9608 // will never be used, so skip the check. For an anonymous union declared at
9609 // namespace scope, the constructor and destructor are used.
9612 return false;
9613
9614 // C++11 [class.copy]p7, p18:
9615 // If the class definition declares a move constructor or move assignment
9616 // operator, an implicitly declared copy constructor or copy assignment
9617 // operator is defined as deleted.
9620 CXXMethodDecl *UserDeclaredMove = nullptr;
9621
9622 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9623 // deletion of the corresponding copy operation, not both copy operations.
9624 // MSVC 2015 has adopted the standards conforming behavior.
9625 bool DeletesOnlyMatchingCopy =
9626 getLangOpts().MSVCCompat &&
9628
9630 (!DeletesOnlyMatchingCopy ||
9632 if (!Diagnose) return true;
9633
9634 // Find any user-declared move constructor.
9635 for (auto *I : RD->ctors()) {
9636 if (I->isMoveConstructor()) {
9637 UserDeclaredMove = I;
9638 break;
9639 }
9640 }
9641 assert(UserDeclaredMove);
9642 } else if (RD->hasUserDeclaredMoveAssignment() &&
9643 (!DeletesOnlyMatchingCopy ||
9645 if (!Diagnose) return true;
9646
9647 // Find any user-declared move assignment operator.
9648 for (auto *I : RD->methods()) {
9649 if (I->isMoveAssignmentOperator()) {
9650 UserDeclaredMove = I;
9651 break;
9652 }
9653 }
9654 assert(UserDeclaredMove);
9655 }
9656
9657 if (UserDeclaredMove) {
9658 Diag(UserDeclaredMove->getLocation(),
9659 diag::note_deleted_copy_user_declared_move)
9660 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9661 << UserDeclaredMove->isMoveAssignmentOperator();
9662 return true;
9663 }
9664 }
9665
9666 // Do access control from the special member function
9667 ContextRAII MethodContext(*this, MD);
9668
9669 // C++11 [class.dtor]p5:
9670 // -- for a virtual destructor, lookup of the non-array deallocation function
9671 // results in an ambiguity or in a function that is deleted or inaccessible
9672 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9673 FunctionDecl *OperatorDelete = nullptr;
9674 DeclarationName Name =
9676 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9677 OperatorDelete, /*Diagnose*/false)) {
9678 if (Diagnose)
9679 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9680 return true;
9681 }
9682 }
9683
9684 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9685
9686 // Per DR1611, do not consider virtual bases of constructors of abstract
9687 // classes, since we are not going to construct them.
9688 // Per DR1658, do not consider virtual bases of destructors of abstract
9689 // classes either.
9690 // Per DR2180, for assignment operators we only assign (and thus only
9691 // consider) direct bases.
9692 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9693 : SMI.VisitPotentiallyConstructedBases))
9694 return true;
9695
9696 if (SMI.shouldDeleteForAllConstMembers())
9697 return true;
9698
9699 if (getLangOpts().CUDA) {
9700 // We should delete the special member in CUDA mode if target inference
9701 // failed.
9702 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9703 // is treated as certain special member, which may not reflect what special
9704 // member MD really is. However inferTargetForImplicitSpecialMember
9705 // expects CSM to match MD, therefore recalculate CSM.
9706 assert(ICI || CSM == getSpecialMember(MD));
9707 auto RealCSM = CSM;
9708 if (ICI)
9709 RealCSM = getSpecialMember(MD);
9710
9711 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9712 SMI.ConstArg, Diagnose);
9713 }
9714
9715 return false;
9716}
9717
9720 assert(DFK && "not a defaultable function");
9721 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9722
9723 if (DFK.isSpecialMember()) {
9724 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9725 nullptr, /*Diagnose=*/true);
9726 } else {
9727 DefaultedComparisonAnalyzer(
9728 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9729 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9730 .visit();
9731 }
9732}
9733
9734/// Perform lookup for a special member of the specified kind, and determine
9735/// whether it is trivial. If the triviality can be determined without the
9736/// lookup, skip it. This is intended for use when determining whether a
9737/// special member of a containing object is trivial, and thus does not ever
9738/// perform overload resolution for default constructors.
9739///
9740/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9741/// member that was most likely to be intended to be trivial, if any.
9742///
9743/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9744/// determine whether the special member is trivial.
9746 CXXSpecialMemberKind CSM, unsigned Quals,
9747 bool ConstRHS,
9749 CXXMethodDecl **Selected) {
9750 if (Selected)
9751 *Selected = nullptr;
9752
9753 switch (CSM) {
9755 llvm_unreachable("not a special member");
9756
9758 // C++11 [class.ctor]p5:
9759 // A default constructor is trivial if:
9760 // - all the [direct subobjects] have trivial default constructors
9761 //
9762 // Note, no overload resolution is performed in this case.
9764 return true;
9765
9766 if (Selected) {
9767 // If there's a default constructor which could have been trivial, dig it
9768 // out. Otherwise, if there's any user-provided default constructor, point
9769 // to that as an example of why there's not a trivial one.
9770 CXXConstructorDecl *DefCtor = nullptr;
9773 for (auto *CI : RD->ctors()) {
9774 if (!CI->isDefaultConstructor())
9775 continue;
9776 DefCtor = CI;
9777 if (!DefCtor->isUserProvided())
9778 break;
9779 }
9780
9781 *Selected = DefCtor;
9782 }
9783
9784 return false;
9785
9787 // C++11 [class.dtor]p5:
9788 // A destructor is trivial if:
9789 // - all the direct [subobjects] have trivial destructors
9790 if (RD->hasTrivialDestructor() ||
9793 return true;
9794
9795 if (Selected) {
9796 if (RD->needsImplicitDestructor())
9798 *Selected = RD->getDestructor();
9799 }
9800
9801 return false;
9802
9804 // C++11 [class.copy]p12:
9805 // A copy constructor is trivial if:
9806 // - the constructor selected to copy each direct [subobject] is trivial
9807 if (RD->hasTrivialCopyConstructor() ||
9810 if (Quals == Qualifiers::Const)
9811 // We must either select the trivial copy constructor or reach an
9812 // ambiguity; no need to actually perform overload resolution.
9813 return true;
9814 } else if (!Selected) {
9815 return false;
9816 }
9817 // In C++98, we are not supposed to perform overload resolution here, but we
9818 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9819 // cases like B as having a non-trivial copy constructor:
9820 // struct A { template<typename T> A(T&); };
9821 // struct B { mutable A a; };
9822 goto NeedOverloadResolution;
9823
9825 // C++11 [class.copy]p25:
9826 // A copy assignment operator is trivial if:
9827 // - the assignment operator selected to copy each direct [subobject] is
9828 // trivial
9829 if (RD->hasTrivialCopyAssignment()) {
9830 if (Quals == Qualifiers::Const)
9831 return true;
9832 } else if (!Selected) {
9833 return false;
9834 }
9835 // In C++98, we are not supposed to perform overload resolution here, but we
9836 // treat that as a language defect.
9837 goto NeedOverloadResolution;
9838
9841 NeedOverloadResolution:
9843 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9844
9845 // The standard doesn't describe how to behave if the lookup is ambiguous.
9846 // We treat it as not making the member non-trivial, just like the standard
9847 // mandates for the default constructor. This should rarely matter, because
9848 // the member will also be deleted.
9850 return true;
9851
9852 if (!SMOR.getMethod()) {
9853 assert(SMOR.getKind() ==
9855 return false;
9856 }
9857
9858 // We deliberately don't check if we found a deleted special member. We're
9859 // not supposed to!
9860 if (Selected)
9861 *Selected = SMOR.getMethod();
9862
9863 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9866 return SMOR.getMethod()->isTrivialForCall();
9867 return SMOR.getMethod()->isTrivial();
9868 }
9869
9870 llvm_unreachable("unknown special method kind");
9871}
9872
9874 for (auto *CI : RD->ctors())
9875 if (!CI->isImplicit())
9876 return CI;
9877
9878 // Look for constructor templates.
9880 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9881 if (CXXConstructorDecl *CD =
9882 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9883 return CD;
9884 }
9885
9886 return nullptr;
9887}
9888
9889/// The kind of subobject we are checking for triviality. The values of this
9890/// enumeration are used in diagnostics.
9892 /// The subobject is a base class.
9894 /// The subobject is a non-static data member.
9896 /// The object is actually the complete object.
9899
9900/// Check whether the special member selected for a given type would be trivial.
9902 QualType SubType, bool ConstRHS,
9906 bool Diagnose) {
9907 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9908 if (!SubRD)
9909 return true;
9910
9911 CXXMethodDecl *Selected;
9912 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9913 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9914 return true;
9915
9916 if (Diagnose) {
9917 if (ConstRHS)
9918 SubType.addConst();
9919
9920 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
9921 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9922 << Kind << SubType.getUnqualifiedType();
9924 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9925 } else if (!Selected)
9926 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9927 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
9928 << SubType;
9929 else if (Selected->isUserProvided()) {
9930 if (Kind == TSK_CompleteObject)
9931 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9932 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9933 else {
9934 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9935 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9936 S.Diag(Selected->getLocation(), diag::note_declared_at);
9937 }
9938 } else {
9939 if (Kind != TSK_CompleteObject)
9940 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9941 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9942
9943 // Explain why the defaulted or deleted special member isn't trivial.
9945 Diagnose);
9946 }
9947 }
9948
9949 return false;
9950}
9951
9952/// Check whether the members of a class type allow a special member to be
9953/// trivial.
9955 CXXSpecialMemberKind CSM, bool ConstArg,
9957 bool Diagnose) {
9958 for (const auto *FI : RD->fields()) {
9959 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
9960 continue;
9961
9962 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9963
9964 // Pretend anonymous struct or union members are members of this class.
9965 if (FI->isAnonymousStructOrUnion()) {
9966 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9967 CSM, ConstArg, TAH, Diagnose))
9968 return false;
9969 continue;
9970 }
9971
9972 // C++11 [class.ctor]p5:
9973 // A default constructor is trivial if [...]
9974 // -- no non-static data member of its class has a
9975 // brace-or-equal-initializer
9977 FI->hasInClassInitializer()) {
9978 if (Diagnose)
9979 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9980 << FI;
9981 return false;
9982 }
9983
9984 // Objective C ARC 4.3.5:
9985 // [...] nontrivally ownership-qualified types are [...] not trivially
9986 // default constructible, copy constructible, move constructible, copy
9987 // assignable, move assignable, or destructible [...]
9988 if (FieldType.hasNonTrivialObjCLifetime()) {
9989 if (Diagnose)
9990 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9991 << RD << FieldType.getObjCLifetime();
9992 return false;
9993 }
9994
9995 bool ConstRHS = ConstArg && !FI->isMutable();
9996 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9997 CSM, TSK_Field, TAH, Diagnose))
9998 return false;
9999 }
10000
10001 return true;
10002}
10003
10007
10008 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10010 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10012 /*Diagnose*/true);
10013}
10014
10016 TrivialABIHandling TAH, bool Diagnose) {
10017 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10018 "not special enough");
10019
10020 CXXRecordDecl *RD = MD->getParent();
10021
10022 bool ConstArg = false;
10023
10024 // C++11 [class.copy]p12, p25: [DR1593]
10025 // A [special member] is trivial if [...] its parameter-type-list is
10026 // equivalent to the parameter-type-list of an implicit declaration [...]
10027 switch (CSM) {
10030 // Trivial default constructors and destructors cannot have parameters.
10031 break;
10032
10035 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10036 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10037
10038 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10039 // if they are not user-provided and their parameter-type-list is equivalent
10040 // to the parameter-type-list of an implicit declaration. This maintains the
10041 // behavior before dr2171 was implemented.
10042 //
10043 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10044 // trivial, if they are not user-provided, regardless of the qualifiers on
10045 // the reference type.
10046 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10048 if (!RT ||
10050 ClangABICompat14)) {
10051 if (Diagnose)
10052 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10053 << Param0->getSourceRange() << Param0->getType()
10056 return false;
10057 }
10058
10059 ConstArg = RT->getPointeeType().isConstQualified();
10060 break;
10061 }
10062
10065 // Trivial move operations always have non-cv-qualified parameters.
10066 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10067 const RValueReferenceType *RT =
10068 Param0->getType()->getAs<RValueReferenceType>();
10069 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10070 if (Diagnose)
10071 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10072 << Param0->getSourceRange() << Param0->getType()
10074 return false;
10075 }
10076 break;
10077 }
10078
10080 llvm_unreachable("not a special member");
10081 }
10082
10083 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10084 if (Diagnose)
10086 diag::note_nontrivial_default_arg)
10088 return false;
10089 }
10090 if (MD->isVariadic()) {
10091 if (Diagnose)
10092 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10093 return false;
10094 }
10095
10096 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10097 // A copy/move [constructor or assignment operator] is trivial if
10098 // -- the [member] selected to copy/move each direct base class subobject
10099 // is trivial
10100 //
10101 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10102 // A [default constructor or destructor] is trivial if
10103 // -- all the direct base classes have trivial [default constructors or
10104 // destructors]
10105 for (const auto &BI : RD->bases())
10106 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10107 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10108 return false;
10109
10110 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10111 // A copy/move [constructor or assignment operator] for a class X is
10112 // trivial if
10113 // -- for each non-static data member of X that is of class type (or array
10114 // thereof), the constructor selected to copy/move that member is
10115 // trivial
10116 //
10117 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10118 // A [default constructor or destructor] is trivial if
10119 // -- for all of the non-static data members of its class that are of class
10120 // type (or array thereof), each such class has a trivial [default
10121 // constructor or destructor]
10122 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10123 return false;
10124
10125 // C++11 [class.dtor]p5:
10126 // A destructor is trivial if [...]
10127 // -- the destructor is not virtual
10128 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10129 if (Diagnose)
10130 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10131 return false;
10132 }
10133
10134 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10135 // A [special member] for class X is trivial if [...]
10136 // -- class X has no virtual functions and no virtual base classes
10138 MD->getParent()->isDynamicClass()) {
10139 if (!Diagnose)
10140 return false;
10141
10142 if (RD->getNumVBases()) {
10143 // Check for virtual bases. We already know that the corresponding
10144 // member in all bases is trivial, so vbases must all be direct.
10145 CXXBaseSpecifier &BS = *RD->vbases_begin();
10146 assert(BS.isVirtual());
10147 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10148 return false;
10149 }
10150
10151 // Must have a virtual method.
10152 for (const auto *MI : RD->methods()) {
10153 if (MI->isVirtual()) {
10154 SourceLocation MLoc = MI->getBeginLoc();
10155 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10156 return false;
10157 }
10158 }
10159
10160 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10161 }
10162
10163 // Looks like it's trivial!
10164 return true;
10165}
10166
10167namespace {
10168struct FindHiddenVirtualMethod {
10169 Sema *S;
10170 CXXMethodDecl *Method;
10171 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10172 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10173
10174private:
10175 /// Check whether any most overridden method from MD in Methods
10176 static bool CheckMostOverridenMethods(
10177 const CXXMethodDecl *MD,
10178 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10179 if (MD->size_overridden_methods() == 0)
10180 return Methods.count(MD->getCanonicalDecl());
10181 for (const CXXMethodDecl *O : MD->overridden_methods())
10182 if (CheckMostOverridenMethods(O, Methods))
10183 return true;
10184 return false;
10185 }
10186
10187public:
10188 /// Member lookup function that determines whether a given C++
10189 /// method overloads virtual methods in a base class without overriding any,
10190 /// to be used with CXXRecordDecl::lookupInBases().
10191 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10192 RecordDecl *BaseRecord =
10193 Specifier->getType()->castAs<RecordType>()->getDecl();
10194
10195 DeclarationName Name = Method->getDeclName();
10196 assert(Name.getNameKind() == DeclarationName::Identifier);
10197
10198 bool foundSameNameMethod = false;
10199 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10200 for (Path.Decls = BaseRecord->lookup(Name).begin();
10201 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10202 NamedDecl *D = *Path.Decls;
10203 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10204 MD = MD->getCanonicalDecl();
10205 foundSameNameMethod = true;
10206 // Interested only in hidden virtual methods.
10207 if (!MD->isVirtual())
10208 continue;
10209 // If the method we are checking overrides a method from its base
10210 // don't warn about the other overloaded methods. Clang deviates from
10211 // GCC by only diagnosing overloads of inherited virtual functions that
10212 // do not override any other virtual functions in the base. GCC's
10213 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10214 // function from a base class. These cases may be better served by a
10215 // warning (not specific to virtual functions) on call sites when the
10216 // call would select a different function from the base class, were it
10217 // visible.
10218 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10219 if (!S->IsOverload(Method, MD, false))
10220 return true;
10221 // Collect the overload only if its hidden.
10222 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10223 overloadedMethods.push_back(MD);
10224 }
10225 }
10226
10227 if (foundSameNameMethod)
10228 OverloadedMethods.append(overloadedMethods.begin(),
10229 overloadedMethods.end());
10230 return foundSameNameMethod;
10231 }
10232};
10233} // end anonymous namespace
10234
10235/// Add the most overridden methods from MD to Methods
10237 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10238 if (MD->size_overridden_methods() == 0)
10239 Methods.insert(MD->getCanonicalDecl());
10240 else
10241 for (const CXXMethodDecl *O : MD->overridden_methods())
10242 AddMostOverridenMethods(O, Methods);
10243}
10244
10246 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10247 if (!MD->getDeclName().isIdentifier())
10248 return;
10249
10250 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10251 /*bool RecordPaths=*/false,
10252 /*bool DetectVirtual=*/false);
10253 FindHiddenVirtualMethod FHVM;
10254 FHVM.Method = MD;
10255 FHVM.S = this;
10256
10257 // Keep the base methods that were overridden or introduced in the subclass
10258 // by 'using' in a set. A base method not in this set is hidden.
10259 CXXRecordDecl *DC = MD->getParent();
10261 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10262 NamedDecl *ND = *I;
10263 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10264 ND = shad->getTargetDecl();
10265 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10266 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10267 }
10268
10269 if (DC->lookupInBases(FHVM, Paths))
10270 OverloadedMethods = FHVM.OverloadedMethods;
10271}
10272
10274 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10275 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10276 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10278 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10279 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10280 Diag(overloadedMD->getLocation(), PD);
10281 }
10282}
10283
10285 if (MD->isInvalidDecl())
10286 return;
10287
10288 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10289 return;
10290
10291 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10292 FindHiddenVirtualMethods(MD, OverloadedMethods);
10293 if (!OverloadedMethods.empty()) {
10294 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10295 << MD << (OverloadedMethods.size() > 1);
10296
10297 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10298 }
10299}
10300
10302 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10303 // No diagnostics if this is a template instantiation.
10305 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10306 diag::ext_cannot_use_trivial_abi) << &RD;
10307 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10308 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10309 }
10310 RD.dropAttr<TrivialABIAttr>();
10311 };
10312
10313 // Ill-formed if the copy and move constructors are deleted.
10314 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10315 // If the type is dependent, then assume it might have
10316 // implicit copy or move ctor because we won't know yet at this point.
10317 if (RD.isDependentType())
10318 return true;
10321 return true;
10324 return true;
10325 for (const CXXConstructorDecl *CD : RD.ctors())
10326 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10327 return true;
10328 return false;
10329 };
10330
10331 if (!HasNonDeletedCopyOrMoveConstructor()) {
10332 PrintDiagAndRemoveAttr(0);
10333 return;
10334 }
10335
10336 // Ill-formed if the struct has virtual functions.
10337 if (RD.isPolymorphic()) {
10338 PrintDiagAndRemoveAttr(1);
10339 return;
10340 }
10341
10342 for (const auto &B : RD.bases()) {
10343 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10344 // virtual base.
10345 if (!B.getType()->isDependentType() &&
10346 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10347 PrintDiagAndRemoveAttr(2);
10348 return;
10349 }
10350
10351 if (B.isVirtual()) {
10352 PrintDiagAndRemoveAttr(3);
10353 return;
10354 }
10355 }
10356
10357 for (const auto *FD : RD.fields()) {
10358 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10359 // non-trivial for the purpose of calls.
10360 QualType FT = FD->getType();
10362 PrintDiagAndRemoveAttr(4);
10363 return;
10364 }
10365
10366 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10367 if (!RT->isDependentType() &&
10368 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10369 PrintDiagAndRemoveAttr(5);
10370 return;
10371 }
10372 }
10373}
10374
10376 CXXRecordDecl &RD) {
10378 diag::err_incomplete_type_vtable_pointer_auth))
10379 return;
10380
10381 const CXXRecordDecl *PrimaryBase = &RD;
10382 if (PrimaryBase->hasAnyDependentBases())
10383 return;
10384
10385 while (1) {
10386 assert(PrimaryBase);
10387 const CXXRecordDecl *Base = nullptr;
10388 for (auto BasePtr : PrimaryBase->bases()) {
10389 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10390 continue;
10391 Base = BasePtr.getType()->getAsCXXRecordDecl();
10392 break;
10393 }
10394 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10395 break;
10396 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10397 diag::err_non_top_level_vtable_pointer_auth)
10398 << &RD << Base;
10399 PrimaryBase = Base;
10400 }
10401
10402 if (!RD.isPolymorphic())
10403 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10404 diag::err_non_polymorphic_vtable_pointer_auth)
10405 << &RD;
10406}
10407
10410 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10411 if (!TagDecl)
10412 return;
10413
10415
10416 for (const ParsedAttr &AL : AttrList) {
10417 if (AL.getKind() != ParsedAttr::AT_Visibility)
10418 continue;
10419 AL.setInvalid();
10420 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10421 }
10422
10423 ActOnFields(S, RLoc, TagDecl,
10425 // strict aliasing violation!
10426 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10427 FieldCollector->getCurNumFields()),
10428 LBrac, RBrac, AttrList);
10429
10430 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10431}
10432
10433/// Find the equality comparison functions that should be implicitly declared
10434/// in a given class definition, per C++2a [class.compare.default]p3.
10436 ASTContext &Ctx, CXXRecordDecl *RD,
10438 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10439 if (!RD->lookup(EqEq).empty())
10440 // Member operator== explicitly declared: no implicit operator==s.
10441 return;
10442
10443 // Traverse friends looking for an '==' or a '<=>'.
10444 for (FriendDecl *Friend : RD->friends()) {
10445 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10446 if (!FD) continue;
10447
10448 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10449 // Friend operator== explicitly declared: no implicit operator==s.
10450 Spaceships.clear();
10451 return;
10452 }
10453
10454 if (FD->getOverloadedOperator() == OO_Spaceship &&
10456 Spaceships.push_back(FD);
10457 }
10458
10459 // Look for members named 'operator<=>'.
10460 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10461 for (NamedDecl *ND : RD->lookup(Cmp)) {
10462 // Note that we could find a non-function here (either a function template
10463 // or a using-declaration). Neither case results in an implicit
10464 // 'operator=='.
10465 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10466 if (FD->isExplicitlyDefaulted())
10467 Spaceships.push_back(FD);
10468 }
10469}
10470
10472 // Don't add implicit special members to templated classes.
10473 // FIXME: This means unqualified lookups for 'operator=' within a class
10474 // template don't work properly.
10475 if (!ClassDecl->isDependentType()) {
10476 if (ClassDecl->needsImplicitDefaultConstructor()) {
10478
10479 if (ClassDecl->hasInheritedConstructor())
10481 }
10482
10483 if (ClassDecl->needsImplicitCopyConstructor()) {
10485
10486 // If the properties or semantics of the copy constructor couldn't be
10487 // determined while the class was being declared, force a declaration
10488 // of it now.
10490 ClassDecl->hasInheritedConstructor())
10492 // For the MS ABI we need to know whether the copy ctor is deleted. A
10493 // prerequisite for deleting the implicit copy ctor is that the class has
10494 // a move ctor or move assignment that is either user-declared or whose
10495 // semantics are inherited from a subobject. FIXME: We should provide a
10496 // more direct way for CodeGen to ask whether the constructor was deleted.
10497 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10498 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10500 ClassDecl->hasUserDeclaredMoveAssignment() ||
10503 }
10504
10505 if (getLangOpts().CPlusPlus11 &&
10506 ClassDecl->needsImplicitMoveConstructor()) {
10508
10510 ClassDecl->hasInheritedConstructor())
10512 }
10513
10514 if (ClassDecl->needsImplicitCopyAssignment()) {
10516
10517 // If we have a dynamic class, then the copy assignment operator may be
10518 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10519 // it shows up in the right place in the vtable and that we diagnose
10520 // problems with the implicit exception specification.
10521 if (ClassDecl->isDynamicClass() ||
10523 ClassDecl->hasInheritedAssignment())
10525 }
10526
10527 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10529
10530 // Likewise for the move assignment operator.
10531 if (ClassDecl->isDynamicClass() ||
10533 ClassDecl->hasInheritedAssignment())
10535 }
10536
10537 if (ClassDecl->needsImplicitDestructor()) {
10539
10540 // If we have a dynamic class, then the destructor may be virtual, so we
10541 // have to declare the destructor immediately. This ensures that, e.g., it
10542 // shows up in the right place in the vtable and that we diagnose problems
10543 // with the implicit exception specification.
10544 if (ClassDecl->isDynamicClass() ||
10546 DeclareImplicitDestructor(ClassDecl);
10547 }
10548 }
10549
10550 // C++2a [class.compare.default]p3:
10551 // If the member-specification does not explicitly declare any member or
10552 // friend named operator==, an == operator function is declared implicitly
10553 // for each defaulted three-way comparison operator function defined in
10554 // the member-specification
10555 // FIXME: Consider doing this lazily.
10556 // We do this during the initial parse for a class template, not during
10557 // instantiation, so that we can handle unqualified lookups for 'operator=='
10558 // when parsing the template.
10560 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10562 DefaultedSpaceships);
10563 for (auto *FD : DefaultedSpaceships)
10564 DeclareImplicitEqualityComparison(ClassDecl, FD);
10565 }
10566}
10567
10568unsigned
10570 llvm::function_ref<Scope *()> EnterScope) {
10571 if (!D)
10572 return 0;
10574
10575 // In order to get name lookup right, reenter template scopes in order from
10576 // outermost to innermost.
10578 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10579
10580 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10581 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10582 ParameterLists.push_back(DD->getTemplateParameterList(i));
10583
10584 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10585 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10586 ParameterLists.push_back(FTD->getTemplateParameters());
10587 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10588 LookupDC = VD->getDeclContext();
10589
10591 ParameterLists.push_back(VTD->getTemplateParameters());
10592 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10593 ParameterLists.push_back(PSD->getTemplateParameters());
10594 }
10595 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10596 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10597 ParameterLists.push_back(TD->getTemplateParameterList(i));
10598
10599 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10601 ParameterLists.push_back(CTD->getTemplateParameters());
10602 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10603 ParameterLists.push_back(PSD->getTemplateParameters());
10604 }
10605 }
10606 // FIXME: Alias declarations and concepts.
10607
10608 unsigned Count = 0;
10609 Scope *InnermostTemplateScope = nullptr;
10610 for (TemplateParameterList *Params : ParameterLists) {
10611 // Ignore explicit specializations; they don't contribute to the template
10612 // depth.
10613 if (Params->size() == 0)
10614 continue;
10615
10616 InnermostTemplateScope = EnterScope();
10617 for (NamedDecl *Param : *Params) {
10618 if (Param->getDeclName()) {
10619 InnermostTemplateScope->AddDecl(Param);
10620 IdResolver.AddDecl(Param);
10621 }
10622 }
10623 ++Count;
10624 }
10625
10626 // Associate the new template scopes with the corresponding entities.
10627 if (InnermostTemplateScope) {
10628 assert(LookupDC && "no enclosing DeclContext for template lookup");
10629 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10630 }
10631
10632 return Count;
10633}
10634
10636 if (!RecordD) return;
10637 AdjustDeclIfTemplate(RecordD);
10638 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10640}
10641
10643 if (!RecordD) return;
10645}
10646
10648 if (!Param)
10649 return;
10650
10651 S->AddDecl(Param);
10652 if (Param->getDeclName())
10653 IdResolver.AddDecl(Param);
10654}
10655
10657}
10658
10659/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10660/// C++ method declaration. We're (re-)introducing the given
10661/// function parameter into scope for use in parsing later parts of
10662/// the method declaration. For example, we could see an
10663/// ActOnParamDefaultArgument event for this parameter.
10665 if (!ParamD)
10666 return;
10667
10668 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10669
10670 S->AddDecl(Param);
10671 if (Param->getDeclName())
10672 IdResolver.AddDecl(Param);
10673}
10674
10676 if (!MethodD)
10677 return;
10678
10679 AdjustDeclIfTemplate(MethodD);
10680
10681 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10682
10683 // Now that we have our default arguments, check the constructor
10684 // again. It could produce additional diagnostics or affect whether
10685 // the class has implicitly-declared destructors, among other
10686 // things.
10687 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10688 CheckConstructor(Constructor);
10689
10690 // Check the default arguments, which we may have added.
10691 if (!Method->isInvalidDecl())
10693}
10694
10695// Emit the given diagnostic for each non-address-space qualifier.
10696// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10697static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10698 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10699 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10700 bool DiagOccured = false;
10702 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10703 SourceLocation SL) {
10704 // This diagnostic should be emitted on any qualifier except an addr
10705 // space qualifier. However, forEachQualifier currently doesn't visit
10706 // addr space qualifiers, so there's no way to write this condition
10707 // right now; we just diagnose on everything.
10708 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10709 DiagOccured = true;
10710 });
10711 if (DiagOccured)
10712 D.setInvalidType();
10713 }
10714}
10715
10717 StorageClass &SC) {
10718 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10719
10720 // C++ [class.ctor]p3:
10721 // A constructor shall not be virtual (10.3) or static (9.4). A
10722 // constructor can be invoked for a const, volatile or const
10723 // volatile object. A constructor shall not be declared const,
10724 // volatile, or const volatile (9.3.2).
10725 if (isVirtual) {
10726 if (!D.isInvalidType())
10727 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10728 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10729 << SourceRange(D.getIdentifierLoc());
10730 D.setInvalidType();
10731 }
10732 if (SC == SC_Static) {
10733 if (!D.isInvalidType())
10734 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10735 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10736 << SourceRange(D.getIdentifierLoc());
10737 D.setInvalidType();
10738 SC = SC_None;
10739 }
10740
10741 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10743 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10744 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10745 D.getDeclSpec().getRestrictSpecLoc(),
10746 D.getDeclSpec().getAtomicSpecLoc());
10747 D.setInvalidType();
10748 }
10749
10750 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10751
10752 // C++0x [class.ctor]p4:
10753 // A constructor shall not be declared with a ref-qualifier.
10754 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10755 if (FTI.hasRefQualifier()) {
10756 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10759 D.setInvalidType();
10760 }
10761
10762 // Rebuild the function type "R" without any type qualifiers (in
10763 // case any of the errors above fired) and with "void" as the
10764 // return type, since constructors don't have return types.
10765 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10766 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10767 return R;
10768
10770 EPI.TypeQuals = Qualifiers();
10771 EPI.RefQualifier = RQ_None;
10772
10773 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10774}
10775
10777 CXXRecordDecl *ClassDecl
10778 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10779 if (!ClassDecl)
10780 return Constructor->setInvalidDecl();
10781
10782 // C++ [class.copy]p3:
10783 // A declaration of a constructor for a class X is ill-formed if
10784 // its first parameter is of type (optionally cv-qualified) X and
10785 // either there are no other parameters or else all other
10786 // parameters have default arguments.
10787 if (!Constructor->isInvalidDecl() &&
10788 Constructor->hasOneParamOrDefaultArgs() &&
10789 Constructor->getTemplateSpecializationKind() !=
10791 QualType ParamType = Constructor->getParamDecl(0)->getType();
10792 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10793 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10794 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10795 const char *ConstRef
10796 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10797 : " const &";
10798 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10799 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10800
10801 // FIXME: Rather that making the constructor invalid, we should endeavor
10802 // to fix the type.
10803 Constructor->setInvalidDecl();
10804 }
10805 }
10806}
10807
10809 CXXRecordDecl *RD = Destructor->getParent();
10810
10811 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10813
10814 if (!Destructor->isImplicit())
10815 Loc = Destructor->getLocation();
10816 else
10817 Loc = RD->getLocation();
10818
10819 // If we have a virtual destructor, look up the deallocation function
10820 if (FunctionDecl *OperatorDelete =
10822 Expr *ThisArg = nullptr;
10823
10824 // If the notional 'delete this' expression requires a non-trivial
10825 // conversion from 'this' to the type of a destroying operator delete's
10826 // first parameter, perform that conversion now.
10827 if (OperatorDelete->isDestroyingOperatorDelete()) {
10828 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10829 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10830 // C++ [class.dtor]p13:
10831 // ... as if for the expression 'delete this' appearing in a
10832 // non-virtual destructor of the destructor's class.
10833 ContextRAII SwitchContext(*this, Destructor);
10834 ExprResult This =
10835 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10836 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10837 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10838 if (This.isInvalid()) {
10839 // FIXME: Register this as a context note so that it comes out
10840 // in the right order.
10841 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10842 return true;
10843 }
10844 ThisArg = This.get();
10845 }
10846 }
10847
10848 DiagnoseUseOfDecl(OperatorDelete, Loc);
10849 MarkFunctionReferenced(Loc, OperatorDelete);
10850 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10851 }
10852 }
10853
10854 return false;
10855}
10856
10858 StorageClass& SC) {
10859 // C++ [class.dtor]p1:
10860 // [...] A typedef-name that names a class is a class-name
10861 // (7.1.3); however, a typedef-name that names a class shall not
10862 // be used as the identifier in the declarator for a destructor
10863 // declaration.
10864 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10865 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10866 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10867 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10868 else if (const TemplateSpecializationType *TST =
10869 DeclaratorType->getAs<TemplateSpecializationType>())
10870 if (TST->isTypeAlias())
10871 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10872 << DeclaratorType << 1;
10873
10874 // C++ [class.dtor]p2:
10875 // A destructor is used to destroy objects of its class type. A
10876 // destructor takes no parameters, and no return type can be
10877 // specified for it (not even void). The address of a destructor
10878 // shall not be taken. A destructor shall not be static. A
10879 // destructor can be invoked for a const, volatile or const
10880 // volatile object. A destructor shall not be declared const,
10881 // volatile or const volatile (9.3.2).
10882 if (SC == SC_Static) {
10883 if (!D.isInvalidType())
10884 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10885 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10886 << SourceRange(D.getIdentifierLoc())
10887 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10888
10889 SC = SC_None;
10890 }
10891 if (!D.isInvalidType()) {
10892 // Destructors don't have return types, but the parser will
10893 // happily parse something like:
10894 //
10895 // class X {
10896 // float ~X();
10897 // };
10898 //
10899 // The return type will be eliminated later.
10900 if (D.getDeclSpec().hasTypeSpecifier())
10901 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10902 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10903 << SourceRange(D.getIdentifierLoc());
10904 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10905 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10907 D.getDeclSpec().getConstSpecLoc(),
10908 D.getDeclSpec().getVolatileSpecLoc(),
10909 D.getDeclSpec().getRestrictSpecLoc(),
10910 D.getDeclSpec().getAtomicSpecLoc());
10911 D.setInvalidType();
10912 }
10913 }
10914
10915 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10916
10917 // C++0x [class.dtor]p2:
10918 // A destructor shall not be declared with a ref-qualifier.
10919 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10920 if (FTI.hasRefQualifier()) {
10921 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10924 D.setInvalidType();
10925 }
10926
10927 // Make sure we don't have any parameters.
10928 if (FTIHasNonVoidParameters(FTI)) {
10929 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10930
10931 // Delete the parameters.
10932 FTI.freeParams();
10933 D.setInvalidType();
10934 }
10935
10936 // Make sure the destructor isn't variadic.
10937 if (FTI.isVariadic) {
10938 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10939 D.setInvalidType();
10940 }
10941
10942 // Rebuild the function type "R" without any type qualifiers or
10943 // parameters (in case any of the errors above fired) and with
10944 // "void" as the return type, since destructors don't have return
10945 // types.
10946 if (!D.isInvalidType())
10947 return R;
10948
10949 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10951 EPI.Variadic = false;
10952 EPI.TypeQuals = Qualifiers();
10953 EPI.RefQualifier = RQ_None;
10954 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
10955}
10956
10957static void extendLeft(SourceRange &R, SourceRange Before) {
10958 if (Before.isInvalid())
10959 return;
10960 R.setBegin(Before.getBegin());
10961 if (R.getEnd().isInvalid())
10962 R.setEnd(Before.getEnd());
10963}
10964
10965static void extendRight(SourceRange &R, SourceRange After) {
10966 if (After.isInvalid())
10967 return;
10968 if (R.getBegin().isInvalid())
10969 R.setBegin(After.getBegin());
10970 R.setEnd(After.getEnd());
10971}
10972
10974 StorageClass& SC) {
10975 // C++ [class.conv.fct]p1:
10976 // Neither parameter types nor return type can be specified. The
10977 // type of a conversion function (8.3.5) is "function taking no
10978 // parameter returning conversion-type-id."
10979 if (SC == SC_Static) {
10980 if (!D.isInvalidType())
10981 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10982 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10983 << D.getName().getSourceRange();
10984 D.setInvalidType();
10985 SC = SC_None;
10986 }
10987
10988 TypeSourceInfo *ConvTSI = nullptr;
10989 QualType ConvType =
10990 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10991
10992 const DeclSpec &DS = D.getDeclSpec();
10993 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10994 // Conversion functions don't have return types, but the parser will
10995 // happily parse something like:
10996 //
10997 // class X {
10998 // float operator bool();
10999 // };
11000 //
11001 // The return type will be changed later anyway.
11002 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11004 << SourceRange(D.getIdentifierLoc());
11005 D.setInvalidType();
11006 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11007 // It's also plausible that the user writes type qualifiers in the wrong
11008 // place, such as:
11009 // struct S { const operator int(); };
11010 // FIXME: we could provide a fixit to move the qualifiers onto the
11011 // conversion type.
11012 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11013 << SourceRange(D.getIdentifierLoc()) << 0;
11014 D.setInvalidType();
11015 }
11016 const auto *Proto = R->castAs<FunctionProtoType>();
11017 // Make sure we don't have any parameters.
11018 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11019 unsigned NumParam = Proto->getNumParams();
11020
11021 // [C++2b]
11022 // A conversion function shall have no non-object parameters.
11023 if (NumParam == 1) {
11024 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11025 if (const auto *First =
11026 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11027 First && First->isExplicitObjectParameter())
11028 NumParam--;
11029 }
11030
11031 if (NumParam != 0) {
11032 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11033 // Delete the parameters.
11034 FTI.freeParams();
11035 D.setInvalidType();
11036 } else if (Proto->isVariadic()) {
11037 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11038 D.setInvalidType();
11039 }
11040
11041 // Diagnose "&operator bool()" and other such nonsense. This
11042 // is actually a gcc extension which we don't support.
11043 if (Proto->getReturnType() != ConvType) {
11044 bool NeedsTypedef = false;
11045 SourceRange Before, After;
11046
11047 // Walk the chunks and extract information on them for our diagnostic.
11048 bool PastFunctionChunk = false;
11049 for (auto &Chunk : D.type_objects()) {
11050 switch (Chunk.Kind) {
11052 if (!PastFunctionChunk) {
11053 if (Chunk.Fun.HasTrailingReturnType) {
11054 TypeSourceInfo *TRT = nullptr;
11055 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11056 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11057 }
11058 PastFunctionChunk = true;
11059 break;
11060 }
11061 [[fallthrough]];
11063 NeedsTypedef = true;
11064 extendRight(After, Chunk.getSourceRange());
11065 break;
11066
11072 extendLeft(Before, Chunk.getSourceRange());
11073 break;
11074
11076 extendLeft(Before, Chunk.Loc);
11077 extendRight(After, Chunk.EndLoc);
11078 break;
11079 }
11080 }
11081
11082 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11083 After.isValid() ? After.getBegin() :
11084 D.getIdentifierLoc();
11085 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11086 DB << Before << After;
11087
11088 if (!NeedsTypedef) {
11089 DB << /*don't need a typedef*/0;
11090
11091 // If we can provide a correct fix-it hint, do so.
11092 if (After.isInvalid() && ConvTSI) {
11093 SourceLocation InsertLoc =
11095 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11097 InsertLoc, CharSourceRange::getTokenRange(Before))
11098 << FixItHint::CreateRemoval(Before);
11099 }
11100 } else if (!Proto->getReturnType()->isDependentType()) {
11101 DB << /*typedef*/1 << Proto->getReturnType();
11102 } else if (getLangOpts().CPlusPlus11) {
11103 DB << /*alias template*/2 << Proto->getReturnType();
11104 } else {
11105 DB << /*might not be fixable*/3;
11106 }
11107
11108 // Recover by incorporating the other type chunks into the result type.
11109 // Note, this does *not* change the name of the function. This is compatible
11110 // with the GCC extension:
11111 // struct S { &operator int(); } s;
11112 // int &r = s.operator int(); // ok in GCC
11113 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11114 ConvType = Proto->getReturnType();
11115 }
11116
11117 // C++ [class.conv.fct]p4:
11118 // The conversion-type-id shall not represent a function type nor
11119 // an array type.
11120 if (ConvType->isArrayType()) {
11121 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11122 ConvType = Context.getPointerType(ConvType);
11123 D.setInvalidType();
11124 } else if (ConvType->isFunctionType()) {
11125 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11126 ConvType = Context.getPointerType(ConvType);
11127 D.setInvalidType();
11128 }
11129
11130 // Rebuild the function type "R" without any parameters (in case any
11131 // of the errors above fired) and with the conversion type as the
11132 // return type.
11133 if (D.isInvalidType())
11134 R = Context.getFunctionType(ConvType, std::nullopt,
11135 Proto->getExtProtoInfo());
11136
11137 // C++0x explicit conversion operators.
11141 ? diag::warn_cxx98_compat_explicit_conversion_functions
11142 : diag::ext_explicit_conversion_functions)
11144}
11145
11147 assert(Conversion && "Expected to receive a conversion function declaration");
11148
11149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11150
11151 // Make sure we aren't redeclaring the conversion function.
11152 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11153 // C++ [class.conv.fct]p1:
11154 // [...] A conversion function is never used to convert a
11155 // (possibly cv-qualified) object to the (possibly cv-qualified)
11156 // same object type (or a reference to it), to a (possibly
11157 // cv-qualified) base class of that type (or a reference to it),
11158 // or to (possibly cv-qualified) void.
11159 QualType ClassType
11161 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11162 ConvType = ConvTypeRef->getPointeeType();
11163 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11165 /* Suppress diagnostics for instantiations. */;
11166 else if (Conversion->size_overridden_methods() != 0)
11167 /* Suppress diagnostics for overriding virtual function in a base class. */;
11168 else if (ConvType->isRecordType()) {
11169 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11170 if (ConvType == ClassType)
11171 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11172 << ClassType;
11173 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11174 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11175 << ClassType << ConvType;
11176 } else if (ConvType->isVoidType()) {
11177 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11178 << ClassType << ConvType;
11179 }
11180
11181 if (FunctionTemplateDecl *ConversionTemplate =
11182 Conversion->getDescribedFunctionTemplate()) {
11183 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11184 ConvType = ConvTypePtr->getPointeeType();
11185 }
11186 if (ConvType->isUndeducedAutoType()) {
11187 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11188 << getReturnTypeLoc(Conversion).getSourceRange()
11189 << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11190 << /* in declaration of conversion function template= */ 24;
11191 }
11192
11193 return ConversionTemplate;
11194 }
11195
11196 return Conversion;
11197}
11198
11200 DeclarationName Name, QualType R) {
11201 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11202}
11203
11205 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11206}
11207
11209 DeclarationName Name, QualType R,
11210 bool IsLambda, DeclContext *DC) {
11211 if (!D.isFunctionDeclarator())
11212 return;
11213
11214 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11215 if (FTI.NumParams == 0)
11216 return;
11217 ParmVarDecl *ExplicitObjectParam = nullptr;
11218 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11219 const auto &ParamInfo = FTI.Params[Idx];
11220 if (!ParamInfo.Param)
11221 continue;
11222 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11223 if (!Param->isExplicitObjectParameter())
11224 continue;
11225 if (Idx == 0) {
11226 ExplicitObjectParam = Param;
11227 continue;
11228 } else {
11229 Diag(Param->getLocation(),
11230 diag::err_explicit_object_parameter_must_be_first)
11231 << IsLambda << Param->getSourceRange();
11232 }
11233 }
11234 if (!ExplicitObjectParam)
11235 return;
11236
11237 if (ExplicitObjectParam->hasDefaultArg()) {
11238 Diag(ExplicitObjectParam->getLocation(),
11239 diag::err_explicit_object_default_arg)
11240 << ExplicitObjectParam->getSourceRange();
11241 }
11242
11243 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11244 (D.getContext() == clang::DeclaratorContext::Member &&
11245 D.isStaticMember())) {
11246 Diag(ExplicitObjectParam->getBeginLoc(),
11247 diag::err_explicit_object_parameter_nonmember)
11248 << D.getSourceRange() << /*static=*/0 << IsLambda;
11249 D.setInvalidType();
11250 }
11251
11252 if (D.getDeclSpec().isVirtualSpecified()) {
11253 Diag(ExplicitObjectParam->getBeginLoc(),
11254 diag::err_explicit_object_parameter_nonmember)
11255 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11256 D.setInvalidType();
11257 }
11258
11259 // Friend declarations require some care. Consider:
11260 //
11261 // namespace N {
11262 // struct A{};
11263 // int f(A);
11264 // }
11265 //
11266 // struct S {
11267 // struct T {
11268 // int f(this T);
11269 // };
11270 //
11271 // friend int T::f(this T); // Allow this.
11272 // friend int f(this S); // But disallow this.
11273 // friend int N::f(this A); // And disallow this.
11274 // };
11275 //
11276 // Here, it seems to suffice to check whether the scope
11277 // specifier designates a class type.
11278 if (D.getDeclSpec().isFriendSpecified() &&
11279 !isa_and_present<CXXRecordDecl>(
11280 computeDeclContext(D.getCXXScopeSpec()))) {
11281 Diag(ExplicitObjectParam->getBeginLoc(),
11282 diag::err_explicit_object_parameter_nonmember)
11283 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11284 D.setInvalidType();
11285 }
11286
11287 if (IsLambda && FTI.hasMutableQualifier()) {
11288 Diag(ExplicitObjectParam->getBeginLoc(),
11289 diag::err_explicit_object_parameter_mutable)
11290 << D.getSourceRange();
11291 }
11292
11293 if (IsLambda)
11294 return;
11295
11296 if (!DC || !DC->isRecord()) {
11297 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11298 "should have been diagnosed already");
11299 return;
11300 }
11301
11302 // CWG2674: constructors and destructors cannot have explicit parameters.
11303 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11304 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11305 Diag(ExplicitObjectParam->getBeginLoc(),
11306 diag::err_explicit_object_parameter_constructor)
11307 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11308 << D.getSourceRange();
11309 D.setInvalidType();
11310 }
11311}
11312
11313namespace {
11314/// Utility class to accumulate and print a diagnostic listing the invalid
11315/// specifier(s) on a declaration.
11316struct BadSpecifierDiagnoser {
11317 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11318 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11319 ~BadSpecifierDiagnoser() {
11320 Diagnostic << Specifiers;
11321 }
11322
11323 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11324 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11325 }
11326 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11327 return check(SpecLoc,
11329 }
11330 void check(SourceLocation SpecLoc, const char *Spec) {
11331 if (SpecLoc.isInvalid()) return;
11332 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11333 if (!Specifiers.empty()) Specifiers += " ";
11334 Specifiers += Spec;
11335 }
11336
11337 Sema &S;
11339 std::string Specifiers;
11340};
11341}
11342
11344 StorageClass &SC) {
11345 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11346 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11347 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11348
11349 // C++ [temp.deduct.guide]p3:
11350 // A deduction-gide shall be declared in the same scope as the
11351 // corresponding class template.
11353 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11354 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11355 << GuidedTemplateDecl;
11356 NoteTemplateLocation(*GuidedTemplateDecl);
11357 }
11358
11359 auto &DS = D.getMutableDeclSpec();
11360 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11361 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11362 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11363 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11364 BadSpecifierDiagnoser Diagnoser(
11365 *this, D.getIdentifierLoc(),
11366 diag::err_deduction_guide_invalid_specifier);
11367
11368 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11369 DS.ClearStorageClassSpecs();
11370 SC = SC_None;
11371
11372 // 'explicit' is permitted.
11373 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11374 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11375 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11376 DS.ClearConstexprSpec();
11377
11378 Diagnoser.check(DS.getConstSpecLoc(), "const");
11379 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11380 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11381 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11382 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11383 DS.ClearTypeQualifiers();
11384
11385 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11386 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11387 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11388 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11389 DS.ClearTypeSpecType();
11390 }
11391
11392 if (D.isInvalidType())
11393 return true;
11394
11395 // Check the declarator is simple enough.
11396 bool FoundFunction = false;
11397 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11398 if (Chunk.Kind == DeclaratorChunk::Paren)
11399 continue;
11400 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11401 Diag(D.getDeclSpec().getBeginLoc(),
11402 diag::err_deduction_guide_with_complex_decl)
11403 << D.getSourceRange();
11404 break;
11405 }
11406 if (!Chunk.Fun.hasTrailingReturnType())
11407 return Diag(D.getName().getBeginLoc(),
11408 diag::err_deduction_guide_no_trailing_return_type);
11409
11410 // Check that the return type is written as a specialization of
11411 // the template specified as the deduction-guide's name.
11412 // The template name may not be qualified. [temp.deduct.guide]
11413 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11414 TypeSourceInfo *TSI = nullptr;
11415 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11416 assert(TSI && "deduction guide has valid type but invalid return type?");
11417 bool AcceptableReturnType = false;
11418 bool MightInstantiateToSpecialization = false;
11419 if (auto RetTST =
11421 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11422 bool TemplateMatches =
11423 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11424
11426 SpecifiedName.getAsQualifiedTemplateName();
11427 assert(Qualifiers && "expected QualifiedTemplate");
11428 bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11429 Qualifiers->getQualifier() == nullptr;
11430 if (SimplyWritten && TemplateMatches)
11431 AcceptableReturnType = true;
11432 else {
11433 // This could still instantiate to the right type, unless we know it
11434 // names the wrong class template.
11435 auto *TD = SpecifiedName.getAsTemplateDecl();
11436 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11437 !TemplateMatches);
11438 }
11439 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11440 MightInstantiateToSpecialization = true;
11441 }
11442
11443 if (!AcceptableReturnType)
11444 return Diag(TSI->getTypeLoc().getBeginLoc(),
11445 diag::err_deduction_guide_bad_trailing_return_type)
11446 << GuidedTemplate << TSI->getType()
11447 << MightInstantiateToSpecialization
11448 << TSI->getTypeLoc().getSourceRange();
11449
11450 // Keep going to check that we don't have any inner declarator pieces (we
11451 // could still have a function returning a pointer to a function).
11452 FoundFunction = true;
11453 }
11454
11455 if (D.isFunctionDefinition())
11456 // we can still create a valid deduction guide here.
11457 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11458 return false;
11459}
11460
11461//===----------------------------------------------------------------------===//
11462// Namespace Handling
11463//===----------------------------------------------------------------------===//
11464
11465/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11466/// reopened.
11469 IdentifierInfo *II, bool *IsInline,
11470 NamespaceDecl *PrevNS) {
11471 assert(*IsInline != PrevNS->isInline());
11472
11473 // 'inline' must appear on the original definition, but not necessarily
11474 // on all extension definitions, so the note should point to the first
11475 // definition to avoid confusion.
11476 PrevNS = PrevNS->getFirstDecl();
11477
11478 if (PrevNS->isInline())
11479 // The user probably just forgot the 'inline', so suggest that it
11480 // be added back.
11481 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11482 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11483 else
11484 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11485
11486 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11487 *IsInline = PrevNS->isInline();
11488}
11489
11490/// ActOnStartNamespaceDef - This is called at the start of a namespace
11491/// definition.
11493 SourceLocation InlineLoc,
11494 SourceLocation NamespaceLoc,
11495 SourceLocation IdentLoc, IdentifierInfo *II,
11496 SourceLocation LBrace,
11497 const ParsedAttributesView &AttrList,
11498 UsingDirectiveDecl *&UD, bool IsNested) {
11499 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11500 // For anonymous namespace, take the location of the left brace.
11501 SourceLocation Loc = II ? IdentLoc : LBrace;
11502 bool IsInline = InlineLoc.isValid();
11503 bool IsInvalid = false;
11504 bool IsStd = false;
11505 bool AddToKnown = false;
11506 Scope *DeclRegionScope = NamespcScope->getParent();
11507
11508 NamespaceDecl *PrevNS = nullptr;
11509 if (II) {
11510 // C++ [namespace.std]p7:
11511 // A translation unit shall not declare namespace std to be an inline
11512 // namespace (9.8.2).
11513 //
11514 // Precondition: the std namespace is in the file scope and is declared to
11515 // be inline
11516 auto DiagnoseInlineStdNS = [&]() {
11517 assert(IsInline && II->isStr("std") &&
11519 "Precondition of DiagnoseInlineStdNS not met");
11520 Diag(InlineLoc, diag::err_inline_namespace_std)
11521 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11522 IsInline = false;
11523 };
11524 // C++ [namespace.def]p2:
11525 // The identifier in an original-namespace-definition shall not
11526 // have been previously defined in the declarative region in
11527 // which the original-namespace-definition appears. The
11528 // identifier in an original-namespace-definition is the name of
11529 // the namespace. Subsequently in that declarative region, it is
11530 // treated as an original-namespace-name.
11531 //
11532 // Since namespace names are unique in their scope, and we don't
11533 // look through using directives, just look for any ordinary names
11534 // as if by qualified name lookup.
11535 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11536 RedeclarationKind::ForExternalRedeclaration);
11538 NamedDecl *PrevDecl =
11539 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11540 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11541
11542 if (PrevNS) {
11543 // This is an extended namespace definition.
11544 if (IsInline && II->isStr("std") &&
11546 DiagnoseInlineStdNS();
11547 else if (IsInline != PrevNS->isInline())
11548 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11549 &IsInline, PrevNS);
11550 } else if (PrevDecl) {
11551 // This is an invalid name redefinition.
11552 Diag(Loc, diag::err_redefinition_different_kind)
11553 << II;
11554 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11555 IsInvalid = true;
11556 // Continue on to push Namespc as current DeclContext and return it.
11557 } else if (II->isStr("std") &&
11559 if (IsInline)
11560 DiagnoseInlineStdNS();
11561 // This is the first "real" definition of the namespace "std", so update
11562 // our cache of the "std" namespace to point at this definition.
11563 PrevNS = getStdNamespace();
11564 IsStd = true;
11565 AddToKnown = !IsInline;
11566 } else {
11567 // We've seen this namespace for the first time.
11568 AddToKnown = !IsInline;
11569 }
11570 } else {
11571 // Anonymous namespaces.
11572
11573 // Determine whether the parent already has an anonymous namespace.
11575 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11576 PrevNS = TU->getAnonymousNamespace();
11577 } else {
11578 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11579 PrevNS = ND->getAnonymousNamespace();
11580 }
11581
11582 if (PrevNS && IsInline != PrevNS->isInline())
11583 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11584 &IsInline, PrevNS);
11585 }
11586
11588 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11589 if (IsInvalid)
11590 Namespc->setInvalidDecl();
11591
11592 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11593 AddPragmaAttributes(DeclRegionScope, Namespc);
11594 ProcessAPINotes(Namespc);
11595
11596 // FIXME: Should we be merging attributes?
11597 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11599
11600 if (IsStd)
11601 StdNamespace = Namespc;
11602 if (AddToKnown)
11603 KnownNamespaces[Namespc] = false;
11604
11605 if (II) {
11606 PushOnScopeChains(Namespc, DeclRegionScope);
11607 } else {
11608 // Link the anonymous namespace into its parent.
11610 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11611 TU->setAnonymousNamespace(Namespc);
11612 } else {
11613 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11614 }
11615
11616 CurContext->addDecl(Namespc);
11617
11618 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11619 // behaves as if it were replaced by
11620 // namespace unique { /* empty body */ }
11621 // using namespace unique;
11622 // namespace unique { namespace-body }
11623 // where all occurrences of 'unique' in a translation unit are
11624 // replaced by the same identifier and this identifier differs
11625 // from all other identifiers in the entire program.
11626
11627 // We just create the namespace with an empty name and then add an
11628 // implicit using declaration, just like the standard suggests.
11629 //
11630 // CodeGen enforces the "universally unique" aspect by giving all
11631 // declarations semantically contained within an anonymous
11632 // namespace internal linkage.
11633
11634 if (!PrevNS) {
11636 /* 'using' */ LBrace,
11637 /* 'namespace' */ SourceLocation(),
11638 /* qualifier */ NestedNameSpecifierLoc(),
11639 /* identifier */ SourceLocation(),
11640 Namespc,
11641 /* Ancestor */ Parent);
11642 UD->setImplicit();
11643 Parent->addDecl(UD);
11644 }
11645 }
11646
11647 ActOnDocumentableDecl(Namespc);
11648
11649 // Although we could have an invalid decl (i.e. the namespace name is a
11650 // redefinition), push it as current DeclContext and try to continue parsing.
11651 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11652 // for the namespace has the declarations that showed up in that particular
11653 // namespace definition.
11654 PushDeclContext(NamespcScope, Namespc);
11655 return Namespc;
11656}
11657
11658/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11659/// is a namespace alias, returns the namespace it points to.
11661 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11662 return AD->getNamespace();
11663 return dyn_cast_or_null<NamespaceDecl>(D);
11664}
11665
11667 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11668 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11669 Namespc->setRBraceLoc(RBrace);
11671 if (Namespc->hasAttr<VisibilityAttr>())
11672 PopPragmaVisibility(true, RBrace);
11673 // If this namespace contains an export-declaration, export it now.
11674 if (DeferredExportedNamespaces.erase(Namespc))
11676}
11677
11679 return cast_or_null<CXXRecordDecl>(
11681}
11682
11684 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11685}
11686
11688 return cast_or_null<NamespaceDecl>(
11690}
11691namespace {
11692
11693enum UnsupportedSTLSelect {
11694 USS_InvalidMember,
11695 USS_MissingMember,
11696 USS_NonTrivial,
11697 USS_Other
11698};
11699
11700struct InvalidSTLDiagnoser {
11701 Sema &S;
11703 QualType TyForDiags;
11704
11705 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11706 const VarDecl *VD = nullptr) {
11707 {
11708 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11709 << TyForDiags << ((int)Sel);
11710 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11711 assert(!Name.empty());
11712 D << Name;
11713 }
11714 }
11715 if (Sel == USS_InvalidMember) {
11716 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11717 << VD << VD->getSourceRange();
11718 }
11719 return QualType();
11720 }
11721};
11722} // namespace
11723
11727 assert(getLangOpts().CPlusPlus &&
11728 "Looking for comparison category type outside of C++.");
11729
11730 // Use an elaborated type for diagnostics which has a name containing the
11731 // prepended 'std' namespace but not any inline namespace names.
11732 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11733 auto *NNS =
11736 Info->getType());
11737 };
11738
11739 // Check if we've already successfully checked the comparison category type
11740 // before. If so, skip checking it again.
11742 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11743 // The only thing we need to check is that the type has a reachable
11744 // definition in the current context.
11745 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11746 return QualType();
11747
11748 return Info->getType();
11749 }
11750
11751 // If lookup failed
11752 if (!Info) {
11753 std::string NameForDiags = "std::";
11754 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11755 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11756 << NameForDiags << (int)Usage;
11757 return QualType();
11758 }
11759
11760 assert(Info->Kind == Kind);
11761 assert(Info->Record);
11762
11763 // Update the Record decl in case we encountered a forward declaration on our
11764 // first pass. FIXME: This is a bit of a hack.
11765 if (Info->Record->hasDefinition())
11766 Info->Record = Info->Record->getDefinition();
11767
11768 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11769 return QualType();
11770
11771 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11772
11773 if (!Info->Record->isTriviallyCopyable())
11774 return UnsupportedSTLError(USS_NonTrivial);
11775
11776 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11777 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11778 // Tolerate empty base classes.
11779 if (Base->isEmpty())
11780 continue;
11781 // Reject STL implementations which have at least one non-empty base.
11782 return UnsupportedSTLError();
11783 }
11784
11785 // Check that the STL has implemented the types using a single integer field.
11786 // This expectation allows better codegen for builtin operators. We require:
11787 // (1) The class has exactly one field.
11788 // (2) The field is an integral or enumeration type.
11789 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11790 if (std::distance(FIt, FEnd) != 1 ||
11791 !FIt->getType()->isIntegralOrEnumerationType()) {
11792 return UnsupportedSTLError();
11793 }
11794
11795 // Build each of the require values and store them in Info.
11796 for (ComparisonCategoryResult CCR :
11798 StringRef MemName = ComparisonCategories::getResultString(CCR);
11799 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11800
11801 if (!ValInfo)
11802 return UnsupportedSTLError(USS_MissingMember, MemName);
11803
11804 VarDecl *VD = ValInfo->VD;
11805 assert(VD && "should not be null!");
11806
11807 // Attempt to diagnose reasons why the STL definition of this type
11808 // might be foobar, including it failing to be a constant expression.
11809 // TODO Handle more ways the lookup or result can be invalid.
11810 if (!VD->isStaticDataMember() ||
11812 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11813
11814 // Attempt to evaluate the var decl as a constant expression and extract
11815 // the value of its first field as a ICE. If this fails, the STL
11816 // implementation is not supported.
11817 if (!ValInfo->hasValidIntValue())
11818 return UnsupportedSTLError();
11819
11821 }
11822
11823 // We've successfully built the required types and expressions. Update
11824 // the cache and return the newly cached value.
11825 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11826 return Info->getType();
11827}
11828
11830 if (!StdNamespace) {
11831 // The "std" namespace has not yet been defined, so build one implicitly.
11834 /*Inline=*/false, SourceLocation(), SourceLocation(),
11835 &PP.getIdentifierTable().get("std"),
11836 /*PrevDecl=*/nullptr, /*Nested=*/false);
11838 // We want the created NamespaceDecl to be available for redeclaration
11839 // lookups, but not for regular name lookups.
11842 }
11843
11844 return getStdNamespace();
11845}
11846
11848 assert(getLangOpts().CPlusPlus &&
11849 "Looking for std::initializer_list outside of C++.");
11850
11851 // We're looking for implicit instantiations of
11852 // template <typename E> class std::initializer_list.
11853
11854 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11855 return false;
11856
11857 ClassTemplateDecl *Template = nullptr;
11858 const TemplateArgument *Arguments = nullptr;
11859
11860 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11861
11863 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11864 if (!Specialization)
11865 return false;
11866
11867 Template = Specialization->getSpecializedTemplate();
11868 Arguments = Specialization->getTemplateArgs().data();
11869 } else {
11870 const TemplateSpecializationType *TST = nullptr;
11871 if (auto *ICN = Ty->getAs<InjectedClassNameType>())
11872 TST = ICN->getInjectedTST();
11873 else
11874 TST = Ty->getAs<TemplateSpecializationType>();
11875 if (TST) {
11876 Template = dyn_cast_or_null<ClassTemplateDecl>(
11878 Arguments = TST->template_arguments().begin();
11879 }
11880 }
11881 if (!Template)
11882 return false;
11883
11884 if (!StdInitializerList) {
11885 // Haven't recognized std::initializer_list yet, maybe this is it.
11886 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11887 if (TemplateClass->getIdentifier() !=
11888 &PP.getIdentifierTable().get("initializer_list") ||
11889 !getStdNamespace()->InEnclosingNamespaceSetOf(
11890 TemplateClass->getDeclContext()))
11891 return false;
11892 // This is a template called std::initializer_list, but is it the right
11893 // template?
11894 TemplateParameterList *Params = Template->getTemplateParameters();
11895 if (Params->getMinRequiredArguments() != 1)
11896 return false;
11897 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11898 return false;
11899
11900 // It's the right template.
11901 StdInitializerList = Template;
11902 }
11903
11905 return false;
11906
11907 // This is an instance of std::initializer_list. Find the argument type.
11908 if (Element)
11909 *Element = Arguments[0].getAsType();
11910 return true;
11911}
11912
11915 if (!Std) {
11916 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11917 return nullptr;
11918 }
11919
11920 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11922 if (!S.LookupQualifiedName(Result, Std)) {
11923 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11924 return nullptr;
11925 }
11926 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11927 if (!Template) {
11928 Result.suppressDiagnostics();
11929 // We found something weird. Complain about the first thing we found.
11930 NamedDecl *Found = *Result.begin();
11931 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11932 return nullptr;
11933 }
11934
11935 // We found some template called std::initializer_list. Now verify that it's
11936 // correct.
11937 TemplateParameterList *Params = Template->getTemplateParameters();
11938 if (Params->getMinRequiredArguments() != 1 ||
11939 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11940 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11941 return nullptr;
11942 }
11943
11944 return Template;
11945}
11946
11948 if (!StdInitializerList) {
11950 if (!StdInitializerList)
11951 return QualType();
11952 }
11953
11957 Loc)));
11962}
11963
11965 // C++ [dcl.init.list]p2:
11966 // A constructor is an initializer-list constructor if its first parameter
11967 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11968 // std::initializer_list<E> for some type E, and either there are no other
11969 // parameters or else all other parameters have default arguments.
11970 if (!Ctor->hasOneParamOrDefaultArgs())
11971 return false;
11972
11973 QualType ArgType = Ctor->getParamDecl(0)->getType();
11974 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11975 ArgType = RT->getPointeeType().getUnqualifiedType();
11976
11977 return isStdInitializerList(ArgType, nullptr);
11978}
11979
11980/// Determine whether a using statement is in a context where it will be
11981/// apply in all contexts.
11983 switch (CurContext->getDeclKind()) {
11984 case Decl::TranslationUnit:
11985 return true;
11986 case Decl::LinkageSpec:
11988 default:
11989 return false;
11990 }
11991}
11992
11993namespace {
11994
11995// Callback to only accept typo corrections that are namespaces.
11996class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11997public:
11998 bool ValidateCandidate(const TypoCorrection &candidate) override {
11999 if (NamedDecl *ND = candidate.getCorrectionDecl())
12000 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12001 return false;
12002 }
12003
12004 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12005 return std::make_unique<NamespaceValidatorCCC>(*this);
12006 }
12007};
12008
12009}
12010
12011static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12012 Sema &S) {
12013 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12014 Module *M = ND->getOwningModule();
12015 assert(M && "hidden namespace definition not in a module?");
12016
12017 if (M->isExplicitGlobalModule())
12018 S.Diag(Corrected.getCorrectionRange().getBegin(),
12019 diag::err_module_unimported_use_header)
12021 << /*Header Name*/ false;
12022 else
12023 S.Diag(Corrected.getCorrectionRange().getBegin(),
12024 diag::err_module_unimported_use)
12026 << M->getTopLevelModuleName();
12027}
12028
12030 CXXScopeSpec &SS,
12031 SourceLocation IdentLoc,
12032 IdentifierInfo *Ident) {
12033 R.clear();
12034 NamespaceValidatorCCC CCC{};
12035 if (TypoCorrection Corrected =
12036 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12038 // Generally we find it is confusing more than helpful to diagnose the
12039 // invisible namespace.
12040 // See https://github.com/llvm/llvm-project/issues/73893.
12041 //
12042 // However, we should diagnose when the users are trying to using an
12043 // invisible namespace. So we handle the case specially here.
12044 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12045 Corrected.requiresImport()) {
12046 DiagnoseInvisibleNamespace(Corrected, S);
12047 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12048 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12049 bool DroppedSpecifier =
12050 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12051 S.diagnoseTypo(Corrected,
12052 S.PDiag(diag::err_using_directive_member_suggest)
12053 << Ident << DC << DroppedSpecifier << SS.getRange(),
12054 S.PDiag(diag::note_namespace_defined_here));
12055 } else {
12056 S.diagnoseTypo(Corrected,
12057 S.PDiag(diag::err_using_directive_suggest) << Ident,
12058 S.PDiag(diag::note_namespace_defined_here));
12059 }
12060 R.addDecl(Corrected.getFoundDecl());
12061 return true;
12062 }
12063 return false;
12064}
12065
12067 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12068 SourceLocation IdentLoc,
12069 IdentifierInfo *NamespcName,
12070 const ParsedAttributesView &AttrList) {
12071 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12072 assert(NamespcName && "Invalid NamespcName.");
12073 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12074
12075 // Get the innermost enclosing declaration scope.
12076 S = S->getDeclParent();
12077
12078 UsingDirectiveDecl *UDir = nullptr;
12079 NestedNameSpecifier *Qualifier = nullptr;
12080 if (SS.isSet())
12081 Qualifier = SS.getScopeRep();
12082
12083 // Lookup namespace name.
12084 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12085 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12086 if (R.isAmbiguous())
12087 return nullptr;
12088
12089 if (R.empty()) {
12090 R.clear();
12091 // Allow "using namespace std;" or "using namespace ::std;" even if
12092 // "std" hasn't been defined yet, for GCC compatibility.
12093 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12094 NamespcName->isStr("std")) {
12095 Diag(IdentLoc, diag::ext_using_undefined_std);
12097 R.resolveKind();
12098 }
12099 // Otherwise, attempt typo correction.
12100 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12101 }
12102
12103 if (!R.empty()) {
12104 NamedDecl *Named = R.getRepresentativeDecl();
12106 assert(NS && "expected namespace decl");
12107
12108 // The use of a nested name specifier may trigger deprecation warnings.
12109 DiagnoseUseOfDecl(Named, IdentLoc);
12110
12111 // C++ [namespace.udir]p1:
12112 // A using-directive specifies that the names in the nominated
12113 // namespace can be used in the scope in which the
12114 // using-directive appears after the using-directive. During
12115 // unqualified name lookup (3.4.1), the names appear as if they
12116 // were declared in the nearest enclosing namespace which
12117 // contains both the using-directive and the nominated
12118 // namespace. [Note: in this context, "contains" means "contains
12119 // directly or indirectly". ]
12120
12121 // Find enclosing context containing both using-directive and
12122 // nominated namespace.
12123 DeclContext *CommonAncestor = NS;
12124 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12125 CommonAncestor = CommonAncestor->getParent();
12126
12127 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12129 IdentLoc, Named, CommonAncestor);
12130
12133 Diag(IdentLoc, diag::warn_using_directive_in_header);
12134 }
12135
12136 PushUsingDirective(S, UDir);
12137 } else {
12138 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12139 }
12140
12141 if (UDir) {
12142 ProcessDeclAttributeList(S, UDir, AttrList);
12143 ProcessAPINotes(UDir);
12144 }
12145
12146 return UDir;
12147}
12148
12150 // If the scope has an associated entity and the using directive is at
12151 // namespace or translation unit scope, add the UsingDirectiveDecl into
12152 // its lookup structure so qualified name lookup can find it.
12153 DeclContext *Ctx = S->getEntity();
12154 if (Ctx && !Ctx->isFunctionOrMethod())
12155 Ctx->addDecl(UDir);
12156 else
12157 // Otherwise, it is at block scope. The using-directives will affect lookup
12158 // only to the end of the scope.
12159 S->PushUsingDirective(UDir);
12160}
12161
12163 SourceLocation UsingLoc,
12164 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12165 UnqualifiedId &Name,
12166 SourceLocation EllipsisLoc,
12167 const ParsedAttributesView &AttrList) {
12168 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12169
12170 if (SS.isEmpty()) {
12171 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12172 return nullptr;
12173 }
12174
12175 switch (Name.getKind()) {
12181 break;
12182
12185 // C++11 inheriting constructors.
12186 Diag(Name.getBeginLoc(),
12188 ? diag::warn_cxx98_compat_using_decl_constructor
12189 : diag::err_using_decl_constructor)
12190 << SS.getRange();
12191
12192 if (getLangOpts().CPlusPlus11) break;
12193
12194 return nullptr;
12195
12197 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12198 return nullptr;
12199
12201 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12202 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12203 return nullptr;
12204
12206 llvm_unreachable("cannot parse qualified deduction guide name");
12207 }
12208
12209 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12210 DeclarationName TargetName = TargetNameInfo.getName();
12211 if (!TargetName)
12212 return nullptr;
12213
12214 // Warn about access declarations.
12215 if (UsingLoc.isInvalid()) {
12216 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12217 ? diag::err_access_decl
12218 : diag::warn_access_decl_deprecated)
12219 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12220 }
12221
12222 if (EllipsisLoc.isInvalid()) {
12225 return nullptr;
12226 } else {
12228 !TargetNameInfo.containsUnexpandedParameterPack()) {
12229 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12230 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12231 EllipsisLoc = SourceLocation();
12232 }
12233 }
12234
12235 NamedDecl *UD =
12236 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12237 SS, TargetNameInfo, EllipsisLoc, AttrList,
12238 /*IsInstantiation*/ false,
12239 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12240 if (UD)
12241 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12242
12243 return UD;
12244}
12245
12247 SourceLocation UsingLoc,
12248 SourceLocation EnumLoc, SourceRange TyLoc,
12249 const IdentifierInfo &II, ParsedType Ty,
12250 CXXScopeSpec *SS) {
12251 assert(!SS->isInvalid() && "ScopeSpec is invalid");
12252 TypeSourceInfo *TSI = nullptr;
12253 SourceLocation IdentLoc = TyLoc.getBegin();
12254 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12255 if (EnumTy.isNull()) {
12256 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12257 ? diag::err_using_enum_is_dependent
12258 : diag::err_unknown_typename)
12259 << II.getName()
12260 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, TyLoc.getEnd());
12261 return nullptr;
12262 }
12263
12264 if (EnumTy->isDependentType()) {
12265 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12266 return nullptr;
12267 }
12268
12269 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12270 if (!Enum) {
12271 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12272 return nullptr;
12273 }
12274
12275 if (auto *Def = Enum->getDefinition())
12276 Enum = Def;
12277
12278 if (TSI == nullptr)
12279 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12280
12281 auto *UD =
12282 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12283
12284 if (UD)
12285 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12286
12287 return UD;
12288}
12289
12290/// Determine whether a using declaration considers the given
12291/// declarations as "equivalent", e.g., if they are redeclarations of
12292/// the same entity or are both typedefs of the same type.
12293static bool
12295 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12296 return true;
12297
12298 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12299 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12300 return Context.hasSameType(TD1->getUnderlyingType(),
12301 TD2->getUnderlyingType());
12302
12303 // Two using_if_exists using-declarations are equivalent if both are
12304 // unresolved.
12305 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12306 isa<UnresolvedUsingIfExistsDecl>(D2))
12307 return true;
12308
12309 return false;
12310}
12311
12313 const LookupResult &Previous,
12314 UsingShadowDecl *&PrevShadow) {
12315 // Diagnose finding a decl which is not from a base class of the
12316 // current class. We do this now because there are cases where this
12317 // function will silently decide not to build a shadow decl, which
12318 // will pre-empt further diagnostics.
12319 //
12320 // We don't need to do this in C++11 because we do the check once on
12321 // the qualifier.
12322 //
12323 // FIXME: diagnose the following if we care enough:
12324 // struct A { int foo; };
12325 // struct B : A { using A::foo; };
12326 // template <class T> struct C : A {};
12327 // template <class T> struct D : C<T> { using B::foo; } // <---
12328 // This is invalid (during instantiation) in C++03 because B::foo
12329 // resolves to the using decl in B, which is not a base class of D<T>.
12330 // We can't diagnose it immediately because C<T> is an unknown
12331 // specialization. The UsingShadowDecl in D<T> then points directly
12332 // to A::foo, which will look well-formed when we instantiate.
12333 // The right solution is to not collapse the shadow-decl chain.
12335 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12336 DeclContext *OrigDC = Orig->getDeclContext();
12337
12338 // Handle enums and anonymous structs.
12339 if (isa<EnumDecl>(OrigDC))
12340 OrigDC = OrigDC->getParent();
12341 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12342 while (OrigRec->isAnonymousStructOrUnion())
12343 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12344
12345 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12346 if (OrigDC == CurContext) {
12347 Diag(Using->getLocation(),
12348 diag::err_using_decl_nested_name_specifier_is_current_class)
12349 << Using->getQualifierLoc().getSourceRange();
12350 Diag(Orig->getLocation(), diag::note_using_decl_target);
12351 Using->setInvalidDecl();
12352 return true;
12353 }
12354
12355 Diag(Using->getQualifierLoc().getBeginLoc(),
12356 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12357 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12358 << Using->getQualifierLoc().getSourceRange();
12359 Diag(Orig->getLocation(), diag::note_using_decl_target);
12360 Using->setInvalidDecl();
12361 return true;
12362 }
12363 }
12364
12365 if (Previous.empty()) return false;
12366
12367 NamedDecl *Target = Orig;
12368 if (isa<UsingShadowDecl>(Target))
12369 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12370
12371 // If the target happens to be one of the previous declarations, we
12372 // don't have a conflict.
12373 //
12374 // FIXME: but we might be increasing its access, in which case we
12375 // should redeclare it.
12376 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12377 bool FoundEquivalentDecl = false;
12378 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12379 I != E; ++I) {
12380 NamedDecl *D = (*I)->getUnderlyingDecl();
12381 // We can have UsingDecls in our Previous results because we use the same
12382 // LookupResult for checking whether the UsingDecl itself is a valid
12383 // redeclaration.
12384 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12385 continue;
12386
12387 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12388 // C++ [class.mem]p19:
12389 // If T is the name of a class, then [every named member other than
12390 // a non-static data member] shall have a name different from T
12391 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12392 !isa<IndirectFieldDecl>(Target) &&
12393 !isa<UnresolvedUsingValueDecl>(Target) &&
12395 CurContext,
12397 return true;
12398 }
12399
12401 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12402 PrevShadow = Shadow;
12403 FoundEquivalentDecl = true;
12405 // We don't conflict with an existing using shadow decl of an equivalent
12406 // declaration, but we're not a redeclaration of it.
12407 FoundEquivalentDecl = true;
12408 }
12409
12410 if (isVisible(D))
12411 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12412 }
12413
12414 if (FoundEquivalentDecl)
12415 return false;
12416
12417 // Always emit a diagnostic for a mismatch between an unresolved
12418 // using_if_exists and a resolved using declaration in either direction.
12419 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12420 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12421 if (!NonTag && !Tag)
12422 return false;
12423 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12424 Diag(Target->getLocation(), diag::note_using_decl_target);
12425 Diag((NonTag ? NonTag : Tag)->getLocation(),
12426 diag::note_using_decl_conflict);
12427 BUD->setInvalidDecl();
12428 return true;
12429 }
12430
12431 if (FunctionDecl *FD = Target->getAsFunction()) {
12432 NamedDecl *OldDecl = nullptr;
12433 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12434 /*IsForUsingDecl*/ true)) {
12435 case Ovl_Overload:
12436 return false;
12437
12438 case Ovl_NonFunction:
12439 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12440 break;
12441
12442 // We found a decl with the exact signature.
12443 case Ovl_Match:
12444 // If we're in a record, we want to hide the target, so we
12445 // return true (without a diagnostic) to tell the caller not to
12446 // build a shadow decl.
12447 if (CurContext->isRecord())
12448 return true;
12449
12450 // If we're not in a record, this is an error.
12451 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12452 break;
12453 }
12454
12455 Diag(Target->getLocation(), diag::note_using_decl_target);
12456 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12457 BUD->setInvalidDecl();
12458 return true;
12459 }
12460
12461 // Target is not a function.
12462
12463 if (isa<TagDecl>(Target)) {
12464 // No conflict between a tag and a non-tag.
12465 if (!Tag) return false;
12466
12467 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12468 Diag(Target->getLocation(), diag::note_using_decl_target);
12469 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12470 BUD->setInvalidDecl();
12471 return true;
12472 }
12473
12474 // No conflict between a tag and a non-tag.
12475 if (!NonTag) return false;
12476
12477 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12478 Diag(Target->getLocation(), diag::note_using_decl_target);
12479 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12480 BUD->setInvalidDecl();
12481 return true;
12482}
12483
12484/// Determine whether a direct base class is a virtual base class.
12486 if (!Derived->getNumVBases())
12487 return false;
12488 for (auto &B : Derived->bases())
12489 if (B.getType()->getAsCXXRecordDecl() == Base)
12490 return B.isVirtual();
12491 llvm_unreachable("not a direct base class");
12492}
12493
12495 NamedDecl *Orig,
12496 UsingShadowDecl *PrevDecl) {
12497 // If we resolved to another shadow declaration, just coalesce them.
12498 NamedDecl *Target = Orig;
12499 if (isa<UsingShadowDecl>(Target)) {
12500 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12501 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12502 }
12503
12504 NamedDecl *NonTemplateTarget = Target;
12505 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12506 NonTemplateTarget = TargetTD->getTemplatedDecl();
12507
12508 UsingShadowDecl *Shadow;
12509 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12510 UsingDecl *Using = cast<UsingDecl>(BUD);
12511 bool IsVirtualBase =
12512 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12513 Using->getQualifier()->getAsRecordDecl());
12515 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12516 } else {
12518 Target->getDeclName(), BUD, Target);
12519 }
12520 BUD->addShadowDecl(Shadow);
12521
12522 Shadow->setAccess(BUD->getAccess());
12523 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12524 Shadow->setInvalidDecl();
12525
12526 Shadow->setPreviousDecl(PrevDecl);
12527
12528 if (S)
12529 PushOnScopeChains(Shadow, S);
12530 else
12531 CurContext->addDecl(Shadow);
12532
12533
12534 return Shadow;
12535}
12536
12538 if (Shadow->getDeclName().getNameKind() ==
12540 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12541
12542 // Remove it from the DeclContext...
12543 Shadow->getDeclContext()->removeDecl(Shadow);
12544
12545 // ...and the scope, if applicable...
12546 if (S) {
12547 S->RemoveDecl(Shadow);
12548 IdResolver.RemoveDecl(Shadow);
12549 }
12550
12551 // ...and the using decl.
12552 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12553
12554 // TODO: complain somehow if Shadow was used. It shouldn't
12555 // be possible for this to happen, because...?
12556}
12557
12558/// Find the base specifier for a base class with the given type.
12560 QualType DesiredBase,
12561 bool &AnyDependentBases) {
12562 // Check whether the named type is a direct base class.
12563 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12565 for (auto &Base : Derived->bases()) {
12566 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12567 if (CanonicalDesiredBase == BaseType)
12568 return &Base;
12569 if (BaseType->isDependentType())
12570 AnyDependentBases = true;
12571 }
12572 return nullptr;
12573}
12574
12575namespace {
12576class UsingValidatorCCC final : public CorrectionCandidateCallback {
12577public:
12578 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12579 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12580 : HasTypenameKeyword(HasTypenameKeyword),
12581 IsInstantiation(IsInstantiation), OldNNS(NNS),
12582 RequireMemberOf(RequireMemberOf) {}
12583
12584 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12585 NamedDecl *ND = Candidate.getCorrectionDecl();
12586
12587 // Keywords are not valid here.
12588 if (!ND || isa<NamespaceDecl>(ND))
12589 return false;
12590
12591 // Completely unqualified names are invalid for a 'using' declaration.
12592 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12593 return false;
12594
12595 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12596 // reject.
12597
12598 if (RequireMemberOf) {
12599 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12600 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12601 // No-one ever wants a using-declaration to name an injected-class-name
12602 // of a base class, unless they're declaring an inheriting constructor.
12603 ASTContext &Ctx = ND->getASTContext();
12604 if (!Ctx.getLangOpts().CPlusPlus11)
12605 return false;
12606 QualType FoundType = Ctx.getRecordType(FoundRecord);
12607
12608 // Check that the injected-class-name is named as a member of its own
12609 // type; we don't want to suggest 'using Derived::Base;', since that
12610 // means something else.
12612 Candidate.WillReplaceSpecifier()
12613 ? Candidate.getCorrectionSpecifier()
12614 : OldNNS;
12615 if (!Specifier->getAsType() ||
12616 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12617 return false;
12618
12619 // Check that this inheriting constructor declaration actually names a
12620 // direct base class of the current class.
12621 bool AnyDependentBases = false;
12622 if (!findDirectBaseWithType(RequireMemberOf,
12623 Ctx.getRecordType(FoundRecord),
12624 AnyDependentBases) &&
12625 !AnyDependentBases)
12626 return false;
12627 } else {
12628 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12629 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12630 return false;
12631
12632 // FIXME: Check that the base class member is accessible?
12633 }
12634 } else {
12635 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12636 if (FoundRecord && FoundRecord->isInjectedClassName())
12637 return false;
12638 }
12639
12640 if (isa<TypeDecl>(ND))
12641 return HasTypenameKeyword || !IsInstantiation;
12642
12643 return !HasTypenameKeyword;
12644 }
12645
12646 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12647 return std::make_unique<UsingValidatorCCC>(*this);
12648 }
12649
12650private:
12651 bool HasTypenameKeyword;
12652 bool IsInstantiation;
12653 NestedNameSpecifier *OldNNS;
12654 CXXRecordDecl *RequireMemberOf;
12655};
12656} // end anonymous namespace
12657
12659 // It is really dumb that we have to do this.
12660 LookupResult::Filter F = Previous.makeFilter();
12661 while (F.hasNext()) {
12662 NamedDecl *D = F.next();
12663 if (!isDeclInScope(D, CurContext, S))
12664 F.erase();
12665 // If we found a local extern declaration that's not ordinarily visible,
12666 // and this declaration is being added to a non-block scope, ignore it.
12667 // We're only checking for scope conflicts here, not also for violations
12668 // of the linkage rules.
12669 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12671 F.erase();
12672 }
12673 F.done();
12674}
12675
12677 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12678 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12679 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12680 const ParsedAttributesView &AttrList, bool IsInstantiation,
12681 bool IsUsingIfExists) {
12682 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12683 SourceLocation IdentLoc = NameInfo.getLoc();
12684 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12685
12686 // FIXME: We ignore attributes for now.
12687
12688 // For an inheriting constructor declaration, the name of the using
12689 // declaration is the name of a constructor in this class, not in the
12690 // base class.
12691 DeclarationNameInfo UsingName = NameInfo;
12693 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12696
12697 // Do the redeclaration lookup in the current scope.
12698 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12699 RedeclarationKind::ForVisibleRedeclaration);
12700 Previous.setHideTags(false);
12701 if (S) {
12702 LookupName(Previous, S);
12703
12705 } else {
12706 assert(IsInstantiation && "no scope in non-instantiation");
12707 if (CurContext->isRecord())
12709 else {
12710 // No redeclaration check is needed here; in non-member contexts we
12711 // diagnosed all possible conflicts with other using-declarations when
12712 // building the template:
12713 //
12714 // For a dependent non-type using declaration, the only valid case is
12715 // if we instantiate to a single enumerator. We check for conflicts
12716 // between shadow declarations we introduce, and we check in the template
12717 // definition for conflicts between a non-type using declaration and any
12718 // other declaration, which together covers all cases.
12719 //
12720 // A dependent typename using declaration will never successfully
12721 // instantiate, since it will always name a class member, so we reject
12722 // that in the template definition.
12723 }
12724 }
12725
12726 // Check for invalid redeclarations.
12727 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12728 SS, IdentLoc, Previous))
12729 return nullptr;
12730
12731 // 'using_if_exists' doesn't make sense on an inherited constructor.
12732 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12734 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12735 return nullptr;
12736 }
12737
12738 DeclContext *LookupContext = computeDeclContext(SS);
12740 if (!LookupContext || EllipsisLoc.isValid()) {
12741 NamedDecl *D;
12742 // Dependent scope, or an unexpanded pack
12743 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12744 SS, NameInfo, IdentLoc))
12745 return nullptr;
12746
12747 if (HasTypenameKeyword) {
12748 // FIXME: not all declaration name kinds are legal here
12750 UsingLoc, TypenameLoc,
12751 QualifierLoc,
12752 IdentLoc, NameInfo.getName(),
12753 EllipsisLoc);
12754 } else {
12756 QualifierLoc, NameInfo, EllipsisLoc);
12757 }
12758 D->setAccess(AS);
12760 ProcessDeclAttributeList(S, D, AttrList);
12761 return D;
12762 }
12763
12764 auto Build = [&](bool Invalid) {
12765 UsingDecl *UD =
12766 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12767 UsingName, HasTypenameKeyword);
12768 UD->setAccess(AS);
12769 CurContext->addDecl(UD);
12770 ProcessDeclAttributeList(S, UD, AttrList);
12772 return UD;
12773 };
12774 auto BuildInvalid = [&]{ return Build(true); };
12775 auto BuildValid = [&]{ return Build(false); };
12776
12777 if (RequireCompleteDeclContext(SS, LookupContext))
12778 return BuildInvalid();
12779
12780 // Look up the target name.
12781 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12782
12783 // Unlike most lookups, we don't always want to hide tag
12784 // declarations: tag names are visible through the using declaration
12785 // even if hidden by ordinary names, *except* in a dependent context
12786 // where they may be used by two-phase lookup.
12787 if (!IsInstantiation)
12788 R.setHideTags(false);
12789
12790 // For the purposes of this lookup, we have a base object type
12791 // equal to that of the current context.
12792 if (CurContext->isRecord()) {
12794 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12795 }
12796
12797 LookupQualifiedName(R, LookupContext);
12798
12799 // Validate the context, now we have a lookup
12800 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12801 IdentLoc, &R))
12802 return nullptr;
12803
12804 if (R.empty() && IsUsingIfExists)
12806 UsingName.getName()),
12807 AS_public);
12808
12809 // Try to correct typos if possible. If constructor name lookup finds no
12810 // results, that means the named class has no explicit constructors, and we
12811 // suppressed declaring implicit ones (probably because it's dependent or
12812 // invalid).
12813 if (R.empty() &&
12815 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12816 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12817 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12818 auto *II = NameInfo.getName().getAsIdentifierInfo();
12819 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12821 isa<TranslationUnitDecl>(LookupContext) &&
12822 getSourceManager().isInSystemHeader(UsingLoc))
12823 return nullptr;
12824 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12825 dyn_cast<CXXRecordDecl>(CurContext));
12826 if (TypoCorrection Corrected =
12827 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12829 // We reject candidates where DroppedSpecifier == true, hence the
12830 // literal '0' below.
12831 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12832 << NameInfo.getName() << LookupContext << 0
12833 << SS.getRange());
12834
12835 // If we picked a correction with no attached Decl we can't do anything
12836 // useful with it, bail out.
12837 NamedDecl *ND = Corrected.getCorrectionDecl();
12838 if (!ND)
12839 return BuildInvalid();
12840
12841 // If we corrected to an inheriting constructor, handle it as one.
12842 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12843 if (RD && RD->isInjectedClassName()) {
12844 // The parent of the injected class name is the class itself.
12845 RD = cast<CXXRecordDecl>(RD->getParent());
12846
12847 // Fix up the information we'll use to build the using declaration.
12848 if (Corrected.WillReplaceSpecifier()) {
12850 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12851 QualifierLoc.getSourceRange());
12852 QualifierLoc = Builder.getWithLocInContext(Context);
12853 }
12854
12855 // In this case, the name we introduce is the name of a derived class
12856 // constructor.
12857 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12860 UsingName.setNamedTypeInfo(nullptr);
12861 for (auto *Ctor : LookupConstructors(RD))
12862 R.addDecl(Ctor);
12863 R.resolveKind();
12864 } else {
12865 // FIXME: Pick up all the declarations if we found an overloaded
12866 // function.
12867 UsingName.setName(ND->getDeclName());
12868 R.addDecl(ND);
12869 }
12870 } else {
12871 Diag(IdentLoc, diag::err_no_member)
12872 << NameInfo.getName() << LookupContext << SS.getRange();
12873 return BuildInvalid();
12874 }
12875 }
12876
12877 if (R.isAmbiguous())
12878 return BuildInvalid();
12879
12880 if (HasTypenameKeyword) {
12881 // If we asked for a typename and got a non-type decl, error out.
12882 if (!R.getAsSingle<TypeDecl>() &&
12884 Diag(IdentLoc, diag::err_using_typename_non_type);
12885 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12886 Diag((*I)->getUnderlyingDecl()->getLocation(),
12887 diag::note_using_decl_target);
12888 return BuildInvalid();
12889 }
12890 } else {
12891 // If we asked for a non-typename and we got a type, error out,
12892 // but only if this is an instantiation of an unresolved using
12893 // decl. Otherwise just silently find the type name.
12894 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12895 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12896 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12897 return BuildInvalid();
12898 }
12899 }
12900
12901 // C++14 [namespace.udecl]p6:
12902 // A using-declaration shall not name a namespace.
12903 if (R.getAsSingle<NamespaceDecl>()) {
12904 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12905 << SS.getRange();
12906 // Suggest using 'using namespace ...' instead.
12907 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
12908 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
12909 return BuildInvalid();
12910 }
12911
12912 UsingDecl *UD = BuildValid();
12913
12914 // Some additional rules apply to inheriting constructors.
12915 if (UsingName.getName().getNameKind() ==
12917 // Suppress access diagnostics; the access check is instead performed at the
12918 // point of use for an inheriting constructor.
12921 return UD;
12922 }
12923
12924 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12925 UsingShadowDecl *PrevDecl = nullptr;
12926 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12927 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12928 }
12929
12930 return UD;
12931}
12932
12934 SourceLocation UsingLoc,
12935 SourceLocation EnumLoc,
12936 SourceLocation NameLoc,
12938 EnumDecl *ED) {
12939 bool Invalid = false;
12940
12942 /// In class scope, check if this is a duplicate, for better a diagnostic.
12943 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12944 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12945 RedeclarationKind::ForVisibleRedeclaration);
12946
12947 LookupName(Previous, S);
12948
12949 for (NamedDecl *D : Previous)
12950 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12951 if (UED->getEnumDecl() == ED) {
12952 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12953 << SourceRange(EnumLoc, NameLoc);
12954 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12955 Invalid = true;
12956 break;
12957 }
12958 }
12959
12960 if (RequireCompleteEnumDecl(ED, NameLoc))
12961 Invalid = true;
12962
12964 EnumLoc, NameLoc, EnumType);
12965 UD->setAccess(AS);
12966 CurContext->addDecl(UD);
12967
12968 if (Invalid) {
12969 UD->setInvalidDecl();
12970 return UD;
12971 }
12972
12973 // Create the shadow decls for each enumerator
12974 for (EnumConstantDecl *EC : ED->enumerators()) {
12975 UsingShadowDecl *PrevDecl = nullptr;
12976 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12978 RedeclarationKind::ForVisibleRedeclaration);
12979 LookupName(Previous, S);
12981
12982 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12983 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12984 }
12985
12986 return UD;
12987}
12988
12990 ArrayRef<NamedDecl *> Expansions) {
12991 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12992 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12993 isa<UsingPackDecl>(InstantiatedFrom));
12994
12995 auto *UPD =
12996 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12997 UPD->setAccess(InstantiatedFrom->getAccess());
12998 CurContext->addDecl(UPD);
12999 return UPD;
13000}
13001
13003 assert(!UD->hasTypename() && "expecting a constructor name");
13004
13005 const Type *SourceType = UD->getQualifier()->getAsType();
13006 assert(SourceType &&
13007 "Using decl naming constructor doesn't have type in scope spec.");
13008 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13009
13010 // Check whether the named type is a direct base class.
13011 bool AnyDependentBases = false;
13012 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13013 AnyDependentBases);
13014 if (!Base && !AnyDependentBases) {
13015 Diag(UD->getUsingLoc(),
13016 diag::err_using_decl_constructor_not_in_direct_base)
13017 << UD->getNameInfo().getSourceRange()
13018 << QualType(SourceType, 0) << TargetClass;
13019 UD->setInvalidDecl();
13020 return true;
13021 }
13022
13023 if (Base)
13024 Base->setInheritConstructors();
13025
13026 return false;
13027}
13028
13030 bool HasTypenameKeyword,
13031 const CXXScopeSpec &SS,
13032 SourceLocation NameLoc,
13033 const LookupResult &Prev) {
13034 NestedNameSpecifier *Qual = SS.getScopeRep();
13035
13036 // C++03 [namespace.udecl]p8:
13037 // C++0x [namespace.udecl]p10:
13038 // A using-declaration is a declaration and can therefore be used
13039 // repeatedly where (and only where) multiple declarations are
13040 // allowed.
13041 //
13042 // That's in non-member contexts.
13044 // A dependent qualifier outside a class can only ever resolve to an
13045 // enumeration type. Therefore it conflicts with any other non-type
13046 // declaration in the same scope.
13047 // FIXME: How should we check for dependent type-type conflicts at block
13048 // scope?
13049 if (Qual->isDependent() && !HasTypenameKeyword) {
13050 for (auto *D : Prev) {
13051 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13052 bool OldCouldBeEnumerator =
13053 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13054 Diag(NameLoc,
13055 OldCouldBeEnumerator ? diag::err_redefinition
13056 : diag::err_redefinition_different_kind)
13057 << Prev.getLookupName();
13058 Diag(D->getLocation(), diag::note_previous_definition);
13059 return true;
13060 }
13061 }
13062 }
13063 return false;
13064 }
13065
13066 const NestedNameSpecifier *CNNS =
13068 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13069 NamedDecl *D = *I;
13070
13071 bool DTypename;
13072 NestedNameSpecifier *DQual;
13073 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13074 DTypename = UD->hasTypename();
13075 DQual = UD->getQualifier();
13076 } else if (UnresolvedUsingValueDecl *UD
13077 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13078 DTypename = false;
13079 DQual = UD->getQualifier();
13080 } else if (UnresolvedUsingTypenameDecl *UD
13081 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13082 DTypename = true;
13083 DQual = UD->getQualifier();
13084 } else continue;
13085
13086 // using decls differ if one says 'typename' and the other doesn't.
13087 // FIXME: non-dependent using decls?
13088 if (HasTypenameKeyword != DTypename) continue;
13089
13090 // using decls differ if they name different scopes (but note that
13091 // template instantiation can cause this check to trigger when it
13092 // didn't before instantiation).
13093 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13094 continue;
13095
13096 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13097 Diag(D->getLocation(), diag::note_using_decl) << 1;
13098 return true;
13099 }
13100
13101 return false;
13102}
13103
13104bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13105 const CXXScopeSpec &SS,
13106 const DeclarationNameInfo &NameInfo,
13107 SourceLocation NameLoc,
13108 const LookupResult *R, const UsingDecl *UD) {
13109 DeclContext *NamedContext = computeDeclContext(SS);
13110 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13111 "resolvable context must have exactly one set of decls");
13112
13113 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13114 // relationship.
13115 bool Cxx20Enumerator = false;
13116 if (NamedContext) {
13117 EnumConstantDecl *EC = nullptr;
13118 if (R)
13119 EC = R->getAsSingle<EnumConstantDecl>();
13120 else if (UD && UD->shadow_size() == 1)
13121 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13122 if (EC)
13123 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13124
13125 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13126 // C++14 [namespace.udecl]p7:
13127 // A using-declaration shall not name a scoped enumerator.
13128 // C++20 p1099 permits enumerators.
13129 if (EC && R && ED->isScoped())
13130 Diag(SS.getBeginLoc(),
13132 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13133 : diag::ext_using_decl_scoped_enumerator)
13134 << SS.getRange();
13135
13136 // We want to consider the scope of the enumerator
13137 NamedContext = ED->getDeclContext();
13138 }
13139 }
13140
13141 if (!CurContext->isRecord()) {
13142 // C++03 [namespace.udecl]p3:
13143 // C++0x [namespace.udecl]p8:
13144 // A using-declaration for a class member shall be a member-declaration.
13145 // C++20 [namespace.udecl]p7
13146 // ... other than an enumerator ...
13147
13148 // If we weren't able to compute a valid scope, it might validly be a
13149 // dependent class or enumeration scope. If we have a 'typename' keyword,
13150 // the scope must resolve to a class type.
13151 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13152 : !HasTypename)
13153 return false; // OK
13154
13155 Diag(NameLoc,
13156 Cxx20Enumerator
13157 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13158 : diag::err_using_decl_can_not_refer_to_class_member)
13159 << SS.getRange();
13160
13161 if (Cxx20Enumerator)
13162 return false; // OK
13163
13164 auto *RD = NamedContext
13165 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13166 : nullptr;
13167 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13168 // See if there's a helpful fixit
13169
13170 if (!R) {
13171 // We will have already diagnosed the problem on the template
13172 // definition, Maybe we should do so again?
13173 } else if (R->getAsSingle<TypeDecl>()) {
13174 if (getLangOpts().CPlusPlus11) {
13175 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13176 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13177 << 0 // alias declaration
13179 NameInfo.getName().getAsString() +
13180 " = ");
13181 } else {
13182 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13183 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13184 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13185 << 1 // typedef declaration
13186 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13188 InsertLoc, " " + NameInfo.getName().getAsString());
13189 }
13190 } else if (R->getAsSingle<VarDecl>()) {
13191 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13192 // repeating the type of the static data member here.
13193 FixItHint FixIt;
13194 if (getLangOpts().CPlusPlus11) {
13195 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13197 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13198 }
13199
13200 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13201 << 2 // reference declaration
13202 << FixIt;
13203 } else if (R->getAsSingle<EnumConstantDecl>()) {
13204 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13205 // repeating the type of the enumeration here, and we can't do so if
13206 // the type is anonymous.
13207 FixItHint FixIt;
13208 if (getLangOpts().CPlusPlus11) {
13209 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13211 UsingLoc,
13212 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13213 }
13214
13215 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13216 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13217 << FixIt;
13218 }
13219 }
13220
13221 return true; // Fail
13222 }
13223
13224 // If the named context is dependent, we can't decide much.
13225 if (!NamedContext) {
13226 // FIXME: in C++0x, we can diagnose if we can prove that the
13227 // nested-name-specifier does not refer to a base class, which is
13228 // still possible in some cases.
13229
13230 // Otherwise we have to conservatively report that things might be
13231 // okay.
13232 return false;
13233 }
13234
13235 // The current scope is a record.
13236 if (!NamedContext->isRecord()) {
13237 // Ideally this would point at the last name in the specifier,
13238 // but we don't have that level of source info.
13239 Diag(SS.getBeginLoc(),
13240 Cxx20Enumerator
13241 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13242 : diag::err_using_decl_nested_name_specifier_is_not_class)
13243 << SS.getScopeRep() << SS.getRange();
13244
13245 if (Cxx20Enumerator)
13246 return false; // OK
13247
13248 return true;
13249 }
13250
13251 if (!NamedContext->isDependentContext() &&
13252 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13253 return true;
13254
13255 if (getLangOpts().CPlusPlus11) {
13256 // C++11 [namespace.udecl]p3:
13257 // In a using-declaration used as a member-declaration, the
13258 // nested-name-specifier shall name a base class of the class
13259 // being defined.
13260
13261 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13262 cast<CXXRecordDecl>(NamedContext))) {
13263
13264 if (Cxx20Enumerator) {
13265 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13266 << SS.getRange();
13267 return false;
13268 }
13269
13270 if (CurContext == NamedContext) {
13271 Diag(SS.getBeginLoc(),
13272 diag::err_using_decl_nested_name_specifier_is_current_class)
13273 << SS.getRange();
13274 return !getLangOpts().CPlusPlus20;
13275 }
13276
13277 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13278 Diag(SS.getBeginLoc(),
13279 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13280 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13281 << SS.getRange();
13282 }
13283 return true;
13284 }
13285
13286 return false;
13287 }
13288
13289 // C++03 [namespace.udecl]p4:
13290 // A using-declaration used as a member-declaration shall refer
13291 // to a member of a base class of the class being defined [etc.].
13292
13293 // Salient point: SS doesn't have to name a base class as long as
13294 // lookup only finds members from base classes. Therefore we can
13295 // diagnose here only if we can prove that can't happen,
13296 // i.e. if the class hierarchies provably don't intersect.
13297
13298 // TODO: it would be nice if "definitely valid" results were cached
13299 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13300 // need to be repeated.
13301
13303 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13304 Bases.insert(Base);
13305 return true;
13306 };
13307
13308 // Collect all bases. Return false if we find a dependent base.
13309 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13310 return false;
13311
13312 // Returns true if the base is dependent or is one of the accumulated base
13313 // classes.
13314 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13315 return !Bases.count(Base);
13316 };
13317
13318 // Return false if the class has a dependent base or if it or one
13319 // of its bases is present in the base set of the current context.
13320 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13321 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13322 return false;
13323
13324 Diag(SS.getRange().getBegin(),
13325 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13326 << SS.getScopeRep()
13327 << cast<CXXRecordDecl>(CurContext)
13328 << SS.getRange();
13329
13330 return true;
13331}
13332
13334 MultiTemplateParamsArg TemplateParamLists,
13335 SourceLocation UsingLoc, UnqualifiedId &Name,
13336 const ParsedAttributesView &AttrList,
13337 TypeResult Type, Decl *DeclFromDeclSpec) {
13338 // Get the innermost enclosing declaration scope.
13339 S = S->getDeclParent();
13340
13341 if (Type.isInvalid())
13342 return nullptr;
13343
13344 bool Invalid = false;
13346 TypeSourceInfo *TInfo = nullptr;
13347 GetTypeFromParser(Type.get(), &TInfo);
13348
13349 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13350 return nullptr;
13351
13352 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13354 Invalid = true;
13356 TInfo->getTypeLoc().getBeginLoc());
13357 }
13358
13359 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13360 TemplateParamLists.size()
13362 : RedeclarationKind::ForVisibleRedeclaration);
13363 LookupName(Previous, S);
13364
13365 // Warn about shadowing the name of a template parameter.
13366 if (Previous.isSingleResult() &&
13367 Previous.getFoundDecl()->isTemplateParameter()) {
13368 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13369 Previous.clear();
13370 }
13371
13372 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13373 "name in alias declaration must be an identifier");
13375 Name.StartLocation,
13376 Name.Identifier, TInfo);
13377
13378 NewTD->setAccess(AS);
13379
13380 if (Invalid)
13381 NewTD->setInvalidDecl();
13382
13383 ProcessDeclAttributeList(S, NewTD, AttrList);
13384 AddPragmaAttributes(S, NewTD);
13385 ProcessAPINotes(NewTD);
13386
13388 Invalid |= NewTD->isInvalidDecl();
13389
13390 bool Redeclaration = false;
13391
13392 NamedDecl *NewND;
13393 if (TemplateParamLists.size()) {
13394 TypeAliasTemplateDecl *OldDecl = nullptr;
13395 TemplateParameterList *OldTemplateParams = nullptr;
13396
13397 if (TemplateParamLists.size() != 1) {
13398 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13399 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13400 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13401 Invalid = true;
13402 }
13403 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13404
13405 // Check that we can declare a template here.
13406 if (CheckTemplateDeclScope(S, TemplateParams))
13407 return nullptr;
13408
13409 // Only consider previous declarations in the same scope.
13410 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13411 /*ExplicitInstantiationOrSpecialization*/false);
13412 if (!Previous.empty()) {
13413 Redeclaration = true;
13414
13415 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13416 if (!OldDecl && !Invalid) {
13417 Diag(UsingLoc, diag::err_redefinition_different_kind)
13418 << Name.Identifier;
13419
13420 NamedDecl *OldD = Previous.getRepresentativeDecl();
13421 if (OldD->getLocation().isValid())
13422 Diag(OldD->getLocation(), diag::note_previous_definition);
13423
13424 Invalid = true;
13425 }
13426
13427 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13428 if (TemplateParameterListsAreEqual(TemplateParams,
13429 OldDecl->getTemplateParameters(),
13430 /*Complain=*/true,
13432 OldTemplateParams =
13434 else
13435 Invalid = true;
13436
13437 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13438 if (!Invalid &&
13440 NewTD->getUnderlyingType())) {
13441 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13442 // but we can't reasonably accept it.
13443 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13444 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13445 if (OldTD->getLocation().isValid())
13446 Diag(OldTD->getLocation(), diag::note_previous_definition);
13447 Invalid = true;
13448 }
13449 }
13450 }
13451
13452 // Merge any previous default template arguments into our parameters,
13453 // and check the parameter list.
13454 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13456 return nullptr;
13457
13458 TypeAliasTemplateDecl *NewDecl =
13460 Name.Identifier, TemplateParams,
13461 NewTD);
13462 NewTD->setDescribedAliasTemplate(NewDecl);
13463
13464 NewDecl->setAccess(AS);
13465
13466 if (Invalid)
13467 NewDecl->setInvalidDecl();
13468 else if (OldDecl) {
13469 NewDecl->setPreviousDecl(OldDecl);
13470 CheckRedeclarationInModule(NewDecl, OldDecl);
13471 }
13472
13473 NewND = NewDecl;
13474 } else {
13475 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13477 handleTagNumbering(TD, S);
13478 }
13479 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13480 NewND = NewTD;
13481 }
13482
13483 PushOnScopeChains(NewND, S);
13484 ActOnDocumentableDecl(NewND);
13485 return NewND;
13486}
13487
13489 SourceLocation AliasLoc,
13490 IdentifierInfo *Alias, CXXScopeSpec &SS,
13491 SourceLocation IdentLoc,
13492 IdentifierInfo *Ident) {
13493
13494 // Lookup the namespace name.
13495 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13496 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13497
13498 if (R.isAmbiguous())
13499 return nullptr;
13500
13501 if (R.empty()) {
13502 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13503 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13504 return nullptr;
13505 }
13506 }
13507 assert(!R.isAmbiguous() && !R.empty());
13509
13510 // Check if we have a previous declaration with the same name.
13511 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13512 RedeclarationKind::ForVisibleRedeclaration);
13513 LookupName(PrevR, S);
13514
13515 // Check we're not shadowing a template parameter.
13516 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13518 PrevR.clear();
13519 }
13520
13521 // Filter out any other lookup result from an enclosing scope.
13522 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13523 /*AllowInlineNamespace*/false);
13524
13525 // Find the previous declaration and check that we can redeclare it.
13526 NamespaceAliasDecl *Prev = nullptr;
13527 if (PrevR.isSingleResult()) {
13528 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13529 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13530 // We already have an alias with the same name that points to the same
13531 // namespace; check that it matches.
13532 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13533 Prev = AD;
13534 } else if (isVisible(PrevDecl)) {
13535 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13536 << Alias;
13537 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13538 << AD->getNamespace();
13539 return nullptr;
13540 }
13541 } else if (isVisible(PrevDecl)) {
13542 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13543 ? diag::err_redefinition
13544 : diag::err_redefinition_different_kind;
13545 Diag(AliasLoc, DiagID) << Alias;
13546 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13547 return nullptr;
13548 }
13549 }
13550
13551 // The use of a nested name specifier may trigger deprecation warnings.
13552 DiagnoseUseOfDecl(ND, IdentLoc);
13553
13555 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13556 Alias, SS.getWithLocInContext(Context),
13557 IdentLoc, ND);
13558 if (Prev)
13559 AliasDecl->setPreviousDecl(Prev);
13560
13562 return AliasDecl;
13563}
13564
13565namespace {
13566struct SpecialMemberExceptionSpecInfo
13567 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13570
13571 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13575 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13576
13577 bool visitBase(CXXBaseSpecifier *Base);
13578 bool visitField(FieldDecl *FD);
13579
13580 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13581 unsigned Quals);
13582
13583 void visitSubobjectCall(Subobject Subobj,
13585};
13586}
13587
13588bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13589 auto *RT = Base->getType()->getAs<RecordType>();
13590 if (!RT)
13591 return false;
13592
13593 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13594 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13595 if (auto *BaseCtor = SMOR.getMethod()) {
13596 visitSubobjectCall(Base, BaseCtor);
13597 return false;
13598 }
13599
13600 visitClassSubobject(BaseClass, Base, 0);
13601 return false;
13602}
13603
13604bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13606 FD->hasInClassInitializer()) {
13607 Expr *E = FD->getInClassInitializer();
13608 if (!E)
13609 // FIXME: It's a little wasteful to build and throw away a
13610 // CXXDefaultInitExpr here.
13611 // FIXME: We should have a single context note pointing at Loc, and
13612 // this location should be MD->getLocation() instead, since that's
13613 // the location where we actually use the default init expression.
13614 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13615 if (E)
13616 ExceptSpec.CalledExpr(E);
13617 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13618 ->getAs<RecordType>()) {
13619 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13620 FD->getType().getCVRQualifiers());
13621 }
13622 return false;
13623}
13624
13625void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13626 Subobject Subobj,
13627 unsigned Quals) {
13628 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13629 bool IsMutable = Field && Field->isMutable();
13630 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13631}
13632
13633void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13634 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13635 // Note, if lookup fails, it doesn't matter what exception specification we
13636 // choose because the special member will be deleted.
13637 if (CXXMethodDecl *MD = SMOR.getMethod())
13638 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13639}
13640
13642 llvm::APSInt Result;
13644 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13645 ExplicitSpec.setExpr(Converted.get());
13646 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13647 ExplicitSpec.setKind(Result.getBoolValue()
13650 return true;
13651 }
13653 return false;
13654}
13655
13658 if (!ExplicitExpr->isTypeDependent())
13660 return ES;
13661}
13662
13667 ComputingExceptionSpec CES(S, MD, Loc);
13668
13669 CXXRecordDecl *ClassDecl = MD->getParent();
13670
13671 // C++ [except.spec]p14:
13672 // An implicitly declared special member function (Clause 12) shall have an
13673 // exception-specification. [...]
13674 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13675 if (ClassDecl->isInvalidDecl())
13676 return Info.ExceptSpec;
13677
13678 // FIXME: If this diagnostic fires, we're probably missing a check for
13679 // attempting to resolve an exception specification before it's known
13680 // at a higher level.
13681 if (S.RequireCompleteType(MD->getLocation(),
13682 S.Context.getRecordType(ClassDecl),
13683 diag::err_exception_spec_incomplete_type))
13684 return Info.ExceptSpec;
13685
13686 // C++1z [except.spec]p7:
13687 // [Look for exceptions thrown by] a constructor selected [...] to
13688 // initialize a potentially constructed subobject,
13689 // C++1z [except.spec]p8:
13690 // The exception specification for an implicitly-declared destructor, or a
13691 // destructor without a noexcept-specifier, is potentially-throwing if and
13692 // only if any of the destructors for any of its potentially constructed
13693 // subojects is potentially throwing.
13694 // FIXME: We respect the first rule but ignore the "potentially constructed"
13695 // in the second rule to resolve a core issue (no number yet) that would have
13696 // us reject:
13697 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13698 // struct B : A {};
13699 // struct C : B { void f(); };
13700 // ... due to giving B::~B() a non-throwing exception specification.
13701 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13702 : Info.VisitAllBases);
13703
13704 return Info.ExceptSpec;
13705}
13706
13707namespace {
13708/// RAII object to register a special member as being currently declared.
13709struct DeclaringSpecialMember {
13710 Sema &S;
13712 Sema::ContextRAII SavedContext;
13713 bool WasAlreadyBeingDeclared;
13714
13715 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13716 : S(S), D(RD, CSM), SavedContext(S, RD) {
13717 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13718 if (WasAlreadyBeingDeclared)
13719 // This almost never happens, but if it does, ensure that our cache
13720 // doesn't contain a stale result.
13721 S.SpecialMemberCache.clear();
13722 else {
13723 // Register a note to be produced if we encounter an error while
13724 // declaring the special member.
13727 // FIXME: We don't have a location to use here. Using the class's
13728 // location maintains the fiction that we declare all special members
13729 // with the class, but (1) it's not clear that lying about that helps our
13730 // users understand what's going on, and (2) there may be outer contexts
13731 // on the stack (some of which are relevant) and printing them exposes
13732 // our lies.
13734 Ctx.Entity = RD;
13735 Ctx.SpecialMember = CSM;
13737 }
13738 }
13739 ~DeclaringSpecialMember() {
13740 if (!WasAlreadyBeingDeclared) {
13743 }
13744 }
13745
13746 /// Are we already trying to declare this special member?
13747 bool isAlreadyBeingDeclared() const {
13748 return WasAlreadyBeingDeclared;
13749 }
13750};
13751}
13752
13754 // Look up any existing declarations, but don't trigger declaration of all
13755 // implicit special members with this name.
13756 DeclarationName Name = FD->getDeclName();
13758 RedeclarationKind::ForExternalRedeclaration);
13759 for (auto *D : FD->getParent()->lookup(Name))
13760 if (auto *Acceptable = R.getAcceptableDecl(D))
13761 R.addDecl(Acceptable);
13762 R.resolveKind();
13764
13765 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13767}
13768
13769void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13770 QualType ResultTy,
13771 ArrayRef<QualType> Args) {
13772 // Build an exception specification pointing back at this constructor.
13774
13776 if (AS != LangAS::Default) {
13777 EPI.TypeQuals.addAddressSpace(AS);
13778 }
13779
13780 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13781 SpecialMem->setType(QT);
13782
13783 // During template instantiation of implicit special member functions we need
13784 // a reliable TypeSourceInfo for the function prototype in order to allow
13785 // functions to be substituted.
13787 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13788 TypeSourceInfo *TSI =
13790 SpecialMem->setTypeSourceInfo(TSI);
13791 }
13792}
13793
13795 CXXRecordDecl *ClassDecl) {
13796 // C++ [class.ctor]p5:
13797 // A default constructor for a class X is a constructor of class X
13798 // that can be called without an argument. If there is no
13799 // user-declared constructor for class X, a default constructor is
13800 // implicitly declared. An implicitly-declared default constructor
13801 // is an inline public member of its class.
13802 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13803 "Should not build implicit default constructor!");
13804
13805 DeclaringSpecialMember DSM(*this, ClassDecl,
13807 if (DSM.isAlreadyBeingDeclared())
13808 return nullptr;
13809
13811 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
13812
13813 // Create the actual constructor declaration.
13814 CanQualType ClassType
13816 SourceLocation ClassLoc = ClassDecl->getLocation();
13817 DeclarationName Name
13819 DeclarationNameInfo NameInfo(Name, ClassLoc);
13821 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13822 /*TInfo=*/nullptr, ExplicitSpecifier(),
13823 getCurFPFeatures().isFPConstrained(),
13824 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13827 DefaultCon->setAccess(AS_public);
13828 DefaultCon->setDefaulted();
13829
13830 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13831
13832 if (getLangOpts().CUDA)
13834 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
13835 /* ConstRHS */ false,
13836 /* Diagnose */ false);
13837
13838 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13839 // constructors is easy to compute.
13840 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13841
13842 // Note that we have declared this constructor.
13844
13845 Scope *S = getScopeForContext(ClassDecl);
13847
13848 if (ShouldDeleteSpecialMember(DefaultCon,
13850 SetDeclDeleted(DefaultCon, ClassLoc);
13851
13852 if (S)
13853 PushOnScopeChains(DefaultCon, S, false);
13854 ClassDecl->addDecl(DefaultCon);
13855
13856 return DefaultCon;
13857}
13858
13860 CXXConstructorDecl *Constructor) {
13861 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13862 !Constructor->doesThisDeclarationHaveABody() &&
13863 !Constructor->isDeleted()) &&
13864 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13865 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13866 return;
13867
13868 CXXRecordDecl *ClassDecl = Constructor->getParent();
13869 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13870 if (ClassDecl->isInvalidDecl()) {
13871 return;
13872 }
13873
13874 SynthesizedFunctionScope Scope(*this, Constructor);
13875
13876 // The exception specification is needed because we are defining the
13877 // function.
13878 ResolveExceptionSpec(CurrentLocation,
13879 Constructor->getType()->castAs<FunctionProtoType>());
13880 MarkVTableUsed(CurrentLocation, ClassDecl);
13881
13882 // Add a context note for diagnostics produced after this point.
13883 Scope.addContextNote(CurrentLocation);
13884
13885 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13886 Constructor->setInvalidDecl();
13887 return;
13888 }
13889
13890 SourceLocation Loc = Constructor->getEndLoc().isValid()
13891 ? Constructor->getEndLoc()
13892 : Constructor->getLocation();
13893 Constructor->setBody(new (Context) CompoundStmt(Loc));
13894 Constructor->markUsed(Context);
13895
13897 L->CompletedImplicitDefinition(Constructor);
13898 }
13899
13900 DiagnoseUninitializedFields(*this, Constructor);
13901}
13902
13904 // Perform any delayed checks on exception specifications.
13906}
13907
13908/// Find or create the fake constructor we synthesize to model constructing an
13909/// object of a derived class via a constructor of a base class.
13912 CXXConstructorDecl *BaseCtor,
13914 CXXRecordDecl *Derived = Shadow->getParent();
13915 SourceLocation UsingLoc = Shadow->getLocation();
13916
13917 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13918 // For now we use the name of the base class constructor as a member of the
13919 // derived class to indicate a (fake) inherited constructor name.
13920 DeclarationName Name = BaseCtor->getDeclName();
13921
13922 // Check to see if we already have a fake constructor for this inherited
13923 // constructor call.
13924 for (NamedDecl *Ctor : Derived->lookup(Name))
13925 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13926 ->getInheritedConstructor()
13927 .getConstructor(),
13928 BaseCtor))
13929 return cast<CXXConstructorDecl>(Ctor);
13930
13931 DeclarationNameInfo NameInfo(Name, UsingLoc);
13932 TypeSourceInfo *TInfo =
13933 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13934 FunctionProtoTypeLoc ProtoLoc =
13936
13937 // Check the inherited constructor is valid and find the list of base classes
13938 // from which it was inherited.
13939 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13940
13941 bool Constexpr = BaseCtor->isConstexpr() &&
13944 false, BaseCtor, &ICI);
13945
13947 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13948 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13949 /*isInline=*/true,
13950 /*isImplicitlyDeclared=*/true,
13952 InheritedConstructor(Shadow, BaseCtor),
13953 BaseCtor->getTrailingRequiresClause());
13954 if (Shadow->isInvalidDecl())
13955 DerivedCtor->setInvalidDecl();
13956
13957 // Build an unevaluated exception specification for this fake constructor.
13958 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13961 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13962 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13963 FPT->getParamTypes(), EPI));
13964
13965 // Build the parameter declarations.
13967 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13968 TypeSourceInfo *TInfo =
13971 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13972 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13973 PD->setScopeInfo(0, I);
13974 PD->setImplicit();
13975 // Ensure attributes are propagated onto parameters (this matters for
13976 // format, pass_object_size, ...).
13977 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13978 ParamDecls.push_back(PD);
13979 ProtoLoc.setParam(I, PD);
13980 }
13981
13982 // Set up the new constructor.
13983 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13984 DerivedCtor->setAccess(BaseCtor->getAccess());
13985 DerivedCtor->setParams(ParamDecls);
13986 Derived->addDecl(DerivedCtor);
13987
13988 if (ShouldDeleteSpecialMember(DerivedCtor,
13990 SetDeclDeleted(DerivedCtor, UsingLoc);
13991
13992 return DerivedCtor;
13993}
13994
13996 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13999 &ICI,
14000 /*Diagnose*/ true);
14001}
14002
14004 CXXConstructorDecl *Constructor) {
14005 CXXRecordDecl *ClassDecl = Constructor->getParent();
14006 assert(Constructor->getInheritedConstructor() &&
14007 !Constructor->doesThisDeclarationHaveABody() &&
14008 !Constructor->isDeleted());
14009 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14010 return;
14011
14012 // Initializations are performed "as if by a defaulted default constructor",
14013 // so enter the appropriate scope.
14014 SynthesizedFunctionScope Scope(*this, Constructor);
14015
14016 // The exception specification is needed because we are defining the
14017 // function.
14018 ResolveExceptionSpec(CurrentLocation,
14019 Constructor->getType()->castAs<FunctionProtoType>());
14020 MarkVTableUsed(CurrentLocation, ClassDecl);
14021
14022 // Add a context note for diagnostics produced after this point.
14023 Scope.addContextNote(CurrentLocation);
14024
14026 Constructor->getInheritedConstructor().getShadowDecl();
14027 CXXConstructorDecl *InheritedCtor =
14028 Constructor->getInheritedConstructor().getConstructor();
14029
14030 // [class.inhctor.init]p1:
14031 // initialization proceeds as if a defaulted default constructor is used to
14032 // initialize the D object and each base class subobject from which the
14033 // constructor was inherited
14034
14035 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14036 CXXRecordDecl *RD = Shadow->getParent();
14037 SourceLocation InitLoc = Shadow->getLocation();
14038
14039 // Build explicit initializers for all base classes from which the
14040 // constructor was inherited.
14042 for (bool VBase : {false, true}) {
14043 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14044 if (B.isVirtual() != VBase)
14045 continue;
14046
14047 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14048 if (!BaseRD)
14049 continue;
14050
14051 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14052 if (!BaseCtor.first)
14053 continue;
14054
14055 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14057 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14058
14059 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14060 Inits.push_back(new (Context) CXXCtorInitializer(
14061 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14062 SourceLocation()));
14063 }
14064 }
14065
14066 // We now proceed as if for a defaulted default constructor, with the relevant
14067 // initializers replaced.
14068
14069 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14070 Constructor->setInvalidDecl();
14071 return;
14072 }
14073
14074 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14075 Constructor->markUsed(Context);
14076
14078 L->CompletedImplicitDefinition(Constructor);
14079 }
14080
14081 DiagnoseUninitializedFields(*this, Constructor);
14082}
14083
14085 // C++ [class.dtor]p2:
14086 // If a class has no user-declared destructor, a destructor is
14087 // declared implicitly. An implicitly-declared destructor is an
14088 // inline public member of its class.
14089 assert(ClassDecl->needsImplicitDestructor());
14090
14091 DeclaringSpecialMember DSM(*this, ClassDecl,
14093 if (DSM.isAlreadyBeingDeclared())
14094 return nullptr;
14095
14097 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14098
14099 // Create the actual destructor declaration.
14100 CanQualType ClassType
14102 SourceLocation ClassLoc = ClassDecl->getLocation();
14103 DeclarationName Name
14105 DeclarationNameInfo NameInfo(Name, ClassLoc);
14107 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14108 getCurFPFeatures().isFPConstrained(),
14109 /*isInline=*/true,
14110 /*isImplicitlyDeclared=*/true,
14113 Destructor->setAccess(AS_public);
14114 Destructor->setDefaulted();
14115
14116 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14117
14118 if (getLangOpts().CUDA)
14121 /* ConstRHS */ false,
14122 /* Diagnose */ false);
14123
14124 // We don't need to use SpecialMemberIsTrivial here; triviality for
14125 // destructors is easy to compute.
14126 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14127 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14128 ClassDecl->hasTrivialDestructorForCall());
14129
14130 // Note that we have declared this destructor.
14132
14133 Scope *S = getScopeForContext(ClassDecl);
14135
14136 // We can't check whether an implicit destructor is deleted before we complete
14137 // the definition of the class, because its validity depends on the alignment
14138 // of the class. We'll check this from ActOnFields once the class is complete.
14139 if (ClassDecl->isCompleteDefinition() &&
14141 SetDeclDeleted(Destructor, ClassLoc);
14142
14143 // Introduce this destructor into its scope.
14144 if (S)
14145 PushOnScopeChains(Destructor, S, false);
14146 ClassDecl->addDecl(Destructor);
14147
14148 return Destructor;
14149}
14150
14153 assert((Destructor->isDefaulted() &&
14154 !Destructor->doesThisDeclarationHaveABody() &&
14155 !Destructor->isDeleted()) &&
14156 "DefineImplicitDestructor - call it for implicit default dtor");
14157 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14158 return;
14159
14160 CXXRecordDecl *ClassDecl = Destructor->getParent();
14161 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14162
14164
14165 // The exception specification is needed because we are defining the
14166 // function.
14167 ResolveExceptionSpec(CurrentLocation,
14168 Destructor->getType()->castAs<FunctionProtoType>());
14169 MarkVTableUsed(CurrentLocation, ClassDecl);
14170
14171 // Add a context note for diagnostics produced after this point.
14172 Scope.addContextNote(CurrentLocation);
14173
14175 Destructor->getParent());
14176
14178 Destructor->setInvalidDecl();
14179 return;
14180 }
14181
14182 SourceLocation Loc = Destructor->getEndLoc().isValid()
14183 ? Destructor->getEndLoc()
14184 : Destructor->getLocation();
14185 Destructor->setBody(new (Context) CompoundStmt(Loc));
14186 Destructor->markUsed(Context);
14187
14189 L->CompletedImplicitDefinition(Destructor);
14190 }
14191}
14192
14195 if (Destructor->isInvalidDecl())
14196 return;
14197
14198 CXXRecordDecl *ClassDecl = Destructor->getParent();
14200 "implicit complete dtors unneeded outside MS ABI");
14201 assert(ClassDecl->getNumVBases() > 0 &&
14202 "complete dtor only exists for classes with vbases");
14203
14205
14206 // Add a context note for diagnostics produced after this point.
14207 Scope.addContextNote(CurrentLocation);
14208
14209 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14210}
14211
14213 // If the context is an invalid C++ class, just suppress these checks.
14214 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14215 if (Record->isInvalidDecl()) {
14218 return;
14219 }
14221 }
14222}
14223
14226
14227 if (!DelayedDllExportMemberFunctions.empty()) {
14229 std::swap(DelayedDllExportMemberFunctions, WorkList);
14230 for (CXXMethodDecl *M : WorkList) {
14231 DefineDefaultedFunction(*this, M, M->getLocation());
14232
14233 // Pass the method to the consumer to get emitted. This is not necessary
14234 // for explicit instantiation definitions, as they will get emitted
14235 // anyway.
14236 if (M->getParent()->getTemplateSpecializationKind() !=
14239 }
14240 }
14241}
14242
14244 if (!DelayedDllExportClasses.empty()) {
14245 // Calling ReferenceDllExportedMembers might cause the current function to
14246 // be called again, so use a local copy of DelayedDllExportClasses.
14248 std::swap(DelayedDllExportClasses, WorkList);
14249 for (CXXRecordDecl *Class : WorkList)
14251 }
14252}
14253
14255 assert(getLangOpts().CPlusPlus11 &&
14256 "adjusting dtor exception specs was introduced in c++11");
14257
14258 if (Destructor->isDependentContext())
14259 return;
14260
14261 // C++11 [class.dtor]p3:
14262 // A declaration of a destructor that does not have an exception-
14263 // specification is implicitly considered to have the same exception-
14264 // specification as an implicit declaration.
14265 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14266 if (DtorType->hasExceptionSpec())
14267 return;
14268
14269 // Replace the destructor's type, building off the existing one. Fortunately,
14270 // the only thing of interest in the destructor type is its extended info.
14271 // The return and arguments are fixed.
14272 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14275 Destructor->setType(
14276 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14277
14278 // FIXME: If the destructor has a body that could throw, and the newly created
14279 // spec doesn't allow exceptions, we should emit a warning, because this
14280 // change in behavior can break conforming C++03 programs at runtime.
14281 // However, we don't have a body or an exception specification yet, so it
14282 // needs to be done somewhere else.
14283}
14284
14285namespace {
14286/// An abstract base class for all helper classes used in building the
14287// copy/move operators. These classes serve as factory functions and help us
14288// avoid using the same Expr* in the AST twice.
14289class ExprBuilder {
14290 ExprBuilder(const ExprBuilder&) = delete;
14291 ExprBuilder &operator=(const ExprBuilder&) = delete;
14292
14293protected:
14294 static Expr *assertNotNull(Expr *E) {
14295 assert(E && "Expression construction must not fail.");
14296 return E;
14297 }
14298
14299public:
14300 ExprBuilder() {}
14301 virtual ~ExprBuilder() {}
14302
14303 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14304};
14305
14306class RefBuilder: public ExprBuilder {
14307 VarDecl *Var;
14308 QualType VarType;
14309
14310public:
14311 Expr *build(Sema &S, SourceLocation Loc) const override {
14312 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14313 }
14314
14315 RefBuilder(VarDecl *Var, QualType VarType)
14316 : Var(Var), VarType(VarType) {}
14317};
14318
14319class ThisBuilder: public ExprBuilder {
14320public:
14321 Expr *build(Sema &S, SourceLocation Loc) const override {
14322 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14323 }
14324};
14325
14326class CastBuilder: public ExprBuilder {
14327 const ExprBuilder &Builder;
14328 QualType Type;
14330 const CXXCastPath &Path;
14331
14332public:
14333 Expr *build(Sema &S, SourceLocation Loc) const override {
14334 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14335 CK_UncheckedDerivedToBase, Kind,
14336 &Path).get());
14337 }
14338
14339 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14340 const CXXCastPath &Path)
14341 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14342};
14343
14344class DerefBuilder: public ExprBuilder {
14345 const ExprBuilder &Builder;
14346
14347public:
14348 Expr *build(Sema &S, SourceLocation Loc) const override {
14349 return assertNotNull(
14350 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14351 }
14352
14353 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14354};
14355
14356class MemberBuilder: public ExprBuilder {
14357 const ExprBuilder &Builder;
14358 QualType Type;
14359 CXXScopeSpec SS;
14360 bool IsArrow;
14361 LookupResult &MemberLookup;
14362
14363public:
14364 Expr *build(Sema &S, SourceLocation Loc) const override {
14365 return assertNotNull(S.BuildMemberReferenceExpr(
14366 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14367 nullptr, MemberLookup, nullptr, nullptr).get());
14368 }
14369
14370 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14371 LookupResult &MemberLookup)
14372 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14373 MemberLookup(MemberLookup) {}
14374};
14375
14376class MoveCastBuilder: public ExprBuilder {
14377 const ExprBuilder &Builder;
14378
14379public:
14380 Expr *build(Sema &S, SourceLocation Loc) const override {
14381 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14382 }
14383
14384 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14385};
14386
14387class LvalueConvBuilder: public ExprBuilder {
14388 const ExprBuilder &Builder;
14389
14390public:
14391 Expr *build(Sema &S, SourceLocation Loc) const override {
14392 return assertNotNull(
14393 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14394 }
14395
14396 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14397};
14398
14399class SubscriptBuilder: public ExprBuilder {
14400 const ExprBuilder &Base;
14401 const ExprBuilder &Index;
14402
14403public:
14404 Expr *build(Sema &S, SourceLocation Loc) const override {
14405 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14406 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14407 }
14408
14409 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14410 : Base(Base), Index(Index) {}
14411};
14412
14413} // end anonymous namespace
14414
14415/// When generating a defaulted copy or move assignment operator, if a field
14416/// should be copied with __builtin_memcpy rather than via explicit assignments,
14417/// do so. This optimization only applies for arrays of scalars, and for arrays
14418/// of class type where the selected copy/move-assignment operator is trivial.
14419static StmtResult
14421 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14422 // Compute the size of the memory buffer to be copied.
14423 QualType SizeType = S.Context.getSizeType();
14424 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14426
14427 // Take the address of the field references for "from" and "to". We
14428 // directly construct UnaryOperators here because semantic analysis
14429 // does not permit us to take the address of an xvalue.
14430 Expr *From = FromB.build(S, Loc);
14431 From = UnaryOperator::Create(
14432 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14434 Expr *To = ToB.build(S, Loc);
14436 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14438
14439 const Type *E = T->getBaseElementTypeUnsafe();
14440 bool NeedsCollectableMemCpy =
14441 E->isRecordType() &&
14442 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14443
14444 // Create a reference to the __builtin_objc_memmove_collectable function
14445 StringRef MemCpyName = NeedsCollectableMemCpy ?
14446 "__builtin_objc_memmove_collectable" :
14447 "__builtin_memcpy";
14448 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14450 S.LookupName(R, S.TUScope, true);
14451
14452 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14453 if (!MemCpy)
14454 // Something went horribly wrong earlier, and we will have complained
14455 // about it.
14456 return StmtError();
14457
14458 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14459 VK_PRValue, Loc, nullptr);
14460 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14461
14462 Expr *CallArgs[] = {
14463 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14464 };
14465 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14466 Loc, CallArgs, Loc);
14467
14468 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14469 return Call.getAs<Stmt>();
14470}
14471
14472/// Builds a statement that copies/moves the given entity from \p From to
14473/// \c To.
14474///
14475/// This routine is used to copy/move the members of a class with an
14476/// implicitly-declared copy/move assignment operator. When the entities being
14477/// copied are arrays, this routine builds for loops to copy them.
14478///
14479/// \param S The Sema object used for type-checking.
14480///
14481/// \param Loc The location where the implicit copy/move is being generated.
14482///
14483/// \param T The type of the expressions being copied/moved. Both expressions
14484/// must have this type.
14485///
14486/// \param To The expression we are copying/moving to.
14487///
14488/// \param From The expression we are copying/moving from.
14489///
14490/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14491/// Otherwise, it's a non-static member subobject.
14492///
14493/// \param Copying Whether we're copying or moving.
14494///
14495/// \param Depth Internal parameter recording the depth of the recursion.
14496///
14497/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14498/// if a memcpy should be used instead.
14499static StmtResult
14501 const ExprBuilder &To, const ExprBuilder &From,
14502 bool CopyingBaseSubobject, bool Copying,
14503 unsigned Depth = 0) {
14504 // C++11 [class.copy]p28:
14505 // Each subobject is assigned in the manner appropriate to its type:
14506 //
14507 // - if the subobject is of class type, as if by a call to operator= with
14508 // the subobject as the object expression and the corresponding
14509 // subobject of x as a single function argument (as if by explicit
14510 // qualification; that is, ignoring any possible virtual overriding
14511 // functions in more derived classes);
14512 //
14513 // C++03 [class.copy]p13:
14514 // - if the subobject is of class type, the copy assignment operator for
14515 // the class is used (as if by explicit qualification; that is,
14516 // ignoring any possible virtual overriding functions in more derived
14517 // classes);
14518 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14519 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14520
14521 // Look for operator=.
14522 DeclarationName Name
14524 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14525 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14526
14527 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14528 // operator.
14529 if (!S.getLangOpts().CPlusPlus11) {
14530 LookupResult::Filter F = OpLookup.makeFilter();
14531 while (F.hasNext()) {
14532 NamedDecl *D = F.next();
14533 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14534 if (Method->isCopyAssignmentOperator() ||
14535 (!Copying && Method->isMoveAssignmentOperator()))
14536 continue;
14537
14538 F.erase();
14539 }
14540 F.done();
14541 }
14542
14543 // Suppress the protected check (C++ [class.protected]) for each of the
14544 // assignment operators we found. This strange dance is required when
14545 // we're assigning via a base classes's copy-assignment operator. To
14546 // ensure that we're getting the right base class subobject (without
14547 // ambiguities), we need to cast "this" to that subobject type; to
14548 // ensure that we don't go through the virtual call mechanism, we need
14549 // to qualify the operator= name with the base class (see below). However,
14550 // this means that if the base class has a protected copy assignment
14551 // operator, the protected member access check will fail. So, we
14552 // rewrite "protected" access to "public" access in this case, since we
14553 // know by construction that we're calling from a derived class.
14554 if (CopyingBaseSubobject) {
14555 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14556 L != LEnd; ++L) {
14557 if (L.getAccess() == AS_protected)
14558 L.setAccess(AS_public);
14559 }
14560 }
14561
14562 // Create the nested-name-specifier that will be used to qualify the
14563 // reference to operator=; this is required to suppress the virtual
14564 // call mechanism.
14565 CXXScopeSpec SS;
14566 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14567 SS.MakeTrivial(S.Context,
14568 NestedNameSpecifier::Create(S.Context, nullptr, false,
14569 CanonicalT),
14570 Loc);
14571
14572 // Create the reference to operator=.
14573 ExprResult OpEqualRef
14574 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14575 SS, /*TemplateKWLoc=*/SourceLocation(),
14576 /*FirstQualifierInScope=*/nullptr,
14577 OpLookup,
14578 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14579 /*SuppressQualifierCheck=*/true);
14580 if (OpEqualRef.isInvalid())
14581 return StmtError();
14582
14583 // Build the call to the assignment operator.
14584
14585 Expr *FromInst = From.build(S, Loc);
14586 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14587 OpEqualRef.getAs<Expr>(),
14588 Loc, FromInst, Loc);
14589 if (Call.isInvalid())
14590 return StmtError();
14591
14592 // If we built a call to a trivial 'operator=' while copying an array,
14593 // bail out. We'll replace the whole shebang with a memcpy.
14594 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14595 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14596 return StmtResult((Stmt*)nullptr);
14597
14598 // Convert to an expression-statement, and clean up any produced
14599 // temporaries.
14600 return S.ActOnExprStmt(Call);
14601 }
14602
14603 // - if the subobject is of scalar type, the built-in assignment
14604 // operator is used.
14606 if (!ArrayTy) {
14607 ExprResult Assignment = S.CreateBuiltinBinOp(
14608 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14609 if (Assignment.isInvalid())
14610 return StmtError();
14611 return S.ActOnExprStmt(Assignment);
14612 }
14613
14614 // - if the subobject is an array, each element is assigned, in the
14615 // manner appropriate to the element type;
14616
14617 // Construct a loop over the array bounds, e.g.,
14618 //
14619 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14620 //
14621 // that will copy each of the array elements.
14622 QualType SizeType = S.Context.getSizeType();
14623
14624 // Create the iteration variable.
14625 IdentifierInfo *IterationVarName = nullptr;
14626 {
14627 SmallString<8> Str;
14628 llvm::raw_svector_ostream OS(Str);
14629 OS << "__i" << Depth;
14630 IterationVarName = &S.Context.Idents.get(OS.str());
14631 }
14632 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14633 IterationVarName, SizeType,
14635 SC_None);
14636
14637 // Initialize the iteration variable to zero.
14638 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14639 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14640
14641 // Creates a reference to the iteration variable.
14642 RefBuilder IterationVarRef(IterationVar, SizeType);
14643 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14644
14645 // Create the DeclStmt that holds the iteration variable.
14646 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14647
14648 // Subscript the "from" and "to" expressions with the iteration variable.
14649 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14650 MoveCastBuilder FromIndexMove(FromIndexCopy);
14651 const ExprBuilder *FromIndex;
14652 if (Copying)
14653 FromIndex = &FromIndexCopy;
14654 else
14655 FromIndex = &FromIndexMove;
14656
14657 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14658
14659 // Build the copy/move for an individual element of the array.
14662 ToIndex, *FromIndex, CopyingBaseSubobject,
14663 Copying, Depth + 1);
14664 // Bail out if copying fails or if we determined that we should use memcpy.
14665 if (Copy.isInvalid() || !Copy.get())
14666 return Copy;
14667
14668 // Create the comparison against the array bound.
14669 llvm::APInt Upper
14670 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14671 Expr *Comparison = BinaryOperator::Create(
14672 S.Context, IterationVarRefRVal.build(S, Loc),
14673 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14676
14677 // Create the pre-increment of the iteration variable. We can determine
14678 // whether the increment will overflow based on the value of the array
14679 // bound.
14680 Expr *Increment = UnaryOperator::Create(
14681 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14682 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14683
14684 // Construct the loop that copies all elements of this array.
14685 return S.ActOnForStmt(
14686 Loc, Loc, InitStmt,
14687 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14688 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14689}
14690
14691static StmtResult
14693 const ExprBuilder &To, const ExprBuilder &From,
14694 bool CopyingBaseSubobject, bool Copying) {
14695 // Maybe we should use a memcpy?
14696 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14697 T.isTriviallyCopyableType(S.Context))
14698 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14699
14701 CopyingBaseSubobject,
14702 Copying, 0));
14703
14704 // If we ended up picking a trivial assignment operator for an array of a
14705 // non-trivially-copyable class type, just emit a memcpy.
14706 if (!Result.isInvalid() && !Result.get())
14707 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14708
14709 return Result;
14710}
14711
14713 // Note: The following rules are largely analoguous to the copy
14714 // constructor rules. Note that virtual bases are not taken into account
14715 // for determining the argument type of the operator. Note also that
14716 // operators taking an object instead of a reference are allowed.
14717 assert(ClassDecl->needsImplicitCopyAssignment());
14718
14719 DeclaringSpecialMember DSM(*this, ClassDecl,
14721 if (DSM.isAlreadyBeingDeclared())
14722 return nullptr;
14723
14724 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14726 ArgType, nullptr);
14728 if (AS != LangAS::Default)
14729 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14730 QualType RetType = Context.getLValueReferenceType(ArgType);
14731 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14732 if (Const)
14733 ArgType = ArgType.withConst();
14734
14735 ArgType = Context.getLValueReferenceType(ArgType);
14736
14738 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14739
14740 // An implicitly-declared copy assignment operator is an inline public
14741 // member of its class.
14743 SourceLocation ClassLoc = ClassDecl->getLocation();
14744 DeclarationNameInfo NameInfo(Name, ClassLoc);
14746 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14747 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14748 getCurFPFeatures().isFPConstrained(),
14749 /*isInline=*/true,
14751 SourceLocation());
14752 CopyAssignment->setAccess(AS_public);
14753 CopyAssignment->setDefaulted();
14754 CopyAssignment->setImplicit();
14755
14756 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14757
14758 if (getLangOpts().CUDA)
14761 /* ConstRHS */ Const,
14762 /* Diagnose */ false);
14763
14764 // Add the parameter to the operator.
14766 ClassLoc, ClassLoc,
14767 /*Id=*/nullptr, ArgType,
14768 /*TInfo=*/nullptr, SC_None,
14769 nullptr);
14770 CopyAssignment->setParams(FromParam);
14771
14772 CopyAssignment->setTrivial(
14776 : ClassDecl->hasTrivialCopyAssignment());
14777
14778 // Note that we have added this copy-assignment operator.
14780
14781 Scope *S = getScopeForContext(ClassDecl);
14783
14787 SetDeclDeleted(CopyAssignment, ClassLoc);
14788 }
14789
14790 if (S)
14792 ClassDecl->addDecl(CopyAssignment);
14793
14794 return CopyAssignment;
14795}
14796
14797/// Diagnose an implicit copy operation for a class which is odr-used, but
14798/// which is deprecated because the class has a user-declared copy constructor,
14799/// copy assignment operator, or destructor.
14801 assert(CopyOp->isImplicit());
14802
14803 CXXRecordDecl *RD = CopyOp->getParent();
14804 CXXMethodDecl *UserDeclaredOperation = nullptr;
14805
14806 if (RD->hasUserDeclaredDestructor()) {
14807 UserDeclaredOperation = RD->getDestructor();
14808 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14810 // Find any user-declared copy constructor.
14811 for (auto *I : RD->ctors()) {
14812 if (I->isCopyConstructor()) {
14813 UserDeclaredOperation = I;
14814 break;
14815 }
14816 }
14817 assert(UserDeclaredOperation);
14818 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14820 // Find any user-declared move assignment operator.
14821 for (auto *I : RD->methods()) {
14822 if (I->isCopyAssignmentOperator()) {
14823 UserDeclaredOperation = I;
14824 break;
14825 }
14826 }
14827 assert(UserDeclaredOperation);
14828 }
14829
14830 if (UserDeclaredOperation) {
14831 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14832 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14833 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14834 unsigned DiagID =
14835 (UDOIsUserProvided && UDOIsDestructor)
14836 ? diag::warn_deprecated_copy_with_user_provided_dtor
14837 : (UDOIsUserProvided && !UDOIsDestructor)
14838 ? diag::warn_deprecated_copy_with_user_provided_copy
14839 : (!UDOIsUserProvided && UDOIsDestructor)
14840 ? diag::warn_deprecated_copy_with_dtor
14841 : diag::warn_deprecated_copy;
14842 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14843 << RD << IsCopyAssignment;
14844 }
14845}
14846
14848 CXXMethodDecl *CopyAssignOperator) {
14849 assert((CopyAssignOperator->isDefaulted() &&
14850 CopyAssignOperator->isOverloadedOperator() &&
14851 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14852 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14853 !CopyAssignOperator->isDeleted()) &&
14854 "DefineImplicitCopyAssignment called for wrong function");
14855 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14856 return;
14857
14858 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14859 if (ClassDecl->isInvalidDecl()) {
14860 CopyAssignOperator->setInvalidDecl();
14861 return;
14862 }
14863
14864 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14865
14866 // The exception specification is needed because we are defining the
14867 // function.
14868 ResolveExceptionSpec(CurrentLocation,
14869 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14870
14871 // Add a context note for diagnostics produced after this point.
14872 Scope.addContextNote(CurrentLocation);
14873
14874 // C++11 [class.copy]p18:
14875 // The [definition of an implicitly declared copy assignment operator] is
14876 // deprecated if the class has a user-declared copy constructor or a
14877 // user-declared destructor.
14878 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14879 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14880
14881 // C++0x [class.copy]p30:
14882 // The implicitly-defined or explicitly-defaulted copy assignment operator
14883 // for a non-union class X performs memberwise copy assignment of its
14884 // subobjects. The direct base classes of X are assigned first, in the
14885 // order of their declaration in the base-specifier-list, and then the
14886 // immediate non-static data members of X are assigned, in the order in
14887 // which they were declared in the class definition.
14888
14889 // The statements that form the synthesized function body.
14890 SmallVector<Stmt*, 8> Statements;
14891
14892 // The parameter for the "other" object, which we are copying from.
14893 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
14894 Qualifiers OtherQuals = Other->getType().getQualifiers();
14895 QualType OtherRefType = Other->getType();
14896 if (OtherRefType->isLValueReferenceType()) {
14897 OtherRefType = OtherRefType->getPointeeType();
14898 OtherQuals = OtherRefType.getQualifiers();
14899 }
14900
14901 // Our location for everything implicitly-generated.
14902 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14903 ? CopyAssignOperator->getEndLoc()
14904 : CopyAssignOperator->getLocation();
14905
14906 // Builds a DeclRefExpr for the "other" object.
14907 RefBuilder OtherRef(Other, OtherRefType);
14908
14909 // Builds the function object parameter.
14910 std::optional<ThisBuilder> This;
14911 std::optional<DerefBuilder> DerefThis;
14912 std::optional<RefBuilder> ExplicitObject;
14913 bool IsArrow = false;
14914 QualType ObjectType;
14915 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
14916 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
14917 if (ObjectType->isReferenceType())
14918 ObjectType = ObjectType->getPointeeType();
14919 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
14920 } else {
14921 ObjectType = getCurrentThisType();
14922 This.emplace();
14923 DerefThis.emplace(*This);
14924 IsArrow = !LangOpts.HLSL;
14925 }
14926 ExprBuilder &ObjectParameter =
14927 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14928 : static_cast<ExprBuilder &>(*This);
14929
14930 // Assign base classes.
14931 bool Invalid = false;
14932 for (auto &Base : ClassDecl->bases()) {
14933 // Form the assignment:
14934 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14935 QualType BaseType = Base.getType().getUnqualifiedType();
14936 if (!BaseType->isRecordType()) {
14937 Invalid = true;
14938 continue;
14939 }
14940
14941 CXXCastPath BasePath;
14942 BasePath.push_back(&Base);
14943
14944 // Construct the "from" expression, which is an implicit cast to the
14945 // appropriately-qualified base type.
14946 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14947 VK_LValue, BasePath);
14948
14949 // Dereference "this".
14950 CastBuilder To(
14951 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14952 : static_cast<ExprBuilder &>(*DerefThis),
14953 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
14954 VK_LValue, BasePath);
14955
14956 // Build the copy.
14957 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14958 To, From,
14959 /*CopyingBaseSubobject=*/true,
14960 /*Copying=*/true);
14961 if (Copy.isInvalid()) {
14962 CopyAssignOperator->setInvalidDecl();
14963 return;
14964 }
14965
14966 // Success! Record the copy.
14967 Statements.push_back(Copy.getAs<Expr>());
14968 }
14969
14970 // Assign non-static members.
14971 for (auto *Field : ClassDecl->fields()) {
14972 // FIXME: We should form some kind of AST representation for the implied
14973 // memcpy in a union copy operation.
14974 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
14975 continue;
14976
14977 if (Field->isInvalidDecl()) {
14978 Invalid = true;
14979 continue;
14980 }
14981
14982 // Check for members of reference type; we can't copy those.
14983 if (Field->getType()->isReferenceType()) {
14984 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14985 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14986 Diag(Field->getLocation(), diag::note_declared_at);
14987 Invalid = true;
14988 continue;
14989 }
14990
14991 // Check for members of const-qualified, non-class type.
14992 QualType BaseType = Context.getBaseElementType(Field->getType());
14993 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14994 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14995 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14996 Diag(Field->getLocation(), diag::note_declared_at);
14997 Invalid = true;
14998 continue;
14999 }
15000
15001 // Suppress assigning zero-width bitfields.
15002 if (Field->isZeroLengthBitField(Context))
15003 continue;
15004
15005 QualType FieldType = Field->getType().getNonReferenceType();
15006 if (FieldType->isIncompleteArrayType()) {
15007 assert(ClassDecl->hasFlexibleArrayMember() &&
15008 "Incomplete array type is not valid");
15009 continue;
15010 }
15011
15012 // Build references to the field in the object we're copying from and to.
15013 CXXScopeSpec SS; // Intentionally empty
15014 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15016 MemberLookup.addDecl(Field);
15017 MemberLookup.resolveKind();
15018
15019 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15020 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15021 // Build the copy of this field.
15022 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15023 To, From,
15024 /*CopyingBaseSubobject=*/false,
15025 /*Copying=*/true);
15026 if (Copy.isInvalid()) {
15027 CopyAssignOperator->setInvalidDecl();
15028 return;
15029 }
15030
15031 // Success! Record the copy.
15032 Statements.push_back(Copy.getAs<Stmt>());
15033 }
15034
15035 if (!Invalid) {
15036 // Add a "return *this;"
15037 Expr *ThisExpr =
15038 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15039 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15040 : static_cast<ExprBuilder &>(*DerefThis))
15041 .build(*this, Loc);
15042 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15043 if (Return.isInvalid())
15044 Invalid = true;
15045 else
15046 Statements.push_back(Return.getAs<Stmt>());
15047 }
15048
15049 if (Invalid) {
15050 CopyAssignOperator->setInvalidDecl();
15051 return;
15052 }
15053
15054 StmtResult Body;
15055 {
15056 CompoundScopeRAII CompoundScope(*this);
15057 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15058 /*isStmtExpr=*/false);
15059 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15060 }
15061 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15062 CopyAssignOperator->markUsed(Context);
15063
15065 L->CompletedImplicitDefinition(CopyAssignOperator);
15066 }
15067}
15068
15070 assert(ClassDecl->needsImplicitMoveAssignment());
15071
15072 DeclaringSpecialMember DSM(*this, ClassDecl,
15074 if (DSM.isAlreadyBeingDeclared())
15075 return nullptr;
15076
15077 // Note: The following rules are largely analoguous to the move
15078 // constructor rules.
15079
15080 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15082 ArgType, nullptr);
15084 if (AS != LangAS::Default)
15085 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15086 QualType RetType = Context.getLValueReferenceType(ArgType);
15087 ArgType = Context.getRValueReferenceType(ArgType);
15088
15090 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15091
15092 // An implicitly-declared move assignment operator is an inline public
15093 // member of its class.
15095 SourceLocation ClassLoc = ClassDecl->getLocation();
15096 DeclarationNameInfo NameInfo(Name, ClassLoc);
15098 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15099 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15100 getCurFPFeatures().isFPConstrained(),
15101 /*isInline=*/true,
15103 SourceLocation());
15104 MoveAssignment->setAccess(AS_public);
15105 MoveAssignment->setDefaulted();
15106 MoveAssignment->setImplicit();
15107
15108 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15109
15110 if (getLangOpts().CUDA)
15113 /* ConstRHS */ false,
15114 /* Diagnose */ false);
15115
15116 // Add the parameter to the operator.
15118 ClassLoc, ClassLoc,
15119 /*Id=*/nullptr, ArgType,
15120 /*TInfo=*/nullptr, SC_None,
15121 nullptr);
15122 MoveAssignment->setParams(FromParam);
15123
15124 MoveAssignment->setTrivial(
15128 : ClassDecl->hasTrivialMoveAssignment());
15129
15130 // Note that we have added this copy-assignment operator.
15132
15133 Scope *S = getScopeForContext(ClassDecl);
15135
15139 SetDeclDeleted(MoveAssignment, ClassLoc);
15140 }
15141
15142 if (S)
15144 ClassDecl->addDecl(MoveAssignment);
15145
15146 return MoveAssignment;
15147}
15148
15149/// Check if we're implicitly defining a move assignment operator for a class
15150/// with virtual bases. Such a move assignment might move-assign the virtual
15151/// base multiple times.
15153 SourceLocation CurrentLocation) {
15154 assert(!Class->isDependentContext() && "should not define dependent move");
15155
15156 // Only a virtual base could get implicitly move-assigned multiple times.
15157 // Only a non-trivial move assignment can observe this. We only want to
15158 // diagnose if we implicitly define an assignment operator that assigns
15159 // two base classes, both of which move-assign the same virtual base.
15160 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15161 Class->getNumBases() < 2)
15162 return;
15163
15165 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15166 VBaseMap VBases;
15167
15168 for (auto &BI : Class->bases()) {
15169 Worklist.push_back(&BI);
15170 while (!Worklist.empty()) {
15171 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15172 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15173
15174 // If the base has no non-trivial move assignment operators,
15175 // we don't care about moves from it.
15176 if (!Base->hasNonTrivialMoveAssignment())
15177 continue;
15178
15179 // If there's nothing virtual here, skip it.
15180 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15181 continue;
15182
15183 // If we're not actually going to call a move assignment for this base,
15184 // or the selected move assignment is trivial, skip it.
15187 /*ConstArg*/ false, /*VolatileArg*/ false,
15188 /*RValueThis*/ true, /*ConstThis*/ false,
15189 /*VolatileThis*/ false);
15190 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15192 continue;
15193
15194 if (BaseSpec->isVirtual()) {
15195 // We're going to move-assign this virtual base, and its move
15196 // assignment operator is not trivial. If this can happen for
15197 // multiple distinct direct bases of Class, diagnose it. (If it
15198 // only happens in one base, we'll diagnose it when synthesizing
15199 // that base class's move assignment operator.)
15200 CXXBaseSpecifier *&Existing =
15201 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15202 .first->second;
15203 if (Existing && Existing != &BI) {
15204 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15205 << Class << Base;
15206 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15207 << (Base->getCanonicalDecl() ==
15209 << Base << Existing->getType() << Existing->getSourceRange();
15210 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15211 << (Base->getCanonicalDecl() ==
15212 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15213 << Base << BI.getType() << BaseSpec->getSourceRange();
15214
15215 // Only diagnose each vbase once.
15216 Existing = nullptr;
15217 }
15218 } else {
15219 // Only walk over bases that have defaulted move assignment operators.
15220 // We assume that any user-provided move assignment operator handles
15221 // the multiple-moves-of-vbase case itself somehow.
15222 if (!SMOR.getMethod()->isDefaulted())
15223 continue;
15224
15225 // We're going to move the base classes of Base. Add them to the list.
15226 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15227 }
15228 }
15229 }
15230}
15231
15233 CXXMethodDecl *MoveAssignOperator) {
15234 assert((MoveAssignOperator->isDefaulted() &&
15235 MoveAssignOperator->isOverloadedOperator() &&
15236 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15237 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15238 !MoveAssignOperator->isDeleted()) &&
15239 "DefineImplicitMoveAssignment called for wrong function");
15240 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15241 return;
15242
15243 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15244 if (ClassDecl->isInvalidDecl()) {
15245 MoveAssignOperator->setInvalidDecl();
15246 return;
15247 }
15248
15249 // C++0x [class.copy]p28:
15250 // The implicitly-defined or move assignment operator for a non-union class
15251 // X performs memberwise move assignment of its subobjects. The direct base
15252 // classes of X are assigned first, in the order of their declaration in the
15253 // base-specifier-list, and then the immediate non-static data members of X
15254 // are assigned, in the order in which they were declared in the class
15255 // definition.
15256
15257 // Issue a warning if our implicit move assignment operator will move
15258 // from a virtual base more than once.
15259 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15260
15261 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15262
15263 // The exception specification is needed because we are defining the
15264 // function.
15265 ResolveExceptionSpec(CurrentLocation,
15266 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15267
15268 // Add a context note for diagnostics produced after this point.
15269 Scope.addContextNote(CurrentLocation);
15270
15271 // The statements that form the synthesized function body.
15272 SmallVector<Stmt*, 8> Statements;
15273
15274 // The parameter for the "other" object, which we are move from.
15275 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15276 QualType OtherRefType =
15277 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15278
15279 // Our location for everything implicitly-generated.
15280 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15281 ? MoveAssignOperator->getEndLoc()
15282 : MoveAssignOperator->getLocation();
15283
15284 // Builds a reference to the "other" object.
15285 RefBuilder OtherRef(Other, OtherRefType);
15286 // Cast to rvalue.
15287 MoveCastBuilder MoveOther(OtherRef);
15288
15289 // Builds the function object parameter.
15290 std::optional<ThisBuilder> This;
15291 std::optional<DerefBuilder> DerefThis;
15292 std::optional<RefBuilder> ExplicitObject;
15293 QualType ObjectType;
15294 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15295 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15296 if (ObjectType->isReferenceType())
15297 ObjectType = ObjectType->getPointeeType();
15298 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15299 } else {
15300 ObjectType = getCurrentThisType();
15301 This.emplace();
15302 DerefThis.emplace(*This);
15303 }
15304 ExprBuilder &ObjectParameter =
15305 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15306
15307 // Assign base classes.
15308 bool Invalid = false;
15309 for (auto &Base : ClassDecl->bases()) {
15310 // C++11 [class.copy]p28:
15311 // It is unspecified whether subobjects representing virtual base classes
15312 // are assigned more than once by the implicitly-defined copy assignment
15313 // operator.
15314 // FIXME: Do not assign to a vbase that will be assigned by some other base
15315 // class. For a move-assignment, this can result in the vbase being moved
15316 // multiple times.
15317
15318 // Form the assignment:
15319 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15320 QualType BaseType = Base.getType().getUnqualifiedType();
15321 if (!BaseType->isRecordType()) {
15322 Invalid = true;
15323 continue;
15324 }
15325
15326 CXXCastPath BasePath;
15327 BasePath.push_back(&Base);
15328
15329 // Construct the "from" expression, which is an implicit cast to the
15330 // appropriately-qualified base type.
15331 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15332
15333 // Implicitly cast "this" to the appropriately-qualified base type.
15334 // Dereference "this".
15335 CastBuilder To(
15336 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15337 : static_cast<ExprBuilder &>(*DerefThis),
15338 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15339 VK_LValue, BasePath);
15340
15341 // Build the move.
15342 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15343 To, From,
15344 /*CopyingBaseSubobject=*/true,
15345 /*Copying=*/false);
15346 if (Move.isInvalid()) {
15347 MoveAssignOperator->setInvalidDecl();
15348 return;
15349 }
15350
15351 // Success! Record the move.
15352 Statements.push_back(Move.getAs<Expr>());
15353 }
15354
15355 // Assign non-static members.
15356 for (auto *Field : ClassDecl->fields()) {
15357 // FIXME: We should form some kind of AST representation for the implied
15358 // memcpy in a union copy operation.
15359 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15360 continue;
15361
15362 if (Field->isInvalidDecl()) {
15363 Invalid = true;
15364 continue;
15365 }
15366
15367 // Check for members of reference type; we can't move those.
15368 if (Field->getType()->isReferenceType()) {
15369 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15370 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15371 Diag(Field->getLocation(), diag::note_declared_at);
15372 Invalid = true;
15373 continue;
15374 }
15375
15376 // Check for members of const-qualified, non-class type.
15377 QualType BaseType = Context.getBaseElementType(Field->getType());
15378 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15379 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15380 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15381 Diag(Field->getLocation(), diag::note_declared_at);
15382 Invalid = true;
15383 continue;
15384 }
15385
15386 // Suppress assigning zero-width bitfields.
15387 if (Field->isZeroLengthBitField(Context))
15388 continue;
15389
15390 QualType FieldType = Field->getType().getNonReferenceType();
15391 if (FieldType->isIncompleteArrayType()) {
15392 assert(ClassDecl->hasFlexibleArrayMember() &&
15393 "Incomplete array type is not valid");
15394 continue;
15395 }
15396
15397 // Build references to the field in the object we're copying from and to.
15398 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15400 MemberLookup.addDecl(Field);
15401 MemberLookup.resolveKind();
15402 MemberBuilder From(MoveOther, OtherRefType,
15403 /*IsArrow=*/false, MemberLookup);
15404 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15405 MemberLookup);
15406
15407 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15408 "Member reference with rvalue base must be rvalue except for reference "
15409 "members, which aren't allowed for move assignment.");
15410
15411 // Build the move of this field.
15412 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15413 To, From,
15414 /*CopyingBaseSubobject=*/false,
15415 /*Copying=*/false);
15416 if (Move.isInvalid()) {
15417 MoveAssignOperator->setInvalidDecl();
15418 return;
15419 }
15420
15421 // Success! Record the copy.
15422 Statements.push_back(Move.getAs<Stmt>());
15423 }
15424
15425 if (!Invalid) {
15426 // Add a "return *this;"
15427 Expr *ThisExpr =
15428 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15429 : static_cast<ExprBuilder &>(*DerefThis))
15430 .build(*this, Loc);
15431
15432 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15433 if (Return.isInvalid())
15434 Invalid = true;
15435 else
15436 Statements.push_back(Return.getAs<Stmt>());
15437 }
15438
15439 if (Invalid) {
15440 MoveAssignOperator->setInvalidDecl();
15441 return;
15442 }
15443
15444 StmtResult Body;
15445 {
15446 CompoundScopeRAII CompoundScope(*this);
15447 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15448 /*isStmtExpr=*/false);
15449 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15450 }
15451 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15452 MoveAssignOperator->markUsed(Context);
15453
15455 L->CompletedImplicitDefinition(MoveAssignOperator);
15456 }
15457}
15458
15460 CXXRecordDecl *ClassDecl) {
15461 // C++ [class.copy]p4:
15462 // If the class definition does not explicitly declare a copy
15463 // constructor, one is declared implicitly.
15464 assert(ClassDecl->needsImplicitCopyConstructor());
15465
15466 DeclaringSpecialMember DSM(*this, ClassDecl,
15468 if (DSM.isAlreadyBeingDeclared())
15469 return nullptr;
15470
15471 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15472 QualType ArgType = ClassType;
15474 ArgType, nullptr);
15475 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15476 if (Const)
15477 ArgType = ArgType.withConst();
15478
15480 if (AS != LangAS::Default)
15481 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15482
15483 ArgType = Context.getLValueReferenceType(ArgType);
15484
15486 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15487
15488 DeclarationName Name
15490 Context.getCanonicalType(ClassType));
15491 SourceLocation ClassLoc = ClassDecl->getLocation();
15492 DeclarationNameInfo NameInfo(Name, ClassLoc);
15493
15494 // An implicitly-declared copy constructor is an inline public
15495 // member of its class.
15497 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15498 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15499 /*isInline=*/true,
15500 /*isImplicitlyDeclared=*/true,
15503 CopyConstructor->setAccess(AS_public);
15504 CopyConstructor->setDefaulted();
15505
15506 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15507
15508 if (getLangOpts().CUDA)
15511 /* ConstRHS */ Const,
15512 /* Diagnose */ false);
15513
15514 // During template instantiation of special member functions we need a
15515 // reliable TypeSourceInfo for the parameter types in order to allow functions
15516 // to be substituted.
15517 TypeSourceInfo *TSI = nullptr;
15518 if (inTemplateInstantiation() && ClassDecl->isLambda())
15519 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15520
15521 // Add the parameter to the constructor.
15522 ParmVarDecl *FromParam =
15523 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15524 /*IdentifierInfo=*/nullptr, ArgType,
15525 /*TInfo=*/TSI, SC_None, nullptr);
15526 CopyConstructor->setParams(FromParam);
15527
15528 CopyConstructor->setTrivial(
15532 : ClassDecl->hasTrivialCopyConstructor());
15533
15534 CopyConstructor->setTrivialForCall(
15535 ClassDecl->hasAttr<TrivialABIAttr>() ||
15540 : ClassDecl->hasTrivialCopyConstructorForCall()));
15541
15542 // Note that we have declared this constructor.
15544
15545 Scope *S = getScopeForContext(ClassDecl);
15547
15552 }
15553
15554 if (S)
15556 ClassDecl->addDecl(CopyConstructor);
15557
15558 return CopyConstructor;
15559}
15560
15563 assert((CopyConstructor->isDefaulted() &&
15564 CopyConstructor->isCopyConstructor() &&
15565 !CopyConstructor->doesThisDeclarationHaveABody() &&
15566 !CopyConstructor->isDeleted()) &&
15567 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15568 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15569 return;
15570
15571 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15572 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15573
15575
15576 // The exception specification is needed because we are defining the
15577 // function.
15578 ResolveExceptionSpec(CurrentLocation,
15579 CopyConstructor->getType()->castAs<FunctionProtoType>());
15580 MarkVTableUsed(CurrentLocation, ClassDecl);
15581
15582 // Add a context note for diagnostics produced after this point.
15583 Scope.addContextNote(CurrentLocation);
15584
15585 // C++11 [class.copy]p7:
15586 // The [definition of an implicitly declared copy constructor] is
15587 // deprecated if the class has a user-declared copy assignment operator
15588 // or a user-declared destructor.
15589 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15591
15592 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15593 CopyConstructor->setInvalidDecl();
15594 } else {
15595 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15596 ? CopyConstructor->getEndLoc()
15597 : CopyConstructor->getLocation();
15598 Sema::CompoundScopeRAII CompoundScope(*this);
15599 CopyConstructor->setBody(
15600 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15601 .getAs<Stmt>());
15602 CopyConstructor->markUsed(Context);
15603 }
15604
15606 L->CompletedImplicitDefinition(CopyConstructor);
15607 }
15608}
15609
15611 CXXRecordDecl *ClassDecl) {
15612 assert(ClassDecl->needsImplicitMoveConstructor());
15613
15614 DeclaringSpecialMember DSM(*this, ClassDecl,
15616 if (DSM.isAlreadyBeingDeclared())
15617 return nullptr;
15618
15619 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15620
15621 QualType ArgType = ClassType;
15623 ArgType, nullptr);
15625 if (AS != LangAS::Default)
15626 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15627 ArgType = Context.getRValueReferenceType(ArgType);
15628
15630 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15631
15632 DeclarationName Name
15634 Context.getCanonicalType(ClassType));
15635 SourceLocation ClassLoc = ClassDecl->getLocation();
15636 DeclarationNameInfo NameInfo(Name, ClassLoc);
15637
15638 // C++11 [class.copy]p11:
15639 // An implicitly-declared copy/move constructor is an inline public
15640 // member of its class.
15642 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15643 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15644 /*isInline=*/true,
15645 /*isImplicitlyDeclared=*/true,
15648 MoveConstructor->setAccess(AS_public);
15649 MoveConstructor->setDefaulted();
15650
15651 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15652
15653 if (getLangOpts().CUDA)
15656 /* ConstRHS */ false,
15657 /* Diagnose */ false);
15658
15659 // Add the parameter to the constructor.
15661 ClassLoc, ClassLoc,
15662 /*IdentifierInfo=*/nullptr,
15663 ArgType, /*TInfo=*/nullptr,
15664 SC_None, nullptr);
15665 MoveConstructor->setParams(FromParam);
15666
15667 MoveConstructor->setTrivial(
15671 : ClassDecl->hasTrivialMoveConstructor());
15672
15673 MoveConstructor->setTrivialForCall(
15674 ClassDecl->hasAttr<TrivialABIAttr>() ||
15679 : ClassDecl->hasTrivialMoveConstructorForCall()));
15680
15681 // Note that we have declared this constructor.
15683
15684 Scope *S = getScopeForContext(ClassDecl);
15686
15691 }
15692
15693 if (S)
15695 ClassDecl->addDecl(MoveConstructor);
15696
15697 return MoveConstructor;
15698}
15699
15702 assert((MoveConstructor->isDefaulted() &&
15703 MoveConstructor->isMoveConstructor() &&
15704 !MoveConstructor->doesThisDeclarationHaveABody() &&
15705 !MoveConstructor->isDeleted()) &&
15706 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15707 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15708 return;
15709
15710 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15711 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15712
15714
15715 // The exception specification is needed because we are defining the
15716 // function.
15717 ResolveExceptionSpec(CurrentLocation,
15718 MoveConstructor->getType()->castAs<FunctionProtoType>());
15719 MarkVTableUsed(CurrentLocation, ClassDecl);
15720
15721 // Add a context note for diagnostics produced after this point.
15722 Scope.addContextNote(CurrentLocation);
15723
15724 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15725 MoveConstructor->setInvalidDecl();
15726 } else {
15727 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15728 ? MoveConstructor->getEndLoc()
15729 : MoveConstructor->getLocation();
15730 Sema::CompoundScopeRAII CompoundScope(*this);
15731 MoveConstructor->setBody(
15732 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15733 .getAs<Stmt>());
15734 MoveConstructor->markUsed(Context);
15735 }
15736
15738 L->CompletedImplicitDefinition(MoveConstructor);
15739 }
15740}
15741
15743 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15744}
15745
15747 SourceLocation CurrentLocation,
15748 CXXConversionDecl *Conv) {
15749 SynthesizedFunctionScope Scope(*this, Conv);
15750 assert(!Conv->getReturnType()->isUndeducedType());
15751
15752 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15753 CallingConv CC =
15754 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15755
15756 CXXRecordDecl *Lambda = Conv->getParent();
15757 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15758 FunctionDecl *Invoker =
15759 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15760 ? CallOp
15761 : Lambda->getLambdaStaticInvoker(CC);
15762
15763 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15765 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15766 if (!CallOp)
15767 return;
15768
15769 if (CallOp != Invoker) {
15771 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15772 CurrentLocation);
15773 if (!Invoker)
15774 return;
15775 }
15776 }
15777
15778 if (CallOp->isInvalidDecl())
15779 return;
15780
15781 // Mark the call operator referenced (and add to pending instantiations
15782 // if necessary).
15783 // For both the conversion and static-invoker template specializations
15784 // we construct their body's in this function, so no need to add them
15785 // to the PendingInstantiations.
15786 MarkFunctionReferenced(CurrentLocation, CallOp);
15787
15788 if (Invoker != CallOp) {
15789 // Fill in the __invoke function with a dummy implementation. IR generation
15790 // will fill in the actual details. Update its type in case it contained
15791 // an 'auto'.
15792 Invoker->markUsed(Context);
15793 Invoker->setReferenced();
15794 Invoker->setType(Conv->getReturnType()->getPointeeType());
15795 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15796 }
15797
15798 // Construct the body of the conversion function { return __invoke; }.
15799 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15800 Conv->getLocation());
15801 assert(FunctionRef && "Can't refer to __invoke function?");
15802 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15804 Conv->getLocation(), Conv->getLocation()));
15805 Conv->markUsed(Context);
15806 Conv->setReferenced();
15807
15809 L->CompletedImplicitDefinition(Conv);
15810 if (Invoker != CallOp)
15811 L->CompletedImplicitDefinition(Invoker);
15812 }
15813}
15814
15816 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15817 assert(!Conv->getParent()->isGenericLambda());
15818
15819 SynthesizedFunctionScope Scope(*this, Conv);
15820
15821 // Copy-initialize the lambda object as needed to capture it.
15822 Expr *This = ActOnCXXThis(CurrentLocation).get();
15823 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15824
15825 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15826 Conv->getLocation(),
15827 Conv, DerefThis);
15828
15829 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15830 // behavior. Note that only the general conversion function does this
15831 // (since it's unusable otherwise); in the case where we inline the
15832 // block literal, it has block literal lifetime semantics.
15833 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15834 BuildBlock = ImplicitCastExpr::Create(
15835 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15836 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15837
15838 if (BuildBlock.isInvalid()) {
15839 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15840 Conv->setInvalidDecl();
15841 return;
15842 }
15843
15844 // Create the return statement that returns the block from the conversion
15845 // function.
15846 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15847 if (Return.isInvalid()) {
15848 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15849 Conv->setInvalidDecl();
15850 return;
15851 }
15852
15853 // Set the body of the conversion function.
15854 Stmt *ReturnS = Return.get();
15856 Conv->getLocation(), Conv->getLocation()));
15857 Conv->markUsed(Context);
15858
15859 // We're done; notify the mutation listener, if any.
15861 L->CompletedImplicitDefinition(Conv);
15862 }
15863}
15864
15865/// Determine whether the given list arguments contains exactly one
15866/// "real" (non-default) argument.
15868 switch (Args.size()) {
15869 case 0:
15870 return false;
15871
15872 default:
15873 if (!Args[1]->isDefaultArgument())
15874 return false;
15875
15876 [[fallthrough]];
15877 case 1:
15878 return !Args[0]->isDefaultArgument();
15879 }
15880
15881 return false;
15882}
15883
15885 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15886 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
15887 bool HadMultipleCandidates, bool IsListInitialization,
15888 bool IsStdInitListInitialization, bool RequiresZeroInit,
15889 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15890 bool Elidable = false;
15891
15892 // C++0x [class.copy]p34:
15893 // When certain criteria are met, an implementation is allowed to
15894 // omit the copy/move construction of a class object, even if the
15895 // copy/move constructor and/or destructor for the object have
15896 // side effects. [...]
15897 // - when a temporary class object that has not been bound to a
15898 // reference (12.2) would be copied/moved to a class object
15899 // with the same cv-unqualified type, the copy/move operation
15900 // can be omitted by constructing the temporary object
15901 // directly into the target of the omitted copy/move
15902 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
15903 // FIXME: Converting constructors should also be accepted.
15904 // But to fix this, the logic that digs down into a CXXConstructExpr
15905 // to find the source object needs to handle it.
15906 // Right now it assumes the source object is passed directly as the
15907 // first argument.
15908 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15909 Expr *SubExpr = ExprArgs[0];
15910 // FIXME: Per above, this is also incorrect if we want to accept
15911 // converting constructors, as isTemporaryObject will
15912 // reject temporaries with different type from the
15913 // CXXRecord itself.
15914 Elidable = SubExpr->isTemporaryObject(
15915 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15916 }
15917
15918 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15919 FoundDecl, Constructor,
15920 Elidable, ExprArgs, HadMultipleCandidates,
15921 IsListInitialization,
15922 IsStdInitListInitialization, RequiresZeroInit,
15923 ConstructKind, ParenRange);
15924}
15925
15927 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15928 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15929 bool HadMultipleCandidates, bool IsListInitialization,
15930 bool IsStdInitListInitialization, bool RequiresZeroInit,
15931 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15932 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15933 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15934 // The only way to get here is if we did overload resolution to find the
15935 // shadow decl, so we don't need to worry about re-checking the trailing
15936 // requires clause.
15937 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15938 return ExprError();
15939 }
15940
15941 return BuildCXXConstructExpr(
15942 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15943 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15944 RequiresZeroInit, ConstructKind, ParenRange);
15945}
15946
15947/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15948/// including handling of its default argument expressions.
15950 SourceLocation ConstructLoc, QualType DeclInitType,
15951 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15952 bool HadMultipleCandidates, bool IsListInitialization,
15953 bool IsStdInitListInitialization, bool RequiresZeroInit,
15954 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15955 assert(declaresSameEntity(
15956 Constructor->getParent(),
15957 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15958 "given constructor for wrong type");
15959 MarkFunctionReferenced(ConstructLoc, Constructor);
15960 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
15961 return ExprError();
15962
15965 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15966 HadMultipleCandidates, IsListInitialization,
15967 IsStdInitListInitialization, RequiresZeroInit,
15968 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
15969 Constructor);
15970}
15971
15973 if (VD->isInvalidDecl()) return;
15974 // If initializing the variable failed, don't also diagnose problems with
15975 // the destructor, they're likely related.
15976 if (VD->getInit() && VD->getInit()->containsErrors())
15977 return;
15978
15979 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15980 if (ClassDecl->isInvalidDecl()) return;
15981 if (ClassDecl->hasIrrelevantDestructor()) return;
15982 if (ClassDecl->isDependentContext()) return;
15983
15984 if (VD->isNoDestroy(getASTContext()))
15985 return;
15986
15988 // The result of `LookupDestructor` might be nullptr if the destructor is
15989 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
15990 // will not be selected by `CXXRecordDecl::getDestructor()`.
15991 if (!Destructor)
15992 return;
15993 // If this is an array, we'll require the destructor during initialization, so
15994 // we can skip over this. We still want to emit exit-time destructor warnings
15995 // though.
15996 if (!VD->getType()->isArrayType()) {
15999 PDiag(diag::err_access_dtor_var)
16000 << VD->getDeclName() << VD->getType());
16002 }
16003
16004 if (Destructor->isTrivial()) return;
16005
16006 // If the destructor is constexpr, check whether the variable has constant
16007 // destruction now.
16008 if (Destructor->isConstexpr()) {
16009 bool HasConstantInit = false;
16010 if (VD->getInit() && !VD->getInit()->isValueDependent())
16011 HasConstantInit = VD->evaluateValue();
16013 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16014 HasConstantInit) {
16015 Diag(VD->getLocation(),
16016 diag::err_constexpr_var_requires_const_destruction) << VD;
16017 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16018 Diag(Notes[I].first, Notes[I].second);
16019 }
16020 }
16021
16022 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16023 return;
16024
16025 // Emit warning for non-trivial dtor in global scope (a real global,
16026 // class-static, function-static).
16027 if (!VD->hasAttr<AlwaysDestroyAttr>())
16028 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16029
16030 // TODO: this should be re-enabled for static locals by !CXAAtExit
16031 if (!VD->isStaticLocal())
16032 Diag(VD->getLocation(), diag::warn_global_destructor);
16033}
16034
16036 QualType DeclInitType, MultiExprArg ArgsPtr,
16038 SmallVectorImpl<Expr *> &ConvertedArgs,
16039 bool AllowExplicit,
16040 bool IsListInitialization) {
16041 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16042 unsigned NumArgs = ArgsPtr.size();
16043 Expr **Args = ArgsPtr.data();
16044
16045 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16046 unsigned NumParams = Proto->getNumParams();
16047
16048 // If too few arguments are available, we'll fill in the rest with defaults.
16049 if (NumArgs < NumParams)
16050 ConvertedArgs.reserve(NumParams);
16051 else
16052 ConvertedArgs.reserve(NumArgs);
16053
16054 VariadicCallType CallType =
16055 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16056 SmallVector<Expr *, 8> AllArgs;
16058 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16059 CallType, AllowExplicit, IsListInitialization);
16060 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16061
16062 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16063
16064 CheckConstructorCall(Constructor, DeclInitType,
16065 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16066 Loc);
16067
16068 return Invalid;
16069}
16070
16071static inline bool
16073 const FunctionDecl *FnDecl) {
16074 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16075 if (isa<NamespaceDecl>(DC)) {
16076 return SemaRef.Diag(FnDecl->getLocation(),
16077 diag::err_operator_new_delete_declared_in_namespace)
16078 << FnDecl->getDeclName();
16079 }
16080
16081 if (isa<TranslationUnitDecl>(DC) &&
16082 FnDecl->getStorageClass() == SC_Static) {
16083 return SemaRef.Diag(FnDecl->getLocation(),
16084 diag::err_operator_new_delete_declared_static)
16085 << FnDecl->getDeclName();
16086 }
16087
16088 return false;
16089}
16090
16092 const PointerType *PtrTy) {
16093 auto &Ctx = SemaRef.Context;
16094 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16095 PtrQuals.removeAddressSpace();
16096 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16097 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16098}
16099
16100static inline bool
16102 CanQualType ExpectedResultType,
16103 CanQualType ExpectedFirstParamType,
16104 unsigned DependentParamTypeDiag,
16105 unsigned InvalidParamTypeDiag) {
16106 QualType ResultType =
16107 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16108
16109 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16110 // The operator is valid on any address space for OpenCL.
16111 // Drop address space from actual and expected result types.
16112 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16113 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16114
16115 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16116 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16117 }
16118
16119 // Check that the result type is what we expect.
16120 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16121 // Reject even if the type is dependent; an operator delete function is
16122 // required to have a non-dependent result type.
16123 return SemaRef.Diag(
16124 FnDecl->getLocation(),
16125 ResultType->isDependentType()
16126 ? diag::err_operator_new_delete_dependent_result_type
16127 : diag::err_operator_new_delete_invalid_result_type)
16128 << FnDecl->getDeclName() << ExpectedResultType;
16129 }
16130
16131 // A function template must have at least 2 parameters.
16132 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16133 return SemaRef.Diag(FnDecl->getLocation(),
16134 diag::err_operator_new_delete_template_too_few_parameters)
16135 << FnDecl->getDeclName();
16136
16137 // The function decl must have at least 1 parameter.
16138 if (FnDecl->getNumParams() == 0)
16139 return SemaRef.Diag(FnDecl->getLocation(),
16140 diag::err_operator_new_delete_too_few_parameters)
16141 << FnDecl->getDeclName();
16142
16143 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16144 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16145 // The operator is valid on any address space for OpenCL.
16146 // Drop address space from actual and expected first parameter types.
16147 if (const auto *PtrTy =
16148 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16149 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16150
16151 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16152 ExpectedFirstParamType =
16153 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16154 }
16155
16156 // Check that the first parameter type is what we expect.
16157 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16158 ExpectedFirstParamType) {
16159 // The first parameter type is not allowed to be dependent. As a tentative
16160 // DR resolution, we allow a dependent parameter type if it is the right
16161 // type anyway, to allow destroying operator delete in class templates.
16162 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16163 ? DependentParamTypeDiag
16164 : InvalidParamTypeDiag)
16165 << FnDecl->getDeclName() << ExpectedFirstParamType;
16166 }
16167
16168 return false;
16169}
16170
16171static bool
16173 // C++ [basic.stc.dynamic.allocation]p1:
16174 // A program is ill-formed if an allocation function is declared in a
16175 // namespace scope other than global scope or declared static in global
16176 // scope.
16178 return true;
16179
16180 CanQualType SizeTy =
16182
16183 // C++ [basic.stc.dynamic.allocation]p1:
16184 // The return type shall be void*. The first parameter shall have type
16185 // std::size_t.
16187 SizeTy,
16188 diag::err_operator_new_dependent_param_type,
16189 diag::err_operator_new_param_type))
16190 return true;
16191
16192 // C++ [basic.stc.dynamic.allocation]p1:
16193 // The first parameter shall not have an associated default argument.
16194 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16195 return SemaRef.Diag(FnDecl->getLocation(),
16196 diag::err_operator_new_default_arg)
16197 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16198
16199 return false;
16200}
16201
16202static bool
16204 // C++ [basic.stc.dynamic.deallocation]p1:
16205 // A program is ill-formed if deallocation functions are declared in a
16206 // namespace scope other than global scope or declared static in global
16207 // scope.
16209 return true;
16210
16211 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16212
16213 // C++ P0722:
16214 // Within a class C, the first parameter of a destroying operator delete
16215 // shall be of type C *. The first parameter of any other deallocation
16216 // function shall be of type void *.
16217 CanQualType ExpectedFirstParamType =
16218 MD && MD->isDestroyingOperatorDelete()
16222
16223 // C++ [basic.stc.dynamic.deallocation]p2:
16224 // Each deallocation function shall return void
16226 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16227 diag::err_operator_delete_dependent_param_type,
16228 diag::err_operator_delete_param_type))
16229 return true;
16230
16231 // C++ P0722:
16232 // A destroying operator delete shall be a usual deallocation function.
16233 if (MD && !MD->getParent()->isDependentContext() &&
16236 SemaRef.Diag(MD->getLocation(),
16237 diag::err_destroying_operator_delete_not_usual);
16238 return true;
16239 }
16240
16241 return false;
16242}
16243
16245 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16246 "Expected an overloaded operator declaration");
16247
16249
16250 // C++ [over.oper]p5:
16251 // The allocation and deallocation functions, operator new,
16252 // operator new[], operator delete and operator delete[], are
16253 // described completely in 3.7.3. The attributes and restrictions
16254 // found in the rest of this subclause do not apply to them unless
16255 // explicitly stated in 3.7.3.
16256 if (Op == OO_Delete || Op == OO_Array_Delete)
16257 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16258
16259 if (Op == OO_New || Op == OO_Array_New)
16260 return CheckOperatorNewDeclaration(*this, FnDecl);
16261
16262 // C++ [over.oper]p7:
16263 // An operator function shall either be a member function or
16264 // be a non-member function and have at least one parameter
16265 // whose type is a class, a reference to a class, an enumeration,
16266 // or a reference to an enumeration.
16267 // Note: Before C++23, a member function could not be static. The only member
16268 // function allowed to be static is the call operator function.
16269 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16270 if (MethodDecl->isStatic()) {
16271 if (Op == OO_Call || Op == OO_Subscript)
16272 Diag(FnDecl->getLocation(),
16273 (LangOpts.CPlusPlus23
16274 ? diag::warn_cxx20_compat_operator_overload_static
16275 : diag::ext_operator_overload_static))
16276 << FnDecl;
16277 else
16278 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16279 << FnDecl;
16280 }
16281 } else {
16282 bool ClassOrEnumParam = false;
16283 for (auto *Param : FnDecl->parameters()) {
16284 QualType ParamType = Param->getType().getNonReferenceType();
16285 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16286 ParamType->isEnumeralType()) {
16287 ClassOrEnumParam = true;
16288 break;
16289 }
16290 }
16291
16292 if (!ClassOrEnumParam)
16293 return Diag(FnDecl->getLocation(),
16294 diag::err_operator_overload_needs_class_or_enum)
16295 << FnDecl->getDeclName();
16296 }
16297
16298 // C++ [over.oper]p8:
16299 // An operator function cannot have default arguments (8.3.6),
16300 // except where explicitly stated below.
16301 //
16302 // Only the function-call operator (C++ [over.call]p1) and the subscript
16303 // operator (CWG2507) allow default arguments.
16304 if (Op != OO_Call) {
16305 ParmVarDecl *FirstDefaultedParam = nullptr;
16306 for (auto *Param : FnDecl->parameters()) {
16307 if (Param->hasDefaultArg()) {
16308 FirstDefaultedParam = Param;
16309 break;
16310 }
16311 }
16312 if (FirstDefaultedParam) {
16313 if (Op == OO_Subscript) {
16314 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16315 ? diag::ext_subscript_overload
16316 : diag::error_subscript_overload)
16317 << FnDecl->getDeclName() << 1
16318 << FirstDefaultedParam->getDefaultArgRange();
16319 } else {
16320 return Diag(FirstDefaultedParam->getLocation(),
16321 diag::err_operator_overload_default_arg)
16322 << FnDecl->getDeclName()
16323 << FirstDefaultedParam->getDefaultArgRange();
16324 }
16325 }
16326 }
16327
16328 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16329 { false, false, false }
16330#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16331 , { Unary, Binary, MemberOnly }
16332#include "clang/Basic/OperatorKinds.def"
16333 };
16334
16335 bool CanBeUnaryOperator = OperatorUses[Op][0];
16336 bool CanBeBinaryOperator = OperatorUses[Op][1];
16337 bool MustBeMemberOperator = OperatorUses[Op][2];
16338
16339 // C++ [over.oper]p8:
16340 // [...] Operator functions cannot have more or fewer parameters
16341 // than the number required for the corresponding operator, as
16342 // described in the rest of this subclause.
16343 unsigned NumParams = FnDecl->getNumParams() +
16344 (isa<CXXMethodDecl>(FnDecl) &&
16346 ? 1
16347 : 0);
16348 if (Op != OO_Call && Op != OO_Subscript &&
16349 ((NumParams == 1 && !CanBeUnaryOperator) ||
16350 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16351 (NumParams > 2))) {
16352 // We have the wrong number of parameters.
16353 unsigned ErrorKind;
16354 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16355 ErrorKind = 2; // 2 -> unary or binary.
16356 } else if (CanBeUnaryOperator) {
16357 ErrorKind = 0; // 0 -> unary
16358 } else {
16359 assert(CanBeBinaryOperator &&
16360 "All non-call overloaded operators are unary or binary!");
16361 ErrorKind = 1; // 1 -> binary
16362 }
16363 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16364 << FnDecl->getDeclName() << NumParams << ErrorKind;
16365 }
16366
16367 if (Op == OO_Subscript && NumParams != 2) {
16368 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16369 ? diag::ext_subscript_overload
16370 : diag::error_subscript_overload)
16371 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16372 }
16373
16374 // Overloaded operators other than operator() and operator[] cannot be
16375 // variadic.
16376 if (Op != OO_Call &&
16377 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16378 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16379 << FnDecl->getDeclName();
16380 }
16381
16382 // Some operators must be member functions.
16383 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16384 return Diag(FnDecl->getLocation(),
16385 diag::err_operator_overload_must_be_member)
16386 << FnDecl->getDeclName();
16387 }
16388
16389 // C++ [over.inc]p1:
16390 // The user-defined function called operator++ implements the
16391 // prefix and postfix ++ operator. If this function is a member
16392 // function with no parameters, or a non-member function with one
16393 // parameter of class or enumeration type, it defines the prefix
16394 // increment operator ++ for objects of that type. If the function
16395 // is a member function with one parameter (which shall be of type
16396 // int) or a non-member function with two parameters (the second
16397 // of which shall be of type int), it defines the postfix
16398 // increment operator ++ for objects of that type.
16399 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16400 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16401 QualType ParamType = LastParam->getType();
16402
16403 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16404 !ParamType->isDependentType())
16405 return Diag(LastParam->getLocation(),
16406 diag::err_operator_overload_post_incdec_must_be_int)
16407 << LastParam->getType() << (Op == OO_MinusMinus);
16408 }
16409
16410 return false;
16411}
16412
16413static bool
16415 FunctionTemplateDecl *TpDecl) {
16416 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16417
16418 // Must have one or two template parameters.
16419 if (TemplateParams->size() == 1) {
16420 NonTypeTemplateParmDecl *PmDecl =
16421 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16422
16423 // The template parameter must be a char parameter pack.
16424 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16426 return false;
16427
16428 // C++20 [over.literal]p5:
16429 // A string literal operator template is a literal operator template
16430 // whose template-parameter-list comprises a single non-type
16431 // template-parameter of class type.
16432 //
16433 // As a DR resolution, we also allow placeholders for deduced class
16434 // template specializations.
16435 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16436 !PmDecl->isTemplateParameterPack() &&
16437 (PmDecl->getType()->isRecordType() ||
16439 return false;
16440 } else if (TemplateParams->size() == 2) {
16441 TemplateTypeParmDecl *PmType =
16442 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16443 NonTypeTemplateParmDecl *PmArgs =
16444 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16445
16446 // The second template parameter must be a parameter pack with the
16447 // first template parameter as its type.
16448 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16449 PmArgs->isTemplateParameterPack()) {
16450 const TemplateTypeParmType *TArgs =
16451 PmArgs->getType()->getAs<TemplateTypeParmType>();
16452 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16453 TArgs->getIndex() == PmType->getIndex()) {
16455 SemaRef.Diag(TpDecl->getLocation(),
16456 diag::ext_string_literal_operator_template);
16457 return false;
16458 }
16459 }
16460 }
16461
16463 diag::err_literal_operator_template)
16464 << TpDecl->getTemplateParameters()->getSourceRange();
16465 return true;
16466}
16467
16469 if (isa<CXXMethodDecl>(FnDecl)) {
16470 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16471 << FnDecl->getDeclName();
16472 return true;
16473 }
16474
16475 if (FnDecl->isExternC()) {
16476 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16477 if (const LinkageSpecDecl *LSD =
16478 FnDecl->getDeclContext()->getExternCContext())
16479 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16480 return true;
16481 }
16482
16483 // This might be the definition of a literal operator template.
16485
16486 // This might be a specialization of a literal operator template.
16487 if (!TpDecl)
16488 TpDecl = FnDecl->getPrimaryTemplate();
16489
16490 // template <char...> type operator "" name() and
16491 // template <class T, T...> type operator "" name() are the only valid
16492 // template signatures, and the only valid signatures with no parameters.
16493 //
16494 // C++20 also allows template <SomeClass T> type operator "" name().
16495 if (TpDecl) {
16496 if (FnDecl->param_size() != 0) {
16497 Diag(FnDecl->getLocation(),
16498 diag::err_literal_operator_template_with_params);
16499 return true;
16500 }
16501
16503 return true;
16504
16505 } else if (FnDecl->param_size() == 1) {
16506 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16507
16508 QualType ParamType = Param->getType().getUnqualifiedType();
16509
16510 // Only unsigned long long int, long double, any character type, and const
16511 // char * are allowed as the only parameters.
16512 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16513 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16514 Context.hasSameType(ParamType, Context.CharTy) ||
16515 Context.hasSameType(ParamType, Context.WideCharTy) ||
16516 Context.hasSameType(ParamType, Context.Char8Ty) ||
16517 Context.hasSameType(ParamType, Context.Char16Ty) ||
16518 Context.hasSameType(ParamType, Context.Char32Ty)) {
16519 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16520 QualType InnerType = Ptr->getPointeeType();
16521
16522 // Pointer parameter must be a const char *.
16523 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16524 Context.CharTy) &&
16525 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16526 Diag(Param->getSourceRange().getBegin(),
16527 diag::err_literal_operator_param)
16528 << ParamType << "'const char *'" << Param->getSourceRange();
16529 return true;
16530 }
16531
16532 } else if (ParamType->isRealFloatingType()) {
16533 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16534 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16535 return true;
16536
16537 } else if (ParamType->isIntegerType()) {
16538 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16539 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16540 return true;
16541
16542 } else {
16543 Diag(Param->getSourceRange().getBegin(),
16544 diag::err_literal_operator_invalid_param)
16545 << ParamType << Param->getSourceRange();
16546 return true;
16547 }
16548
16549 } else if (FnDecl->param_size() == 2) {
16550 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16551
16552 // First, verify that the first parameter is correct.
16553
16554 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16555
16556 // Two parameter function must have a pointer to const as a
16557 // first parameter; let's strip those qualifiers.
16558 const PointerType *PT = FirstParamType->getAs<PointerType>();
16559
16560 if (!PT) {
16561 Diag((*Param)->getSourceRange().getBegin(),
16562 diag::err_literal_operator_param)
16563 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16564 return true;
16565 }
16566
16567 QualType PointeeType = PT->getPointeeType();
16568 // First parameter must be const
16569 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16570 Diag((*Param)->getSourceRange().getBegin(),
16571 diag::err_literal_operator_param)
16572 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16573 return true;
16574 }
16575
16576 QualType InnerType = PointeeType.getUnqualifiedType();
16577 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16578 // const char32_t* are allowed as the first parameter to a two-parameter
16579 // function
16580 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16581 Context.hasSameType(InnerType, Context.WideCharTy) ||
16582 Context.hasSameType(InnerType, Context.Char8Ty) ||
16583 Context.hasSameType(InnerType, Context.Char16Ty) ||
16584 Context.hasSameType(InnerType, Context.Char32Ty))) {
16585 Diag((*Param)->getSourceRange().getBegin(),
16586 diag::err_literal_operator_param)
16587 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16588 return true;
16589 }
16590
16591 // Move on to the second and final parameter.
16592 ++Param;
16593
16594 // The second parameter must be a std::size_t.
16595 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16596 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16597 Diag((*Param)->getSourceRange().getBegin(),
16598 diag::err_literal_operator_param)
16599 << SecondParamType << Context.getSizeType()
16600 << (*Param)->getSourceRange();
16601 return true;
16602 }
16603 } else {
16604 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16605 return true;
16606 }
16607
16608 // Parameters are good.
16609
16610 // A parameter-declaration-clause containing a default argument is not
16611 // equivalent to any of the permitted forms.
16612 for (auto *Param : FnDecl->parameters()) {
16613 if (Param->hasDefaultArg()) {
16614 Diag(Param->getDefaultArgRange().getBegin(),
16615 diag::err_literal_operator_default_argument)
16616 << Param->getDefaultArgRange();
16617 break;
16618 }
16619 }
16620
16621 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16624 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16625 // C++23 [usrlit.suffix]p1:
16626 // Literal suffix identifiers that do not start with an underscore are
16627 // reserved for future standardization. Literal suffix identifiers that
16628 // contain a double underscore __ are reserved for use by C++
16629 // implementations.
16630 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16631 << static_cast<int>(Status)
16633 }
16634
16635 return false;
16636}
16637
16639 Expr *LangStr,
16640 SourceLocation LBraceLoc) {
16641 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16642 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16643
16644 StringRef Lang = Lit->getString();
16646 if (Lang == "C")
16648 else if (Lang == "C++")
16650 else {
16651 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16652 << LangStr->getSourceRange();
16653 return nullptr;
16654 }
16655
16656 // FIXME: Add all the various semantics of linkage specifications
16657
16659 LangStr->getExprLoc(), Language,
16660 LBraceLoc.isValid());
16661
16662 /// C++ [module.unit]p7.2.3
16663 /// - Otherwise, if the declaration
16664 /// - ...
16665 /// - ...
16666 /// - appears within a linkage-specification,
16667 /// it is attached to the global module.
16668 ///
16669 /// If the declaration is already in global module fragment, we don't
16670 /// need to attach it again.
16671 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16672 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16673 D->setLocalOwningModule(GlobalModule);
16674 }
16675
16677 PushDeclContext(S, D);
16678 return D;
16679}
16680
16682 Decl *LinkageSpec,
16683 SourceLocation RBraceLoc) {
16684 if (RBraceLoc.isValid()) {
16685 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16686 LSDecl->setRBraceLoc(RBraceLoc);
16687 }
16688
16689 // If the current module doesn't has Parent, it implies that the
16690 // LinkageSpec isn't in the module created by itself. So we don't
16691 // need to pop it.
16692 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16693 getCurrentModule()->isImplicitGlobalModule() &&
16695 PopImplicitGlobalModuleFragment();
16696
16698 return LinkageSpec;
16699}
16700
16702 const ParsedAttributesView &AttrList,
16703 SourceLocation SemiLoc) {
16704 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16705 // Attribute declarations appertain to empty declaration so we handle
16706 // them here.
16707 ProcessDeclAttributeList(S, ED, AttrList);
16708
16709 CurContext->addDecl(ED);
16710 return ED;
16711}
16712
16714 SourceLocation StartLoc,
16716 const IdentifierInfo *Name) {
16717 bool Invalid = false;
16718 QualType ExDeclType = TInfo->getType();
16719
16720 // Arrays and functions decay.
16721 if (ExDeclType->isArrayType())
16722 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16723 else if (ExDeclType->isFunctionType())
16724 ExDeclType = Context.getPointerType(ExDeclType);
16725
16726 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16727 // The exception-declaration shall not denote a pointer or reference to an
16728 // incomplete type, other than [cv] void*.
16729 // N2844 forbids rvalue references.
16730 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16731 Diag(Loc, diag::err_catch_rvalue_ref);
16732 Invalid = true;
16733 }
16734
16735 if (ExDeclType->isVariablyModifiedType()) {
16736 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16737 Invalid = true;
16738 }
16739
16740 QualType BaseType = ExDeclType;
16741 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16742 unsigned DK = diag::err_catch_incomplete;
16743 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16744 BaseType = Ptr->getPointeeType();
16745 Mode = 1;
16746 DK = diag::err_catch_incomplete_ptr;
16747 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16748 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16749 BaseType = Ref->getPointeeType();
16750 Mode = 2;
16751 DK = diag::err_catch_incomplete_ref;
16752 }
16753 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16754 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16755 Invalid = true;
16756
16757 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16758 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16759 Invalid = true;
16760 }
16761
16762 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16763 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16764 Invalid = true;
16765 }
16766
16767 if (!Invalid && !ExDeclType->isDependentType() &&
16768 RequireNonAbstractType(Loc, ExDeclType,
16769 diag::err_abstract_type_in_decl,
16771 Invalid = true;
16772
16773 // Only the non-fragile NeXT runtime currently supports C++ catches
16774 // of ObjC types, and no runtime supports catching ObjC types by value.
16775 if (!Invalid && getLangOpts().ObjC) {
16776 QualType T = ExDeclType;
16777 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16778 T = RT->getPointeeType();
16779
16780 if (T->isObjCObjectType()) {
16781 Diag(Loc, diag::err_objc_object_catch);
16782 Invalid = true;
16783 } else if (T->isObjCObjectPointerType()) {
16784 // FIXME: should this be a test for macosx-fragile specifically?
16786 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16787 }
16788 }
16789
16790 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16791 ExDeclType, TInfo, SC_None);
16792 ExDecl->setExceptionVariable(true);
16793
16794 // In ARC, infer 'retaining' for variables of retainable type.
16795 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
16796 Invalid = true;
16797
16798 if (!Invalid && !ExDeclType->isDependentType()) {
16799 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16800 // Insulate this from anything else we might currently be parsing.
16803
16804 // C++ [except.handle]p16:
16805 // The object declared in an exception-declaration or, if the
16806 // exception-declaration does not specify a name, a temporary (12.2) is
16807 // copy-initialized (8.5) from the exception object. [...]
16808 // The object is destroyed when the handler exits, after the destruction
16809 // of any automatic objects initialized within the handler.
16810 //
16811 // We just pretend to initialize the object with itself, then make sure
16812 // it can be destroyed later.
16813 QualType initType = Context.getExceptionObjectType(ExDeclType);
16814
16815 InitializedEntity entity =
16817 InitializationKind initKind =
16819
16820 Expr *opaqueValue =
16821 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16822 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16823 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16824 if (result.isInvalid())
16825 Invalid = true;
16826 else {
16827 // If the constructor used was non-trivial, set this as the
16828 // "initializer".
16829 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16830 if (!construct->getConstructor()->isTrivial()) {
16831 Expr *init = MaybeCreateExprWithCleanups(construct);
16832 ExDecl->setInit(init);
16833 }
16834
16835 // And make sure it's destructable.
16837 }
16838 }
16839 }
16840
16841 if (Invalid)
16842 ExDecl->setInvalidDecl();
16843
16844 return ExDecl;
16845}
16846
16849 bool Invalid = D.isInvalidType();
16850
16851 // Check for unexpanded parameter packs.
16852 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16855 D.getIdentifierLoc());
16856 Invalid = true;
16857 }
16858
16859 const IdentifierInfo *II = D.getIdentifier();
16860 if (NamedDecl *PrevDecl =
16861 LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
16862 RedeclarationKind::ForVisibleRedeclaration)) {
16863 // The scope should be freshly made just for us. There is just no way
16864 // it contains any previous declaration, except for function parameters in
16865 // a function-try-block's catch statement.
16866 assert(!S->isDeclScope(PrevDecl));
16867 if (isDeclInScope(PrevDecl, CurContext, S)) {
16868 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16869 << D.getIdentifier();
16870 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16871 Invalid = true;
16872 } else if (PrevDecl->isTemplateParameter())
16873 // Maybe we will complain about the shadowed template parameter.
16874 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16875 }
16876
16877 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16878 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16879 << D.getCXXScopeSpec().getRange();
16880 Invalid = true;
16881 }
16882
16884 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16885 if (Invalid)
16886 ExDecl->setInvalidDecl();
16887
16888 // Add the exception declaration into this scope.
16889 if (II)
16890 PushOnScopeChains(ExDecl, S);
16891 else
16892 CurContext->addDecl(ExDecl);
16893
16894 ProcessDeclAttributes(S, ExDecl, D);
16895 return ExDecl;
16896}
16897
16899 Expr *AssertExpr,
16900 Expr *AssertMessageExpr,
16901 SourceLocation RParenLoc) {
16903 return nullptr;
16904
16905 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16906 AssertMessageExpr, RParenLoc, false);
16907}
16908
16909static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
16910 switch (BTK) {
16911 case BuiltinType::Char_S:
16912 case BuiltinType::Char_U:
16913 break;
16914 case BuiltinType::Char8:
16915 OS << "u8";
16916 break;
16917 case BuiltinType::Char16:
16918 OS << 'u';
16919 break;
16920 case BuiltinType::Char32:
16921 OS << 'U';
16922 break;
16923 case BuiltinType::WChar_S:
16924 case BuiltinType::WChar_U:
16925 OS << 'L';
16926 break;
16927 default:
16928 llvm_unreachable("Non-character type");
16929 }
16930}
16931
16932/// Convert character's value, interpreted as a code unit, to a string.
16933/// The value needs to be zero-extended to 32-bits.
16934/// FIXME: This assumes Unicode literal encodings
16935static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
16936 unsigned TyWidth,
16937 SmallVectorImpl<char> &Str) {
16938 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
16939 char *Ptr = Arr;
16940 BuiltinType::Kind K = BTy->getKind();
16941 llvm::raw_svector_ostream OS(Str);
16942
16943 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
16944 // other types.
16945 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
16946 K == BuiltinType::Char8 || Value <= 0x7F) {
16947 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
16948 if (!Escaped.empty())
16949 EscapeStringForDiagnostic(Escaped, Str);
16950 else
16951 OS << static_cast<char>(Value);
16952 return;
16953 }
16954
16955 switch (K) {
16956 case BuiltinType::Char16:
16957 case BuiltinType::Char32:
16958 case BuiltinType::WChar_S:
16959 case BuiltinType::WChar_U: {
16960 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
16961 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
16962 else
16963 OS << "\\x"
16964 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
16965 break;
16966 }
16967 default:
16968 llvm_unreachable("Non-character type is passed");
16969 }
16970}
16971
16972/// Convert \V to a string we can present to the user in a diagnostic
16973/// \T is the type of the expression that has been evaluated into \V
16977 if (!V.hasValue())
16978 return false;
16979
16980 switch (V.getKind()) {
16982 if (T->isBooleanType()) {
16983 // Bools are reduced to ints during evaluation, but for
16984 // diagnostic purposes we want to print them as
16985 // true or false.
16986 int64_t BoolValue = V.getInt().getExtValue();
16987 assert((BoolValue == 0 || BoolValue == 1) &&
16988 "Bool type, but value is not 0 or 1");
16989 llvm::raw_svector_ostream OS(Str);
16990 OS << (BoolValue ? "true" : "false");
16991 } else {
16992 llvm::raw_svector_ostream OS(Str);
16993 // Same is true for chars.
16994 // We want to print the character representation for textual types
16995 const auto *BTy = T->getAs<BuiltinType>();
16996 if (BTy) {
16997 switch (BTy->getKind()) {
16998 case BuiltinType::Char_S:
16999 case BuiltinType::Char_U:
17000 case BuiltinType::Char8:
17001 case BuiltinType::Char16:
17002 case BuiltinType::Char32:
17003 case BuiltinType::WChar_S:
17004 case BuiltinType::WChar_U: {
17005 unsigned TyWidth = Context.getIntWidth(T);
17006 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17007 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17008 WriteCharTypePrefix(BTy->getKind(), OS);
17009 OS << '\'';
17010 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17011 OS << "' (0x"
17012 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17013 /*Upper=*/true)
17014 << ", " << V.getInt() << ')';
17015 return true;
17016 }
17017 default:
17018 break;
17019 }
17020 }
17021 V.getInt().toString(Str);
17022 }
17023
17024 break;
17025
17027 V.getFloat().toString(Str);
17028 break;
17029
17031 if (V.isNullPointer()) {
17032 llvm::raw_svector_ostream OS(Str);
17033 OS << "nullptr";
17034 } else
17035 return false;
17036 break;
17037
17039 llvm::raw_svector_ostream OS(Str);
17040 OS << '(';
17041 V.getComplexFloatReal().toString(Str);
17042 OS << " + ";
17043 V.getComplexFloatImag().toString(Str);
17044 OS << "i)";
17045 } break;
17046
17048 llvm::raw_svector_ostream OS(Str);
17049 OS << '(';
17050 V.getComplexIntReal().toString(Str);
17051 OS << " + ";
17052 V.getComplexIntImag().toString(Str);
17053 OS << "i)";
17054 } break;
17055
17056 default:
17057 return false;
17058 }
17059
17060 return true;
17061}
17062
17063/// Some Expression types are not useful to print notes about,
17064/// e.g. literals and values that have already been expanded
17065/// before such as int-valued template parameters.
17066static bool UsefulToPrintExpr(const Expr *E) {
17067 E = E->IgnoreParenImpCasts();
17068 // Literals are pretty easy for humans to understand.
17071 return false;
17072
17073 // These have been substituted from template parameters
17074 // and appear as literals in the static assert error.
17075 if (isa<SubstNonTypeTemplateParmExpr>(E))
17076 return false;
17077
17078 // -5 is also simple to understand.
17079 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17080 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17081
17082 // Only print nested arithmetic operators.
17083 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17084 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17085 BO->isBitwiseOp());
17086
17087 return true;
17088}
17089
17091 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17092 Op && Op->getOpcode() != BO_LOr) {
17093 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17094 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17095
17096 // Ignore comparisons of boolean expressions with a boolean literal.
17097 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17098 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17099 return;
17100
17101 // Don't print obvious expressions.
17102 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17103 return;
17104
17105 struct {
17106 const clang::Expr *Cond;
17108 SmallString<12> ValueString;
17109 bool Print;
17110 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17111 {RHS, Expr::EvalResult(), {}, false}};
17112 for (unsigned I = 0; I < 2; I++) {
17113 const Expr *Side = DiagSide[I].Cond;
17114
17115 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17116
17117 DiagSide[I].Print =
17118 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17119 DiagSide[I].ValueString, Context);
17120 }
17121 if (DiagSide[0].Print && DiagSide[1].Print) {
17122 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17123 << DiagSide[0].ValueString << Op->getOpcodeStr()
17124 << DiagSide[1].ValueString << Op->getSourceRange();
17125 }
17126 }
17127}
17128
17130 std::string &Result,
17131 ASTContext &Ctx,
17132 bool ErrorOnInvalidMessage) {
17133 assert(Message);
17134 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17135 "can't evaluate a dependant static assert message");
17136
17137 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17138 assert(SL->isUnevaluated() && "expected an unevaluated string");
17139 Result.assign(SL->getString().begin(), SL->getString().end());
17140 return true;
17141 }
17142
17143 SourceLocation Loc = Message->getBeginLoc();
17144 QualType T = Message->getType().getNonReferenceType();
17145 auto *RD = T->getAsCXXRecordDecl();
17146 if (!RD) {
17147 Diag(Loc, diag::err_static_assert_invalid_message);
17148 return false;
17149 }
17150
17151 auto FindMember = [&](StringRef Member, bool &Empty,
17152 bool Diag = false) -> std::optional<LookupResult> {
17154 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17155 LookupQualifiedName(MemberLookup, RD);
17156 Empty = MemberLookup.empty();
17157 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17159 if (MemberLookup.empty())
17160 return std::nullopt;
17161 return std::move(MemberLookup);
17162 };
17163
17164 bool SizeNotFound, DataNotFound;
17165 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17166 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17167 if (SizeNotFound || DataNotFound) {
17168 Diag(Loc, diag::err_static_assert_missing_member_function)
17169 << ((SizeNotFound && DataNotFound) ? 2
17170 : SizeNotFound ? 0
17171 : 1);
17172 return false;
17173 }
17174
17175 if (!SizeMember || !DataMember) {
17176 if (!SizeMember)
17177 FindMember("size", SizeNotFound, /*Diag=*/true);
17178 if (!DataMember)
17179 FindMember("data", DataNotFound, /*Diag=*/true);
17180 return false;
17181 }
17182
17183 auto BuildExpr = [&](LookupResult &LR) {
17185 Message, Message->getType(), Message->getBeginLoc(), false,
17186 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17187 if (Res.isInvalid())
17188 return ExprError();
17189 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17190 false, true);
17191 if (Res.isInvalid())
17192 return ExprError();
17193 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17194 return ExprError();
17196 };
17197
17198 ExprResult SizeE = BuildExpr(*SizeMember);
17199 ExprResult DataE = BuildExpr(*DataMember);
17200
17201 QualType SizeT = Context.getSizeType();
17202 QualType ConstCharPtr =
17204
17205 ExprResult EvaluatedSize =
17206 SizeE.isInvalid() ? ExprError()
17208 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17209 if (EvaluatedSize.isInvalid()) {
17210 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17211 return false;
17212 }
17213
17214 ExprResult EvaluatedData =
17215 DataE.isInvalid()
17216 ? ExprError()
17217 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17219 if (EvaluatedData.isInvalid()) {
17220 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17221 return false;
17222 }
17223
17224 if (!ErrorOnInvalidMessage &&
17225 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17226 return true;
17227
17228 Expr::EvalResult Status;
17230 Status.Diag = &Notes;
17231 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17232 EvaluatedData.get(), Ctx, Status) ||
17233 !Notes.empty()) {
17234 Diag(Message->getBeginLoc(),
17235 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17236 : diag::warn_static_assert_message_constexpr);
17237 for (const auto &Note : Notes)
17238 Diag(Note.first, Note.second);
17239 return !ErrorOnInvalidMessage;
17240 }
17241 return true;
17242}
17243
17245 Expr *AssertExpr, Expr *AssertMessage,
17246 SourceLocation RParenLoc,
17247 bool Failed) {
17248 assert(AssertExpr != nullptr && "Expected non-null condition");
17249 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17250 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17251 !AssertMessage->isValueDependent())) &&
17252 !Failed) {
17253 // In a static_assert-declaration, the constant-expression shall be a
17254 // constant expression that can be contextually converted to bool.
17255 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17256 if (Converted.isInvalid())
17257 Failed = true;
17258
17259 ExprResult FullAssertExpr =
17260 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17261 /*DiscardedValue*/ false,
17262 /*IsConstexpr*/ true);
17263 if (FullAssertExpr.isInvalid())
17264 Failed = true;
17265 else
17266 AssertExpr = FullAssertExpr.get();
17267
17268 llvm::APSInt Cond;
17269 Expr *BaseExpr = AssertExpr;
17270 AllowFoldKind FoldKind = NoFold;
17271
17272 if (!getLangOpts().CPlusPlus) {
17273 // In C mode, allow folding as an extension for better compatibility with
17274 // C++ in terms of expressions like static_assert("test") or
17275 // static_assert(nullptr).
17276 FoldKind = AllowFold;
17277 }
17278
17279 if (!Failed && VerifyIntegerConstantExpression(
17280 BaseExpr, &Cond,
17281 diag::err_static_assert_expression_is_not_constant,
17282 FoldKind).isInvalid())
17283 Failed = true;
17284
17285 // If the static_assert passes, only verify that
17286 // the message is grammatically valid without evaluating it.
17287 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17288 std::string Str;
17289 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17290 /*ErrorOnInvalidMessage=*/false);
17291 }
17292
17293 // CWG2518
17294 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17295 // template definition, the declaration has no effect.
17296 bool InTemplateDefinition =
17297 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17298
17299 if (!Failed && !Cond && !InTemplateDefinition) {
17300 SmallString<256> MsgBuffer;
17301 llvm::raw_svector_ostream Msg(MsgBuffer);
17302 bool HasMessage = AssertMessage;
17303 if (AssertMessage) {
17304 std::string Str;
17305 HasMessage =
17307 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17308 !Str.empty();
17309 Msg << Str;
17310 }
17311 Expr *InnerCond = nullptr;
17312 std::string InnerCondDescription;
17313 std::tie(InnerCond, InnerCondDescription) =
17314 findFailedBooleanCondition(Converted.get());
17315 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17316 // Drill down into concept specialization expressions to see why they
17317 // weren't satisfied.
17318 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17319 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17320 ConstraintSatisfaction Satisfaction;
17321 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17322 DiagnoseUnsatisfiedConstraint(Satisfaction);
17323 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17324 && !isa<IntegerLiteral>(InnerCond)) {
17325 Diag(InnerCond->getBeginLoc(),
17326 diag::err_static_assert_requirement_failed)
17327 << InnerCondDescription << !HasMessage << Msg.str()
17328 << InnerCond->getSourceRange();
17329 DiagnoseStaticAssertDetails(InnerCond);
17330 } else {
17331 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17332 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17334 }
17335 Failed = true;
17336 }
17337 } else {
17338 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17339 /*DiscardedValue*/false,
17340 /*IsConstexpr*/true);
17341 if (FullAssertExpr.isInvalid())
17342 Failed = true;
17343 else
17344 AssertExpr = FullAssertExpr.get();
17345 }
17346
17348 AssertExpr, AssertMessage, RParenLoc,
17349 Failed);
17350
17352 return Decl;
17353}
17354
17356 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17357 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17358 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17360
17361 bool IsMemberSpecialization = false;
17362 bool Invalid = false;
17363
17364 if (TemplateParameterList *TemplateParams =
17366 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17367 IsMemberSpecialization, Invalid)) {
17368 if (TemplateParams->size() > 0) {
17369 // This is a declaration of a class template.
17370 if (Invalid)
17371 return true;
17372
17373 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17374 Name, NameLoc, Attr, TemplateParams, AS_public,
17375 /*ModulePrivateLoc=*/SourceLocation(),
17376 FriendLoc, TempParamLists.size() - 1,
17377 TempParamLists.data())
17378 .get();
17379 } else {
17380 // The "template<>" header is extraneous.
17381 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17382 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17383 IsMemberSpecialization = true;
17384 }
17385 }
17386
17387 if (Invalid) return true;
17388
17389 bool isAllExplicitSpecializations = true;
17390 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17391 if (TempParamLists[I]->size()) {
17392 isAllExplicitSpecializations = false;
17393 break;
17394 }
17395 }
17396
17397 // FIXME: don't ignore attributes.
17398
17399 // If it's explicit specializations all the way down, just forget
17400 // about the template header and build an appropriate non-templated
17401 // friend. TODO: for source fidelity, remember the headers.
17402 if (isAllExplicitSpecializations) {
17403 if (SS.isEmpty()) {
17404 bool Owned = false;
17405 bool IsDependent = false;
17406 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17407 Attr, AS_public,
17408 /*ModulePrivateLoc=*/SourceLocation(),
17409 MultiTemplateParamsArg(), Owned, IsDependent,
17410 /*ScopedEnumKWLoc=*/SourceLocation(),
17411 /*ScopedEnumUsesClassTag=*/false,
17412 /*UnderlyingType=*/TypeResult(),
17413 /*IsTypeSpecifier=*/false,
17414 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17415 }
17416
17418 ElaboratedTypeKeyword Keyword
17420 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17421 *Name, NameLoc);
17422 if (T.isNull())
17423 return true;
17424
17426 if (isa<DependentNameType>(T)) {
17429 TL.setElaboratedKeywordLoc(TagLoc);
17430 TL.setQualifierLoc(QualifierLoc);
17431 TL.setNameLoc(NameLoc);
17432 } else {
17434 TL.setElaboratedKeywordLoc(TagLoc);
17435 TL.setQualifierLoc(QualifierLoc);
17436 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17437 }
17438
17440 TSI, FriendLoc, TempParamLists);
17441 Friend->setAccess(AS_public);
17443 return Friend;
17444 }
17445
17446 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17447
17448
17449
17450 // Handle the case of a templated-scope friend class. e.g.
17451 // template <class T> class A<T>::B;
17452 // FIXME: we don't support these right now.
17453 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17454 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17459 TL.setElaboratedKeywordLoc(TagLoc);
17461 TL.setNameLoc(NameLoc);
17462
17464 TSI, FriendLoc, TempParamLists);
17465 Friend->setAccess(AS_public);
17466 Friend->setUnsupportedFriend(true);
17468 return Friend;
17469}
17470
17472 MultiTemplateParamsArg TempParams) {
17474 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17475
17476 assert(DS.isFriendSpecified());
17478
17479 // C++ [class.friend]p3:
17480 // A friend declaration that does not declare a function shall have one of
17481 // the following forms:
17482 // friend elaborated-type-specifier ;
17483 // friend simple-type-specifier ;
17484 // friend typename-specifier ;
17485 //
17486 // If the friend keyword isn't first, or if the declarations has any type
17487 // qualifiers, then the declaration doesn't have that form.
17489 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17490 if (DS.getTypeQualifiers()) {
17492 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17494 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17496 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17498 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17500 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17501 }
17502
17503 // Try to convert the decl specifier to a type. This works for
17504 // friend templates because ActOnTag never produces a ClassTemplateDecl
17505 // for a TagUseKind::Friend.
17506 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17508 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17509 QualType T = TSI->getType();
17510 if (TheDeclarator.isInvalidType())
17511 return nullptr;
17512
17514 return nullptr;
17515
17516 if (!T->isElaboratedTypeSpecifier()) {
17517 if (TempParams.size()) {
17518 // C++23 [dcl.pre]p5:
17519 // In a simple-declaration, the optional init-declarator-list can be
17520 // omitted only when declaring a class or enumeration, that is, when
17521 // the decl-specifier-seq contains either a class-specifier, an
17522 // elaborated-type-specifier with a class-key, or an enum-specifier.
17523 //
17524 // The declaration of a template-declaration or explicit-specialization
17525 // is never a member-declaration, so this must be a simple-declaration
17526 // with no init-declarator-list. Therefore, this is ill-formed.
17527 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17528 return nullptr;
17529 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17530 SmallString<16> InsertionText(" ");
17531 InsertionText += RD->getKindName();
17532
17534 ? diag::warn_cxx98_compat_unelaborated_friend_type
17535 : diag::ext_unelaborated_friend_type)
17536 << (unsigned)RD->getTagKind() << T
17538 InsertionText);
17539 } else {
17540 Diag(FriendLoc, getLangOpts().CPlusPlus11
17541 ? diag::warn_cxx98_compat_nonclass_type_friend
17542 : diag::ext_nonclass_type_friend)
17543 << T << DS.getSourceRange();
17544 }
17545 }
17546
17547 // C++98 [class.friend]p1: A friend of a class is a function
17548 // or class that is not a member of the class . . .
17549 // This is fixed in DR77, which just barely didn't make the C++03
17550 // deadline. It's also a very silly restriction that seriously
17551 // affects inner classes and which nobody else seems to implement;
17552 // thus we never diagnose it, not even in -pedantic.
17553 //
17554 // But note that we could warn about it: it's always useless to
17555 // friend one of your own members (it's not, however, worthless to
17556 // friend a member of an arbitrary specialization of your template).
17557
17558 Decl *D;
17559 if (!TempParams.empty())
17560 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17561 FriendLoc);
17562 else
17564 TSI, FriendLoc);
17565
17566 if (!D)
17567 return nullptr;
17568
17571
17572 return D;
17573}
17574
17576 MultiTemplateParamsArg TemplateParams) {
17577 const DeclSpec &DS = D.getDeclSpec();
17578
17579 assert(DS.isFriendSpecified());
17581
17582 SourceLocation Loc = D.getIdentifierLoc();
17584
17585 // C++ [class.friend]p1
17586 // A friend of a class is a function or class....
17587 // Note that this sees through typedefs, which is intended.
17588 // It *doesn't* see through dependent types, which is correct
17589 // according to [temp.arg.type]p3:
17590 // If a declaration acquires a function type through a
17591 // type dependent on a template-parameter and this causes
17592 // a declaration that does not use the syntactic form of a
17593 // function declarator to have a function type, the program
17594 // is ill-formed.
17595 if (!TInfo->getType()->isFunctionType()) {
17596 Diag(Loc, diag::err_unexpected_friend);
17597
17598 // It might be worthwhile to try to recover by creating an
17599 // appropriate declaration.
17600 return nullptr;
17601 }
17602
17603 // C++ [namespace.memdef]p3
17604 // - If a friend declaration in a non-local class first declares a
17605 // class or function, the friend class or function is a member
17606 // of the innermost enclosing namespace.
17607 // - The name of the friend is not found by simple name lookup
17608 // until a matching declaration is provided in that namespace
17609 // scope (either before or after the class declaration granting
17610 // friendship).
17611 // - If a friend function is called, its name may be found by the
17612 // name lookup that considers functions from namespaces and
17613 // classes associated with the types of the function arguments.
17614 // - When looking for a prior declaration of a class or a function
17615 // declared as a friend, scopes outside the innermost enclosing
17616 // namespace scope are not considered.
17617
17618 CXXScopeSpec &SS = D.getCXXScopeSpec();
17620 assert(NameInfo.getName());
17621
17622 // Check for unexpanded parameter packs.
17626 return nullptr;
17627
17628 // The context we found the declaration in, or in which we should
17629 // create the declaration.
17630 DeclContext *DC;
17631 Scope *DCScope = S;
17632 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17633 RedeclarationKind::ForExternalRedeclaration);
17634
17635 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17636
17637 // There are five cases here.
17638 // - There's no scope specifier and we're in a local class. Only look
17639 // for functions declared in the immediately-enclosing block scope.
17640 // We recover from invalid scope qualifiers as if they just weren't there.
17641 FunctionDecl *FunctionContainingLocalClass = nullptr;
17642 if ((SS.isInvalid() || !SS.isSet()) &&
17643 (FunctionContainingLocalClass =
17644 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17645 // C++11 [class.friend]p11:
17646 // If a friend declaration appears in a local class and the name
17647 // specified is an unqualified name, a prior declaration is
17648 // looked up without considering scopes that are outside the
17649 // innermost enclosing non-class scope. For a friend function
17650 // declaration, if there is no prior declaration, the program is
17651 // ill-formed.
17652
17653 // Find the innermost enclosing non-class scope. This is the block
17654 // scope containing the local class definition (or for a nested class,
17655 // the outer local class).
17656 DCScope = S->getFnParent();
17657
17658 // Look up the function name in the scope.
17660 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17661
17662 if (!Previous.empty()) {
17663 // All possible previous declarations must have the same context:
17664 // either they were declared at block scope or they are members of
17665 // one of the enclosing local classes.
17666 DC = Previous.getRepresentativeDecl()->getDeclContext();
17667 } else {
17668 // This is ill-formed, but provide the context that we would have
17669 // declared the function in, if we were permitted to, for error recovery.
17670 DC = FunctionContainingLocalClass;
17671 }
17673
17674 // - There's no scope specifier, in which case we just go to the
17675 // appropriate scope and look for a function or function template
17676 // there as appropriate.
17677 } else if (SS.isInvalid() || !SS.isSet()) {
17678 // C++11 [namespace.memdef]p3:
17679 // If the name in a friend declaration is neither qualified nor
17680 // a template-id and the declaration is a function or an
17681 // elaborated-type-specifier, the lookup to determine whether
17682 // the entity has been previously declared shall not consider
17683 // any scopes outside the innermost enclosing namespace.
17684
17685 // Find the appropriate context according to the above.
17686 DC = CurContext;
17687
17688 // Skip class contexts. If someone can cite chapter and verse
17689 // for this behavior, that would be nice --- it's what GCC and
17690 // EDG do, and it seems like a reasonable intent, but the spec
17691 // really only says that checks for unqualified existing
17692 // declarations should stop at the nearest enclosing namespace,
17693 // not that they should only consider the nearest enclosing
17694 // namespace.
17695 while (DC->isRecord())
17696 DC = DC->getParent();
17697
17698 DeclContext *LookupDC = DC->getNonTransparentContext();
17699 while (true) {
17700 LookupQualifiedName(Previous, LookupDC);
17701
17702 if (!Previous.empty()) {
17703 DC = LookupDC;
17704 break;
17705 }
17706
17707 if (isTemplateId) {
17708 if (isa<TranslationUnitDecl>(LookupDC)) break;
17709 } else {
17710 if (LookupDC->isFileContext()) break;
17711 }
17712 LookupDC = LookupDC->getParent();
17713 }
17714
17715 DCScope = getScopeForDeclContext(S, DC);
17716
17717 // - There's a non-dependent scope specifier, in which case we
17718 // compute it and do a previous lookup there for a function
17719 // or function template.
17720 } else if (!SS.getScopeRep()->isDependent()) {
17721 DC = computeDeclContext(SS);
17722 if (!DC) return nullptr;
17723
17724 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17725
17727
17728 // C++ [class.friend]p1: A friend of a class is a function or
17729 // class that is not a member of the class . . .
17730 if (DC->Equals(CurContext))
17733 diag::warn_cxx98_compat_friend_is_member :
17734 diag::err_friend_is_member);
17735
17736 // - There's a scope specifier that does not match any template
17737 // parameter lists, in which case we use some arbitrary context,
17738 // create a method or method template, and wait for instantiation.
17739 // - There's a scope specifier that does match some template
17740 // parameter lists, which we don't handle right now.
17741 } else {
17742 DC = CurContext;
17743 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17744 }
17745
17746 if (!DC->isRecord()) {
17747 int DiagArg = -1;
17748 switch (D.getName().getKind()) {
17751 DiagArg = 0;
17752 break;
17754 DiagArg = 1;
17755 break;
17757 DiagArg = 2;
17758 break;
17760 DiagArg = 3;
17761 break;
17767 break;
17768 }
17769 // This implies that it has to be an operator or function.
17770 if (DiagArg >= 0) {
17771 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17772 return nullptr;
17773 }
17774 }
17775
17776 // FIXME: This is an egregious hack to cope with cases where the scope stack
17777 // does not contain the declaration context, i.e., in an out-of-line
17778 // definition of a class.
17779 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17780 if (!DCScope) {
17781 FakeDCScope.setEntity(DC);
17782 DCScope = &FakeDCScope;
17783 }
17784
17785 bool AddToScope = true;
17786 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17787 TemplateParams, AddToScope);
17788 if (!ND) return nullptr;
17789
17790 assert(ND->getLexicalDeclContext() == CurContext);
17791
17792 // If we performed typo correction, we might have added a scope specifier
17793 // and changed the decl context.
17794 DC = ND->getDeclContext();
17795
17796 // Add the function declaration to the appropriate lookup tables,
17797 // adjusting the redeclarations list as necessary. We don't
17798 // want to do this yet if the friending class is dependent.
17799 //
17800 // Also update the scope-based lookup if the target context's
17801 // lookup context is in lexical scope.
17803 DC = DC->getRedeclContext();
17805 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17806 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17807 }
17808
17810 D.getIdentifierLoc(), ND,
17811 DS.getFriendSpecLoc());
17812 FrD->setAccess(AS_public);
17813 CurContext->addDecl(FrD);
17814
17815 if (ND->isInvalidDecl()) {
17816 FrD->setInvalidDecl();
17817 } else {
17818 if (DC->isRecord()) CheckFriendAccess(ND);
17819
17820 FunctionDecl *FD;
17821 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17822 FD = FTD->getTemplatedDecl();
17823 else
17824 FD = cast<FunctionDecl>(ND);
17825
17826 // C++ [class.friend]p6:
17827 // A function may be defined in a friend declaration of a class if and
17828 // only if the class is a non-local class, and the function name is
17829 // unqualified.
17830 if (D.isFunctionDefinition()) {
17831 // Qualified friend function definition.
17832 if (SS.isNotEmpty()) {
17833 // FIXME: We should only do this if the scope specifier names the
17834 // innermost enclosing namespace; otherwise the fixit changes the
17835 // meaning of the code.
17837 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17838
17839 DB << SS.getScopeRep();
17840 if (DC->isFileContext())
17842
17843 // Friend function defined in a local class.
17844 } else if (FunctionContainingLocalClass) {
17845 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17846
17847 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
17848 // a template-id, the function name is not unqualified because these is
17849 // no name. While the wording requires some reading in-between the
17850 // lines, GCC, MSVC, and EDG all consider a friend function
17851 // specialization definitions // to be de facto explicit specialization
17852 // and diagnose them as such.
17853 } else if (isTemplateId) {
17854 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
17855 }
17856 }
17857
17858 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17859 // default argument expression, that declaration shall be a definition
17860 // and shall be the only declaration of the function or function
17861 // template in the translation unit.
17863 // We can't look at FD->getPreviousDecl() because it may not have been set
17864 // if we're in a dependent context. If the function is known to be a
17865 // redeclaration, we will have narrowed Previous down to the right decl.
17866 if (D.isRedeclaration()) {
17867 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17868 Diag(Previous.getRepresentativeDecl()->getLocation(),
17869 diag::note_previous_declaration);
17870 } else if (!D.isFunctionDefinition())
17871 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17872 }
17873
17874 // Mark templated-scope function declarations as unsupported.
17875 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17876 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17877 << SS.getScopeRep() << SS.getRange()
17878 << cast<CXXRecordDecl>(CurContext);
17879 FrD->setUnsupportedFriend(true);
17880 }
17881 }
17882
17884
17885 return ND;
17886}
17887
17889 StringLiteral *Message) {
17891
17892 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17893 if (!Fn) {
17894 Diag(DelLoc, diag::err_deleted_non_function);
17895 return;
17896 }
17897
17898 // Deleted function does not have a body.
17899 Fn->setWillHaveBody(false);
17900
17901 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17902 // Don't consider the implicit declaration we generate for explicit
17903 // specializations. FIXME: Do not generate these implicit declarations.
17904 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17905 Prev->getPreviousDecl()) &&
17906 !Prev->isDefined()) {
17907 Diag(DelLoc, diag::err_deleted_decl_not_first);
17908 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17909 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17910 : diag::note_previous_declaration);
17911 // We can't recover from this; the declaration might have already
17912 // been used.
17913 Fn->setInvalidDecl();
17914 return;
17915 }
17916
17917 // To maintain the invariant that functions are only deleted on their first
17918 // declaration, mark the implicitly-instantiated declaration of the
17919 // explicitly-specialized function as deleted instead of marking the
17920 // instantiated redeclaration.
17921 Fn = Fn->getCanonicalDecl();
17922 }
17923
17924 // dllimport/dllexport cannot be deleted.
17925 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17926 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17927 Fn->setInvalidDecl();
17928 }
17929
17930 // C++11 [basic.start.main]p3:
17931 // A program that defines main as deleted [...] is ill-formed.
17932 if (Fn->isMain())
17933 Diag(DelLoc, diag::err_deleted_main);
17934
17935 // C++11 [dcl.fct.def.delete]p4:
17936 // A deleted function is implicitly inline.
17937 Fn->setImplicitlyInline();
17938 Fn->setDeletedAsWritten(true, Message);
17939}
17940
17942 if (!Dcl || Dcl->isInvalidDecl())
17943 return;
17944
17945 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17946 if (!FD) {
17947 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17948 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17949 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17950 return;
17951 }
17952 }
17953
17954 Diag(DefaultLoc, diag::err_default_special_members)
17955 << getLangOpts().CPlusPlus20;
17956 return;
17957 }
17958
17959 // Reject if this can't possibly be a defaultable function.
17961 if (!DefKind &&
17962 // A dependent function that doesn't locally look defaultable can
17963 // still instantiate to a defaultable function if it's a constructor
17964 // or assignment operator.
17965 (!FD->isDependentContext() ||
17966 (!isa<CXXConstructorDecl>(FD) &&
17967 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17968 Diag(DefaultLoc, diag::err_default_special_members)
17969 << getLangOpts().CPlusPlus20;
17970 return;
17971 }
17972
17973 // Issue compatibility warning. We already warned if the operator is
17974 // 'operator<=>' when parsing the '<=>' token.
17975 if (DefKind.isComparison() &&
17977 Diag(DefaultLoc, getLangOpts().CPlusPlus20
17978 ? diag::warn_cxx17_compat_defaulted_comparison
17979 : diag::ext_defaulted_comparison);
17980 }
17981
17982 FD->setDefaulted();
17983 FD->setExplicitlyDefaulted();
17984 FD->setDefaultLoc(DefaultLoc);
17985
17986 // Defer checking functions that are defaulted in a dependent context.
17987 if (FD->isDependentContext())
17988 return;
17989
17990 // Unset that we will have a body for this function. We might not,
17991 // if it turns out to be trivial, and we don't need this marking now
17992 // that we've marked it as defaulted.
17993 FD->setWillHaveBody(false);
17994
17995 if (DefKind.isComparison()) {
17996 // If this comparison's defaulting occurs within the definition of its
17997 // lexical class context, we have to do the checking when complete.
17998 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17999 if (!RD->isCompleteDefinition())
18000 return;
18001 }
18002
18003 // If this member fn was defaulted on its first declaration, we will have
18004 // already performed the checking in CheckCompletedCXXClass. Such a
18005 // declaration doesn't trigger an implicit definition.
18006 if (isa<CXXMethodDecl>(FD)) {
18007 const FunctionDecl *Primary = FD;
18008 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18009 // Ask the template instantiation pattern that actually had the
18010 // '= default' on it.
18011 Primary = Pattern;
18012 if (Primary->getCanonicalDecl()->isDefaulted())
18013 return;
18014 }
18015
18016 if (DefKind.isComparison()) {
18017 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18018 FD->setInvalidDecl();
18019 else
18020 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18021 } else {
18022 auto *MD = cast<CXXMethodDecl>(FD);
18023
18025 DefaultLoc))
18026 MD->setInvalidDecl();
18027 else
18028 DefineDefaultedFunction(*this, MD, DefaultLoc);
18029 }
18030}
18031
18033 for (Stmt *SubStmt : S->children()) {
18034 if (!SubStmt)
18035 continue;
18036 if (isa<ReturnStmt>(SubStmt))
18037 Self.Diag(SubStmt->getBeginLoc(),
18038 diag::err_return_in_constructor_handler);
18039 if (!isa<Expr>(SubStmt))
18040 SearchForReturnInStmt(Self, SubStmt);
18041 }
18042}
18043
18045 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18046 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18047 SearchForReturnInStmt(*this, Handler);
18048 }
18049}
18050
18052 StringLiteral *DeletedMessage) {
18053 switch (BodyKind) {
18054 case FnBodyKind::Delete:
18055 SetDeclDeleted(D, Loc, DeletedMessage);
18056 break;
18059 break;
18060 case FnBodyKind::Other:
18061 llvm_unreachable(
18062 "Parsed function body should be '= delete;' or '= default;'");
18063 }
18064}
18065
18067 const CXXMethodDecl *Old) {
18068 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18069 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18070
18071 if (OldFT->hasExtParameterInfos()) {
18072 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18073 // A parameter of the overriding method should be annotated with noescape
18074 // if the corresponding parameter of the overridden method is annotated.
18075 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18076 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18077 Diag(New->getParamDecl(I)->getLocation(),
18078 diag::warn_overriding_method_missing_noescape);
18079 Diag(Old->getParamDecl(I)->getLocation(),
18080 diag::note_overridden_marked_noescape);
18081 }
18082 }
18083
18084 // SME attributes must match when overriding a function declaration.
18085 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18086 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18087 << New << New->getType() << Old->getType();
18088 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18089 return true;
18090 }
18091
18092 // Virtual overrides must have the same code_seg.
18093 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18094 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18095 if ((NewCSA || OldCSA) &&
18096 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18097 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18098 Diag(Old->getLocation(), diag::note_previous_declaration);
18099 return true;
18100 }
18101
18102 // Virtual overrides: check for matching effects.
18104 const auto OldFX = Old->getFunctionEffects();
18105 const auto NewFXOrig = New->getFunctionEffects();
18106
18107 if (OldFX != NewFXOrig) {
18108 FunctionEffectSet NewFX(NewFXOrig);
18109 const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
18111 for (const auto &Diff : Diffs) {
18112 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18114 break;
18116 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18117 << Diff.effectName();
18118 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18119 << Old->getReturnTypeSourceRange();
18120 break;
18122 NewFX.insert(Diff.Old, Errs);
18123 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18124 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18126 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18127 NewFT->getParamTypes(), EPI);
18128 New->setType(ModQT);
18129 break;
18130 }
18131 }
18132 }
18133 if (!Errs.empty())
18135 Old->getLocation());
18136 }
18137 }
18138
18139 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18140
18141 // If the calling conventions match, everything is fine
18142 if (NewCC == OldCC)
18143 return false;
18144
18145 // If the calling conventions mismatch because the new function is static,
18146 // suppress the calling convention mismatch error; the error about static
18147 // function override (err_static_overrides_virtual from
18148 // Sema::CheckFunctionDeclaration) is more clear.
18149 if (New->getStorageClass() == SC_Static)
18150 return false;
18151
18152 Diag(New->getLocation(),
18153 diag::err_conflicting_overriding_cc_attributes)
18154 << New->getDeclName() << New->getType() << Old->getType();
18155 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18156 return true;
18157}
18158
18160 const CXXMethodDecl *Old) {
18161 // CWG2553
18162 // A virtual function shall not be an explicit object member function.
18164 return true;
18165 Diag(New->getParamDecl(0)->getBeginLoc(),
18166 diag::err_explicit_object_parameter_nonmember)
18167 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18168 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18169 New->setInvalidDecl();
18170 return false;
18171}
18172
18174 const CXXMethodDecl *Old) {
18175 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18176 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18177
18178 if (Context.hasSameType(NewTy, OldTy) ||
18179 NewTy->isDependentType() || OldTy->isDependentType())
18180 return false;
18181
18182 // Check if the return types are covariant
18183 QualType NewClassTy, OldClassTy;
18184
18185 /// Both types must be pointers or references to classes.
18186 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18187 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18188 NewClassTy = NewPT->getPointeeType();
18189 OldClassTy = OldPT->getPointeeType();
18190 }
18191 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18192 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18193 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18194 NewClassTy = NewRT->getPointeeType();
18195 OldClassTy = OldRT->getPointeeType();
18196 }
18197 }
18198 }
18199
18200 // The return types aren't either both pointers or references to a class type.
18201 if (NewClassTy.isNull()) {
18202 Diag(New->getLocation(),
18203 diag::err_different_return_type_for_overriding_virtual_function)
18204 << New->getDeclName() << NewTy << OldTy
18205 << New->getReturnTypeSourceRange();
18206 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18207 << Old->getReturnTypeSourceRange();
18208
18209 return true;
18210 }
18211
18212 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18213 // C++14 [class.virtual]p8:
18214 // If the class type in the covariant return type of D::f differs from
18215 // that of B::f, the class type in the return type of D::f shall be
18216 // complete at the point of declaration of D::f or shall be the class
18217 // type D.
18218 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18219 if (!RT->isBeingDefined() &&
18220 RequireCompleteType(New->getLocation(), NewClassTy,
18221 diag::err_covariant_return_incomplete,
18222 New->getDeclName()))
18223 return true;
18224 }
18225
18226 // Check if the new class derives from the old class.
18227 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18228 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18229 << New->getDeclName() << NewTy << OldTy
18230 << New->getReturnTypeSourceRange();
18231 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18232 << Old->getReturnTypeSourceRange();
18233 return true;
18234 }
18235
18236 // Check if we the conversion from derived to base is valid.
18238 NewClassTy, OldClassTy,
18239 diag::err_covariant_return_inaccessible_base,
18240 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18242 New->getDeclName(), nullptr)) {
18243 // FIXME: this note won't trigger for delayed access control
18244 // diagnostics, and it's impossible to get an undelayed error
18245 // here from access control during the original parse because
18246 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18247 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18248 << Old->getReturnTypeSourceRange();
18249 return true;
18250 }
18251 }
18252
18253 // The qualifiers of the return types must be the same.
18254 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18255 Diag(New->getLocation(),
18256 diag::err_covariant_return_type_different_qualifications)
18257 << New->getDeclName() << NewTy << OldTy
18258 << New->getReturnTypeSourceRange();
18259 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18260 << Old->getReturnTypeSourceRange();
18261 return true;
18262 }
18263
18264
18265 // The new class type must have the same or less qualifiers as the old type.
18266 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18267 Diag(New->getLocation(),
18268 diag::err_covariant_return_type_class_type_more_qualified)
18269 << New->getDeclName() << NewTy << OldTy
18270 << New->getReturnTypeSourceRange();
18271 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18272 << Old->getReturnTypeSourceRange();
18273 return true;
18274 }
18275
18276 return false;
18277}
18278
18280 SourceLocation EndLoc = InitRange.getEnd();
18281 if (EndLoc.isValid())
18282 Method->setRangeEnd(EndLoc);
18283
18284 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18285 Method->setIsPureVirtual();
18286 return false;
18287 }
18288
18289 if (!Method->isInvalidDecl())
18290 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18291 << Method->getDeclName() << InitRange;
18292 return true;
18293}
18294
18296 if (D->getFriendObjectKind())
18297 Diag(D->getLocation(), diag::err_pure_friend);
18298 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18299 CheckPureMethod(M, ZeroLoc);
18300 else
18301 Diag(D->getLocation(), diag::err_illegal_initializer);
18302}
18303
18304/// Invoked when we are about to parse an initializer for the declaration
18305/// 'Dcl'.
18306///
18307/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18308/// static data member of class X, names should be looked up in the scope of
18309/// class X. If the declaration had a scope specifier, a scope will have
18310/// been created and passed in for this purpose. Otherwise, S will be null.
18312 assert(D && !D->isInvalidDecl());
18313
18314 // We will always have a nested name specifier here, but this declaration
18315 // might not be out of line if the specifier names the current namespace:
18316 // extern int n;
18317 // int ::n = 0;
18318 if (S && D->isOutOfLine())
18320
18323}
18324
18326 assert(D);
18327
18328 if (S && D->isOutOfLine())
18330
18331 if (getLangOpts().CPlusPlus23) {
18332 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18333 // [...]
18334 // - the initializer of a variable that is usable in constant expressions or
18335 // has constant initialization.
18336 if (auto *VD = dyn_cast<VarDecl>(D);
18339 // An expression or conversion is in an 'immediate function context' if it
18340 // is potentially evaluated and either:
18341 // [...]
18342 // - it is a subexpression of a manifestly constant-evaluated expression
18343 // or conversion.
18344 ExprEvalContexts.back().InImmediateFunctionContext = true;
18345 }
18346 }
18347
18348 // Unless the initializer is in an immediate function context (as determined
18349 // above), this will evaluate all contained immediate function calls as
18350 // constant expressions. If the initializer IS an immediate function context,
18351 // the initializer has been determined to be a constant expression, and all
18352 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18353 // it was a constant expression).
18355}
18356
18358 // C++ 6.4p2:
18359 // The declarator shall not specify a function or an array.
18360 // The type-specifier-seq shall not contain typedef and shall not declare a
18361 // new class or enumeration.
18362 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18363 "Parser allowed 'typedef' as storage class of condition decl.");
18364
18365 Decl *Dcl = ActOnDeclarator(S, D);
18366 if (!Dcl)
18367 return true;
18368
18369 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18370 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18371 << D.getSourceRange();
18372 return true;
18373 }
18374
18375 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18376 VD->setCXXCondDecl();
18377
18378 return Dcl;
18379}
18380
18382 if (!ExternalSource)
18383 return;
18384
18386 ExternalSource->ReadUsedVTables(VTables);
18388 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18389 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18390 = VTablesUsed.find(VTables[I].Record);
18391 // Even if a definition wasn't required before, it may be required now.
18392 if (Pos != VTablesUsed.end()) {
18393 if (!Pos->second && VTables[I].DefinitionRequired)
18394 Pos->second = true;
18395 continue;
18396 }
18397
18398 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18399 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18400 }
18401
18402 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18403}
18404
18406 bool DefinitionRequired) {
18407 // Ignore any vtable uses in unevaluated operands or for classes that do
18408 // not have a vtable.
18409 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18411 return;
18412 // Do not mark as used if compiling for the device outside of the target
18413 // region.
18414 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18415 !OpenMP().isInOpenMPDeclareTargetContext() &&
18416 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18417 if (!DefinitionRequired)
18419 return;
18420 }
18421
18422 // Try to insert this class into the map.
18424 Class = Class->getCanonicalDecl();
18425 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18426 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18427 if (!Pos.second) {
18428 // If we already had an entry, check to see if we are promoting this vtable
18429 // to require a definition. If so, we need to reappend to the VTableUses
18430 // list, since we may have already processed the first entry.
18431 if (DefinitionRequired && !Pos.first->second) {
18432 Pos.first->second = true;
18433 } else {
18434 // Otherwise, we can early exit.
18435 return;
18436 }
18437 } else {
18438 // The Microsoft ABI requires that we perform the destructor body
18439 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18440 // the deleting destructor is emitted with the vtable, not with the
18441 // destructor definition as in the Itanium ABI.
18443 CXXDestructorDecl *DD = Class->getDestructor();
18444 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18445 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18446 // If this is an out-of-line declaration, marking it referenced will
18447 // not do anything. Manually call CheckDestructor to look up operator
18448 // delete().
18449 ContextRAII SavedContext(*this, DD);
18450 CheckDestructor(DD);
18451 } else {
18452 MarkFunctionReferenced(Loc, Class->getDestructor());
18453 }
18454 }
18455 }
18456 }
18457
18458 // Local classes need to have their virtual members marked
18459 // immediately. For all other classes, we mark their virtual members
18460 // at the end of the translation unit.
18461 if (Class->isLocalClass())
18462 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18463 else
18464 VTableUses.push_back(std::make_pair(Class, Loc));
18465}
18466
18469 if (VTableUses.empty())
18470 return false;
18471
18472 // Note: The VTableUses vector could grow as a result of marking
18473 // the members of a class as "used", so we check the size each
18474 // time through the loop and prefer indices (which are stable) to
18475 // iterators (which are not).
18476 bool DefinedAnything = false;
18477 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18478 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18479 if (!Class)
18480 continue;
18482 Class->getTemplateSpecializationKind();
18483
18484 SourceLocation Loc = VTableUses[I].second;
18485
18486 bool DefineVTable = true;
18487
18488 // If this class has a key function, but that key function is
18489 // defined in another translation unit, we don't need to emit the
18490 // vtable even though we're using it.
18491 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18492 if (KeyFunction && !KeyFunction->hasBody()) {
18493 // The key function is in another translation unit.
18494 DefineVTable = false;
18496 KeyFunction->getTemplateSpecializationKind();
18499 "Instantiations don't have key functions");
18500 (void)TSK;
18501 } else if (!KeyFunction) {
18502 // If we have a class with no key function that is the subject
18503 // of an explicit instantiation declaration, suppress the
18504 // vtable; it will live with the explicit instantiation
18505 // definition.
18506 bool IsExplicitInstantiationDeclaration =
18508 for (auto *R : Class->redecls()) {
18510 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18512 IsExplicitInstantiationDeclaration = true;
18513 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18514 IsExplicitInstantiationDeclaration = false;
18515 break;
18516 }
18517 }
18518
18519 if (IsExplicitInstantiationDeclaration)
18520 DefineVTable = false;
18521 }
18522
18523 // The exception specifications for all virtual members may be needed even
18524 // if we are not providing an authoritative form of the vtable in this TU.
18525 // We may choose to emit it available_externally anyway.
18526 if (!DefineVTable) {
18528 continue;
18529 }
18530
18531 // Mark all of the virtual members of this class as referenced, so
18532 // that we can build a vtable. Then, tell the AST consumer that a
18533 // vtable for this class is required.
18534 DefinedAnything = true;
18536 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18537 if (VTablesUsed[Canonical])
18539
18540 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18541 // no key function or the key function is inlined. Don't warn in C++ ABIs
18542 // that lack key functions, since the user won't be able to make one.
18544 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18546 const FunctionDecl *KeyFunctionDef = nullptr;
18547 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18548 KeyFunctionDef->isInlined()))
18549 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18550 }
18551 }
18552 VTableUses.clear();
18553
18554 return DefinedAnything;
18555}
18556
18558 const CXXRecordDecl *RD) {
18559 for (const auto *I : RD->methods())
18560 if (I->isVirtual() && !I->isPureVirtual())
18561 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18562}
18563
18565 const CXXRecordDecl *RD,
18566 bool ConstexprOnly) {
18567 // Mark all functions which will appear in RD's vtable as used.
18568 CXXFinalOverriderMap FinalOverriders;
18569 RD->getFinalOverriders(FinalOverriders);
18570 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18571 E = FinalOverriders.end();
18572 I != E; ++I) {
18573 for (OverridingMethods::const_iterator OI = I->second.begin(),
18574 OE = I->second.end();
18575 OI != OE; ++OI) {
18576 assert(OI->second.size() > 0 && "no final overrider");
18577 CXXMethodDecl *Overrider = OI->second.front().Method;
18578
18579 // C++ [basic.def.odr]p2:
18580 // [...] A virtual member function is used if it is not pure. [...]
18581 if (!Overrider->isPureVirtual() &&
18582 (!ConstexprOnly || Overrider->isConstexpr()))
18583 MarkFunctionReferenced(Loc, Overrider);
18584 }
18585 }
18586
18587 // Only classes that have virtual bases need a VTT.
18588 if (RD->getNumVBases() == 0)
18589 return;
18590
18591 for (const auto &I : RD->bases()) {
18592 const auto *Base =
18593 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18594 if (Base->getNumVBases() == 0)
18595 continue;
18597 }
18598}
18599
18600static
18605 Sema &S) {
18606 if (Ctor->isInvalidDecl())
18607 return;
18608
18610
18611 // Target may not be determinable yet, for instance if this is a dependent
18612 // call in an uninstantiated template.
18613 if (Target) {
18614 const FunctionDecl *FNTarget = nullptr;
18615 (void)Target->hasBody(FNTarget);
18616 Target = const_cast<CXXConstructorDecl*>(
18617 cast_or_null<CXXConstructorDecl>(FNTarget));
18618 }
18619
18620 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18621 // Avoid dereferencing a null pointer here.
18622 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18623
18624 if (!Current.insert(Canonical).second)
18625 return;
18626
18627 // We know that beyond here, we aren't chaining into a cycle.
18628 if (!Target || !Target->isDelegatingConstructor() ||
18629 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18630 Valid.insert(Current.begin(), Current.end());
18631 Current.clear();
18632 // We've hit a cycle.
18633 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18634 Current.count(TCanonical)) {
18635 // If we haven't diagnosed this cycle yet, do so now.
18636 if (!Invalid.count(TCanonical)) {
18637 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18638 diag::warn_delegating_ctor_cycle)
18639 << Ctor;
18640
18641 // Don't add a note for a function delegating directly to itself.
18642 if (TCanonical != Canonical)
18643 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18644
18646 while (C->getCanonicalDecl() != Canonical) {
18647 const FunctionDecl *FNTarget = nullptr;
18648 (void)C->getTargetConstructor()->hasBody(FNTarget);
18649 assert(FNTarget && "Ctor cycle through bodiless function");
18650
18651 C = const_cast<CXXConstructorDecl*>(
18652 cast<CXXConstructorDecl>(FNTarget));
18653 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18654 }
18655 }
18656
18657 Invalid.insert(Current.begin(), Current.end());
18658 Current.clear();
18659 } else {
18660 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18661 }
18662}
18663
18664
18667
18668 for (DelegatingCtorDeclsType::iterator
18671 I != E; ++I)
18672 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18673
18674 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18675 (*CI)->setInvalidDecl();
18676}
18677
18678namespace {
18679 /// AST visitor that finds references to the 'this' expression.
18680 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18681 Sema &S;
18682
18683 public:
18684 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18685
18686 bool VisitCXXThisExpr(CXXThisExpr *E) {
18687 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18688 << E->isImplicit();
18689 return false;
18690 }
18691 };
18692}
18693
18695 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18696 if (!TSInfo)
18697 return false;
18698
18699 TypeLoc TL = TSInfo->getTypeLoc();
18701 if (!ProtoTL)
18702 return false;
18703
18704 // C++11 [expr.prim.general]p3:
18705 // [The expression this] shall not appear before the optional
18706 // cv-qualifier-seq and it shall not appear within the declaration of a
18707 // static member function (although its type and value category are defined
18708 // within a static member function as they are within a non-static member
18709 // function). [ Note: this is because declaration matching does not occur
18710 // until the complete declarator is known. - end note ]
18711 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18712 FindCXXThisExpr Finder(*this);
18713
18714 // If the return type came after the cv-qualifier-seq, check it now.
18715 if (Proto->hasTrailingReturn() &&
18716 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18717 return true;
18718
18719 // Check the exception specification.
18721 return true;
18722
18723 // Check the trailing requires clause
18724 if (Expr *E = Method->getTrailingRequiresClause())
18725 if (!Finder.TraverseStmt(E))
18726 return true;
18727
18729}
18730
18732 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18733 if (!TSInfo)
18734 return false;
18735
18736 TypeLoc TL = TSInfo->getTypeLoc();
18738 if (!ProtoTL)
18739 return false;
18740
18741 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18742 FindCXXThisExpr Finder(*this);
18743
18744 switch (Proto->getExceptionSpecType()) {
18745 case EST_Unparsed:
18746 case EST_Uninstantiated:
18747 case EST_Unevaluated:
18748 case EST_BasicNoexcept:
18749 case EST_NoThrow:
18750 case EST_DynamicNone:
18751 case EST_MSAny:
18752 case EST_None:
18753 break;
18754
18756 case EST_NoexceptFalse:
18757 case EST_NoexceptTrue:
18758 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18759 return true;
18760 [[fallthrough]];
18761
18762 case EST_Dynamic:
18763 for (const auto &E : Proto->exceptions()) {
18764 if (!Finder.TraverseType(E))
18765 return true;
18766 }
18767 break;
18768 }
18769
18770 return false;
18771}
18772
18774 FindCXXThisExpr Finder(*this);
18775
18776 // Check attributes.
18777 for (const auto *A : Method->attrs()) {
18778 // FIXME: This should be emitted by tblgen.
18779 Expr *Arg = nullptr;
18780 ArrayRef<Expr *> Args;
18781 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18782 Arg = G->getArg();
18783 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18784 Arg = G->getArg();
18785 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18786 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18787 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18788 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18789 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18790 Arg = ETLF->getSuccessValue();
18791 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18792 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18793 Arg = STLF->getSuccessValue();
18794 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18795 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18796 Arg = LR->getArg();
18797 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18798 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18799 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18800 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18801 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18802 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18803 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18804 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18805 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18806 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18807
18808 if (Arg && !Finder.TraverseStmt(Arg))
18809 return true;
18810
18811 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18812 if (!Finder.TraverseStmt(Args[I]))
18813 return true;
18814 }
18815 }
18816
18817 return false;
18818}
18819
18821 bool IsTopLevel, ExceptionSpecificationType EST,
18822 ArrayRef<ParsedType> DynamicExceptions,
18823 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18824 SmallVectorImpl<QualType> &Exceptions,
18826 Exceptions.clear();
18827 ESI.Type = EST;
18828 if (EST == EST_Dynamic) {
18829 Exceptions.reserve(DynamicExceptions.size());
18830 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18831 // FIXME: Preserve type source info.
18832 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18833
18834 if (IsTopLevel) {
18836 collectUnexpandedParameterPacks(ET, Unexpanded);
18837 if (!Unexpanded.empty()) {
18839 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18840 Unexpanded);
18841 continue;
18842 }
18843 }
18844
18845 // Check that the type is valid for an exception spec, and
18846 // drop it if not.
18847 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18848 Exceptions.push_back(ET);
18849 }
18850 ESI.Exceptions = Exceptions;
18851 return;
18852 }
18853
18854 if (isComputedNoexcept(EST)) {
18855 assert((NoexceptExpr->isTypeDependent() ||
18856 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18857 Context.BoolTy) &&
18858 "Parser should have made sure that the expression is boolean");
18859 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18860 ESI.Type = EST_BasicNoexcept;
18861 return;
18862 }
18863
18864 ESI.NoexceptExpr = NoexceptExpr;
18865 return;
18866 }
18867}
18868
18870 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
18871 ArrayRef<ParsedType> DynamicExceptions,
18872 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
18873 if (!D)
18874 return;
18875
18876 // Dig out the function we're referring to.
18877 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
18878 D = FTD->getTemplatedDecl();
18879
18880 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
18881 if (!FD)
18882 return;
18883
18884 // Check the exception specification.
18887 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
18888 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18889 ESI);
18890
18891 // Update the exception specification on the function type.
18892 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
18893
18894 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
18895 if (MD->isStatic())
18897
18898 if (MD->isVirtual()) {
18899 // Check overrides, which we previously had to delay.
18900 for (const CXXMethodDecl *O : MD->overridden_methods())
18902 }
18903 }
18904}
18905
18906/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18907///
18909 SourceLocation DeclStart, Declarator &D,
18910 Expr *BitWidth,
18911 InClassInitStyle InitStyle,
18912 AccessSpecifier AS,
18913 const ParsedAttr &MSPropertyAttr) {
18914 const IdentifierInfo *II = D.getIdentifier();
18915 if (!II) {
18916 Diag(DeclStart, diag::err_anonymous_property);
18917 return nullptr;
18918 }
18919 SourceLocation Loc = D.getIdentifierLoc();
18920
18922 QualType T = TInfo->getType();
18923 if (getLangOpts().CPlusPlus) {
18925
18926 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18928 D.setInvalidType();
18929 T = Context.IntTy;
18931 }
18932 }
18933
18934 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18935
18936 if (D.getDeclSpec().isInlineSpecified())
18937 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18938 << getLangOpts().CPlusPlus17;
18939 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18940 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18941 diag::err_invalid_thread)
18943
18944 // Check to see if this name was declared as a member previously
18945 NamedDecl *PrevDecl = nullptr;
18947 RedeclarationKind::ForVisibleRedeclaration);
18948 LookupName(Previous, S);
18949 switch (Previous.getResultKind()) {
18952 PrevDecl = Previous.getAsSingle<NamedDecl>();
18953 break;
18954
18956 PrevDecl = Previous.getRepresentativeDecl();
18957 break;
18958
18962 break;
18963 }
18964
18965 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18966 // Maybe we will complain about the shadowed template parameter.
18967 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18968 // Just pretend that we didn't see the previous declaration.
18969 PrevDecl = nullptr;
18970 }
18971
18972 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18973 PrevDecl = nullptr;
18974
18975 SourceLocation TSSL = D.getBeginLoc();
18976 MSPropertyDecl *NewPD =
18977 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18978 MSPropertyAttr.getPropertyDataGetter(),
18979 MSPropertyAttr.getPropertyDataSetter());
18981 NewPD->setAccess(AS);
18982
18983 if (NewPD->isInvalidDecl())
18984 Record->setInvalidDecl();
18985
18986 if (D.getDeclSpec().isModulePrivateSpecified())
18987 NewPD->setModulePrivate();
18988
18989 if (NewPD->isInvalidDecl() && PrevDecl) {
18990 // Don't introduce NewFD into scope; there's already something
18991 // with the same name in the same scope.
18992 } else if (II) {
18993 PushOnScopeChains(NewPD, S);
18994 } else
18995 Record->addDecl(NewPD);
18996
18997 return NewPD;
18998}
18999
19001 Declarator &Declarator, unsigned TemplateParameterDepth) {
19002 auto &Info = InventedParameterInfos.emplace_back();
19003 TemplateParameterList *ExplicitParams = nullptr;
19004 ArrayRef<TemplateParameterList *> ExplicitLists =
19006 if (!ExplicitLists.empty()) {
19007 bool IsMemberSpecialization, IsInvalid;
19010 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19011 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19012 /*SuppressDiagnostic=*/true);
19013 }
19014 // C++23 [dcl.fct]p23:
19015 // An abbreviated function template can have a template-head. The invented
19016 // template-parameters are appended to the template-parameter-list after
19017 // the explicitly declared template-parameters.
19018 //
19019 // A template-head must have one or more template-parameters (read:
19020 // 'template<>' is *not* a template-head). Only append the invented
19021 // template parameters if we matched the nested-name-specifier to a non-empty
19022 // TemplateParameterList.
19023 if (ExplicitParams && !ExplicitParams->empty()) {
19024 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19025 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19026 Info.NumExplicitTemplateParams = ExplicitParams->size();
19027 } else {
19028 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19029 Info.NumExplicitTemplateParams = 0;
19030 }
19031}
19032
19034 auto &FSI = InventedParameterInfos.back();
19035 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19036 if (FSI.NumExplicitTemplateParams != 0) {
19037 TemplateParameterList *ExplicitParams =
19041 Context, ExplicitParams->getTemplateLoc(),
19042 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19043 ExplicitParams->getRAngleLoc(),
19044 ExplicitParams->getRequiresClause()));
19045 } else {
19048 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19049 SourceLocation(), /*RequiresClause=*/nullptr));
19050 }
19051 }
19052 InventedParameterInfos.pop_back();
19053}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3338
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
DynTypedNode Node
StringRef P
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
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:2992
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:51
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
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 CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static 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:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
bool Indirect
Definition: SemaObjC.cpp:759
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.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
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:124
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:186
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1100
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
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:663
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3288
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2625
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3302
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
CanQualType LongDoubleTy
Definition: ASTContext.h:1130
CanQualType Char16Ty
Definition: ASTContext.h:1125
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:1145
void Deallocate(void *Ptr) const
Definition: ASTContext.h:739
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:1146
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:1634
CanQualType WideCharTy
Definition: ASTContext.h:1122
IdentifierTable & Idents
Definition: ASTContext.h:659
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1342
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:2322
QualType AutoDeductTy
Definition: ASTContext.h:1178
CanQualType BoolTy
Definition: ASTContext.h:1119
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3267
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,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:2921
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1120
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3281
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3274
CanQualType IntTy
Definition: ASTContext.h:1127
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3298
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
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:712
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
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:2391
CanQualType BuiltinFnTy
Definition: ASTContext.h:1148
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3263
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:3295
CanQualType VoidTy
Definition: ASTContext.h:1118
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3277
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1129
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:1612
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:3082
CanQualType Char32Ty
Definition: ASTContext.h:1126
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:778
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3270
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:1224
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3284
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:1124
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3291
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:3540
QualType getElementType() const
Definition: Type.h:3552
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:6368
AutoTypeKeyword getKeyword() const
Definition: Type.h:6399
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:3121
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3487
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3130
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4265
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
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:4804
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:3315
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6355
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
This class is used for builtin types like 'int'.
Definition: Type.h:3000
Kind getKind() const
Definition: Type.h:3045
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
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:1546
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:1157
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1609
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:2769
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:2746
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:2764
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2755
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:2725
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:2674
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2661
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2446
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
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:2859
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:1737
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:720
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:2457
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:2464
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:2536
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2530
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2520
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:2490
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:2276
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isStatic() const
Definition: DeclCXX.cpp:2188
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2468
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:1567
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 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:1393
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:695
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1908
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 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:1900
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:1978
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:1609
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:2007
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:1597
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:1152
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1172
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:2830
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
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:3108
QualType getElementType() const
Definition: Type.h:3118
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
body_range body()
Definition: Stmt.h:1669
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:4203
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:3578
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3634
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:3103
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:1358
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2359
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2208
bool isFileContext() const
Definition: DeclBase.h:2150
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2019
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
bool isTranslationUnit() const
Definition: DeclBase.h:2155
bool isRecord() const
Definition: DeclBase.h:2159
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1964
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1661
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1742
decl_iterator decls_end() const
Definition: DeclBase.h:2341
bool isStdNamespace() const
Definition: DeclBase.cpp:1293
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2339
bool isFunctionOrMethod() const
Definition: DeclBase.h:2131
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1364
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1379
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1716
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2072
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1390
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1598
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
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:1333
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1457
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:688
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:557
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
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:822
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
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:615
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:559
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:617
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:454
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:1040
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:1205
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1014
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:154
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1193
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:567
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1198
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1196
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2756
bool isInvalidDecl() const
Definition: DeclBase.h:594
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:868
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1148
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:232
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:812
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:552
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:897
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:957
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Kind getKind() const
Definition: DeclBase.h:448
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:860
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:731
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1970
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:819
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2336
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
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 isInvalidType() const
Definition: DeclSpec.h:2714
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
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:6416
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:5617
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:3270
Represents an enum.
Definition: Decl.h:3840
enumerator_range enumerators() const
Definition: Decl.h:3973
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
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:3070
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3058
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:3066
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:3204
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:919
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4558
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3191
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4632
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4548
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3185
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:3214
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4568
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3243
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3254
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:3084
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2741
bool isTrivialForCall() const
Definition: Decl.h:2305
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3701
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4042
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4030
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3243
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2246
bool isImmediateFunction() const
Definition: Decl.cpp:3276
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3105
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3861
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3462
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3719
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
SourceLocation getDefaultLoc() const
Definition: Decl.h:2323
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2314
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4150
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2654
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3605
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3855
param_iterator param_begin()
Definition: Decl.h:2658
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2258
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2411
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4166
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3006
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4094
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2760
bool isStatic() const
Definition: Decl.h:2801
void setTrivial(bool IT)
Definition: Decl.h:2303
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3981
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2285
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3480
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3168
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2150
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4383
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2805
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3967
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2398
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4254
void setDefaulted(bool D=true)
Definition: Decl.h:2311
bool isConsteval() const
Definition: Decl.h:2407
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2335
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:2734
void setBody(Stmt *B)
Definition: Decl.cpp:3236
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2276
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3733
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3680
size_t param_size() const
Definition: Decl.h:2662
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2143
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
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:3191
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2771
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3139
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2677
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2558
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4910
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition: Type.cpp:5193
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4853
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5439
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5253
unsigned getNumParams() const
Definition: Type.h:5226
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5366
QualType getParamType(unsigned i) const
Definition: Type.h:5228
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5311
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5233
ArrayRef< QualType > exceptions() const
Definition: Type.h:5396
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5411
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:4504
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4278
CallingConv getCallConv() const
Definition: Type.h:4611
QualType getReturnType() const
Definition: Type.h:4600
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:2143
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
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:5782
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3314
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:5029
unsigned getNumInits() const
Definition: Expr.h:5059
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5075
child_range children()
Definition: Expr.h:5221
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:7482
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:3577
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:6605
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:1954
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1337
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1350
@ 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:629
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:2922
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:485
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:3380
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3270
Expr * getBase() const
Definition: Expr.h:3264
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3382
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:3482
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:1089
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:689
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:3017
Represent a C++ namespace.
Definition: Decl.h:547
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:603
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2977
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition: Decl.h:630
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:649
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:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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:4746
Represents a parameter to a function.
Definition: Decl.h:1722
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2968
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1818
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1863
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1851
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2973
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2993
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1855
bool hasInheritedDefaultArg() const
Definition: Decl.h:1867
bool isExplicitObjectParameter() const
Definition: Decl.h:1810
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:2903
Expr * getDefaultArg()
Definition: Decl.cpp:2956
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2998
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3004
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1871
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2926
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
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:3161
QualType getPointeeType() const
Definition: Type.h:3171
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:6487
ArrayRef< Expr * > semantics()
Definition: Expr.h:6566
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7827
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7832
QualType withConst() const
Definition: Type.h:1166
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1232
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1163
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
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:7944
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2837
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1093
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7915
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7816
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7789
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2593
Represents a template name as written in source code.
Definition: TemplateName.h:434
The collection of all-type qualifiers we support.
Definition: Type.h:319
void addAddressSpace(LangAS space)
Definition: Type.h:584
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
void removeConst()
Definition: Type.h:446
void removeAddressSpace()
Definition: Type.h:583
void addConst()
Definition: Type.h:447
void removeVolatile()
Definition: Type.h:456
LangAS getAddressSpace() const
Definition: Type.h:558
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3464
Represents a struct/union/class.
Definition: Decl.h:4141
bool hasFlexibleArrayMember() const
Definition: Decl.h:4174
field_iterator field_end() const
Definition: Decl.h:4350
field_range fields() const
Definition: Decl.h:4347
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5023
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4193
bool field_empty() const
Definition: Decl.h:4355
field_iterator field_begin() const
Definition: Decl.cpp:5057
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
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:4974
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:3402
QualType getPointeeType() const
Definition: Type.h:3420
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3024
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:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
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:1009
bool isInvalid() const
Definition: Sema.h:7335
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5885
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5917
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5914
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:4990
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:8951
CXXMethodDecl * getMethod() const
Definition: Sema.h:8963
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:13064
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7233
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
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:10888
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6661
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:12637
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:9660
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:6068
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:1557
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3578
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15265
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:5830
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8999
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9026
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9034
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:9022
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9007
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:407
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6597
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, CXXScopeSpec *SS=nullptr)
VariadicCallType
Definition: Sema.h:2333
@ VariadicDoesNotApply
Definition: Sema.h:2338
@ VariadicConstructor
Definition: Sema.h:2337
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:6074
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:13206
SemaOpenMP & OpenMP()
Definition: Sema.h:1219
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:5805
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:6059
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:958
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:6045
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:6026
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:1094
SemaCUDA & CUDA()
Definition: Sema.h:1164
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:17159
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:1336
@ AR_accessible
Definition: Sema.h:1334
@ AR_inaccessible
Definition: Sema.h:1335
@ AR_delayed
Definition: Sema.h:1337
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:2276
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2145
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6202
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:16917
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4796
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:18201
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1731
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:1002
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:5766
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:597
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1204
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:4906
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:7247
@ AllowFold
Definition: Sema.h:7249
@ NoFold
Definition: Sema.h:7248
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1495
ASTContext & getASTContext() const
Definition: Sema.h:600
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:6052
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:19639
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:6130
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:17580
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:694
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:5601
@ 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:9252
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:6063
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:908
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2186
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:11786
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1566
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7971
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1560
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2164
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:595
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20141
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_RequiresClause
Definition: Sema.h:13940
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:13895
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:13913
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13904
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:13874
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13898
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13907
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13877
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13880
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:13886
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:593
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:5392
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:1386
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:1001
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:6394
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:8147
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:14345
const LangOptions & LangOpts
Definition: Sema.h:1000
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:17276
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7445
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6030
SemaHLSL & HLSL()
Definition: Sema.h:1169
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:11771
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:5398
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:4787
@ 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:6023
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19790
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:3618
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:6122
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6056
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:9348
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:1373
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:1836
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
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:12649
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:5388
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:635
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:3163
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14960
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:9597
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:15282
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:6496
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:6037
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15206
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1137
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:14786
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5771
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:5869
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:5871
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:5874
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7780
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:19739
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2164
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:13471
SourceManager & getSourceManager() const
Definition: Sema.h:598
@ AA_Passing
Definition: Sema.h:6481
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:1338
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:8979
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9502
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:215
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:8170
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:3779
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14915
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:9393
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14152
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:6048
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:10014
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10012
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:10016
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3077
ASTConsumer & Consumer
Definition: Sema.h:1003
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:4224
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9796
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9788
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9792
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5090
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:9470
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5645
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:16957
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:8885
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:963
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18795
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:7299
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:17658
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7930
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1306
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:1005
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:1004
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:7305
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...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7183
@ TPC_TypeAliasTemplate
Definition: Sema.h:11286
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:6698
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5515
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1313
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:2843
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6060
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:1577
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8794
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1562
@ OOK_Outside
Definition: Sema.h:3865
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13224
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:297
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:5804
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:17839
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:5881
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
Definition: SemaDecl.cpp:20223
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:20889
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6033
AbstractDiagSelID
Definition: Sema.h:5750
@ AbstractVariableType
Definition: Sema.h:5754
@ AbstractReturnType
Definition: Sema.h:5752
@ AbstractNone
Definition: Sema.h:5751
@ AbstractFieldType
Definition: Sema.h:5755
@ AbstractArrayType
Definition: Sema.h:5758
@ AbstractParamType
Definition: Sema.h:5753
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:908
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)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1701
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7975
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:14577
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:5945
@ 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:2723
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:3003
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:6020
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:7351
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:5302
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:592
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:8277
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.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
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:3288
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:1778
bool isUnevaluated() const
Definition: Expr.h:1907
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3557
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3680
StringRef getKindName() const
Definition: Decl.h:3748
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3660
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4714
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4708
bool isUnion() const
Definition: Decl.h:3763
TagKind getTagKind() const
Definition: Decl.h:3752
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3711
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:203
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
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:6473
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6541
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6539
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:6166
unsigned getDepth() const
Definition: Type.h:6165
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3528
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5542
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3547
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:3363
const Type * getTypeForDecl() const
Definition: Decl.h:3387
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:7714
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:7725
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:3148
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6736
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3130
The base class of the type hierarchy.
Definition: Type.h:1829
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:2474
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8295
bool isBooleanType() const
Definition: Type.h:8423
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2889
bool isIncompleteArrayType() const
Definition: Type.h:8072
bool isUndeducedAutoType() const
Definition: Type.h:8151
bool isRValueReferenceType() const
Definition: Type.h:8018
bool isArrayType() const
Definition: Type.h:8064
bool isPointerType() const
Definition: Type.h:7996
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8335
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
bool isEnumeralType() const
Definition: Type.h:8096
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3255
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isLValueReferenceType() const
Definition: Type.h:8014
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8264
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2336
QualType getCanonicalTypeInternal() const
Definition: Type.h:2955
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2666
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8466
bool isFunctionProtoType() const
Definition: Type.h:2510
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8436
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2690
bool isObjCObjectType() const
Definition: Type.h:8138
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8429
bool isFunctionType() const
Definition: Type.h:7992
bool isObjCObjectPointerType() const
Definition: Type.h:8134
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isRecordType() const
Definition: Type.h:8092
bool isUnionType() const
Definition: Type.cpp:671
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:1890
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3405
QualType getUnderlyingType() const
Definition: Decl.h:3460
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:2188
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:4861
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:419
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:90
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:3267
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:3246
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:3218
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:3152
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:2939
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:3173
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3196
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:3092
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1510
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2242
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2172
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2801
void setCXXCondDecl()
Definition: Decl.h:1560
bool isInlineSpecified() const
Definition: Decl.h:1495
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2539
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1174
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2612
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:1156
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2808
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1125
const Expr * getInit() const
Definition: Decl.h:1316
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:905
void setInit(Expr *I)
Definition: Decl.cpp:2442
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
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:2493
void setExceptionVariable(bool EV)
Definition: Decl.h:1438
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:3991
unsigned getNumElements() const
Definition: Type.h:4006
QualType getElementType() const
Definition: Type.h:4005
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:776
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2204
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:876
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:32
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:328
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:61
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus26
Definition: LangStandard.h:62
@ CPlusPlus17
Definition: LangStandard.h:59
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:1778
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
@ 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:1538
@ 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:50
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:806
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6683
@ 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:1043
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:445
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:1264
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:6658
@ 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::@225 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:5030
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5042
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5032
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5035
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5038
Extra information about a function prototype.
Definition: Type.h:5058
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5065
FunctionEffectsRef FunctionEffects
Definition: Type.h:5068
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5059
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:1038
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:12654
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12771
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12748
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12745
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12698
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12712
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12716
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12774
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition: Sema.h:12800
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7871
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.