clang 19.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaCUDA.h"
48#include "clang/Sema/Template.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/STLForwardCompat.h"
52#include "llvm/ADT/ScopeExit.h"
53#include "llvm/ADT/SmallString.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/Support/ConvertUTF.h"
56#include "llvm/Support/SaveAndRestore.h"
57#include <map>
58#include <optional>
59#include <set>
60
61using namespace clang;
62
63//===----------------------------------------------------------------------===//
64// CheckDefaultArgumentVisitor
65//===----------------------------------------------------------------------===//
66
67namespace {
68/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
69/// the default argument of a parameter to determine whether it
70/// contains any ill-formed subexpressions. For example, this will
71/// diagnose the use of local variables or parameters within the
72/// default argument expression.
73class CheckDefaultArgumentVisitor
74 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
75 Sema &S;
76 const Expr *DefaultArg;
77
78public:
79 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
80 : S(S), DefaultArg(DefaultArg) {}
81
82 bool VisitExpr(const Expr *Node);
83 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
84 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
85 bool VisitLambdaExpr(const LambdaExpr *Lambda);
86 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
87};
88
89/// VisitExpr - Visit all of the children of this expression.
90bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
91 bool IsInvalid = false;
92 for (const Stmt *SubStmt : Node->children())
93 if (SubStmt)
94 IsInvalid |= Visit(SubStmt);
95 return IsInvalid;
96}
97
98/// VisitDeclRefExpr - Visit a reference to a declaration, to
99/// determine whether this declaration can be used in the default
100/// argument expression.
101bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
102 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
103
104 if (!isa<VarDecl, BindingDecl>(Decl))
105 return false;
106
107 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
108 // C++ [dcl.fct.default]p9:
109 // [...] parameters of a function shall not be used in default
110 // argument expressions, even if they are not evaluated. [...]
111 //
112 // C++17 [dcl.fct.default]p9 (by CWG 2082):
113 // [...] A parameter shall not appear as a potentially-evaluated
114 // expression in a default argument. [...]
115 //
116 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
117 return S.Diag(DRE->getBeginLoc(),
118 diag::err_param_default_argument_references_param)
119 << Param->getDeclName() << DefaultArg->getSourceRange();
120 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
121 // C++ [dcl.fct.default]p7:
122 // Local variables shall not be used in default argument
123 // expressions.
124 //
125 // C++17 [dcl.fct.default]p7 (by CWG 2082):
126 // A local variable shall not appear as a potentially-evaluated
127 // expression in a default argument.
128 //
129 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
130 // Note: A local variable cannot be odr-used (6.3) in a default
131 // argument.
132 //
133 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
134 return S.Diag(DRE->getBeginLoc(),
135 diag::err_param_default_argument_references_local)
136 << Decl << DefaultArg->getSourceRange();
137 }
138 return false;
139}
140
141/// VisitCXXThisExpr - Visit a C++ "this" expression.
142bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
143 // C++ [dcl.fct.default]p8:
144 // The keyword this shall not be used in a default argument of a
145 // member function.
146 return S.Diag(ThisE->getBeginLoc(),
147 diag::err_param_default_argument_references_this)
148 << ThisE->getSourceRange();
149}
150
151bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
152 const PseudoObjectExpr *POE) {
153 bool Invalid = false;
154 for (const Expr *E : POE->semantics()) {
155 // Look through bindings.
156 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
157 E = OVE->getSourceExpr();
158 assert(E && "pseudo-object binding without source expression?");
159 }
160
161 Invalid |= Visit(E);
162 }
163 return Invalid;
164}
165
166bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
167 // [expr.prim.lambda.capture]p9
168 // a lambda-expression appearing in a default argument cannot implicitly or
169 // explicitly capture any local entity. Such a lambda-expression can still
170 // have an init-capture if any full-expression in its initializer satisfies
171 // the constraints of an expression appearing in a default argument.
172 bool Invalid = false;
173 for (const LambdaCapture &LC : Lambda->captures()) {
174 if (!Lambda->isInitCapture(&LC))
175 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
176 // Init captures are always VarDecl.
177 auto *D = cast<VarDecl>(LC.getCapturedVar());
178 Invalid |= Visit(D->getInit());
179 }
180 return Invalid;
181}
182} // namespace
183
184void
186 const CXXMethodDecl *Method) {
187 // If we have an MSAny spec already, don't bother.
188 if (!Method || ComputedEST == EST_MSAny)
189 return;
190
191 const FunctionProtoType *Proto
192 = Method->getType()->getAs<FunctionProtoType>();
193 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
194 if (!Proto)
195 return;
196
198
199 // If we have a throw-all spec at this point, ignore the function.
200 if (ComputedEST == EST_None)
201 return;
202
203 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
204 EST = EST_BasicNoexcept;
205
206 switch (EST) {
207 case EST_Unparsed:
209 case EST_Unevaluated:
210 llvm_unreachable("should not see unresolved exception specs here");
211
212 // If this function can throw any exceptions, make a note of that.
213 case EST_MSAny:
214 case EST_None:
215 // FIXME: Whichever we see last of MSAny and None determines our result.
216 // We should make a consistent, order-independent choice here.
217 ClearExceptions();
218 ComputedEST = EST;
219 return;
221 ClearExceptions();
222 ComputedEST = EST_None;
223 return;
224 // FIXME: If the call to this decl is using any of its default arguments, we
225 // need to search them for potentially-throwing calls.
226 // If this function has a basic noexcept, it doesn't affect the outcome.
228 case EST_NoexceptTrue:
229 case EST_NoThrow:
230 return;
231 // If we're still at noexcept(true) and there's a throw() callee,
232 // change to that specification.
233 case EST_DynamicNone:
234 if (ComputedEST == EST_BasicNoexcept)
235 ComputedEST = EST_DynamicNone;
236 return;
238 llvm_unreachable(
239 "should not generate implicit declarations for dependent cases");
240 case EST_Dynamic:
241 break;
242 }
243 assert(EST == EST_Dynamic && "EST case not considered earlier.");
244 assert(ComputedEST != EST_None &&
245 "Shouldn't collect exceptions when throw-all is guaranteed.");
246 ComputedEST = EST_Dynamic;
247 // Record the exceptions in this function's exception specification.
248 for (const auto &E : Proto->exceptions())
249 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
250 Exceptions.push_back(E);
251}
252
254 if (!S || ComputedEST == EST_MSAny)
255 return;
256
257 // FIXME:
258 //
259 // C++0x [except.spec]p14:
260 // [An] implicit exception-specification specifies the type-id T if and
261 // only if T is allowed by the exception-specification of a function directly
262 // invoked by f's implicit definition; f shall allow all exceptions if any
263 // function it directly invokes allows all exceptions, and f shall allow no
264 // exceptions if every function it directly invokes allows no exceptions.
265 //
266 // Note in particular that if an implicit exception-specification is generated
267 // for a function containing a throw-expression, that specification can still
268 // be noexcept(true).
269 //
270 // Note also that 'directly invoked' is not defined in the standard, and there
271 // is no indication that we should only consider potentially-evaluated calls.
272 //
273 // Ultimately we should implement the intent of the standard: the exception
274 // specification should be the set of exceptions which can be thrown by the
275 // implicit definition. For now, we assume that any non-nothrow expression can
276 // throw any exception.
277
278 if (Self->canThrow(S))
279 ComputedEST = EST_None;
280}
281
283 SourceLocation EqualLoc) {
284 if (RequireCompleteType(Param->getLocation(), Param->getType(),
285 diag::err_typecheck_decl_incomplete_type))
286 return true;
287
288 // C++ [dcl.fct.default]p5
289 // A default argument expression is implicitly converted (clause
290 // 4) to the parameter type. The default argument expression has
291 // the same semantic constraints as the initializer expression in
292 // a declaration of a variable of the parameter type, using the
293 // copy-initialization semantics (8.5).
295 Param);
297 EqualLoc);
298 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
299 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
300 if (Result.isInvalid())
301 return true;
302 Arg = Result.getAs<Expr>();
303
304 CheckCompletedExpr(Arg, EqualLoc);
306
307 return Arg;
308}
309
311 SourceLocation EqualLoc) {
312 // Add the default argument to the parameter
313 Param->setDefaultArg(Arg);
314
315 // We have already instantiated this parameter; provide each of the
316 // instantiations with the uninstantiated default argument.
317 UnparsedDefaultArgInstantiationsMap::iterator InstPos
319 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
320 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
321 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
322
323 // We're done tracking this parameter's instantiations.
325 }
326}
327
328/// ActOnParamDefaultArgument - Check whether the default argument
329/// provided for a function parameter is well-formed. If so, attach it
330/// to the parameter declaration.
331void
333 Expr *DefaultArg) {
334 if (!param || !DefaultArg)
335 return;
336
337 ParmVarDecl *Param = cast<ParmVarDecl>(param);
338 UnparsedDefaultArgLocs.erase(Param);
339
340 // Default arguments are only permitted in C++
341 if (!getLangOpts().CPlusPlus) {
342 Diag(EqualLoc, diag::err_param_default_argument)
343 << DefaultArg->getSourceRange();
344 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
345 }
346
347 // Check for unexpanded parameter packs.
349 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
350
351 // C++11 [dcl.fct.default]p3
352 // A default argument expression [...] shall not be specified for a
353 // parameter pack.
354 if (Param->isParameterPack()) {
355 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
356 << DefaultArg->getSourceRange();
357 // Recover by discarding the default argument.
358 Param->setDefaultArg(nullptr);
359 return;
360 }
361
362 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
363 if (Result.isInvalid())
364 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
365
366 DefaultArg = Result.getAs<Expr>();
367
368 // Check that the default argument is well-formed
369 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
370 if (DefaultArgChecker.Visit(DefaultArg))
371 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
372
373 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
374}
375
376/// ActOnParamUnparsedDefaultArgument - We've seen a default
377/// argument for a function parameter, but we can't parse it yet
378/// because we're inside a class definition. Note that this default
379/// argument will be parsed later.
381 SourceLocation EqualLoc,
382 SourceLocation ArgLoc) {
383 if (!param)
384 return;
385
386 ParmVarDecl *Param = cast<ParmVarDecl>(param);
387 Param->setUnparsedDefaultArg();
388 UnparsedDefaultArgLocs[Param] = ArgLoc;
389}
390
391/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
392/// the default argument for the parameter param failed.
394 Expr *DefaultArg) {
395 if (!param)
396 return;
397
398 ParmVarDecl *Param = cast<ParmVarDecl>(param);
399 Param->setInvalidDecl();
400 UnparsedDefaultArgLocs.erase(Param);
401 ExprResult RE;
402 if (DefaultArg) {
403 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
404 Param->getType().getNonReferenceType());
405 } else {
406 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
407 Param->getType().getNonReferenceType());
408 }
409 Param->setDefaultArg(RE.get());
410}
411
412/// CheckExtraCXXDefaultArguments - Check for any extra default
413/// arguments in the declarator, which is not a function declaration
414/// or definition and therefore is not permitted to have default
415/// arguments. This routine should be invoked for every declarator
416/// that is not a function declaration or definition.
418 // C++ [dcl.fct.default]p3
419 // A default argument expression shall be specified only in the
420 // parameter-declaration-clause of a function declaration or in a
421 // template-parameter (14.1). It shall not be specified for a
422 // parameter pack. If it is specified in a
423 // parameter-declaration-clause, it shall not occur within a
424 // declarator or abstract-declarator of a parameter-declaration.
425 bool MightBeFunction = D.isFunctionDeclarationContext();
426 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
427 DeclaratorChunk &chunk = D.getTypeObject(i);
428 if (chunk.Kind == DeclaratorChunk::Function) {
429 if (MightBeFunction) {
430 // This is a function declaration. It can have default arguments, but
431 // keep looking in case its return type is a function type with default
432 // arguments.
433 MightBeFunction = false;
434 continue;
435 }
436 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
437 ++argIdx) {
438 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
439 if (Param->hasUnparsedDefaultArg()) {
440 std::unique_ptr<CachedTokens> Toks =
441 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
442 SourceRange SR;
443 if (Toks->size() > 1)
444 SR = SourceRange((*Toks)[1].getLocation(),
445 Toks->back().getLocation());
446 else
447 SR = UnparsedDefaultArgLocs[Param];
448 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
449 << SR;
450 } else if (Param->getDefaultArg()) {
451 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
452 << Param->getDefaultArg()->getSourceRange();
453 Param->setDefaultArg(nullptr);
454 }
455 }
456 } else if (chunk.Kind != DeclaratorChunk::Paren) {
457 MightBeFunction = false;
458 }
459 }
460}
461
463 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
464 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
465 });
466}
467
468/// MergeCXXFunctionDecl - Merge two declarations of the same C++
469/// function, once we already know that they have the same
470/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
471/// error, false otherwise.
473 Scope *S) {
474 bool Invalid = false;
475
476 // The declaration context corresponding to the scope is the semantic
477 // parent, unless this is a local function declaration, in which case
478 // it is that surrounding function.
479 DeclContext *ScopeDC = New->isLocalExternDecl()
480 ? New->getLexicalDeclContext()
481 : New->getDeclContext();
482
483 // Find the previous declaration for the purpose of default arguments.
484 FunctionDecl *PrevForDefaultArgs = Old;
485 for (/**/; PrevForDefaultArgs;
486 // Don't bother looking back past the latest decl if this is a local
487 // extern declaration; nothing else could work.
488 PrevForDefaultArgs = New->isLocalExternDecl()
489 ? nullptr
490 : PrevForDefaultArgs->getPreviousDecl()) {
491 // Ignore hidden declarations.
492 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
493 continue;
494
495 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
496 !New->isCXXClassMember()) {
497 // Ignore default arguments of old decl if they are not in
498 // the same scope and this is not an out-of-line definition of
499 // a member function.
500 continue;
501 }
502
503 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
504 // If only one of these is a local function declaration, then they are
505 // declared in different scopes, even though isDeclInScope may think
506 // they're in the same scope. (If both are local, the scope check is
507 // sufficient, and if neither is local, then they are in the same scope.)
508 continue;
509 }
510
511 // We found the right previous declaration.
512 break;
513 }
514
515 // C++ [dcl.fct.default]p4:
516 // For non-template functions, default arguments can be added in
517 // later declarations of a function in the same
518 // scope. Declarations in different scopes have completely
519 // distinct sets of default arguments. That is, declarations in
520 // inner scopes do not acquire default arguments from
521 // declarations in outer scopes, and vice versa. In a given
522 // function declaration, all parameters subsequent to a
523 // parameter with a default argument shall have default
524 // arguments supplied in this or previous declarations. A
525 // default argument shall not be redefined by a later
526 // declaration (not even to the same value).
527 //
528 // C++ [dcl.fct.default]p6:
529 // Except for member functions of class templates, the default arguments
530 // in a member function definition that appears outside of the class
531 // definition are added to the set of default arguments provided by the
532 // member function declaration in the class definition.
533 for (unsigned p = 0, NumParams = PrevForDefaultArgs
534 ? PrevForDefaultArgs->getNumParams()
535 : 0;
536 p < NumParams; ++p) {
537 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
538 ParmVarDecl *NewParam = New->getParamDecl(p);
539
540 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
541 bool NewParamHasDfl = NewParam->hasDefaultArg();
542
543 if (OldParamHasDfl && NewParamHasDfl) {
544 unsigned DiagDefaultParamID =
545 diag::err_param_default_argument_redefinition;
546
547 // MSVC accepts that default parameters be redefined for member functions
548 // of template class. The new default parameter's value is ignored.
549 Invalid = true;
550 if (getLangOpts().MicrosoftExt) {
551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
552 if (MD && MD->getParent()->getDescribedClassTemplate()) {
553 // Merge the old default argument into the new parameter.
554 NewParam->setHasInheritedDefaultArg();
555 if (OldParam->hasUninstantiatedDefaultArg())
557 OldParam->getUninstantiatedDefaultArg());
558 else
559 NewParam->setDefaultArg(OldParam->getInit());
560 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
561 Invalid = false;
562 }
563 }
564
565 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
566 // hint here. Alternatively, we could walk the type-source information
567 // for NewParam to find the last source location in the type... but it
568 // isn't worth the effort right now. This is the kind of test case that
569 // is hard to get right:
570 // int f(int);
571 // void g(int (*fp)(int) = f);
572 // void g(int (*fp)(int) = &f);
573 Diag(NewParam->getLocation(), DiagDefaultParamID)
574 << NewParam->getDefaultArgRange();
575
576 // Look for the function declaration where the default argument was
577 // actually written, which may be a declaration prior to Old.
578 for (auto Older = PrevForDefaultArgs;
579 OldParam->hasInheritedDefaultArg(); /**/) {
580 Older = Older->getPreviousDecl();
581 OldParam = Older->getParamDecl(p);
582 }
583
584 Diag(OldParam->getLocation(), diag::note_previous_definition)
585 << OldParam->getDefaultArgRange();
586 } else if (OldParamHasDfl) {
587 // Merge the old default argument into the new parameter unless the new
588 // function is a friend declaration in a template class. In the latter
589 // case the default arguments will be inherited when the friend
590 // declaration will be instantiated.
591 if (New->getFriendObjectKind() == Decl::FOK_None ||
593 // It's important to use getInit() here; getDefaultArg()
594 // strips off any top-level ExprWithCleanups.
595 NewParam->setHasInheritedDefaultArg();
596 if (OldParam->hasUnparsedDefaultArg())
597 NewParam->setUnparsedDefaultArg();
598 else if (OldParam->hasUninstantiatedDefaultArg())
600 OldParam->getUninstantiatedDefaultArg());
601 else
602 NewParam->setDefaultArg(OldParam->getInit());
603 }
604 } else if (NewParamHasDfl) {
605 if (New->getDescribedFunctionTemplate()) {
606 // Paragraph 4, quoted above, only applies to non-template functions.
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_template_redecl)
609 << NewParam->getDefaultArgRange();
610 Diag(PrevForDefaultArgs->getLocation(),
611 diag::note_template_prev_declaration)
612 << false;
613 } else if (New->getTemplateSpecializationKind()
616 // C++ [temp.expr.spec]p21:
617 // Default function arguments shall not be specified in a declaration
618 // or a definition for one of the following explicit specializations:
619 // - the explicit specialization of a function template;
620 // - the explicit specialization of a member function template;
621 // - the explicit specialization of a member function of a class
622 // template where the class template specialization to which the
623 // member function specialization belongs is implicitly
624 // instantiated.
625 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
627 << New->getDeclName()
628 << NewParam->getDefaultArgRange();
629 } else if (New->getDeclContext()->isDependentContext()) {
630 // C++ [dcl.fct.default]p6 (DR217):
631 // Default arguments for a member function of a class template shall
632 // be specified on the initial declaration of the member function
633 // within the class template.
634 //
635 // Reading the tea leaves a bit in DR217 and its reference to DR205
636 // leads me to the conclusion that one cannot add default function
637 // arguments for an out-of-line definition of a member function of a
638 // dependent type.
639 int WhichKind = 2;
641 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
642 if (Record->getDescribedClassTemplate())
643 WhichKind = 0;
644 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
645 WhichKind = 1;
646 else
647 WhichKind = 2;
648 }
649
650 Diag(NewParam->getLocation(),
651 diag::err_param_default_argument_member_template_redecl)
652 << WhichKind
653 << NewParam->getDefaultArgRange();
654 }
655 }
656 }
657
658 // DR1344: If a default argument is added outside a class definition and that
659 // default argument makes the function a special member function, the program
660 // is ill-formed. This can only happen for constructors.
661 if (isa<CXXConstructorDecl>(New) &&
663 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
664 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
665 if (NewSM != OldSM) {
666 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
667 assert(NewParam->hasDefaultArg());
668 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
669 << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
670 Diag(Old->getLocation(), diag::note_previous_declaration);
671 }
672 }
673
674 const FunctionDecl *Def;
675 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
676 // template has a constexpr specifier then all its declarations shall
677 // contain the constexpr specifier.
678 if (New->getConstexprKind() != Old->getConstexprKind()) {
679 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
680 << New << static_cast<int>(New->getConstexprKind())
681 << static_cast<int>(Old->getConstexprKind());
682 Diag(Old->getLocation(), diag::note_previous_declaration);
683 Invalid = true;
684 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
685 Old->isDefined(Def) &&
686 // If a friend function is inlined but does not have 'inline'
687 // specifier, it is a definition. Do not report attribute conflict
688 // in this case, redefinition will be diagnosed later.
689 (New->isInlineSpecified() ||
691 // C++11 [dcl.fcn.spec]p4:
692 // If the definition of a function appears in a translation unit before its
693 // first declaration as inline, the program is ill-formed.
694 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
695 Diag(Def->getLocation(), diag::note_previous_definition);
696 Invalid = true;
697 }
698
699 // C++17 [temp.deduct.guide]p3:
700 // Two deduction guide declarations in the same translation unit
701 // for the same class template shall not have equivalent
702 // parameter-declaration-clauses.
703 if (isa<CXXDeductionGuideDecl>(New) &&
705 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
706 Diag(Old->getLocation(), diag::note_previous_declaration);
707 }
708
709 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
710 // argument expression, that declaration shall be a definition and shall be
711 // the only declaration of the function or function template in the
712 // translation unit.
715 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
716 Diag(Old->getLocation(), diag::note_previous_declaration);
717 Invalid = true;
718 }
719
720 // C++11 [temp.friend]p4 (DR329):
721 // When a function is defined in a friend function declaration in a class
722 // template, the function is instantiated when the function is odr-used.
723 // The same restrictions on multiple declarations and definitions that
724 // apply to non-template function declarations and definitions also apply
725 // to these implicit definitions.
726 const FunctionDecl *OldDefinition = nullptr;
728 Old->isDefined(OldDefinition, true))
729 CheckForFunctionRedefinition(New, OldDefinition);
730
731 return Invalid;
732}
733
736 ? diag::warn_cxx23_placeholder_var_definition
737 : diag::ext_placeholder_var_definition);
738}
739
740NamedDecl *
742 MultiTemplateParamsArg TemplateParamLists) {
743 assert(D.isDecompositionDeclarator());
745
746 // The syntax only allows a decomposition declarator as a simple-declaration,
747 // a for-range-declaration, or a condition in Clang, but we parse it in more
748 // cases than that.
750 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
751 << Decomp.getSourceRange();
752 return nullptr;
753 }
754
755 if (!TemplateParamLists.empty()) {
756 // FIXME: There's no rule against this, but there are also no rules that
757 // would actually make it usable, so we reject it for now.
758 Diag(TemplateParamLists.front()->getTemplateLoc(),
759 diag::err_decomp_decl_template);
760 return nullptr;
761 }
762
763 Diag(Decomp.getLSquareLoc(),
765 ? diag::ext_decomp_decl
767 ? diag::ext_decomp_decl_cond
768 : diag::warn_cxx14_compat_decomp_decl)
769 << Decomp.getSourceRange();
770
771 // The semantic context is always just the current context.
772 DeclContext *const DC = CurContext;
773
774 // C++17 [dcl.dcl]/8:
775 // The decl-specifier-seq shall contain only the type-specifier auto
776 // and cv-qualifiers.
777 // C++20 [dcl.dcl]/8:
778 // If decl-specifier-seq contains any decl-specifier other than static,
779 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
780 // C++23 [dcl.pre]/6:
781 // Each decl-specifier in the decl-specifier-seq shall be static,
782 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
783 auto &DS = D.getDeclSpec();
784 {
785 // Note: While constrained-auto needs to be checked, we do so separately so
786 // we can emit a better diagnostic.
787 SmallVector<StringRef, 8> BadSpecifiers;
788 SmallVector<SourceLocation, 8> BadSpecifierLocs;
789 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
790 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
791 if (auto SCS = DS.getStorageClassSpec()) {
792 if (SCS == DeclSpec::SCS_static) {
793 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
794 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
795 } else {
796 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
797 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
798 }
799 }
800 if (auto TSCS = DS.getThreadStorageClassSpec()) {
801 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
802 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
803 }
804 if (DS.hasConstexprSpecifier()) {
805 BadSpecifiers.push_back(
806 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
807 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
808 }
809 if (DS.isInlineSpecified()) {
810 BadSpecifiers.push_back("inline");
811 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
812 }
813
814 if (!BadSpecifiers.empty()) {
815 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
816 Err << (int)BadSpecifiers.size()
817 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
818 // Don't add FixItHints to remove the specifiers; we do still respect
819 // them when building the underlying variable.
820 for (auto Loc : BadSpecifierLocs)
821 Err << SourceRange(Loc, Loc);
822 } else if (!CPlusPlus20Specifiers.empty()) {
823 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
825 ? diag::warn_cxx17_compat_decomp_decl_spec
826 : diag::ext_decomp_decl_spec);
827 Warn << (int)CPlusPlus20Specifiers.size()
828 << llvm::join(CPlusPlus20Specifiers.begin(),
829 CPlusPlus20Specifiers.end(), " ");
830 for (auto Loc : CPlusPlus20SpecifierLocs)
831 Warn << SourceRange(Loc, Loc);
832 }
833 // We can't recover from it being declared as a typedef.
834 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
835 return nullptr;
836 }
837
838 // C++2a [dcl.struct.bind]p1:
839 // A cv that includes volatile is deprecated
840 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
842 Diag(DS.getVolatileSpecLoc(),
843 diag::warn_deprecated_volatile_structured_binding);
844
846 QualType R = TInfo->getType();
847
850 D.setInvalidType();
851
852 // The syntax only allows a single ref-qualifier prior to the decomposition
853 // declarator. No other declarator chunks are permitted. Also check the type
854 // specifier here.
855 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
856 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
857 (D.getNumTypeObjects() == 1 &&
859 Diag(Decomp.getLSquareLoc(),
860 (D.hasGroupingParens() ||
861 (D.getNumTypeObjects() &&
863 ? diag::err_decomp_decl_parens
864 : diag::err_decomp_decl_type)
865 << R;
866
867 // In most cases, there's no actual problem with an explicitly-specified
868 // type, but a function type won't work here, and ActOnVariableDeclarator
869 // shouldn't be called for such a type.
870 if (R->isFunctionType())
871 D.setInvalidType();
872 }
873
874 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
875 if (DS.isConstrainedAuto()) {
876 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
877 assert(TemplRep->Kind == TNK_Concept_template &&
878 "No other template kind should be possible for a constrained auto");
879
880 SourceRange TemplRange{TemplRep->TemplateNameLoc,
881 TemplRep->RAngleLoc.isValid()
882 ? TemplRep->RAngleLoc
883 : TemplRep->TemplateNameLoc};
884 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
885 << TemplRange << FixItHint::CreateRemoval(TemplRange);
886 }
887
888 // Build the BindingDecls.
890
891 // Build the BindingDecls.
892 for (auto &B : D.getDecompositionDeclarator().bindings()) {
893 // Check for name conflicts.
894 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
895 IdentifierInfo *VarName = B.Name;
896 assert(VarName && "Cannot have an unnamed binding declaration");
897
899 RedeclarationKind::ForVisibleRedeclaration);
901 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
902
903 // It's not permitted to shadow a template parameter name.
904 if (Previous.isSingleResult() &&
905 Previous.getFoundDecl()->isTemplateParameter()) {
907 Previous.getFoundDecl());
908 Previous.clear();
909 }
910
911 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
912
913 // Find the shadowed declaration before filtering for scope.
914 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
916 : nullptr;
917
918 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
919 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
920 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
921 /*AllowInlineNamespace*/false);
922
923 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
924 DC->isFunctionOrMethod() && VarName->isPlaceholder();
925 if (!Previous.empty()) {
926 if (IsPlaceholder) {
927 bool sameDC = (Previous.end() - 1)
928 ->getDeclContext()
929 ->getRedeclContext()
930 ->Equals(DC->getRedeclContext());
931 if (sameDC &&
932 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
933 Previous.clear();
935 }
936 } else {
937 auto *Old = Previous.getRepresentativeDecl();
938 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
939 Diag(Old->getLocation(), diag::note_previous_definition);
940 }
941 } else if (ShadowedDecl && !D.isRedeclaration()) {
942 CheckShadow(BD, ShadowedDecl, Previous);
943 }
944 PushOnScopeChains(BD, S, true);
945 Bindings.push_back(BD);
946 ParsingInitForAutoVars.insert(BD);
947 }
948
949 // There are no prior lookup results for the variable itself, because it
950 // is unnamed.
951 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
952 Decomp.getLSquareLoc());
954 RedeclarationKind::ForVisibleRedeclaration);
955
956 // Build the variable that holds the non-decomposed object.
957 bool AddToScope = true;
958 NamedDecl *New =
959 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
960 MultiTemplateParamsArg(), AddToScope, Bindings);
961 if (AddToScope) {
962 S->AddDecl(New);
964 }
965
966 if (OpenMP().isInOpenMPDeclareTargetContext())
968
969 return New;
970}
971
974 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
975 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
976 if ((int64_t)Bindings.size() != NumElems) {
977 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
978 << DecompType << (unsigned)Bindings.size()
979 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
980 << toString(NumElems, 10) << (NumElems < Bindings.size());
981 return true;
982 }
983
984 unsigned I = 0;
985 for (auto *B : Bindings) {
986 SourceLocation Loc = B->getLocation();
987 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
988 if (E.isInvalid())
989 return true;
990 E = GetInit(Loc, E.get(), I++);
991 if (E.isInvalid())
992 return true;
993 B->setBinding(ElemType, E.get());
994 }
995
996 return false;
997}
998
1001 ValueDecl *Src, QualType DecompType,
1002 const llvm::APSInt &NumElems,
1003 QualType ElemType) {
1005 S, Bindings, Src, DecompType, NumElems, ElemType,
1006 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1007 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1008 if (E.isInvalid())
1009 return ExprError();
1010 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1011 });
1012}
1013
1015 ValueDecl *Src, QualType DecompType,
1016 const ConstantArrayType *CAT) {
1017 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1018 llvm::APSInt(CAT->getSize()),
1019 CAT->getElementType());
1020}
1021
1023 ValueDecl *Src, QualType DecompType,
1024 const VectorType *VT) {
1026 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1028 DecompType.getQualifiers()));
1029}
1030
1033 ValueDecl *Src, QualType DecompType,
1034 const ComplexType *CT) {
1036 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1038 DecompType.getQualifiers()),
1039 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1040 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1041 });
1042}
1043
1046 const TemplateParameterList *Params) {
1048 llvm::raw_svector_ostream OS(SS);
1049 bool First = true;
1050 unsigned I = 0;
1051 for (auto &Arg : Args.arguments()) {
1052 if (!First)
1053 OS << ", ";
1054 Arg.getArgument().print(PrintingPolicy, OS,
1056 PrintingPolicy, Params, I));
1057 First = false;
1058 I++;
1059 }
1060 return std::string(OS.str());
1061}
1062
1063static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1064 SourceLocation Loc, StringRef Trait,
1066 unsigned DiagID) {
1067 auto DiagnoseMissing = [&] {
1068 if (DiagID)
1069 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1070 Args, /*Params*/ nullptr);
1071 return true;
1072 };
1073
1074 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1076 if (!Std)
1077 return DiagnoseMissing();
1078
1079 // Look up the trait itself, within namespace std. We can diagnose various
1080 // problems with this lookup even if we've been asked to not diagnose a
1081 // missing specialization, because this can only fail if the user has been
1082 // declaring their own names in namespace std or we don't support the
1083 // standard library implementation in use.
1087 return DiagnoseMissing();
1088 if (Result.isAmbiguous())
1089 return true;
1090
1091 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1092 if (!TraitTD) {
1093 Result.suppressDiagnostics();
1094 NamedDecl *Found = *Result.begin();
1095 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1096 S.Diag(Found->getLocation(), diag::note_declared_at);
1097 return true;
1098 }
1099
1100 // Build the template-id.
1101 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1102 if (TraitTy.isNull())
1103 return true;
1104 if (!S.isCompleteType(Loc, TraitTy)) {
1105 if (DiagID)
1107 Loc, TraitTy, DiagID,
1109 TraitTD->getTemplateParameters()));
1110 return true;
1111 }
1112
1113 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1114 assert(RD && "specialization of class template is not a class?");
1115
1116 // Look up the member of the trait type.
1117 S.LookupQualifiedName(TraitMemberLookup, RD);
1118 return TraitMemberLookup.isAmbiguous();
1119}
1120
1123 uint64_t I) {
1125 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1126}
1127
1131}
1132
1133namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1134
1135static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1136 llvm::APSInt &Size) {
1139
1142
1143 // Form template argument list for tuple_size<T>.
1144 TemplateArgumentListInfo Args(Loc, Loc);
1146
1147 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1148 // it's not tuple-like.
1149 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1150 R.empty())
1151 return IsTupleLike::NotTupleLike;
1152
1153 // If we get this far, we've committed to the tuple interpretation, but
1154 // we can still fail if there actually isn't a usable ::value.
1155
1156 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1157 LookupResult &R;
1159 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1160 : R(R), Args(Args) {}
1161 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1162 SourceLocation Loc) override {
1163 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1165 /*Params*/ nullptr);
1166 }
1167 } Diagnoser(R, Args);
1168
1169 ExprResult E =
1170 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1171 if (E.isInvalid())
1172 return IsTupleLike::Error;
1173
1174 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1175 if (E.isInvalid())
1176 return IsTupleLike::Error;
1177
1178 return IsTupleLike::TupleLike;
1179}
1180
1181/// \return std::tuple_element<I, T>::type.
1183 unsigned I, QualType T) {
1184 // Form template argument list for tuple_element<I, T>.
1185 TemplateArgumentListInfo Args(Loc, Loc);
1186 Args.addArgument(
1189
1190 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1191 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1193 S, R, Loc, "tuple_element", Args,
1194 diag::err_decomp_decl_std_tuple_element_not_specialized))
1195 return QualType();
1196
1197 auto *TD = R.getAsSingle<TypeDecl>();
1198 if (!TD) {
1200 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1202 /*Params*/ nullptr);
1203 if (!R.empty())
1204 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1205 return QualType();
1206 }
1207
1208 return S.Context.getTypeDeclType(TD);
1209}
1210
1211namespace {
1212struct InitializingBinding {
1213 Sema &S;
1214 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1218 Ctx.Entity = BD;
1220 }
1221 ~InitializingBinding() {
1223 }
1224};
1225}
1226
1229 VarDecl *Src, QualType DecompType,
1230 const llvm::APSInt &TupleSize) {
1231 if ((int64_t)Bindings.size() != TupleSize) {
1232 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1233 << DecompType << (unsigned)Bindings.size()
1234 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1235 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1236 return true;
1237 }
1238
1239 if (Bindings.empty())
1240 return false;
1241
1242 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1243
1244 // [dcl.decomp]p3:
1245 // The unqualified-id get is looked up in the scope of E by class member
1246 // access lookup ...
1247 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1248 bool UseMemberGet = false;
1249 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1250 if (auto *RD = DecompType->getAsCXXRecordDecl())
1251 S.LookupQualifiedName(MemberGet, RD);
1252 if (MemberGet.isAmbiguous())
1253 return true;
1254 // ... and if that finds at least one declaration that is a function
1255 // template whose first template parameter is a non-type parameter ...
1256 for (NamedDecl *D : MemberGet) {
1257 if (FunctionTemplateDecl *FTD =
1258 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1259 TemplateParameterList *TPL = FTD->getTemplateParameters();
1260 if (TPL->size() != 0 &&
1261 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1262 // ... the initializer is e.get<i>().
1263 UseMemberGet = true;
1264 break;
1265 }
1266 }
1267 }
1268 }
1269
1270 unsigned I = 0;
1271 for (auto *B : Bindings) {
1272 InitializingBinding InitContext(S, B);
1273 SourceLocation Loc = B->getLocation();
1274
1275 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1276 if (E.isInvalid())
1277 return true;
1278
1279 // e is an lvalue if the type of the entity is an lvalue reference and
1280 // an xvalue otherwise
1281 if (!Src->getType()->isLValueReferenceType())
1282 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1283 E.get(), nullptr, VK_XValue,
1285
1286 TemplateArgumentListInfo Args(Loc, Loc);
1287 Args.addArgument(
1289
1290 if (UseMemberGet) {
1291 // if [lookup of member get] finds at least one declaration, the
1292 // initializer is e.get<i-1>().
1293 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1294 CXXScopeSpec(), SourceLocation(), nullptr,
1295 MemberGet, &Args, nullptr);
1296 if (E.isInvalid())
1297 return true;
1298
1299 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1300 } else {
1301 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1302 // in the associated namespaces.
1305 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1307 /*KnownDependent=*/false);
1308
1309 Expr *Arg = E.get();
1310 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1311 }
1312 if (E.isInvalid())
1313 return true;
1314 Expr *Init = E.get();
1315
1316 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1317 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1318 if (T.isNull())
1319 return true;
1320
1321 // each vi is a variable of type "reference to T" initialized with the
1322 // initializer, where the reference is an lvalue reference if the
1323 // initializer is an lvalue and an rvalue reference otherwise
1324 QualType RefType =
1325 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1326 if (RefType.isNull())
1327 return true;
1328 auto *RefVD = VarDecl::Create(
1329 S.Context, Src->getDeclContext(), Loc, Loc,
1330 B->getDeclName().getAsIdentifierInfo(), RefType,
1332 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1333 RefVD->setTSCSpec(Src->getTSCSpec());
1334 RefVD->setImplicit();
1335 if (Src->isInlineSpecified())
1336 RefVD->setInlineSpecified();
1337 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1338
1341 InitializationSequence Seq(S, Entity, Kind, Init);
1342 E = Seq.Perform(S, Entity, Kind, Init);
1343 if (E.isInvalid())
1344 return true;
1345 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1346 if (E.isInvalid())
1347 return true;
1348 RefVD->setInit(E.get());
1350
1352 DeclarationNameInfo(B->getDeclName(), Loc),
1353 RefVD);
1354 if (E.isInvalid())
1355 return true;
1356
1357 B->setBinding(T, E.get());
1358 I++;
1359 }
1360
1361 return false;
1362}
1363
1364/// Find the base class to decompose in a built-in decomposition of a class type.
1365/// This base class search is, unfortunately, not quite like any other that we
1366/// perform anywhere else in C++.
1368 const CXXRecordDecl *RD,
1369 CXXCastPath &BasePath) {
1370 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1371 CXXBasePath &Path) {
1372 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1373 };
1374
1375 const CXXRecordDecl *ClassWithFields = nullptr;
1377 if (RD->hasDirectFields())
1378 // [dcl.decomp]p4:
1379 // Otherwise, all of E's non-static data members shall be public direct
1380 // members of E ...
1381 ClassWithFields = RD;
1382 else {
1383 // ... or of ...
1384 CXXBasePaths Paths;
1385 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1386 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1387 // If no classes have fields, just decompose RD itself. (This will work
1388 // if and only if zero bindings were provided.)
1389 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1390 }
1391
1392 CXXBasePath *BestPath = nullptr;
1393 for (auto &P : Paths) {
1394 if (!BestPath)
1395 BestPath = &P;
1396 else if (!S.Context.hasSameType(P.back().Base->getType(),
1397 BestPath->back().Base->getType())) {
1398 // ... the same ...
1399 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1400 << false << RD << BestPath->back().Base->getType()
1401 << P.back().Base->getType();
1402 return DeclAccessPair();
1403 } else if (P.Access < BestPath->Access) {
1404 BestPath = &P;
1405 }
1406 }
1407
1408 // ... unambiguous ...
1409 QualType BaseType = BestPath->back().Base->getType();
1410 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1411 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1412 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1413 return DeclAccessPair();
1414 }
1415
1416 // ... [accessible, implied by other rules] base class of E.
1417 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1418 *BestPath, diag::err_decomp_decl_inaccessible_base);
1419 AS = BestPath->Access;
1420
1421 ClassWithFields = BaseType->getAsCXXRecordDecl();
1422 S.BuildBasePathArray(Paths, BasePath);
1423 }
1424
1425 // The above search did not check whether the selected class itself has base
1426 // classes with fields, so check that now.
1427 CXXBasePaths Paths;
1428 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1429 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1430 << (ClassWithFields == RD) << RD << ClassWithFields
1431 << Paths.front().back().Base->getType();
1432 return DeclAccessPair();
1433 }
1434
1435 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1436}
1437
1439 ValueDecl *Src, QualType DecompType,
1440 const CXXRecordDecl *OrigRD) {
1441 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1442 diag::err_incomplete_type))
1443 return true;
1444
1445 CXXCastPath BasePath;
1446 DeclAccessPair BasePair =
1447 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1448 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1449 if (!RD)
1450 return true;
1452 DecompType.getQualifiers());
1453
1454 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1455 unsigned NumFields = llvm::count_if(
1456 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1457 assert(Bindings.size() != NumFields);
1458 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1459 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1460 << (NumFields < Bindings.size());
1461 return true;
1462 };
1463
1464 // all of E's non-static data members shall be [...] well-formed
1465 // when named as e.name in the context of the structured binding,
1466 // E shall not have an anonymous union member, ...
1467 unsigned I = 0;
1468 for (auto *FD : RD->fields()) {
1469 if (FD->isUnnamedBitField())
1470 continue;
1471
1472 // All the non-static data members are required to be nameable, so they
1473 // must all have names.
1474 if (!FD->getDeclName()) {
1475 if (RD->isLambda()) {
1476 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1477 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1478 return true;
1479 }
1480
1481 if (FD->isAnonymousStructOrUnion()) {
1482 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1483 << DecompType << FD->getType()->isUnionType();
1484 S.Diag(FD->getLocation(), diag::note_declared_at);
1485 return true;
1486 }
1487
1488 // FIXME: Are there any other ways we could have an anonymous member?
1489 }
1490
1491 // We have a real field to bind.
1492 if (I >= Bindings.size())
1493 return DiagnoseBadNumberOfBindings();
1494 auto *B = Bindings[I++];
1495 SourceLocation Loc = B->getLocation();
1496
1497 // The field must be accessible in the context of the structured binding.
1498 // We already checked that the base class is accessible.
1499 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1500 // const_cast here.
1502 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1504 BasePair.getAccess(), FD->getAccess())));
1505
1506 // Initialize the binding to Src.FD.
1507 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1508 if (E.isInvalid())
1509 return true;
1510 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1511 VK_LValue, &BasePath);
1512 if (E.isInvalid())
1513 return true;
1514 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1515 CXXScopeSpec(), FD,
1516 DeclAccessPair::make(FD, FD->getAccess()),
1517 DeclarationNameInfo(FD->getDeclName(), Loc));
1518 if (E.isInvalid())
1519 return true;
1520
1521 // If the type of the member is T, the referenced type is cv T, where cv is
1522 // the cv-qualification of the decomposition expression.
1523 //
1524 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1525 // 'const' to the type of the field.
1526 Qualifiers Q = DecompType.getQualifiers();
1527 if (FD->isMutable())
1528 Q.removeConst();
1529 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1530 }
1531
1532 if (I != Bindings.size())
1533 return DiagnoseBadNumberOfBindings();
1534
1535 return false;
1536}
1537
1539 QualType DecompType = DD->getType();
1540
1541 // If the type of the decomposition is dependent, then so is the type of
1542 // each binding.
1543 if (DecompType->isDependentType()) {
1544 for (auto *B : DD->bindings())
1545 B->setType(Context.DependentTy);
1546 return;
1547 }
1548
1549 DecompType = DecompType.getNonReferenceType();
1551
1552 // C++1z [dcl.decomp]/2:
1553 // If E is an array type [...]
1554 // As an extension, we also support decomposition of built-in complex and
1555 // vector types.
1556 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1557 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1558 DD->setInvalidDecl();
1559 return;
1560 }
1561 if (auto *VT = DecompType->getAs<VectorType>()) {
1562 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1563 DD->setInvalidDecl();
1564 return;
1565 }
1566 if (auto *CT = DecompType->getAs<ComplexType>()) {
1567 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1568 DD->setInvalidDecl();
1569 return;
1570 }
1571
1572 // C++1z [dcl.decomp]/3:
1573 // if the expression std::tuple_size<E>::value is a well-formed integral
1574 // constant expression, [...]
1575 llvm::APSInt TupleSize(32);
1576 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1577 case IsTupleLike::Error:
1578 DD->setInvalidDecl();
1579 return;
1580
1581 case IsTupleLike::TupleLike:
1582 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1583 DD->setInvalidDecl();
1584 return;
1585
1586 case IsTupleLike::NotTupleLike:
1587 break;
1588 }
1589
1590 // C++1z [dcl.dcl]/8:
1591 // [E shall be of array or non-union class type]
1592 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1593 if (!RD || RD->isUnion()) {
1594 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1595 << DD << !RD << DecompType;
1596 DD->setInvalidDecl();
1597 return;
1598 }
1599
1600 // C++1z [dcl.decomp]/4:
1601 // all of E's non-static data members shall be [...] direct members of
1602 // E or of the same unambiguous public base class of E, ...
1603 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1604 DD->setInvalidDecl();
1605}
1606
1607/// Merge the exception specifications of two variable declarations.
1608///
1609/// This is called when there's a redeclaration of a VarDecl. The function
1610/// checks if the redeclaration might have an exception specification and
1611/// validates compatibility and merges the specs if necessary.
1613 // Shortcut if exceptions are disabled.
1614 if (!getLangOpts().CXXExceptions)
1615 return;
1616
1617 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1618 "Should only be called if types are otherwise the same.");
1619
1620 QualType NewType = New->getType();
1621 QualType OldType = Old->getType();
1622
1623 // We're only interested in pointers and references to functions, as well
1624 // as pointers to member functions.
1625 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1626 NewType = R->getPointeeType();
1627 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1628 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1629 NewType = P->getPointeeType();
1630 OldType = OldType->castAs<PointerType>()->getPointeeType();
1631 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1632 NewType = M->getPointeeType();
1633 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1634 }
1635
1636 if (!NewType->isFunctionProtoType())
1637 return;
1638
1639 // There's lots of special cases for functions. For function pointers, system
1640 // libraries are hopefully not as broken so that we don't need these
1641 // workarounds.
1643 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1644 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1645 New->setInvalidDecl();
1646 }
1647}
1648
1649/// CheckCXXDefaultArguments - Verify that the default arguments for a
1650/// function declaration are well-formed according to C++
1651/// [dcl.fct.default].
1653 unsigned NumParams = FD->getNumParams();
1654 unsigned ParamIdx = 0;
1655
1656 // This checking doesn't make sense for explicit specializations; their
1657 // default arguments are determined by the declaration we're specializing,
1658 // not by FD.
1660 return;
1661 if (auto *FTD = FD->getDescribedFunctionTemplate())
1662 if (FTD->isMemberSpecialization())
1663 return;
1664
1665 // Find first parameter with a default argument
1666 for (; ParamIdx < NumParams; ++ParamIdx) {
1667 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1668 if (Param->hasDefaultArg())
1669 break;
1670 }
1671
1672 // C++20 [dcl.fct.default]p4:
1673 // In a given function declaration, each parameter subsequent to a parameter
1674 // with a default argument shall have a default argument supplied in this or
1675 // a previous declaration, unless the parameter was expanded from a
1676 // parameter pack, or shall be a function parameter pack.
1677 for (; ParamIdx < NumParams; ++ParamIdx) {
1678 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1679 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1682 if (Param->isInvalidDecl())
1683 /* We already complained about this parameter. */;
1684 else if (Param->getIdentifier())
1685 Diag(Param->getLocation(),
1686 diag::err_param_default_argument_missing_name)
1687 << Param->getIdentifier();
1688 else
1689 Diag(Param->getLocation(),
1690 diag::err_param_default_argument_missing);
1691 }
1692 }
1693}
1694
1695/// Check that the given type is a literal type. Issue a diagnostic if not,
1696/// if Kind is Diagnose.
1697/// \return \c true if a problem has been found (and optionally diagnosed).
1698template <typename... Ts>
1700 SourceLocation Loc, QualType T, unsigned DiagID,
1701 Ts &&...DiagArgs) {
1702 if (T->isDependentType())
1703 return false;
1704
1705 switch (Kind) {
1707 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1708 std::forward<Ts>(DiagArgs)...);
1709
1711 return !T->isLiteralType(SemaRef.Context);
1712 }
1713
1714 llvm_unreachable("unknown CheckConstexprKind");
1715}
1716
1717/// Determine whether a destructor cannot be constexpr due to
1719 const CXXDestructorDecl *DD,
1721 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1722 "this check is obsolete for C++23");
1723 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1724 const CXXRecordDecl *RD =
1726 if (!RD || RD->hasConstexprDestructor())
1727 return true;
1728
1730 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1731 << static_cast<int>(DD->getConstexprKind()) << !FD
1732 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1733 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1734 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1735 }
1736 return false;
1737 };
1738
1739 const CXXRecordDecl *RD = DD->getParent();
1740 for (const CXXBaseSpecifier &B : RD->bases())
1741 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1742 return false;
1743 for (const FieldDecl *FD : RD->fields())
1744 if (!Check(FD->getLocation(), FD->getType(), FD))
1745 return false;
1746 return true;
1747}
1748
1749/// Check whether a function's parameter types are all literal types. If so,
1750/// return true. If not, produce a suitable diagnostic and return false.
1752 const FunctionDecl *FD,
1754 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1755 "this check is obsolete for C++23");
1756 unsigned ArgIndex = 0;
1757 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1758 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1759 e = FT->param_type_end();
1760 i != e; ++i, ++ArgIndex) {
1761 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1762 assert(PD && "null in a parameter list");
1763 SourceLocation ParamLoc = PD->getLocation();
1764 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1765 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1766 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1767 FD->isConsteval()))
1768 return false;
1769 }
1770 return true;
1771}
1772
1773/// Check whether a function's return type is a literal type. If so, return
1774/// true. If not, produce a suitable diagnostic and return false.
1777 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1778 "this check is obsolete for C++23");
1779 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1780 diag::err_constexpr_non_literal_return,
1781 FD->isConsteval()))
1782 return false;
1783 return true;
1784}
1785
1786/// Get diagnostic %select index for tag kind for
1787/// record diagnostic message.
1788/// WARNING: Indexes apply to particular diagnostics only!
1789///
1790/// \returns diagnostic %select index.
1792 switch (Tag) {
1794 return 0;
1796 return 1;
1797 case TagTypeKind::Class:
1798 return 2;
1799 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1800 }
1801}
1802
1803static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1804 Stmt *Body,
1806
1807// Check whether a function declaration satisfies the requirements of a
1808// constexpr function definition or a constexpr constructor definition. If so,
1809// return true. If not, produce appropriate diagnostics (unless asked not to by
1810// Kind) and return false.
1811//
1812// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1814 CheckConstexprKind Kind) {
1815 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1816 if (MD && MD->isInstance()) {
1817 // C++11 [dcl.constexpr]p4:
1818 // The definition of a constexpr constructor shall satisfy the following
1819 // constraints:
1820 // - the class shall not have any virtual base classes;
1821 //
1822 // FIXME: This only applies to constructors and destructors, not arbitrary
1823 // member functions.
1824 const CXXRecordDecl *RD = MD->getParent();
1825 if (RD->getNumVBases()) {
1827 return false;
1828
1829 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1830 << isa<CXXConstructorDecl>(NewFD)
1832 for (const auto &I : RD->vbases())
1833 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1834 << I.getSourceRange();
1835 return false;
1836 }
1837 }
1838
1839 if (!isa<CXXConstructorDecl>(NewFD)) {
1840 // C++11 [dcl.constexpr]p3:
1841 // The definition of a constexpr function shall satisfy the following
1842 // constraints:
1843 // - it shall not be virtual; (removed in C++20)
1844 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1845 if (Method && Method->isVirtual()) {
1846 if (getLangOpts().CPlusPlus20) {
1847 if (Kind == CheckConstexprKind::Diagnose)
1848 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1849 } else {
1851 return false;
1852
1853 Method = Method->getCanonicalDecl();
1854 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1855
1856 // If it's not obvious why this function is virtual, find an overridden
1857 // function which uses the 'virtual' keyword.
1858 const CXXMethodDecl *WrittenVirtual = Method;
1859 while (!WrittenVirtual->isVirtualAsWritten())
1860 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1861 if (WrittenVirtual != Method)
1862 Diag(WrittenVirtual->getLocation(),
1863 diag::note_overridden_virtual_function);
1864 return false;
1865 }
1866 }
1867
1868 // - its return type shall be a literal type; (removed in C++23)
1869 if (!getLangOpts().CPlusPlus23 &&
1870 !CheckConstexprReturnType(*this, NewFD, Kind))
1871 return false;
1872 }
1873
1874 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1875 // A destructor can be constexpr only if the defaulted destructor could be;
1876 // we don't need to check the members and bases if we already know they all
1877 // have constexpr destructors. (removed in C++23)
1878 if (!getLangOpts().CPlusPlus23 &&
1879 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1881 return false;
1882 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1883 return false;
1884 }
1885 }
1886
1887 // - each of its parameter types shall be a literal type; (removed in C++23)
1888 if (!getLangOpts().CPlusPlus23 &&
1889 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1890 return false;
1891
1892 Stmt *Body = NewFD->getBody();
1893 assert(Body &&
1894 "CheckConstexprFunctionDefinition called on function with no body");
1895 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1896}
1897
1898/// Check the given declaration statement is legal within a constexpr function
1899/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1900///
1901/// \return true if the body is OK (maybe only as an extension), false if we
1902/// have diagnosed a problem.
1904 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1906 // C++11 [dcl.constexpr]p3 and p4:
1907 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1908 // contain only
1909 for (const auto *DclIt : DS->decls()) {
1910 switch (DclIt->getKind()) {
1911 case Decl::StaticAssert:
1912 case Decl::Using:
1913 case Decl::UsingShadow:
1914 case Decl::UsingDirective:
1915 case Decl::UnresolvedUsingTypename:
1916 case Decl::UnresolvedUsingValue:
1917 case Decl::UsingEnum:
1918 // - static_assert-declarations
1919 // - using-declarations,
1920 // - using-directives,
1921 // - using-enum-declaration
1922 continue;
1923
1924 case Decl::Typedef:
1925 case Decl::TypeAlias: {
1926 // - typedef declarations and alias-declarations that do not define
1927 // classes or enumerations,
1928 const auto *TN = cast<TypedefNameDecl>(DclIt);
1929 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1930 // Don't allow variably-modified types in constexpr functions.
1932 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1933 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1934 << TL.getSourceRange() << TL.getType()
1935 << isa<CXXConstructorDecl>(Dcl);
1936 }
1937 return false;
1938 }
1939 continue;
1940 }
1941
1942 case Decl::Enum:
1943 case Decl::CXXRecord:
1944 // C++1y allows types to be defined, not just declared.
1945 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1947 SemaRef.Diag(DS->getBeginLoc(),
1948 SemaRef.getLangOpts().CPlusPlus14
1949 ? diag::warn_cxx11_compat_constexpr_type_definition
1950 : diag::ext_constexpr_type_definition)
1951 << isa<CXXConstructorDecl>(Dcl);
1952 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1953 return false;
1954 }
1955 }
1956 continue;
1957
1958 case Decl::EnumConstant:
1959 case Decl::IndirectField:
1960 case Decl::ParmVar:
1961 // These can only appear with other declarations which are banned in
1962 // C++11 and permitted in C++1y, so ignore them.
1963 continue;
1964
1965 case Decl::Var:
1966 case Decl::Decomposition: {
1967 // C++1y [dcl.constexpr]p3 allows anything except:
1968 // a definition of a variable of non-literal type or of static or
1969 // thread storage duration or [before C++2a] for which no
1970 // initialization is performed.
1971 const auto *VD = cast<VarDecl>(DclIt);
1972 if (VD->isThisDeclarationADefinition()) {
1973 if (VD->isStaticLocal()) {
1975 SemaRef.Diag(VD->getLocation(),
1976 SemaRef.getLangOpts().CPlusPlus23
1977 ? diag::warn_cxx20_compat_constexpr_var
1978 : diag::ext_constexpr_static_var)
1979 << isa<CXXConstructorDecl>(Dcl)
1980 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1981 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1982 return false;
1983 }
1984 }
1985 if (SemaRef.LangOpts.CPlusPlus23) {
1986 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1987 diag::warn_cxx20_compat_constexpr_var,
1988 isa<CXXConstructorDecl>(Dcl),
1989 /*variable of non-literal type*/ 2);
1990 } else if (CheckLiteralType(
1991 SemaRef, Kind, VD->getLocation(), VD->getType(),
1992 diag::err_constexpr_local_var_non_literal_type,
1993 isa<CXXConstructorDecl>(Dcl))) {
1994 return false;
1995 }
1996 if (!VD->getType()->isDependentType() &&
1997 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1999 SemaRef.Diag(
2000 VD->getLocation(),
2001 SemaRef.getLangOpts().CPlusPlus20
2002 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
2003 : diag::ext_constexpr_local_var_no_init)
2004 << isa<CXXConstructorDecl>(Dcl);
2005 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2006 return false;
2007 }
2008 continue;
2009 }
2010 }
2012 SemaRef.Diag(VD->getLocation(),
2013 SemaRef.getLangOpts().CPlusPlus14
2014 ? diag::warn_cxx11_compat_constexpr_local_var
2015 : diag::ext_constexpr_local_var)
2016 << isa<CXXConstructorDecl>(Dcl);
2017 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2018 return false;
2019 }
2020 continue;
2021 }
2022
2023 case Decl::NamespaceAlias:
2024 case Decl::Function:
2025 // These are disallowed in C++11 and permitted in C++1y. Allow them
2026 // everywhere as an extension.
2027 if (!Cxx1yLoc.isValid())
2028 Cxx1yLoc = DS->getBeginLoc();
2029 continue;
2030
2031 default:
2033 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2034 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2035 }
2036 return false;
2037 }
2038 }
2039
2040 return true;
2041}
2042
2043/// Check that the given field is initialized within a constexpr constructor.
2044///
2045/// \param Dcl The constexpr constructor being checked.
2046/// \param Field The field being checked. This may be a member of an anonymous
2047/// struct or union nested within the class being checked.
2048/// \param Inits All declarations, including anonymous struct/union members and
2049/// indirect members, for which any initialization was provided.
2050/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2051/// multiple notes for different members to the same error.
2052/// \param Kind Whether we're diagnosing a constructor as written or determining
2053/// whether the formal requirements are satisfied.
2054/// \return \c false if we're checking for validity and the constructor does
2055/// not satisfy the requirements on a constexpr constructor.
2057 const FunctionDecl *Dcl,
2058 FieldDecl *Field,
2059 llvm::SmallSet<Decl*, 16> &Inits,
2060 bool &Diagnosed,
2062 // In C++20 onwards, there's nothing to check for validity.
2064 SemaRef.getLangOpts().CPlusPlus20)
2065 return true;
2066
2067 if (Field->isInvalidDecl())
2068 return true;
2069
2070 if (Field->isUnnamedBitField())
2071 return true;
2072
2073 // Anonymous unions with no variant members and empty anonymous structs do not
2074 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2075 // indirect fields don't need initializing.
2076 if (Field->isAnonymousStructOrUnion() &&
2077 (Field->getType()->isUnionType()
2078 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2079 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2080 return true;
2081
2082 if (!Inits.count(Field)) {
2084 if (!Diagnosed) {
2085 SemaRef.Diag(Dcl->getLocation(),
2086 SemaRef.getLangOpts().CPlusPlus20
2087 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2088 : diag::ext_constexpr_ctor_missing_init);
2089 Diagnosed = true;
2090 }
2091 SemaRef.Diag(Field->getLocation(),
2092 diag::note_constexpr_ctor_missing_init);
2093 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2094 return false;
2095 }
2096 } else if (Field->isAnonymousStructOrUnion()) {
2097 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2098 for (auto *I : RD->fields())
2099 // If an anonymous union contains an anonymous struct of which any member
2100 // is initialized, all members must be initialized.
2101 if (!RD->isUnion() || Inits.count(I))
2102 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2103 Kind))
2104 return false;
2105 }
2106 return true;
2107}
2108
2109/// Check the provided statement is allowed in a constexpr function
2110/// definition.
2111static bool
2114 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2115 SourceLocation &Cxx2bLoc,
2117 // - its function-body shall be [...] a compound-statement that contains only
2118 switch (S->getStmtClass()) {
2119 case Stmt::NullStmtClass:
2120 // - null statements,
2121 return true;
2122
2123 case Stmt::DeclStmtClass:
2124 // - static_assert-declarations
2125 // - using-declarations,
2126 // - using-directives,
2127 // - typedef declarations and alias-declarations that do not define
2128 // classes or enumerations,
2129 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2130 return false;
2131 return true;
2132
2133 case Stmt::ReturnStmtClass:
2134 // - and exactly one return statement;
2135 if (isa<CXXConstructorDecl>(Dcl)) {
2136 // C++1y allows return statements in constexpr constructors.
2137 if (!Cxx1yLoc.isValid())
2138 Cxx1yLoc = S->getBeginLoc();
2139 return true;
2140 }
2141
2142 ReturnStmts.push_back(S->getBeginLoc());
2143 return true;
2144
2145 case Stmt::AttributedStmtClass:
2146 // Attributes on a statement don't affect its formal kind and hence don't
2147 // affect its validity in a constexpr function.
2149 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2150 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2151
2152 case Stmt::CompoundStmtClass: {
2153 // C++1y allows compound-statements.
2154 if (!Cxx1yLoc.isValid())
2155 Cxx1yLoc = S->getBeginLoc();
2156
2157 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2158 for (auto *BodyIt : CompStmt->body()) {
2159 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2160 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2161 return false;
2162 }
2163 return true;
2164 }
2165
2166 case Stmt::IfStmtClass: {
2167 // C++1y allows if-statements.
2168 if (!Cxx1yLoc.isValid())
2169 Cxx1yLoc = S->getBeginLoc();
2170
2171 IfStmt *If = cast<IfStmt>(S);
2172 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2173 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2174 return false;
2175 if (If->getElse() &&
2176 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2177 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2178 return false;
2179 return true;
2180 }
2181
2182 case Stmt::WhileStmtClass:
2183 case Stmt::DoStmtClass:
2184 case Stmt::ForStmtClass:
2185 case Stmt::CXXForRangeStmtClass:
2186 case Stmt::ContinueStmtClass:
2187 // C++1y allows all of these. We don't allow them as extensions in C++11,
2188 // because they don't make sense without variable mutation.
2189 if (!SemaRef.getLangOpts().CPlusPlus14)
2190 break;
2191 if (!Cxx1yLoc.isValid())
2192 Cxx1yLoc = S->getBeginLoc();
2193 for (Stmt *SubStmt : S->children()) {
2194 if (SubStmt &&
2195 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2196 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2197 return false;
2198 }
2199 return true;
2200
2201 case Stmt::SwitchStmtClass:
2202 case Stmt::CaseStmtClass:
2203 case Stmt::DefaultStmtClass:
2204 case Stmt::BreakStmtClass:
2205 // C++1y allows switch-statements, and since they don't need variable
2206 // mutation, we can reasonably allow them in C++11 as an extension.
2207 if (!Cxx1yLoc.isValid())
2208 Cxx1yLoc = S->getBeginLoc();
2209 for (Stmt *SubStmt : S->children()) {
2210 if (SubStmt &&
2211 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2212 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2213 return false;
2214 }
2215 return true;
2216
2217 case Stmt::LabelStmtClass:
2218 case Stmt::GotoStmtClass:
2219 if (Cxx2bLoc.isInvalid())
2220 Cxx2bLoc = S->getBeginLoc();
2221 for (Stmt *SubStmt : S->children()) {
2222 if (SubStmt &&
2223 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2224 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2225 return false;
2226 }
2227 return true;
2228
2229 case Stmt::GCCAsmStmtClass:
2230 case Stmt::MSAsmStmtClass:
2231 // C++2a allows inline assembly statements.
2232 case Stmt::CXXTryStmtClass:
2233 if (Cxx2aLoc.isInvalid())
2234 Cxx2aLoc = S->getBeginLoc();
2235 for (Stmt *SubStmt : S->children()) {
2236 if (SubStmt &&
2237 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2238 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2239 return false;
2240 }
2241 return true;
2242
2243 case Stmt::CXXCatchStmtClass:
2244 // Do not bother checking the language mode (already covered by the
2245 // try block check).
2247 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2248 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2249 return false;
2250 return true;
2251
2252 default:
2253 if (!isa<Expr>(S))
2254 break;
2255
2256 // C++1y allows expression-statements.
2257 if (!Cxx1yLoc.isValid())
2258 Cxx1yLoc = S->getBeginLoc();
2259 return true;
2260 }
2261
2263 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2264 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2265 }
2266 return false;
2267}
2268
2269/// Check the body for the given constexpr function declaration only contains
2270/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2271///
2272/// \return true if the body is OK, false if we have found or diagnosed a
2273/// problem.
2275 Stmt *Body,
2278
2279 if (isa<CXXTryStmt>(Body)) {
2280 // C++11 [dcl.constexpr]p3:
2281 // The definition of a constexpr function shall satisfy the following
2282 // constraints: [...]
2283 // - its function-body shall be = delete, = default, or a
2284 // compound-statement
2285 //
2286 // C++11 [dcl.constexpr]p4:
2287 // In the definition of a constexpr constructor, [...]
2288 // - its function-body shall not be a function-try-block;
2289 //
2290 // This restriction is lifted in C++2a, as long as inner statements also
2291 // apply the general constexpr rules.
2292 switch (Kind) {
2294 if (!SemaRef.getLangOpts().CPlusPlus20)
2295 return false;
2296 break;
2297
2299 SemaRef.Diag(Body->getBeginLoc(),
2300 !SemaRef.getLangOpts().CPlusPlus20
2301 ? diag::ext_constexpr_function_try_block_cxx20
2302 : diag::warn_cxx17_compat_constexpr_function_try_block)
2303 << isa<CXXConstructorDecl>(Dcl);
2304 break;
2305 }
2306 }
2307
2308 // - its function-body shall be [...] a compound-statement that contains only
2309 // [... list of cases ...]
2310 //
2311 // Note that walking the children here is enough to properly check for
2312 // CompoundStmt and CXXTryStmt body.
2313 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2314 for (Stmt *SubStmt : Body->children()) {
2315 if (SubStmt &&
2316 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2317 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2318 return false;
2319 }
2320
2322 // If this is only valid as an extension, report that we don't satisfy the
2323 // constraints of the current language.
2324 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2325 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2326 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2327 return false;
2328 } else if (Cxx2bLoc.isValid()) {
2329 SemaRef.Diag(Cxx2bLoc,
2330 SemaRef.getLangOpts().CPlusPlus23
2331 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2332 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2333 << isa<CXXConstructorDecl>(Dcl);
2334 } else if (Cxx2aLoc.isValid()) {
2335 SemaRef.Diag(Cxx2aLoc,
2336 SemaRef.getLangOpts().CPlusPlus20
2337 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2338 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2339 << isa<CXXConstructorDecl>(Dcl);
2340 } else if (Cxx1yLoc.isValid()) {
2341 SemaRef.Diag(Cxx1yLoc,
2342 SemaRef.getLangOpts().CPlusPlus14
2343 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2344 : diag::ext_constexpr_body_invalid_stmt)
2345 << isa<CXXConstructorDecl>(Dcl);
2346 }
2347
2348 if (const CXXConstructorDecl *Constructor
2349 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2350 const CXXRecordDecl *RD = Constructor->getParent();
2351 // DR1359:
2352 // - every non-variant non-static data member and base class sub-object
2353 // shall be initialized;
2354 // DR1460:
2355 // - if the class is a union having variant members, exactly one of them
2356 // shall be initialized;
2357 if (RD->isUnion()) {
2358 if (Constructor->getNumCtorInitializers() == 0 &&
2359 RD->hasVariantMembers()) {
2361 SemaRef.Diag(
2362 Dcl->getLocation(),
2363 SemaRef.getLangOpts().CPlusPlus20
2364 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2365 : diag::ext_constexpr_union_ctor_no_init);
2366 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2367 return false;
2368 }
2369 }
2370 } else if (!Constructor->isDependentContext() &&
2371 !Constructor->isDelegatingConstructor()) {
2372 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2373
2374 // Skip detailed checking if we have enough initializers, and we would
2375 // allow at most one initializer per member.
2376 bool AnyAnonStructUnionMembers = false;
2377 unsigned Fields = 0;
2379 E = RD->field_end(); I != E; ++I, ++Fields) {
2380 if (I->isAnonymousStructOrUnion()) {
2381 AnyAnonStructUnionMembers = true;
2382 break;
2383 }
2384 }
2385 // DR1460:
2386 // - if the class is a union-like class, but is not a union, for each of
2387 // its anonymous union members having variant members, exactly one of
2388 // them shall be initialized;
2389 if (AnyAnonStructUnionMembers ||
2390 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2391 // Check initialization of non-static data members. Base classes are
2392 // always initialized so do not need to be checked. Dependent bases
2393 // might not have initializers in the member initializer list.
2394 llvm::SmallSet<Decl*, 16> Inits;
2395 for (const auto *I: Constructor->inits()) {
2396 if (FieldDecl *FD = I->getMember())
2397 Inits.insert(FD);
2398 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2399 Inits.insert(ID->chain_begin(), ID->chain_end());
2400 }
2401
2402 bool Diagnosed = false;
2403 for (auto *I : RD->fields())
2404 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2405 Kind))
2406 return false;
2407 }
2408 }
2409 } else {
2410 if (ReturnStmts.empty()) {
2411 // C++1y doesn't require constexpr functions to contain a 'return'
2412 // statement. We still do, unless the return type might be void, because
2413 // otherwise if there's no return statement, the function cannot
2414 // be used in a core constant expression.
2415 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2416 (Dcl->getReturnType()->isVoidType() ||
2417 Dcl->getReturnType()->isDependentType());
2418 switch (Kind) {
2420 SemaRef.Diag(Dcl->getLocation(),
2421 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2422 : diag::err_constexpr_body_no_return)
2423 << Dcl->isConsteval();
2424 if (!OK)
2425 return false;
2426 break;
2427
2429 // The formal requirements don't include this rule in C++14, even
2430 // though the "must be able to produce a constant expression" rules
2431 // still imply it in some cases.
2432 if (!SemaRef.getLangOpts().CPlusPlus14)
2433 return false;
2434 break;
2435 }
2436 } else if (ReturnStmts.size() > 1) {
2437 switch (Kind) {
2439 SemaRef.Diag(
2440 ReturnStmts.back(),
2441 SemaRef.getLangOpts().CPlusPlus14
2442 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2443 : diag::ext_constexpr_body_multiple_return);
2444 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2445 SemaRef.Diag(ReturnStmts[I],
2446 diag::note_constexpr_body_previous_return);
2447 break;
2448
2450 if (!SemaRef.getLangOpts().CPlusPlus14)
2451 return false;
2452 break;
2453 }
2454 }
2455 }
2456
2457 // C++11 [dcl.constexpr]p5:
2458 // if no function argument values exist such that the function invocation
2459 // substitution would produce a constant expression, the program is
2460 // ill-formed; no diagnostic required.
2461 // C++11 [dcl.constexpr]p3:
2462 // - every constructor call and implicit conversion used in initializing the
2463 // return value shall be one of those allowed in a constant expression.
2464 // C++11 [dcl.constexpr]p4:
2465 // - every constructor involved in initializing non-static data members and
2466 // base class sub-objects shall be a constexpr constructor.
2467 //
2468 // Note that this rule is distinct from the "requirements for a constexpr
2469 // function", so is not checked in CheckValid mode.
2473 !SemaRef.getLangOpts().CPlusPlus23) {
2474 SemaRef.Diag(Dcl->getLocation(),
2475 diag::ext_constexpr_function_never_constant_expr)
2476 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2477 << Dcl->getNameInfo().getSourceRange();
2478 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2479 SemaRef.Diag(Diags[I].first, Diags[I].second);
2480 // Don't return false here: we allow this for compatibility in
2481 // system headers.
2482 }
2483
2484 return true;
2485}
2486
2488 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2490 return true;
2494 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2495 if (it != UndefinedButUsed.end()) {
2496 Diag(it->second, diag::err_immediate_function_used_before_definition)
2497 << it->first;
2498 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2499 if (FD->isImmediateFunction() && !FD->isConsteval())
2501 return false;
2502 }
2503 }
2504 return true;
2505}
2506
2508 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2509 "expected an immediate function");
2510 assert(FD->hasBody() && "expected the function to have a body");
2511 struct ImmediateEscalatingExpressionsVisitor
2512 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2513
2515 Sema &SemaRef;
2516
2517 const FunctionDecl *ImmediateFn;
2518 bool ImmediateFnIsConstructor;
2519 CXXConstructorDecl *CurrentConstructor = nullptr;
2520 CXXCtorInitializer *CurrentInit = nullptr;
2521
2522 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2523 : SemaRef(SemaRef), ImmediateFn(FD),
2524 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2525
2526 bool shouldVisitImplicitCode() const { return true; }
2527 bool shouldVisitLambdaBody() const { return false; }
2528
2529 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2530 SourceLocation Loc = E->getBeginLoc();
2531 SourceRange Range = E->getSourceRange();
2532 if (CurrentConstructor && CurrentInit) {
2533 Loc = CurrentConstructor->getLocation();
2534 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2535 : SourceRange();
2536 }
2537
2538 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2539
2540 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2541 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2542 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2543 << (InitializedField != nullptr)
2544 << (CurrentInit && !CurrentInit->isWritten())
2545 << InitializedField << Range;
2546 }
2547 bool TraverseCallExpr(CallExpr *E) {
2548 if (const auto *DR =
2549 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2550 DR && DR->isImmediateEscalating()) {
2551 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2552 return false;
2553 }
2554
2555 for (Expr *A : E->arguments())
2556 if (!getDerived().TraverseStmt(A))
2557 return false;
2558
2559 return true;
2560 }
2561
2562 bool VisitDeclRefExpr(DeclRefExpr *E) {
2563 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2564 ReferencedFn && E->isImmediateEscalating()) {
2565 Diag(E, ReferencedFn, /*IsCall=*/false);
2566 return false;
2567 }
2568
2569 return true;
2570 }
2571
2572 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2574 if (E->isImmediateEscalating()) {
2575 Diag(E, D, /*IsCall=*/true);
2576 return false;
2577 }
2578 return true;
2579 }
2580
2581 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2582 llvm::SaveAndRestore RAII(CurrentInit, Init);
2583 return Base::TraverseConstructorInitializer(Init);
2584 }
2585
2586 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2587 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2588 return Base::TraverseCXXConstructorDecl(Ctr);
2589 }
2590
2591 bool TraverseType(QualType T) { return true; }
2592 bool VisitBlockExpr(BlockExpr *T) { return true; }
2593
2594 } Visitor(*this, FD);
2595 Visitor.TraverseDecl(FD);
2596}
2597
2598/// Get the class that is directly named by the current context. This is the
2599/// class for which an unqualified-id in this scope could name a constructor
2600/// or destructor.
2601///
2602/// If the scope specifier denotes a class, this will be that class.
2603/// If the scope specifier is empty, this will be the class whose
2604/// member-specification we are currently within. Otherwise, there
2605/// is no such class.
2607 assert(getLangOpts().CPlusPlus && "No class names in C!");
2608
2609 if (SS && SS->isInvalid())
2610 return nullptr;
2611
2612 if (SS && SS->isNotEmpty()) {
2613 DeclContext *DC = computeDeclContext(*SS, true);
2614 return dyn_cast_or_null<CXXRecordDecl>(DC);
2615 }
2616
2617 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2618}
2619
2620/// isCurrentClassName - Determine whether the identifier II is the
2621/// name of the class type currently being defined. In the case of
2622/// nested classes, this will only return true if II is the name of
2623/// the innermost class.
2625 const CXXScopeSpec *SS) {
2626 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2627 return CurDecl && &II == CurDecl->getIdentifier();
2628}
2629
2630/// Determine whether the identifier II is a typo for the name of
2631/// the class type currently being defined. If so, update it to the identifier
2632/// that should have been used.
2634 assert(getLangOpts().CPlusPlus && "No class names in C!");
2635
2636 if (!getLangOpts().SpellChecking)
2637 return false;
2638
2639 CXXRecordDecl *CurDecl;
2640 if (SS && SS->isSet() && !SS->isInvalid()) {
2641 DeclContext *DC = computeDeclContext(*SS, true);
2642 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2643 } else
2644 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2645
2646 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2647 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2648 < II->getLength()) {
2649 II = CurDecl->getIdentifier();
2650 return true;
2651 }
2652
2653 return false;
2654}
2655
2656/// Determine whether the given class is a base class of the given
2657/// class, including looking at dependent bases.
2659 const CXXRecordDecl *Current) {
2661
2662 Class = Class->getCanonicalDecl();
2663 while (true) {
2664 for (const auto &I : Current->bases()) {
2665 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2666 if (!Base)
2667 continue;
2668
2669 Base = Base->getDefinition();
2670 if (!Base)
2671 continue;
2672
2673 if (Base->getCanonicalDecl() == Class)
2674 return true;
2675
2676 Queue.push_back(Base);
2677 }
2678
2679 if (Queue.empty())
2680 return false;
2681
2682 Current = Queue.pop_back_val();
2683 }
2684
2685 return false;
2686}
2687
2688/// Check the validity of a C++ base class specifier.
2689///
2690/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2691/// and returns NULL otherwise.
2694 SourceRange SpecifierRange,
2695 bool Virtual, AccessSpecifier Access,
2696 TypeSourceInfo *TInfo,
2697 SourceLocation EllipsisLoc) {
2698 // In HLSL, unspecified class access is public rather than private.
2699 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2700 Access == AS_none)
2701 Access = AS_public;
2702
2703 QualType BaseType = TInfo->getType();
2704 if (BaseType->containsErrors()) {
2705 // Already emitted a diagnostic when parsing the error type.
2706 return nullptr;
2707 }
2708 // C++ [class.union]p1:
2709 // A union shall not have base classes.
2710 if (Class->isUnion()) {
2711 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2712 << SpecifierRange;
2713 return nullptr;
2714 }
2715
2716 if (EllipsisLoc.isValid() &&
2718 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2719 << TInfo->getTypeLoc().getSourceRange();
2720 EllipsisLoc = SourceLocation();
2721 }
2722
2723 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2724
2725 if (BaseType->isDependentType()) {
2726 // Make sure that we don't have circular inheritance among our dependent
2727 // bases. For non-dependent bases, the check for completeness below handles
2728 // this.
2729 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2730 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2731 ((BaseDecl = BaseDecl->getDefinition()) &&
2732 findCircularInheritance(Class, BaseDecl))) {
2733 Diag(BaseLoc, diag::err_circular_inheritance)
2734 << BaseType << Context.getTypeDeclType(Class);
2735
2736 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2737 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2738 << BaseType;
2739
2740 return nullptr;
2741 }
2742 }
2743
2744 // Make sure that we don't make an ill-formed AST where the type of the
2745 // Class is non-dependent and its attached base class specifier is an
2746 // dependent type, which violates invariants in many clang code paths (e.g.
2747 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2748 // explicitly mark the Class decl invalid. The diagnostic was already
2749 // emitted.
2750 if (!Class->getTypeForDecl()->isDependentType())
2751 Class->setInvalidDecl();
2752 return new (Context) CXXBaseSpecifier(
2753 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2754 Access, TInfo, EllipsisLoc);
2755 }
2756
2757 // Base specifiers must be record types.
2758 if (!BaseType->isRecordType()) {
2759 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2760 return nullptr;
2761 }
2762
2763 // C++ [class.union]p1:
2764 // A union shall not be used as a base class.
2765 if (BaseType->isUnionType()) {
2766 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2767 return nullptr;
2768 }
2769
2770 // For the MS ABI, propagate DLL attributes to base class templates.
2772 Context.getTargetInfo().getTriple().isPS()) {
2773 if (Attr *ClassAttr = getDLLAttr(Class)) {
2774 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2775 BaseType->getAsCXXRecordDecl())) {
2776 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2777 BaseLoc);
2778 }
2779 }
2780 }
2781
2782 // C++ [class.derived]p2:
2783 // The class-name in a base-specifier shall not be an incompletely
2784 // defined class.
2785 if (RequireCompleteType(BaseLoc, BaseType,
2786 diag::err_incomplete_base_class, SpecifierRange)) {
2787 Class->setInvalidDecl();
2788 return nullptr;
2789 }
2790
2791 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2792 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2793 assert(BaseDecl && "Record type has no declaration");
2794 BaseDecl = BaseDecl->getDefinition();
2795 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2796 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2797 assert(CXXBaseDecl && "Base type is not a C++ type");
2798
2799 // Microsoft docs say:
2800 // "If a base-class has a code_seg attribute, derived classes must have the
2801 // same attribute."
2802 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2803 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2804 if ((DerivedCSA || BaseCSA) &&
2805 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2806 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2807 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2808 << CXXBaseDecl;
2809 return nullptr;
2810 }
2811
2812 // A class which contains a flexible array member is not suitable for use as a
2813 // base class:
2814 // - If the layout determines that a base comes before another base,
2815 // the flexible array member would index into the subsequent base.
2816 // - If the layout determines that base comes before the derived class,
2817 // the flexible array member would index into the derived class.
2818 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2819 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2820 << CXXBaseDecl->getDeclName();
2821 return nullptr;
2822 }
2823
2824 // C++ [class]p3:
2825 // If a class is marked final and it appears as a base-type-specifier in
2826 // base-clause, the program is ill-formed.
2827 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2828 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2829 << CXXBaseDecl->getDeclName()
2830 << FA->isSpelledAsSealed();
2831 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2832 << CXXBaseDecl->getDeclName() << FA->getRange();
2833 return nullptr;
2834 }
2835
2836 if (BaseDecl->isInvalidDecl())
2837 Class->setInvalidDecl();
2838
2839 // Create the base specifier.
2840 return new (Context) CXXBaseSpecifier(
2841 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2842 Access, TInfo, EllipsisLoc);
2843}
2844
2845/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2846/// one entry in the base class list of a class specifier, for
2847/// example:
2848/// class foo : public bar, virtual private baz {
2849/// 'public bar' and 'virtual private baz' are each base-specifiers.
2851 const ParsedAttributesView &Attributes,
2852 bool Virtual, AccessSpecifier Access,
2853 ParsedType basetype, SourceLocation BaseLoc,
2854 SourceLocation EllipsisLoc) {
2855 if (!classdecl)
2856 return true;
2857
2858 AdjustDeclIfTemplate(classdecl);
2859 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2860 if (!Class)
2861 return true;
2862
2863 // We haven't yet attached the base specifiers.
2864 Class->setIsParsingBaseSpecifiers();
2865
2866 // We do not support any C++11 attributes on base-specifiers yet.
2867 // Diagnose any attributes we see.
2868 for (const ParsedAttr &AL : Attributes) {
2869 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2870 continue;
2871 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2872 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2873 << AL << AL.getRange();
2874 else
2875 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2876 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2877 }
2878
2879 TypeSourceInfo *TInfo = nullptr;
2880 GetTypeFromParser(basetype, &TInfo);
2881
2882 if (EllipsisLoc.isInvalid() &&
2883 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2885 return true;
2886
2887 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2888 Virtual, Access, TInfo,
2889 EllipsisLoc))
2890 return BaseSpec;
2891 else
2892 Class->setInvalidDecl();
2893
2894 return true;
2895}
2896
2897/// Use small set to collect indirect bases. As this is only used
2898/// locally, there's no need to abstract the small size parameter.
2900
2901/// Recursively add the bases of Type. Don't add Type itself.
2902static void
2904 const QualType &Type)
2905{
2906 // Even though the incoming type is a base, it might not be
2907 // a class -- it could be a template parm, for instance.
2908 if (auto Rec = Type->getAs<RecordType>()) {
2909 auto Decl = Rec->getAsCXXRecordDecl();
2910
2911 // Iterate over its bases.
2912 for (const auto &BaseSpec : Decl->bases()) {
2913 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2915 if (Set.insert(Base).second)
2916 // If we've not already seen it, recurse.
2918 }
2919 }
2920}
2921
2922/// Performs the actual work of attaching the given base class
2923/// specifiers to a C++ class.
2926 if (Bases.empty())
2927 return false;
2928
2929 // Used to keep track of which base types we have already seen, so
2930 // that we can properly diagnose redundant direct base types. Note
2931 // that the key is always the unqualified canonical type of the base
2932 // class.
2933 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2934
2935 // Used to track indirect bases so we can see if a direct base is
2936 // ambiguous.
2937 IndirectBaseSet IndirectBaseTypes;
2938
2939 // Copy non-redundant base specifiers into permanent storage.
2940 unsigned NumGoodBases = 0;
2941 bool Invalid = false;
2942 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2943 QualType NewBaseType
2944 = Context.getCanonicalType(Bases[idx]->getType());
2945 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2946
2947 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2948 if (KnownBase) {
2949 // C++ [class.mi]p3:
2950 // A class shall not be specified as a direct base class of a
2951 // derived class more than once.
2952 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2953 << KnownBase->getType() << Bases[idx]->getSourceRange();
2954
2955 // Delete the duplicate base class specifier; we're going to
2956 // overwrite its pointer later.
2957 Context.Deallocate(Bases[idx]);
2958
2959 Invalid = true;
2960 } else {
2961 // Okay, add this new base class.
2962 KnownBase = Bases[idx];
2963 Bases[NumGoodBases++] = Bases[idx];
2964
2965 if (NewBaseType->isDependentType())
2966 continue;
2967 // Note this base's direct & indirect bases, if there could be ambiguity.
2968 if (Bases.size() > 1)
2969 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2970
2971 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2972 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2973 if (Class->isInterface() &&
2974 (!RD->isInterfaceLike() ||
2975 KnownBase->getAccessSpecifier() != AS_public)) {
2976 // The Microsoft extension __interface does not permit bases that
2977 // are not themselves public interfaces.
2978 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2979 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2980 << RD->getSourceRange();
2981 Invalid = true;
2982 }
2983 if (RD->hasAttr<WeakAttr>())
2984 Class->addAttr(WeakAttr::CreateImplicit(Context));
2985 }
2986 }
2987 }
2988
2989 // Attach the remaining base class specifiers to the derived class.
2990 Class->setBases(Bases.data(), NumGoodBases);
2991
2992 // Check that the only base classes that are duplicate are virtual.
2993 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2994 // Check whether this direct base is inaccessible due to ambiguity.
2995 QualType BaseType = Bases[idx]->getType();
2996
2997 // Skip all dependent types in templates being used as base specifiers.
2998 // Checks below assume that the base specifier is a CXXRecord.
2999 if (BaseType->isDependentType())
3000 continue;
3001
3002 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3004
3005 if (IndirectBaseTypes.count(CanonicalBase)) {
3006 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3007 /*DetectVirtual=*/true);
3008 bool found
3009 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3010 assert(found);
3011 (void)found;
3012
3013 if (Paths.isAmbiguous(CanonicalBase))
3014 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3015 << BaseType << getAmbiguousPathsDisplayString(Paths)
3016 << Bases[idx]->getSourceRange();
3017 else
3018 assert(Bases[idx]->isVirtual());
3019 }
3020
3021 // Delete the base class specifier, since its data has been copied
3022 // into the CXXRecordDecl.
3023 Context.Deallocate(Bases[idx]);
3024 }
3025
3026 return Invalid;
3027}
3028
3029/// ActOnBaseSpecifiers - Attach the given base specifiers to the
3030/// class, after checking whether there are any duplicate base
3031/// classes.
3034 if (!ClassDecl || Bases.empty())
3035 return;
3036
3037 AdjustDeclIfTemplate(ClassDecl);
3038 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3039}
3040
3041/// Determine whether the type \p Derived is a C++ class that is
3042/// derived from the type \p Base.
3044 if (!getLangOpts().CPlusPlus)
3045 return false;
3046
3047 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3048 if (!DerivedRD)
3049 return false;
3050
3051 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3052 if (!BaseRD)
3053 return false;
3054
3055 // If either the base or the derived type is invalid, don't try to
3056 // check whether one is derived from the other.
3057 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3058 return false;
3059
3060 // FIXME: In a modules build, do we need the entire path to be visible for us
3061 // to be able to use the inheritance relationship?
3062 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3063 return false;
3064
3065 return DerivedRD->isDerivedFrom(BaseRD);
3066}
3067
3068/// Determine whether the type \p Derived is a C++ class that is
3069/// derived from the type \p Base.
3071 CXXBasePaths &Paths) {
3072 if (!getLangOpts().CPlusPlus)
3073 return false;
3074
3075 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3076 if (!DerivedRD)
3077 return false;
3078
3079 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3080 if (!BaseRD)
3081 return false;
3082
3083 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3084 return false;
3085
3086 return DerivedRD->isDerivedFrom(BaseRD, Paths);
3087}
3088
3089static void BuildBasePathArray(const CXXBasePath &Path,
3090 CXXCastPath &BasePathArray) {
3091 // We first go backward and check if we have a virtual base.
3092 // FIXME: It would be better if CXXBasePath had the base specifier for
3093 // the nearest virtual base.
3094 unsigned Start = 0;
3095 for (unsigned I = Path.size(); I != 0; --I) {
3096 if (Path[I - 1].Base->isVirtual()) {
3097 Start = I - 1;
3098 break;
3099 }
3100 }
3101
3102 // Now add all bases.
3103 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3104 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3105}
3106
3107
3109 CXXCastPath &BasePathArray) {
3110 assert(BasePathArray.empty() && "Base path array must be empty!");
3111 assert(Paths.isRecordingPaths() && "Must record paths!");
3112 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3113}
3114/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3115/// conversion (where Derived and Base are class types) is
3116/// well-formed, meaning that the conversion is unambiguous (and
3117/// that all of the base classes are accessible). Returns true
3118/// and emits a diagnostic if the code is ill-formed, returns false
3119/// otherwise. Loc is the location where this routine should point to
3120/// if there is an error, and Range is the source range to highlight
3121/// if there is an error.
3122///
3123/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3124/// diagnostic for the respective type of error will be suppressed, but the
3125/// check for ill-formed code will still be performed.
3126bool
3128 unsigned InaccessibleBaseID,
3129 unsigned AmbiguousBaseConvID,
3130 SourceLocation Loc, SourceRange Range,
3131 DeclarationName Name,
3132 CXXCastPath *BasePath,
3133 bool IgnoreAccess) {
3134 // First, determine whether the path from Derived to Base is
3135 // ambiguous. This is slightly more expensive than checking whether
3136 // the Derived to Base conversion exists, because here we need to
3137 // explore multiple paths to determine if there is an ambiguity.
3138 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3139 /*DetectVirtual=*/false);
3140 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3141 if (!DerivationOkay)
3142 return true;
3143
3144 const CXXBasePath *Path = nullptr;
3145 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3146 Path = &Paths.front();
3147
3148 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3149 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3150 // user to access such bases.
3151 if (!Path && getLangOpts().MSVCCompat) {
3152 for (const CXXBasePath &PossiblePath : Paths) {
3153 if (PossiblePath.size() == 1) {
3154 Path = &PossiblePath;
3155 if (AmbiguousBaseConvID)
3156 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3157 << Base << Derived << Range;
3158 break;
3159 }
3160 }
3161 }
3162
3163 if (Path) {
3164 if (!IgnoreAccess) {
3165 // Check that the base class can be accessed.
3166 switch (
3167 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3168 case AR_inaccessible:
3169 return true;
3170 case AR_accessible:
3171 case AR_dependent:
3172 case AR_delayed:
3173 break;
3174 }
3175 }
3176
3177 // Build a base path if necessary.
3178 if (BasePath)
3179 ::BuildBasePathArray(*Path, *BasePath);
3180 return false;
3181 }
3182
3183 if (AmbiguousBaseConvID) {
3184 // We know that the derived-to-base conversion is ambiguous, and
3185 // we're going to produce a diagnostic. Perform the derived-to-base
3186 // search just one more time to compute all of the possible paths so
3187 // that we can print them out. This is more expensive than any of
3188 // the previous derived-to-base checks we've done, but at this point
3189 // performance isn't as much of an issue.
3190 Paths.clear();
3191 Paths.setRecordingPaths(true);
3192 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3193 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3194 (void)StillOkay;
3195
3196 // Build up a textual representation of the ambiguous paths, e.g.,
3197 // D -> B -> A, that will be used to illustrate the ambiguous
3198 // conversions in the diagnostic. We only print one of the paths
3199 // to each base class subobject.
3200 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3201
3202 Diag(Loc, AmbiguousBaseConvID)
3203 << Derived << Base << PathDisplayStr << Range << Name;
3204 }
3205 return true;
3206}
3207
3208bool
3210 SourceLocation Loc, SourceRange Range,
3211 CXXCastPath *BasePath,
3212 bool IgnoreAccess) {
3214 Derived, Base, diag::err_upcast_to_inaccessible_base,
3215 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3216 BasePath, IgnoreAccess);
3217}
3218
3219
3220/// Builds a string representing ambiguous paths from a
3221/// specific derived class to different subobjects of the same base
3222/// class.
3223///
3224/// This function builds a string that can be used in error messages
3225/// to show the different paths that one can take through the
3226/// inheritance hierarchy to go from the derived class to different
3227/// subobjects of a base class. The result looks something like this:
3228/// @code
3229/// struct D -> struct B -> struct A
3230/// struct D -> struct C -> struct A
3231/// @endcode
3233 std::string PathDisplayStr;
3234 std::set<unsigned> DisplayedPaths;
3235 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3236 Path != Paths.end(); ++Path) {
3237 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3238 // We haven't displayed a path to this particular base
3239 // class subobject yet.
3240 PathDisplayStr += "\n ";
3241 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3242 for (CXXBasePath::const_iterator Element = Path->begin();
3243 Element != Path->end(); ++Element)
3244 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3245 }
3246 }
3247
3248 return PathDisplayStr;
3249}
3250
3251//===----------------------------------------------------------------------===//
3252// C++ class member Handling
3253//===----------------------------------------------------------------------===//
3254
3255/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3257 SourceLocation ColonLoc,
3258 const ParsedAttributesView &Attrs) {
3259 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3261 ASLoc, ColonLoc);
3262 CurContext->addHiddenDecl(ASDecl);
3263 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3264}
3265
3266/// CheckOverrideControl - Check C++11 override control semantics.
3268 if (D->isInvalidDecl())
3269 return;
3270
3271 // We only care about "override" and "final" declarations.
3272 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3273 return;
3274
3275 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3276
3277 // We can't check dependent instance methods.
3278 if (MD && MD->isInstance() &&
3279 (MD->getParent()->hasAnyDependentBases() ||
3280 MD->getType()->isDependentType()))
3281 return;
3282
3283 if (MD && !MD->isVirtual()) {
3284 // If we have a non-virtual method, check if it hides a virtual method.
3285 // (In that case, it's most likely the method has the wrong type.)
3286 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3287 FindHiddenVirtualMethods(MD, OverloadedMethods);
3288
3289 if (!OverloadedMethods.empty()) {
3290 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3291 Diag(OA->getLocation(),
3292 diag::override_keyword_hides_virtual_member_function)
3293 << "override" << (OverloadedMethods.size() > 1);
3294 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3295 Diag(FA->getLocation(),
3296 diag::override_keyword_hides_virtual_member_function)
3297 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3298 << (OverloadedMethods.size() > 1);
3299 }
3300 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3301 MD->setInvalidDecl();
3302 return;
3303 }
3304 // Fall through into the general case diagnostic.
3305 // FIXME: We might want to attempt typo correction here.
3306 }
3307
3308 if (!MD || !MD->isVirtual()) {
3309 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3310 Diag(OA->getLocation(),
3311 diag::override_keyword_only_allowed_on_virtual_member_functions)
3312 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3313 D->dropAttr<OverrideAttr>();
3314 }
3315 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3316 Diag(FA->getLocation(),
3317 diag::override_keyword_only_allowed_on_virtual_member_functions)
3318 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3319 << FixItHint::CreateRemoval(FA->getLocation());
3320 D->dropAttr<FinalAttr>();
3321 }
3322 return;
3323 }
3324
3325 // C++11 [class.virtual]p5:
3326 // If a function is marked with the virt-specifier override and
3327 // does not override a member function of a base class, the program is
3328 // ill-formed.
3329 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3330 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3331 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3332 << MD->getDeclName();
3333}
3334
3336 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3337 return;
3338 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3339 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3340 return;
3341
3342 SourceLocation Loc = MD->getLocation();
3343 SourceLocation SpellingLoc = Loc;
3344 if (getSourceManager().isMacroArgExpansion(Loc))
3346 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3347 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3348 return;
3349
3350 if (MD->size_overridden_methods() > 0) {
3351 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3352 unsigned DiagID =
3353 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3354 ? DiagInconsistent
3355 : DiagSuggest;
3356 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3357 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3358 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3359 };
3360 if (isa<CXXDestructorDecl>(MD))
3361 EmitDiag(
3362 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3363 diag::warn_suggest_destructor_marked_not_override_overriding);
3364 else
3365 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3366 diag::warn_suggest_function_marked_not_override_overriding);
3367 }
3368}
3369
3370/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3371/// function overrides a virtual member function marked 'final', according to
3372/// C++11 [class.virtual]p4.
3374 const CXXMethodDecl *Old) {
3375 FinalAttr *FA = Old->getAttr<FinalAttr>();
3376 if (!FA)
3377 return false;
3378
3379 Diag(New->getLocation(), diag::err_final_function_overridden)
3380 << New->getDeclName()
3381 << FA->isSpelledAsSealed();
3382 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3383 return true;
3384}
3385
3387 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3388 // FIXME: Destruction of ObjC lifetime types has side-effects.
3389 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3390 return !RD->isCompleteDefinition() ||
3391 !RD->hasTrivialDefaultConstructor() ||
3392 !RD->hasTrivialDestructor();
3393 return false;
3394}
3395
3396// Check if there is a field shadowing.
3397void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3398 DeclarationName FieldName,
3399 const CXXRecordDecl *RD,
3400 bool DeclIsField) {
3401 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3402 return;
3403
3404 // To record a shadowed field in a base
3405 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3406 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3407 CXXBasePath &Path) {
3408 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3409 // Record an ambiguous path directly
3410 if (Bases.find(Base) != Bases.end())
3411 return true;
3412 for (const auto Field : Base->lookup(FieldName)) {
3413 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3414 Field->getAccess() != AS_private) {
3415 assert(Field->getAccess() != AS_none);
3416 assert(Bases.find(Base) == Bases.end());
3417 Bases[Base] = Field;
3418 return true;
3419 }
3420 }
3421 return false;
3422 };
3423
3424 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3425 /*DetectVirtual=*/true);
3426 if (!RD->lookupInBases(FieldShadowed, Paths))
3427 return;
3428
3429 for (const auto &P : Paths) {
3430 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3431 auto It = Bases.find(Base);
3432 // Skip duplicated bases
3433 if (It == Bases.end())
3434 continue;
3435 auto BaseField = It->second;
3436 assert(BaseField->getAccess() != AS_private);
3437 if (AS_none !=
3438 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3439 Diag(Loc, diag::warn_shadow_field)
3440 << FieldName << RD << Base << DeclIsField;
3441 Diag(BaseField->getLocation(), diag::note_shadow_field);
3442 Bases.erase(It);
3443 }
3444 }
3445}
3446
3447/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3448/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3449/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3450/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3451/// present (but parsing it has been deferred).
3452NamedDecl *
3454 MultiTemplateParamsArg TemplateParameterLists,
3455 Expr *BW, const VirtSpecifiers &VS,
3456 InClassInitStyle InitStyle) {
3457 const DeclSpec &DS = D.getDeclSpec();
3459 DeclarationName Name = NameInfo.getName();
3460 SourceLocation Loc = NameInfo.getLoc();
3461
3462 // For anonymous bitfields, the location should point to the type.
3463 if (Loc.isInvalid())
3464 Loc = D.getBeginLoc();
3465
3466 Expr *BitWidth = static_cast<Expr*>(BW);
3467
3468 assert(isa<CXXRecordDecl>(CurContext));
3469 assert(!DS.isFriendSpecified());
3470
3471 bool isFunc = D.isDeclarationOfFunction();
3472 const ParsedAttr *MSPropertyAttr =
3474
3475 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3476 // The Microsoft extension __interface only permits public member functions
3477 // and prohibits constructors, destructors, operators, non-public member
3478 // functions, static methods and data members.
3479 unsigned InvalidDecl;
3480 bool ShowDeclName = true;
3481 if (!isFunc &&
3482 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3483 InvalidDecl = 0;
3484 else if (!isFunc)
3485 InvalidDecl = 1;
3486 else if (AS != AS_public)
3487 InvalidDecl = 2;
3489 InvalidDecl = 3;
3490 else switch (Name.getNameKind()) {
3492 InvalidDecl = 4;
3493 ShowDeclName = false;
3494 break;
3495
3497 InvalidDecl = 5;
3498 ShowDeclName = false;
3499 break;
3500
3503 InvalidDecl = 6;
3504 break;
3505
3506 default:
3507 InvalidDecl = 0;
3508 break;
3509 }
3510
3511 if (InvalidDecl) {
3512 if (ShowDeclName)
3513 Diag(Loc, diag::err_invalid_member_in_interface)
3514 << (InvalidDecl-1) << Name;
3515 else
3516 Diag(Loc, diag::err_invalid_member_in_interface)
3517 << (InvalidDecl-1) << "";
3518 return nullptr;
3519 }
3520 }
3521
3522 // C++ 9.2p6: A member shall not be declared to have automatic storage
3523 // duration (auto, register) or with the extern storage-class-specifier.
3524 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3525 // data members and cannot be applied to names declared const or static,
3526 // and cannot be applied to reference members.
3527 switch (DS.getStorageClassSpec()) {
3531 break;
3533 if (isFunc) {
3534 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3535
3536 // FIXME: It would be nicer if the keyword was ignored only for this
3537 // declarator. Otherwise we could get follow-up errors.
3539 }
3540 break;
3541 default:
3543 diag::err_storageclass_invalid_for_member);
3545 break;
3546 }
3547
3548 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3550 !isFunc);
3551
3552 if (DS.hasConstexprSpecifier() && isInstField) {
3554 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3555 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3556 if (InitStyle == ICIS_NoInit) {
3557 B << 0 << 0;
3559 B << FixItHint::CreateRemoval(ConstexprLoc);
3560 else {
3561 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3563 const char *PrevSpec;
3564 unsigned DiagID;
3565 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3566 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3567 (void)Failed;
3568 assert(!Failed && "Making a constexpr member const shouldn't fail");
3569 }
3570 } else {
3571 B << 1;
3572 const char *PrevSpec;
3573 unsigned DiagID;
3575 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3578 "This is the only DeclSpec that should fail to be applied");
3579 B << 1;
3580 } else {
3581 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3582 isInstField = false;
3583 }
3584 }
3585 }
3586
3588 if (isInstField) {
3589 CXXScopeSpec &SS = D.getCXXScopeSpec();
3590
3591 // Data members must have identifiers for names.
3592 if (!Name.isIdentifier()) {
3593 Diag(Loc, diag::err_bad_variable_name)
3594 << Name;
3595 return nullptr;
3596 }
3597
3598 IdentifierInfo *II = Name.getAsIdentifierInfo();
3599
3600 // Member field could not be with "template" keyword.
3601 // So TemplateParameterLists should be empty in this case.
3602 if (TemplateParameterLists.size()) {
3603 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3604 if (TemplateParams->size()) {
3605 // There is no such thing as a member field template.
3606 Diag(D.getIdentifierLoc(), diag::err_template_member)
3607 << II
3608 << SourceRange(TemplateParams->getTemplateLoc(),
3609 TemplateParams->getRAngleLoc());
3610 } else {
3611 // There is an extraneous 'template<>' for this member.
3612 Diag(TemplateParams->getTemplateLoc(),
3613 diag::err_template_member_noparams)
3614 << II
3615 << SourceRange(TemplateParams->getTemplateLoc(),
3616 TemplateParams->getRAngleLoc());
3617 }
3618 return nullptr;
3619 }
3620
3622 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3623 << II
3627 D.SetIdentifier(II, Loc);
3628 }
3629
3630 if (SS.isSet() && !SS.isInvalid()) {
3631 // The user provided a superfluous scope specifier inside a class
3632 // definition:
3633 //
3634 // class X {
3635 // int X::member;
3636 // };
3637 if (DeclContext *DC = computeDeclContext(SS, false)) {
3638 TemplateIdAnnotation *TemplateId =
3640 ? D.getName().TemplateId
3641 : nullptr;
3643 TemplateId,
3644 /*IsMemberSpecialization=*/false);
3645 } else {
3646 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3647 << Name << SS.getRange();
3648 }
3649 SS.clear();
3650 }
3651
3652 if (MSPropertyAttr) {
3653 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3654 BitWidth, InitStyle, AS, *MSPropertyAttr);
3655 if (!Member)
3656 return nullptr;
3657 isInstField = false;
3658 } else {
3659 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3660 BitWidth, InitStyle, AS);
3661 if (!Member)
3662 return nullptr;
3663 }
3664
3665 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3666 } else {
3667 Member = HandleDeclarator(S, D, TemplateParameterLists);
3668 if (!Member)
3669 return nullptr;
3670
3671 // Non-instance-fields can't have a bitfield.
3672 if (BitWidth) {
3673 if (Member->isInvalidDecl()) {
3674 // don't emit another diagnostic.
3675 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3676 // C++ 9.6p3: A bit-field shall not be a static member.
3677 // "static member 'A' cannot be a bit-field"
3678 Diag(Loc, diag::err_static_not_bitfield)
3679 << Name << BitWidth->getSourceRange();
3680 } else if (isa<TypedefDecl>(Member)) {
3681 // "typedef member 'x' cannot be a bit-field"
3682 Diag(Loc, diag::err_typedef_not_bitfield)
3683 << Name << BitWidth->getSourceRange();
3684 } else {
3685 // A function typedef ("typedef int f(); f a;").
3686 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3687 Diag(Loc, diag::err_not_integral_type_bitfield)
3688 << Name << cast<ValueDecl>(Member)->getType()
3689 << BitWidth->getSourceRange();
3690 }
3691
3692 BitWidth = nullptr;
3693 Member->setInvalidDecl();
3694 }
3695
3696 NamedDecl *NonTemplateMember = Member;
3697 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3698 NonTemplateMember = FunTmpl->getTemplatedDecl();
3699 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3700 NonTemplateMember = VarTmpl->getTemplatedDecl();
3701
3702 Member->setAccess(AS);
3703
3704 // If we have declared a member function template or static data member
3705 // template, set the access of the templated declaration as well.
3706 if (NonTemplateMember != Member)
3707 NonTemplateMember->setAccess(AS);
3708
3709 // C++ [temp.deduct.guide]p3:
3710 // A deduction guide [...] for a member class template [shall be
3711 // declared] with the same access [as the template].
3712 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3713 auto *TD = DG->getDeducedTemplate();
3714 // Access specifiers are only meaningful if both the template and the
3715 // deduction guide are from the same scope.
3716 if (AS != TD->getAccess() &&
3717 TD->getDeclContext()->getRedeclContext()->Equals(
3718 DG->getDeclContext()->getRedeclContext())) {
3719 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3720 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3721 << TD->getAccess();
3722 const AccessSpecDecl *LastAccessSpec = nullptr;
3723 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3724 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3725 LastAccessSpec = AccessSpec;
3726 }
3727 assert(LastAccessSpec && "differing access with no access specifier");
3728 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3729 << AS;
3730 }
3731 }
3732 }
3733
3734 if (VS.isOverrideSpecified())
3735 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3736 if (VS.isFinalSpecified())
3737 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3739 ? FinalAttr::Keyword_sealed
3740 : FinalAttr::Keyword_final));
3741
3742 if (VS.getLastLocation().isValid()) {
3743 // Update the end location of a method that has a virt-specifiers.
3744 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3745 MD->setRangeEnd(VS.getLastLocation());
3746 }
3747
3749
3750 assert((Name || isInstField) && "No identifier for non-field ?");
3751
3752 if (isInstField) {
3753 FieldDecl *FD = cast<FieldDecl>(Member);
3754 FieldCollector->Add(FD);
3755
3756 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3757 // Remember all explicit private FieldDecls that have a name, no side
3758 // effects and are not part of a dependent type declaration.
3759
3760 auto DeclHasUnusedAttr = [](const QualType &T) {
3761 if (const TagDecl *TD = T->getAsTagDecl())
3762 return TD->hasAttr<UnusedAttr>();
3763 if (const TypedefType *TDT = T->getAs<TypedefType>())
3764 return TDT->getDecl()->hasAttr<UnusedAttr>();
3765 return false;
3766 };
3767
3768 if (!FD->isImplicit() && FD->getDeclName() &&
3769 FD->getAccess() == AS_private &&
3770 !FD->hasAttr<UnusedAttr>() &&
3771 !FD->getParent()->isDependentContext() &&
3772 !DeclHasUnusedAttr(FD->getType()) &&
3774 UnusedPrivateFields.insert(FD);
3775 }
3776 }
3777
3778 return Member;
3779}
3780
3781namespace {
3782 class UninitializedFieldVisitor
3783 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3784 Sema &S;
3785 // List of Decls to generate a warning on. Also remove Decls that become
3786 // initialized.
3787 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3788 // List of base classes of the record. Classes are removed after their
3789 // initializers.
3790 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3791 // Vector of decls to be removed from the Decl set prior to visiting the
3792 // nodes. These Decls may have been initialized in the prior initializer.
3794 // If non-null, add a note to the warning pointing back to the constructor.
3795 const CXXConstructorDecl *Constructor;
3796 // Variables to hold state when processing an initializer list. When
3797 // InitList is true, special case initialization of FieldDecls matching
3798 // InitListFieldDecl.
3799 bool InitList;
3800 FieldDecl *InitListFieldDecl;
3801 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3802
3803 public:
3805 UninitializedFieldVisitor(Sema &S,
3806 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3807 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3808 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3809 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3810
3811 // Returns true if the use of ME is not an uninitialized use.
3812 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3813 bool CheckReferenceOnly) {
3815 bool ReferenceField = false;
3816 while (ME) {
3817 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3818 if (!FD)
3819 return false;
3820 Fields.push_back(FD);
3821 if (FD->getType()->isReferenceType())
3822 ReferenceField = true;
3823 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3824 }
3825
3826 // Binding a reference to an uninitialized field is not an
3827 // uninitialized use.
3828 if (CheckReferenceOnly && !ReferenceField)
3829 return true;
3830
3831 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3832 // Discard the first field since it is the field decl that is being
3833 // initialized.
3834 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3835 UsedFieldIndex.push_back(FD->getFieldIndex());
3836
3837 for (auto UsedIter = UsedFieldIndex.begin(),
3838 UsedEnd = UsedFieldIndex.end(),
3839 OrigIter = InitFieldIndex.begin(),
3840 OrigEnd = InitFieldIndex.end();
3841 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3842 if (*UsedIter < *OrigIter)
3843 return true;
3844 if (*UsedIter > *OrigIter)
3845 break;
3846 }
3847
3848 return false;
3849 }
3850
3851 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3852 bool AddressOf) {
3853 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3854 return;
3855
3856 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3857 // or union.
3858 MemberExpr *FieldME = ME;
3859
3860 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3861
3862 Expr *Base = ME;
3863 while (MemberExpr *SubME =
3864 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3865
3866 if (isa<VarDecl>(SubME->getMemberDecl()))
3867 return;
3868
3869 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3870 if (!FD->isAnonymousStructOrUnion())
3871 FieldME = SubME;
3872
3873 if (!FieldME->getType().isPODType(S.Context))
3874 AllPODFields = false;
3875
3876 Base = SubME->getBase();
3877 }
3878
3879 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3880 Visit(Base);
3881 return;
3882 }
3883
3884 if (AddressOf && AllPODFields)
3885 return;
3886
3887 ValueDecl* FoundVD = FieldME->getMemberDecl();
3888
3889 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3890 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3891 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3892 }
3893
3894 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3895 QualType T = BaseCast->getType();
3896 if (T->isPointerType() &&
3897 BaseClasses.count(T->getPointeeType())) {
3898 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3899 << T->getPointeeType() << FoundVD;
3900 }
3901 }
3902 }
3903
3904 if (!Decls.count(FoundVD))
3905 return;
3906
3907 const bool IsReference = FoundVD->getType()->isReferenceType();
3908
3909 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3910 // Special checking for initializer lists.
3911 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3912 return;
3913 }
3914 } else {
3915 // Prevent double warnings on use of unbounded references.
3916 if (CheckReferenceOnly && !IsReference)
3917 return;
3918 }
3919
3920 unsigned diag = IsReference
3921 ? diag::warn_reference_field_is_uninit
3922 : diag::warn_field_is_uninit;
3923 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3924 if (Constructor)
3925 S.Diag(Constructor->getLocation(),
3926 diag::note_uninit_in_this_constructor)
3927 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3928
3929 }
3930
3931 void HandleValue(Expr *E, bool AddressOf) {
3932 E = E->IgnoreParens();
3933
3934 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3935 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3936 AddressOf /*AddressOf*/);
3937 return;
3938 }
3939
3940 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3941 Visit(CO->getCond());
3942 HandleValue(CO->getTrueExpr(), AddressOf);
3943 HandleValue(CO->getFalseExpr(), AddressOf);
3944 return;
3945 }
3946
3947 if (BinaryConditionalOperator *BCO =
3948 dyn_cast<BinaryConditionalOperator>(E)) {
3949 Visit(BCO->getCond());
3950 HandleValue(BCO->getFalseExpr(), AddressOf);
3951 return;
3952 }
3953
3954 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3955 HandleValue(OVE->getSourceExpr(), AddressOf);
3956 return;
3957 }
3958
3959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3960 switch (BO->getOpcode()) {
3961 default:
3962 break;
3963 case(BO_PtrMemD):
3964 case(BO_PtrMemI):
3965 HandleValue(BO->getLHS(), AddressOf);
3966 Visit(BO->getRHS());
3967 return;
3968 case(BO_Comma):
3969 Visit(BO->getLHS());
3970 HandleValue(BO->getRHS(), AddressOf);
3971 return;
3972 }
3973 }
3974
3975 Visit(E);
3976 }
3977
3978 void CheckInitListExpr(InitListExpr *ILE) {
3979 InitFieldIndex.push_back(0);
3980 for (auto *Child : ILE->children()) {
3981 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3982 CheckInitListExpr(SubList);
3983 } else {
3984 Visit(Child);
3985 }
3986 ++InitFieldIndex.back();
3987 }
3988 InitFieldIndex.pop_back();
3989 }
3990
3991 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3992 FieldDecl *Field, const Type *BaseClass) {
3993 // Remove Decls that may have been initialized in the previous
3994 // initializer.
3995 for (ValueDecl* VD : DeclsToRemove)
3996 Decls.erase(VD);
3997 DeclsToRemove.clear();
3998
3999 Constructor = FieldConstructor;
4000 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
4001
4002 if (ILE && Field) {
4003 InitList = true;
4004 InitListFieldDecl = Field;
4005 InitFieldIndex.clear();
4006 CheckInitListExpr(ILE);
4007 } else {
4008 InitList = false;
4009 Visit(E);
4010 }
4011
4012 if (Field)
4013 Decls.erase(Field);
4014 if (BaseClass)
4015 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4016 }
4017
4018 void VisitMemberExpr(MemberExpr *ME) {
4019 // All uses of unbounded reference fields will warn.
4020 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4021 }
4022
4023 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4024 if (E->getCastKind() == CK_LValueToRValue) {
4025 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4026 return;
4027 }
4028
4029 Inherited::VisitImplicitCastExpr(E);
4030 }
4031
4032 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4033 if (E->getConstructor()->isCopyConstructor()) {
4034 Expr *ArgExpr = E->getArg(0);
4035 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4036 if (ILE->getNumInits() == 1)
4037 ArgExpr = ILE->getInit(0);
4038 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4039 if (ICE->getCastKind() == CK_NoOp)
4040 ArgExpr = ICE->getSubExpr();
4041 HandleValue(ArgExpr, false /*AddressOf*/);
4042 return;
4043 }
4044 Inherited::VisitCXXConstructExpr(E);
4045 }
4046
4047 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4048 Expr *Callee = E->getCallee();
4049 if (isa<MemberExpr>(Callee)) {
4050 HandleValue(Callee, false /*AddressOf*/);
4051 for (auto *Arg : E->arguments())
4052 Visit(Arg);
4053 return;
4054 }
4055
4056 Inherited::VisitCXXMemberCallExpr(E);
4057 }
4058
4059 void VisitCallExpr(CallExpr *E) {
4060 // Treat std::move as a use.
4061 if (E->isCallToStdMove()) {
4062 HandleValue(E->getArg(0), /*AddressOf=*/false);
4063 return;
4064 }
4065
4066 Inherited::VisitCallExpr(E);
4067 }
4068
4069 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4070 Expr *Callee = E->getCallee();
4071
4072 if (isa<UnresolvedLookupExpr>(Callee))
4073 return Inherited::VisitCXXOperatorCallExpr(E);
4074
4075 Visit(Callee);
4076 for (auto *Arg : E->arguments())
4077 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4078 }
4079
4080 void VisitBinaryOperator(BinaryOperator *E) {
4081 // If a field assignment is detected, remove the field from the
4082 // uninitiailized field set.
4083 if (E->getOpcode() == BO_Assign)
4084 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4085 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4086 if (!FD->getType()->isReferenceType())
4087 DeclsToRemove.push_back(FD);
4088
4089 if (E->isCompoundAssignmentOp()) {
4090 HandleValue(E->getLHS(), false /*AddressOf*/);
4091 Visit(E->getRHS());
4092 return;
4093 }
4094
4095 Inherited::VisitBinaryOperator(E);
4096 }
4097
4098 void VisitUnaryOperator(UnaryOperator *E) {
4099 if (E->isIncrementDecrementOp()) {
4100 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4101 return;
4102 }
4103 if (E->getOpcode() == UO_AddrOf) {
4104 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4105 HandleValue(ME->getBase(), true /*AddressOf*/);
4106 return;
4107 }
4108 }
4109
4110 Inherited::VisitUnaryOperator(E);
4111 }
4112 };
4113
4114 // Diagnose value-uses of fields to initialize themselves, e.g.
4115 // foo(foo)
4116 // where foo is not also a parameter to the constructor.
4117 // Also diagnose across field uninitialized use such as
4118 // x(y), y(x)
4119 // TODO: implement -Wuninitialized and fold this into that framework.
4120 static void DiagnoseUninitializedFields(
4121 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4122
4123 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4124 Constructor->getLocation())) {
4125 return;
4126 }
4127
4128 if (Constructor->isInvalidDecl())
4129 return;
4130
4131 const CXXRecordDecl *RD = Constructor->getParent();
4132
4133 if (RD->isDependentContext())
4134 return;
4135
4136 // Holds fields that are uninitialized.
4137 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4138
4139 // At the beginning, all fields are uninitialized.
4140 for (auto *I : RD->decls()) {
4141 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4142 UninitializedFields.insert(FD);
4143 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4144 UninitializedFields.insert(IFD->getAnonField());
4145 }
4146 }
4147
4148 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4149 for (const auto &I : RD->bases())
4150 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4151
4152 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4153 return;
4154
4155 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4156 UninitializedFields,
4157 UninitializedBaseClasses);
4158
4159 for (const auto *FieldInit : Constructor->inits()) {
4160 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4161 break;
4162
4163 Expr *InitExpr = FieldInit->getInit();
4164 if (!InitExpr)
4165 continue;
4166
4168 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4169 InitExpr = Default->getExpr();
4170 if (!InitExpr)
4171 continue;
4172 // In class initializers will point to the constructor.
4173 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4174 FieldInit->getAnyMember(),
4175 FieldInit->getBaseClass());
4176 } else {
4177 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4178 FieldInit->getAnyMember(),
4179 FieldInit->getBaseClass());
4180 }
4181 }
4182 }
4183} // namespace
4184
4185/// Enter a new C++ default initializer scope. After calling this, the
4186/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4187/// parsing or instantiating the initializer failed.
4189 // Create a synthetic function scope to represent the call to the constructor
4190 // that notionally surrounds a use of this initializer.
4192}
4193
4195 if (!D.isFunctionDeclarator())
4196 return;
4197 auto &FTI = D.getFunctionTypeInfo();
4198 if (!FTI.Params)
4199 return;
4200 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4201 FTI.NumParams)) {
4202 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4203 if (ParamDecl->getDeclName())
4204 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4205 }
4206}
4207
4209 return ActOnRequiresClause(ConstraintExpr);
4210}
4211
4213 if (ConstraintExpr.isInvalid())
4214 return ExprError();
4215
4216 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4217 if (ConstraintExpr.isInvalid())
4218 return ExprError();
4219
4220 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4222 return ExprError();
4223
4224 return ConstraintExpr;
4225}
4226
4228 Expr *InitExpr,
4229 SourceLocation InitLoc) {
4230 InitializedEntity Entity =
4232 InitializationKind Kind =
4235 InitExpr->getBeginLoc(),
4236 InitExpr->getEndLoc())
4237 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4238 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4239 return Seq.Perform(*this, Entity, Kind, InitExpr);
4240}
4241
4242/// This is invoked after parsing an in-class initializer for a
4243/// non-static C++ class member, and after instantiating an in-class initializer
4244/// in a class template. Such actions are deferred until the class is complete.
4246 SourceLocation InitLoc,
4247 Expr *InitExpr) {
4248 // Pop the notional constructor scope we created earlier.
4249 PopFunctionScopeInfo(nullptr, D);
4250
4251 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4252 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4253 "must set init style when field is created");
4254
4255 if (!InitExpr) {
4256 D->setInvalidDecl();
4257 if (FD)
4259 return;
4260 }
4261
4263 FD->setInvalidDecl();
4265 return;
4266 }
4267
4268 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4269 /*RecoverUncorrectedTypos=*/true);
4270 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4271 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4272 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4273 // C++11 [class.base.init]p7:
4274 // The initialization of each base and member constitutes a
4275 // full-expression.
4276 if (!Init.isInvalid())
4277 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4278 if (Init.isInvalid()) {
4279 FD->setInvalidDecl();
4280 return;
4281 }
4282 }
4283
4284 FD->setInClassInitializer(Init.get());
4285}
4286
4287/// Find the direct and/or virtual base specifiers that
4288/// correspond to the given base type, for use in base initialization
4289/// within a constructor.
4291 CXXRecordDecl *ClassDecl,
4292 QualType BaseType,
4293 const CXXBaseSpecifier *&DirectBaseSpec,
4294 const CXXBaseSpecifier *&VirtualBaseSpec) {
4295 // First, check for a direct base class.
4296 DirectBaseSpec = nullptr;
4297 for (const auto &Base : ClassDecl->bases()) {
4298 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4299 // We found a direct base of this type. That's what we're
4300 // initializing.
4301 DirectBaseSpec = &Base;
4302 break;
4303 }
4304 }
4305
4306 // Check for a virtual base class.
4307 // FIXME: We might be able to short-circuit this if we know in advance that
4308 // there are no virtual bases.
4309 VirtualBaseSpec = nullptr;
4310 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4311 // We haven't found a base yet; search the class hierarchy for a
4312 // virtual base class.
4313 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4314 /*DetectVirtual=*/false);
4315 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4316 SemaRef.Context.getTypeDeclType(ClassDecl),
4317 BaseType, Paths)) {
4318 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4319 Path != Paths.end(); ++Path) {
4320 if (Path->back().Base->isVirtual()) {
4321 VirtualBaseSpec = Path->back().Base;
4322 break;
4323 }
4324 }
4325 }
4326 }
4327
4328 return DirectBaseSpec || VirtualBaseSpec;
4329}
4330
4331/// Handle a C++ member initializer using braced-init-list syntax.
4334 Scope *S,
4335 CXXScopeSpec &SS,
4336 IdentifierInfo *MemberOrBase,
4337 ParsedType TemplateTypeTy,
4338 const DeclSpec &DS,
4339 SourceLocation IdLoc,
4340 Expr *InitList,
4341 SourceLocation EllipsisLoc) {
4342 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4343 DS, IdLoc, InitList,
4344 EllipsisLoc);
4345}
4346
4347/// Handle a C++ member initializer using parentheses syntax.
4350 Scope *S,
4351 CXXScopeSpec &SS,
4352 IdentifierInfo *MemberOrBase,
4353 ParsedType TemplateTypeTy,
4354 const DeclSpec &DS,
4355 SourceLocation IdLoc,
4356 SourceLocation LParenLoc,
4357 ArrayRef<Expr *> Args,
4358 SourceLocation RParenLoc,
4359 SourceLocation EllipsisLoc) {
4360 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4361 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4362 DS, IdLoc, List, EllipsisLoc);
4363}
4364
4365namespace {
4366
4367// Callback to only accept typo corrections that can be a valid C++ member
4368// initializer: either a non-static field member or a base class.
4369class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4370public:
4371 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4372 : ClassDecl(ClassDecl) {}
4373
4374 bool ValidateCandidate(const TypoCorrection &candidate) override {
4375 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4376 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4377 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4378 return isa<TypeDecl>(ND);
4379 }
4380 return false;
4381 }
4382
4383 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4384 return std::make_unique<MemInitializerValidatorCCC>(*this);
4385 }
4386
4387private:
4388 CXXRecordDecl *ClassDecl;
4389};
4390
4391}
4392
4394 RecordDecl *ClassDecl,
4395 const IdentifierInfo *Name) {
4396 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4398 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4399 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4401 });
4402 // We did not find a placeholder variable
4403 if (Found == Result.end())
4404 return false;
4405 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4406 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4407 const NamedDecl *ND = *It;
4408 if (ND->getDeclContext() != ND->getDeclContext())
4409 break;
4410 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4412 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4413 }
4414 return true;
4415}
4416
4417ValueDecl *
4419 const IdentifierInfo *MemberOrBase) {
4420 ValueDecl *ND = nullptr;
4421 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4422 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4423 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4424 if (ND) {
4425 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4426 return nullptr;
4427 break;
4428 }
4429 if (!IsPlaceholder)
4430 return cast<ValueDecl>(D);
4431 ND = cast<ValueDecl>(D);
4432 }
4433 }
4434 return ND;
4435}
4436
4437ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4438 CXXScopeSpec &SS,
4439 ParsedType TemplateTypeTy,
4440 IdentifierInfo *MemberOrBase) {
4441 if (SS.getScopeRep() || TemplateTypeTy)
4442 return nullptr;
4443 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4444}
4445
4446/// Handle a C++ member initializer.
4449 Scope *S,
4450 CXXScopeSpec &SS,
4451 IdentifierInfo *MemberOrBase,
4452 ParsedType TemplateTypeTy,
4453 const DeclSpec &DS,
4454 SourceLocation IdLoc,
4455 Expr *Init,
4456 SourceLocation EllipsisLoc) {
4457 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4458 /*RecoverUncorrectedTypos=*/true);
4459 if (!Res.isUsable())
4460 return true;
4461 Init = Res.get();
4462
4463 if (!ConstructorD)
4464 return true;
4465
4466 AdjustDeclIfTemplate(ConstructorD);
4467
4468 CXXConstructorDecl *Constructor
4469 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4470 if (!Constructor) {
4471 // The user wrote a constructor initializer on a function that is
4472 // not a C++ constructor. Ignore the error for now, because we may
4473 // have more member initializers coming; we'll diagnose it just
4474 // once in ActOnMemInitializers.
4475 return true;
4476 }
4477
4478 CXXRecordDecl *ClassDecl = Constructor->getParent();
4479
4480 // C++ [class.base.init]p2:
4481 // Names in a mem-initializer-id are looked up in the scope of the
4482 // constructor's class and, if not found in that scope, are looked
4483 // up in the scope containing the constructor's definition.
4484 // [Note: if the constructor's class contains a member with the
4485 // same name as a direct or virtual base class of the class, a
4486 // mem-initializer-id naming the member or base class and composed
4487 // of a single identifier refers to the class member. A
4488 // mem-initializer-id for the hidden base class may be specified
4489 // using a qualified name. ]
4490
4491 // Look for a member, first.
4492 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4493 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4494 if (EllipsisLoc.isValid())
4495 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4496 << MemberOrBase
4497 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4498
4499 return BuildMemberInitializer(Member, Init, IdLoc);
4500 }
4501 // It didn't name a member, so see if it names a class.
4502 QualType BaseType;
4503 TypeSourceInfo *TInfo = nullptr;
4504
4505 if (TemplateTypeTy) {
4506 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4507 if (BaseType.isNull())
4508 return true;
4509 } else if (DS.getTypeSpecType() == TST_decltype) {
4510 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4511 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4512 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4513 return true;
4514 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4515 BaseType =
4517 DS.getBeginLoc(), DS.getEllipsisLoc());
4518 } else {
4519 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4520 LookupParsedName(R, S, &SS);
4521
4522 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4523 if (!TyD) {
4524 if (R.isAmbiguous()) return true;
4525
4526 // We don't want access-control diagnostics here.
4528
4529 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4530 bool NotUnknownSpecialization = false;
4531 DeclContext *DC = computeDeclContext(SS, false);
4532 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4533 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4534
4535 if (!NotUnknownSpecialization) {
4536 // When the scope specifier can refer to a member of an unknown
4537 // specialization, we take it as a type name.
4538 BaseType = CheckTypenameType(
4540 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4541 if (BaseType.isNull())
4542 return true;
4543
4544 TInfo = Context.CreateTypeSourceInfo(BaseType);
4547 if (!TL.isNull()) {
4548 TL.setNameLoc(IdLoc);
4551 }
4552
4553 R.clear();
4554 R.setLookupName(MemberOrBase);
4555 }
4556 }
4557
4558 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4559 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4560 auto *TempSpec = cast<TemplateSpecializationType>(
4561 UnqualifiedBase->getInjectedClassNameSpecialization());
4562 TemplateName TN = TempSpec->getTemplateName();
4563 for (auto const &Base : ClassDecl->bases()) {
4564 auto BaseTemplate =
4565 Base.getType()->getAs<TemplateSpecializationType>();
4566 if (BaseTemplate && Context.hasSameTemplateName(
4567 BaseTemplate->getTemplateName(), TN)) {
4568 Diag(IdLoc, diag::ext_unqualified_base_class)
4569 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4570 BaseType = Base.getType();
4571 break;
4572 }
4573 }
4574 }
4575 }
4576
4577 // If no results were found, try to correct typos.
4578 TypoCorrection Corr;
4579 MemInitializerValidatorCCC CCC(ClassDecl);
4580 if (R.empty() && BaseType.isNull() &&
4581 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4582 CCC, CTK_ErrorRecovery, ClassDecl))) {
4584 // We have found a non-static data member with a similar
4585 // name to what was typed; complain and initialize that
4586 // member.
4587 diagnoseTypo(Corr,
4588 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4589 << MemberOrBase << true);
4590 return BuildMemberInitializer(Member, Init, IdLoc);
4591 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4592 const CXXBaseSpecifier *DirectBaseSpec;
4593 const CXXBaseSpecifier *VirtualBaseSpec;
4594 if (FindBaseInitializer(*this, ClassDecl,
4596 DirectBaseSpec, VirtualBaseSpec)) {
4597 // We have found a direct or virtual base class with a
4598 // similar name to what was typed; complain and initialize
4599 // that base class.
4600 diagnoseTypo(Corr,
4601 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4602 << MemberOrBase << false,
4603 PDiag() /*Suppress note, we provide our own.*/);
4604
4605 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4606 : VirtualBaseSpec;
4607 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4608 << BaseSpec->getType() << BaseSpec->getSourceRange();
4609
4610 TyD = Type;
4611 }
4612 }
4613 }
4614
4615 if (!TyD && BaseType.isNull()) {
4616 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4617 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4618 return true;
4619 }
4620 }
4621
4622 if (BaseType.isNull()) {
4625 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4626 TInfo = Context.CreateTypeSourceInfo(BaseType);
4628 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4631 }
4632 }
4633
4634 if (!TInfo)
4635 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4636
4637 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4638}
4639
4642 SourceLocation IdLoc) {
4643 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4644 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4645 assert((DirectMember || IndirectMember) &&
4646 "Member must be a FieldDecl or IndirectFieldDecl");
4647
4649 return true;
4650
4651 if (Member->isInvalidDecl())
4652 return true;
4653
4654 MultiExprArg Args;
4655 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4656 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4657 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4658 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4659 } else {
4660 // Template instantiation doesn't reconstruct ParenListExprs for us.
4661 Args = Init;
4662 }
4663
4664 SourceRange InitRange = Init->getSourceRange();
4665
4666 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4667 // Can't check initialization for a member of dependent type or when
4668 // any of the arguments are type-dependent expressions.
4670 } else {
4671 bool InitList = false;
4672 if (isa<InitListExpr>(Init)) {
4673 InitList = true;
4674 Args = Init;
4675 }
4676
4677 // Initialize the member.
4678 InitializedEntity MemberEntity =
4679 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4680 : InitializedEntity::InitializeMember(IndirectMember,
4681 nullptr);
4682 InitializationKind Kind =
4684 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4685 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4686 InitRange.getEnd());
4687
4688 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4689 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4690 nullptr);
4691 if (!MemberInit.isInvalid()) {
4692 // C++11 [class.base.init]p7:
4693 // The initialization of each base and member constitutes a
4694 // full-expression.
4695 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4696 /*DiscardedValue*/ false);
4697 }
4698
4699 if (MemberInit.isInvalid()) {
4700 // Args were sensible expressions but we couldn't initialize the member
4701 // from them. Preserve them in a RecoveryExpr instead.
4702 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4703 Member->getType())
4704 .get();
4705 if (!Init)
4706 return true;
4707 } else {
4708 Init = MemberInit.get();
4709 }
4710 }
4711
4712 if (DirectMember) {
4713 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4714 InitRange.getBegin(), Init,
4715 InitRange.getEnd());
4716 } else {
4717 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4718 InitRange.getBegin(), Init,
4719 InitRange.getEnd());
4720 }
4721}
4722
4725 CXXRecordDecl *ClassDecl) {
4726 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4727 if (!LangOpts.CPlusPlus11)
4728 return Diag(NameLoc, diag::err_delegating_ctor)
4729 << TInfo->getTypeLoc().getSourceRange();
4730 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4731
4732 bool InitList = true;
4733 MultiExprArg Args = Init;
4734 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4735 InitList = false;
4736 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4737 }
4738
4739 SourceRange InitRange = Init->getSourceRange();
4740 // Initialize the object.
4742 QualType(ClassDecl->getTypeForDecl(), 0));
4743 InitializationKind Kind =
4745 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4746 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4747 InitRange.getEnd());
4748 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4749 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4750 Args, nullptr);
4751 if (!DelegationInit.isInvalid()) {
4752 assert((DelegationInit.get()->containsErrors() ||
4753 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4754 "Delegating constructor with no target?");
4755
4756 // C++11 [class.base.init]p7:
4757 // The initialization of each base and member constitutes a
4758 // full-expression.
4759 DelegationInit = ActOnFinishFullExpr(
4760 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4761 }
4762
4763 if (DelegationInit.isInvalid()) {
4764 DelegationInit =
4765 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4766 QualType(ClassDecl->getTypeForDecl(), 0));
4767 if (DelegationInit.isInvalid())
4768 return true;
4769 } else {
4770 // If we are in a dependent context, template instantiation will
4771 // perform this type-checking again. Just save the arguments that we
4772 // received in a ParenListExpr.
4773 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4774 // of the information that we have about the base
4775 // initializer. However, deconstructing the ASTs is a dicey process,
4776 // and this approach is far more likely to get the corner cases right.
4778 DelegationInit = Init;
4779 }
4780
4781 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4782 DelegationInit.getAs<Expr>(),
4783 InitRange.getEnd());
4784}
4785
4788 Expr *Init, CXXRecordDecl *ClassDecl,
4789 SourceLocation EllipsisLoc) {
4790 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4791
4792 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4793 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4794 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4795
4796 // C++ [class.base.init]p2:
4797 // [...] Unless the mem-initializer-id names a nonstatic data
4798 // member of the constructor's class or a direct or virtual base
4799 // of that class, the mem-initializer is ill-formed. A
4800 // mem-initializer-list can initialize a base class using any
4801 // name that denotes that base class type.
4802
4803 // We can store the initializers in "as-written" form and delay analysis until
4804 // instantiation if the constructor is dependent. But not for dependent
4805 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4806 bool Dependent = CurContext->isDependentContext() &&
4807 (BaseType->isDependentType() || Init->isTypeDependent());
4808
4809 SourceRange InitRange = Init->getSourceRange();
4810 if (EllipsisLoc.isValid()) {
4811 // This is a pack expansion.
4812 if (!BaseType->containsUnexpandedParameterPack()) {
4813 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4814 << SourceRange(BaseLoc, InitRange.getEnd());
4815
4816 EllipsisLoc = SourceLocation();
4817 }
4818 } else {
4819 // Check for any unexpanded parameter packs.
4820 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4821 return true;
4822
4824 return true;
4825 }
4826
4827 // Check for direct and virtual base classes.
4828 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4829 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4830 if (!Dependent) {
4832 BaseType))
4833 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4834
4835 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4836 VirtualBaseSpec);
4837
4838 // C++ [base.class.init]p2:
4839 // Unless the mem-initializer-id names a nonstatic data member of the
4840 // constructor's class or a direct or virtual base of that class, the
4841 // mem-initializer is ill-formed.
4842 if (!DirectBaseSpec && !VirtualBaseSpec) {
4843 // If the class has any dependent bases, then it's possible that
4844 // one of those types will resolve to the same type as
4845 // BaseType. Therefore, just treat this as a dependent base
4846 // class initialization. FIXME: Should we try to check the
4847 // initialization anyway? It seems odd.
4848 if (ClassDecl->hasAnyDependentBases())
4849 Dependent = true;
4850 else
4851 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4852 << BaseType << Context.getTypeDeclType(ClassDecl)
4853 << BaseTInfo->getTypeLoc().getSourceRange();
4854 }
4855 }
4856
4857 if (Dependent) {
4859
4860 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4861 /*IsVirtual=*/false,
4862 InitRange.getBegin(), Init,
4863 InitRange.getEnd(), EllipsisLoc);
4864 }
4865
4866 // C++ [base.class.init]p2:
4867 // If a mem-initializer-id is ambiguous because it designates both
4868 // a direct non-virtual base class and an inherited virtual base
4869 // class, the mem-initializer is ill-formed.
4870 if (DirectBaseSpec && VirtualBaseSpec)
4871 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4872 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4873
4874 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4875 if (!BaseSpec)
4876 BaseSpec = VirtualBaseSpec;
4877
4878 // Initialize the base.
4879 bool InitList = true;
4880 MultiExprArg Args = Init;
4881 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4882 InitList = false;
4883 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4884 }
4885
4886 InitializedEntity BaseEntity =
4887 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4888 InitializationKind Kind =
4889 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4890 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4891 InitRange.getEnd());
4892 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4893 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4894 if (!BaseInit.isInvalid()) {
4895 // C++11 [class.base.init]p7:
4896 // The initialization of each base and member constitutes a
4897 // full-expression.
4898 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4899 /*DiscardedValue*/ false);
4900 }
4901
4902 if (BaseInit.isInvalid()) {
4903 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4904 Args, BaseType);
4905 if (BaseInit.isInvalid())
4906 return true;
4907 } else {
4908 // If we are in a dependent context, template instantiation will
4909 // perform this type-checking again. Just save the arguments that we
4910 // received in a ParenListExpr.
4911 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4912 // of the information that we have about the base
4913 // initializer. However, deconstructing the ASTs is a dicey process,
4914 // and this approach is far more likely to get the corner cases right.
4916 BaseInit = Init;
4917 }
4918
4919 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4920 BaseSpec->isVirtual(),
4921 InitRange.getBegin(),
4922 BaseInit.getAs<Expr>(),
4923 InitRange.getEnd(), EllipsisLoc);
4924}
4925
4926// Create a static_cast<T&&>(expr).
4928 QualType TargetType =
4929 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4931 SourceLocation ExprLoc = E->getBeginLoc();
4933 TargetType, ExprLoc);
4934
4935 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4936 SourceRange(ExprLoc, ExprLoc),
4937 E->getSourceRange()).get();
4938}
4939
4940/// ImplicitInitializerKind - How an implicit base or member initializer should
4941/// initialize its base or member.
4948
4949static bool
4951 ImplicitInitializerKind ImplicitInitKind,
4952 CXXBaseSpecifier *BaseSpec,
4953 bool IsInheritedVirtualBase,
4954 CXXCtorInitializer *&CXXBaseInit) {
4955 InitializedEntity InitEntity
4957 IsInheritedVirtualBase);
4958
4959 ExprResult BaseInit;
4960
4961 switch (ImplicitInitKind) {
4962 case IIK_Inherit:
4963 case IIK_Default: {
4964 InitializationKind InitKind
4965 = InitializationKind::CreateDefault(Constructor->getLocation());
4966 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4967 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4968 break;
4969 }
4970
4971 case IIK_Move:
4972 case IIK_Copy: {
4973 bool Moving = ImplicitInitKind == IIK_Move;
4974 ParmVarDecl *Param = Constructor->getParamDecl(0);
4975 QualType ParamType = Param->getType().getNonReferenceType();
4976
4977 Expr *CopyCtorArg =
4979 SourceLocation(), Param, false,
4980 Constructor->getLocation(), ParamType,
4981 VK_LValue, nullptr);
4982
4983 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4984
4985 // Cast to the base class to avoid ambiguities.
4986 QualType ArgTy =
4988 ParamType.getQualifiers());
4989
4990 if (Moving) {
4991 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4992 }
4993
4994 CXXCastPath BasePath;
4995 BasePath.push_back(BaseSpec);
4996 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4997 CK_UncheckedDerivedToBase,
4998 Moving ? VK_XValue : VK_LValue,
4999 &BasePath).get();
5000
5001 InitializationKind InitKind
5002 = InitializationKind::CreateDirect(Constructor->getLocation(),
5004 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5005 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5006 break;
5007 }
5008 }
5009
5010 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5011 if (BaseInit.isInvalid())
5012 return true;
5013
5014 CXXBaseInit =
5017 SourceLocation()),
5018 BaseSpec->isVirtual(),
5020 BaseInit.getAs<Expr>(),
5022 SourceLocation());
5023
5024 return false;
5025}
5026
5027static bool RefersToRValueRef(Expr *MemRef) {
5028 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5029 return Referenced->getType()->isRValueReferenceType();
5030}
5031
5032static bool
5034 ImplicitInitializerKind ImplicitInitKind,
5035 FieldDecl *Field, IndirectFieldDecl *Indirect,
5036 CXXCtorInitializer *&CXXMemberInit) {
5037 if (Field->isInvalidDecl())
5038 return true;
5039
5040 SourceLocation Loc = Constructor->getLocation();
5041
5042 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5043 bool Moving = ImplicitInitKind == IIK_Move;
5044 ParmVarDecl *Param = Constructor->getParamDecl(0);
5045 QualType ParamType = Param->getType().getNonReferenceType();
5046
5047 // Suppress copying zero-width bitfields.
5048 if (Field->isZeroLengthBitField(SemaRef.Context))
5049 return false;
5050
5051 Expr *MemberExprBase =
5053 SourceLocation(), Param, false,
5054 Loc, ParamType, VK_LValue, nullptr);
5055
5056 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5057
5058 if (Moving) {
5059 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5060 }
5061
5062 // Build a reference to this field within the parameter.
5063 CXXScopeSpec SS;
5064 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5066 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5067 : cast<ValueDecl>(Field), AS_public);
5068 MemberLookup.resolveKind();
5069 ExprResult CtorArg
5070 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5071 ParamType, Loc,
5072 /*IsArrow=*/false,
5073 SS,
5074 /*TemplateKWLoc=*/SourceLocation(),
5075 /*FirstQualifierInScope=*/nullptr,
5076 MemberLookup,
5077 /*TemplateArgs=*/nullptr,
5078 /*S*/nullptr);
5079 if (CtorArg.isInvalid())
5080 return true;
5081
5082 // C++11 [class.copy]p15:
5083 // - if a member m has rvalue reference type T&&, it is direct-initialized
5084 // with static_cast<T&&>(x.m);
5085 if (RefersToRValueRef(CtorArg.get())) {
5086 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5087 }
5088
5089 InitializedEntity Entity =
5090 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5091 /*Implicit*/ true)
5092 : InitializedEntity::InitializeMember(Field, nullptr,
5093 /*Implicit*/ true);
5094
5095 // Direct-initialize to use the copy constructor.
5096 InitializationKind InitKind =
5098
5099 Expr *CtorArgE = CtorArg.getAs<Expr>();
5100 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5101 ExprResult MemberInit =
5102 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5103 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5104 if (MemberInit.isInvalid())
5105 return true;
5106
5107 if (Indirect)
5108 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5109 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5110 else
5111 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5112 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5113 return false;
5114 }
5115
5116 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5117 "Unhandled implicit init kind!");
5118
5119 QualType FieldBaseElementType =
5120 SemaRef.Context.getBaseElementType(Field->getType());
5121
5122 if (FieldBaseElementType->isRecordType()) {
5123 InitializedEntity InitEntity =
5124 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5125 /*Implicit*/ true)
5126 : InitializedEntity::InitializeMember(Field, nullptr,
5127 /*Implicit*/ true);
5128 InitializationKind InitKind =
5130
5131 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5132 ExprResult MemberInit =
5133 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5134
5135 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5136 if (MemberInit.isInvalid())
5137 return true;
5138
5139 if (Indirect)
5140 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5141 Indirect, Loc,
5142 Loc,
5143 MemberInit.get(),
5144 Loc);
5145 else
5146 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5147 Field, Loc, Loc,
5148 MemberInit.get(),
5149 Loc);
5150 return false;
5151 }
5152
5153 if (!Field->getParent()->isUnion()) {
5154 if (FieldBaseElementType->isReferenceType()) {
5155 SemaRef.Diag(Constructor->getLocation(),
5156 diag::err_uninitialized_member_in_ctor)
5157 << (int)Constructor->isImplicit()
5158 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5159 << 0 << Field->getDeclName();
5160 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5161 return true;
5162 }
5163
5164 if (FieldBaseElementType.isConstQualified()) {
5165 SemaRef.Diag(Constructor->getLocation(),
5166 diag::err_uninitialized_member_in_ctor)
5167 << (int)Constructor->isImplicit()
5168 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5169 << 1 << Field->getDeclName();
5170 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5171 return true;
5172 }
5173 }
5174
5175 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5176 // ARC and Weak:
5177 // Default-initialize Objective-C pointers to NULL.
5178 CXXMemberInit
5180 Loc, Loc,
5181 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5182 Loc);
5183 return false;
5184 }
5185
5186 // Nothing to initialize.
5187 CXXMemberInit = nullptr;
5188 return false;
5189}
5190
5191namespace {
5192struct BaseAndFieldInfo {
5193 Sema &S;
5194 CXXConstructorDecl *Ctor;
5195 bool AnyErrorsInInits;
5197 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5199 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5200
5201 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5202 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5203 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5204 if (Ctor->getInheritedConstructor())
5205 IIK = IIK_Inherit;
5206 else if (Generated && Ctor->isCopyConstructor())
5207 IIK = IIK_Copy;
5208 else if (Generated && Ctor->isMoveConstructor())
5209 IIK = IIK_Move;
5210 else
5211 IIK = IIK_Default;
5212 }
5213
5214 bool isImplicitCopyOrMove() const {
5215 switch (IIK) {
5216 case IIK_Copy:
5217 case IIK_Move:
5218 return true;
5219
5220 case IIK_Default:
5221 case IIK_Inherit:
5222 return false;
5223 }
5224
5225 llvm_unreachable("Invalid ImplicitInitializerKind!");
5226 }
5227
5228 bool addFieldInitializer(CXXCtorInitializer *Init) {
5229 AllToInit.push_back(Init);
5230
5231 // Check whether this initializer makes the field "used".
5232 if (Init->getInit()->HasSideEffects(S.Context))
5233 S.UnusedPrivateFields.remove(Init->getAnyMember());
5234
5235 return false;
5236 }
5237
5238 bool isInactiveUnionMember(FieldDecl *Field) {
5239 RecordDecl *Record = Field->getParent();
5240 if (!Record->isUnion())
5241 return false;
5242
5243 if (FieldDecl *Active =
5244 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5245 return Active != Field->getCanonicalDecl();
5246
5247 // In an implicit copy or move constructor, ignore any in-class initializer.
5248 if (isImplicitCopyOrMove())
5249 return true;
5250
5251 // If there's no explicit initialization, the field is active only if it
5252 // has an in-class initializer...
5253 if (Field->hasInClassInitializer())
5254 return false;
5255 // ... or it's an anonymous struct or union whose class has an in-class
5256 // initializer.
5257 if (!Field->isAnonymousStructOrUnion())
5258 return true;
5259 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5260 return !FieldRD->hasInClassInitializer();
5261 }
5262
5263 /// Determine whether the given field is, or is within, a union member
5264 /// that is inactive (because there was an initializer given for a different
5265 /// member of the union, or because the union was not initialized at all).
5266 bool isWithinInactiveUnionMember(FieldDecl *Field,
5267 IndirectFieldDecl *Indirect) {
5268 if (!Indirect)
5269 return isInactiveUnionMember(Field);
5270
5271 for (auto *C : Indirect->chain()) {
5272 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5273 if (Field && isInactiveUnionMember(Field))
5274 return true;
5275 }
5276 return false;
5277 }
5278};
5279}
5280
5281/// Determine whether the given type is an incomplete or zero-lenfgth
5282/// array type.
5284 if (T->isIncompleteArrayType())
5285 return true;
5286
5287 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5288 if (ArrayT->isZeroSize())
5289 return true;
5290
5291 T = ArrayT->getElementType();
5292 }
5293
5294 return false;
5295}
5296
5297static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5298 FieldDecl *Field,
5299 IndirectFieldDecl *Indirect = nullptr) {
5300 if (Field->isInvalidDecl())
5301 return false;
5302
5303 // Overwhelmingly common case: we have a direct initializer for this field.
5305 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5306 return Info.addFieldInitializer(Init);
5307
5308 // C++11 [class.base.init]p8:
5309 // if the entity is a non-static data member that has a
5310 // brace-or-equal-initializer and either
5311 // -- the constructor's class is a union and no other variant member of that
5312 // union is designated by a mem-initializer-id or
5313 // -- the constructor's class is not a union, and, if the entity is a member
5314 // of an anonymous union, no other member of that union is designated by
5315 // a mem-initializer-id,
5316 // the entity is initialized as specified in [dcl.init].
5317 //
5318 // We also apply the same rules to handle anonymous structs within anonymous
5319 // unions.
5320 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5321 return false;
5322
5323 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5324 ExprResult DIE =
5325 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5326 if (DIE.isInvalid())
5327 return true;
5328
5329 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5330 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5331
5333 if (Indirect)
5334 Init = new (SemaRef.Context)
5336 SourceLocation(), DIE.get(), SourceLocation());
5337 else
5338 Init = new (SemaRef.Context)
5340 SourceLocation(), DIE.get(), SourceLocation());
5341 return Info.addFieldInitializer(Init);
5342 }
5343
5344 // Don't initialize incomplete or zero-length arrays.
5345 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5346 return false;
5347
5348 // Don't try to build an implicit initializer if there were semantic
5349 // errors in any of the initializers (and therefore we might be
5350 // missing some that the user actually wrote).
5351 if (Info.AnyErrorsInInits)
5352 return false;
5353
5354 CXXCtorInitializer *Init = nullptr;
5355 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5356 Indirect, Init))
5357 return true;
5358
5359 if (!Init)
5360 return false;
5361
5362 return Info.addFieldInitializer(Init);
5363}
5364
5365bool
5368 assert(Initializer->isDelegatingInitializer());
5369 Constructor->setNumCtorInitializers(1);
5370 CXXCtorInitializer **initializer =
5371 new (Context) CXXCtorInitializer*[1];
5372 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5373 Constructor->setCtorInitializers(initializer);
5374
5375 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5376 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5377 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5378 }
5379
5380 DelegatingCtorDecls.push_back(Constructor);
5381
5382 DiagnoseUninitializedFields(*this, Constructor);
5383
5384 return false;
5385}
5386
5387bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5388 ArrayRef<CXXCtorInitializer *> Initializers) {
5389 if (Constructor->isDependentContext()) {
5390 // Just store the initializers as written, they will be checked during
5391 // instantiation.
5392 if (!Initializers.empty()) {
5393 Constructor->setNumCtorInitializers(Initializers.size());
5394 CXXCtorInitializer **baseOrMemberInitializers =
5395 new (Context) CXXCtorInitializer*[Initializers.size()];
5396 memcpy(baseOrMemberInitializers, Initializers.data(),
5397 Initializers.size() * sizeof(CXXCtorInitializer*));
5398 Constructor->setCtorInitializers(baseOrMemberInitializers);
5399 }
5400
5401 // Let template instantiation know whether we had errors.
5402 if (AnyErrors)
5403 Constructor->setInvalidDecl();
5404
5405 return false;
5406 }
5407
5408 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5409
5410 // We need to build the initializer AST according to order of construction
5411 // and not what user specified in the Initializers list.
5412 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5413 if (!ClassDecl)
5414 return true;
5415
5416 bool HadError = false;
5417
5418 for (unsigned i = 0; i < Initializers.size(); i++) {
5419 CXXCtorInitializer *Member = Initializers[i];
5420
5421 if (Member->isBaseInitializer())
5422 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5423 else {
5424 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5425
5426 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5427 for (auto *C : F->chain()) {
5428 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5429 if (FD && FD->getParent()->isUnion())
5430 Info.ActiveUnionMember.insert(std::make_pair(
5432 }
5433 } else if (FieldDecl *FD = Member->getMember()) {
5434 if (FD->getParent()->isUnion())
5435 Info.ActiveUnionMember.insert(std::make_pair(
5437 }
5438 }
5439 }
5440
5441 // Keep track of the direct virtual bases.
5443 for (auto &I : ClassDecl->bases()) {
5444 if (I.isVirtual())
5445 DirectVBases.insert(&I);
5446 }
5447
5448 // Push virtual bases before others.
5449 for (auto &VBase : ClassDecl->vbases()) {
5451 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5452 // [class.base.init]p7, per DR257:
5453 // A mem-initializer where the mem-initializer-id names a virtual base
5454 // class is ignored during execution of a constructor of any class that
5455 // is not the most derived class.
5456 if (ClassDecl->isAbstract()) {
5457 // FIXME: Provide a fixit to remove the base specifier. This requires
5458 // tracking the location of the associated comma for a base specifier.
5459 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5460 << VBase.getType() << ClassDecl;
5461 DiagnoseAbstractType(ClassDecl);
5462 }
5463
5464 Info.AllToInit.push_back(Value);
5465 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5466 // [class.base.init]p8, per DR257:
5467 // If a given [...] base class is not named by a mem-initializer-id
5468 // [...] and the entity is not a virtual base class of an abstract
5469 // class, then [...] the entity is default-initialized.
5470 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5471 CXXCtorInitializer *CXXBaseInit;
5472 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5473 &VBase, IsInheritedVirtualBase,
5474 CXXBaseInit)) {
5475 HadError = true;
5476 continue;
5477 }
5478
5479 Info.AllToInit.push_back(CXXBaseInit);
5480 }
5481 }
5482
5483 // Non-virtual bases.
5484 for (auto &Base : ClassDecl->bases()) {
5485 // Virtuals are in the virtual base list and already constructed.
5486 if (Base.isVirtual())
5487 continue;
5488
5490 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5491 Info.AllToInit.push_back(Value);
5492 } else if (!AnyErrors) {
5493 CXXCtorInitializer *CXXBaseInit;
5494 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5495 &Base, /*IsInheritedVirtualBase=*/false,
5496 CXXBaseInit)) {
5497 HadError = true;
5498 continue;
5499 }
5500
5501 Info.AllToInit.push_back(CXXBaseInit);
5502 }
5503 }
5504
5505 // Fields.
5506 for (auto *Mem : ClassDecl->decls()) {
5507 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5508 // C++ [class.bit]p2:
5509 // A declaration for a bit-field that omits the identifier declares an
5510 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5511 // initialized.
5512 if (F->isUnnamedBitField())
5513 continue;
5514
5515 // If we're not generating the implicit copy/move constructor, then we'll
5516 // handle anonymous struct/union fields based on their individual
5517 // indirect fields.
5518 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5519 continue;
5520
5521 if (CollectFieldInitializer(*this, Info, F))
5522 HadError = true;
5523 continue;
5524 }
5525
5526 // Beyond this point, we only consider default initialization.
5527 if (Info.isImplicitCopyOrMove())
5528 continue;
5529
5530 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5531 if (F->getType()->isIncompleteArrayType()) {
5532 assert(ClassDecl->hasFlexibleArrayMember() &&
5533 "Incomplete array type is not valid");
5534 continue;
5535 }
5536
5537 // Initialize each field of an anonymous struct individually.
5538 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5539 HadError = true;
5540
5541 continue;
5542 }
5543 }
5544
5545 unsigned NumInitializers = Info.AllToInit.size();
5546 if (NumInitializers > 0) {
5547 Constructor->setNumCtorInitializers(NumInitializers);
5548 CXXCtorInitializer **baseOrMemberInitializers =
5549 new (Context) CXXCtorInitializer*[NumInitializers];
5550 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5551 NumInitializers * sizeof(CXXCtorInitializer*));
5552 Constructor->setCtorInitializers(baseOrMemberInitializers);
5553
5554 // Constructors implicitly reference the base and member
5555 // destructors.
5556 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5557 Constructor->getParent());
5558 }
5559
5560 return HadError;
5561}
5562
5564 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5565 const RecordDecl *RD = RT->getDecl();
5566 if (RD->isAnonymousStructOrUnion()) {
5567 for (auto *Field : RD->fields())
5568 PopulateKeysForFields(Field, IdealInits);
5569 return;
5570 }
5571 }
5572 IdealInits.push_back(Field->getCanonicalDecl());
5573}
5574
5575static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5576 return Context.getCanonicalType(BaseType).getTypePtr();
5577}
5578
5581 if (!Member->isAnyMemberInitializer())
5582 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5583
5584 return Member->getAnyMember()->getCanonicalDecl();
5585}
5586
5589 const CXXCtorInitializer *Current) {
5590 if (Previous->isAnyMemberInitializer())
5591 Diag << 0 << Previous->getAnyMember();
5592 else
5593 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5594
5595 if (Current->isAnyMemberInitializer())
5596 Diag << 0 << Current->getAnyMember();
5597 else
5598 Diag << 1 << Current->getTypeSourceInfo()->getType();
5599}
5600
5602 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5604 if (Constructor->getDeclContext()->isDependentContext())
5605 return;
5606
5607 // Don't check initializers order unless the warning is enabled at the
5608 // location of at least one initializer.
5609 bool ShouldCheckOrder = false;
5610 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5611 CXXCtorInitializer *Init = Inits[InitIndex];
5612 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5613 Init->getSourceLocation())) {
5614 ShouldCheckOrder = true;
5615 break;
5616 }
5617 }
5618 if (!ShouldCheckOrder)
5619 return;
5620
5621 // Build the list of bases and members in the order that they'll
5622 // actually be initialized. The explicit initializers should be in
5623 // this same order but may be missing things.
5624 SmallVector<const void*, 32> IdealInitKeys;
5625
5626 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5627
5628 // 1. Virtual bases.
5629 for (const auto &VBase : ClassDecl->vbases())
5630 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5631
5632 // 2. Non-virtual bases.
5633 for (const auto &Base : ClassDecl->bases()) {
5634 if (Base.isVirtual())
5635 continue;
5636 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5637 }
5638
5639 // 3. Direct fields.
5640 for (auto *Field : ClassDecl->fields()) {
5641 if (Field->isUnnamedBitField())
5642 continue;
5643
5644 PopulateKeysForFields(Field, IdealInitKeys);
5645 }
5646
5647 unsigned NumIdealInits = IdealInitKeys.size();
5648 unsigned IdealIndex = 0;
5649
5650 // Track initializers that are in an incorrect order for either a warning or
5651 // note if multiple ones occur.
5652 SmallVector<unsigned> WarnIndexes;
5653 // Correlates the index of an initializer in the init-list to the index of
5654 // the field/base in the class.
5655 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5656
5657 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5658 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5659
5660 // Scan forward to try to find this initializer in the idealized
5661 // initializers list.
5662 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5663 if (InitKey == IdealInitKeys[IdealIndex])
5664 break;
5665
5666 // If we didn't find this initializer, it must be because we
5667 // scanned past it on a previous iteration. That can only
5668 // happen if we're out of order; emit a warning.
5669 if (IdealIndex == NumIdealInits && InitIndex) {
5670 WarnIndexes.push_back(InitIndex);
5671
5672 // Move back to the initializer's location in the ideal list.
5673 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5674 if (InitKey == IdealInitKeys[IdealIndex])
5675 break;
5676
5677 assert(IdealIndex < NumIdealInits &&
5678 "initializer not found in initializer list");
5679 }
5680 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5681 }
5682
5683 if (WarnIndexes.empty())
5684 return;
5685
5686 // Sort based on the ideal order, first in the pair.
5687 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5688
5689 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5690 // emit the diagnostic before we can try adding notes.
5691 {
5693 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5694 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5695 : diag::warn_some_initializers_out_of_order);
5696
5697 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5698 if (CorrelatedInitOrder[I].second == I)
5699 continue;
5700 // Ideally we would be using InsertFromRange here, but clang doesn't
5701 // appear to handle InsertFromRange correctly when the source range is
5702 // modified by another fix-it.
5704 Inits[I]->getSourceRange(),
5707 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5709 }
5710
5711 // If there is only 1 item out of order, the warning expects the name and
5712 // type of each being added to it.
5713 if (WarnIndexes.size() == 1) {
5714 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5715 Inits[WarnIndexes.front()]);
5716 return;
5717 }
5718 }
5719 // More than 1 item to warn, create notes letting the user know which ones
5720 // are bad.
5721 for (unsigned WarnIndex : WarnIndexes) {
5722 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5723 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5724 diag::note_initializer_out_of_order);
5725 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5726 D << PrevInit->getSourceRange();
5727 }
5728}
5729
5730namespace {
5731bool CheckRedundantInit(Sema &S,
5733 CXXCtorInitializer *&PrevInit) {
5734 if (!PrevInit) {
5735 PrevInit = Init;
5736 return false;
5737 }
5738
5739 if (FieldDecl *Field = Init->getAnyMember())
5740 S.Diag(Init->getSourceLocation(),
5741 diag::err_multiple_mem_initialization)
5742 << Field->getDeclName()
5743 << Init->getSourceRange();
5744 else {
5745 const Type *BaseClass = Init->getBaseClass();
5746 assert(BaseClass && "neither field nor base");
5747 S.Diag(Init->getSourceLocation(),
5748 diag::err_multiple_base_initialization)
5749 << QualType(BaseClass, 0)
5750 << Init->getSourceRange();
5751 }
5752 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5753 << 0 << PrevInit->getSourceRange();
5754
5755 return true;
5756}
5757
5758typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5759typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5760
5761bool CheckRedundantUnionInit(Sema &S,
5763 RedundantUnionMap &Unions) {
5764 FieldDecl *Field = Init->getAnyMember();
5765 RecordDecl *Parent = Field->getParent();
5766 NamedDecl *Child = Field;
5767
5768 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5769 if (Parent->isUnion()) {
5770 UnionEntry &En = Unions[Parent];
5771 if (En.first && En.first != Child) {
5772 S.Diag(Init->getSourceLocation(),
5773 diag::err_multiple_mem_union_initialization)
5774 << Field->getDeclName()
5775 << Init->getSourceRange();
5776 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5777 << 0 << En.second->getSourceRange();
5778 return true;
5779 }
5780 if (!En.first) {
5781 En.first = Child;
5782 En.second = Init;
5783 }
5784 if (!Parent->isAnonymousStructOrUnion())
5785 return false;
5786 }
5787
5788 Child = Parent;
5789 Parent = cast<RecordDecl>(Parent->getDeclContext());
5790 }
5791
5792 return false;
5793}
5794} // namespace
5795
5796/// ActOnMemInitializers - Handle the member initializers for a constructor.
5797void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5798 SourceLocation ColonLoc,
5800 bool AnyErrors) {
5801 if (!ConstructorDecl)
5802 return;
5803
5804 AdjustDeclIfTemplate(ConstructorDecl);
5805
5806 CXXConstructorDecl *Constructor
5807 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5808
5809 if (!Constructor) {
5810 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5811 return;
5812 }
5813
5814 // Mapping for the duplicate initializers check.
5815 // For member initializers, this is keyed with a FieldDecl*.
5816 // For base initializers, this is keyed with a Type*.
5817 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5818
5819 // Mapping for the inconsistent anonymous-union initializers check.
5820 RedundantUnionMap MemberUnions;
5821
5822 bool HadError = false;
5823 for (unsigned i = 0; i < MemInits.size(); i++) {
5824 CXXCtorInitializer *Init = MemInits[i];
5825
5826 // Set the source order index.
5827 Init->setSourceOrder(i);
5828
5829 if (Init->isAnyMemberInitializer()) {
5830 const void *Key = GetKeyForMember(Context, Init);
5831 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5832 CheckRedundantUnionInit(*this, Init, MemberUnions))
5833 HadError = true;
5834 } else if (Init->isBaseInitializer()) {
5835 const void *Key = GetKeyForMember(Context, Init);
5836 if (CheckRedundantInit(*this, Init, Members[Key]))
5837 HadError = true;
5838 } else {
5839 assert(Init->isDelegatingInitializer());
5840 // This must be the only initializer
5841 if (MemInits.size() != 1) {
5842 Diag(Init->getSourceLocation(),
5843 diag::err_delegating_initializer_alone)
5844 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5845 // We will treat this as being the only initializer.
5846 }
5847 SetDelegatingInitializer(Constructor, MemInits[i]);
5848 // Return immediately as the initializer is set.
5849 return;
5850 }
5851 }
5852
5853 if (HadError)
5854 return;
5855
5856 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5857
5858 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5859
5860 DiagnoseUninitializedFields(*this, Constructor);
5861}
5862
5863void
5865 CXXRecordDecl *ClassDecl) {
5866 // Ignore dependent contexts. Also ignore unions, since their members never
5867 // have destructors implicitly called.
5868 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5869 return;
5870
5871 // FIXME: all the access-control diagnostics are positioned on the
5872 // field/base declaration. That's probably good; that said, the
5873 // user might reasonably want to know why the destructor is being
5874 // emitted, and we currently don't say.
5875
5876 // Non-static data members.
5877 for (auto *Field : ClassDecl->fields()) {
5878 if (Field->isInvalidDecl())
5879 continue;
5880
5881 // Don't destroy incomplete or zero-length arrays.
5882 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5883 continue;
5884
5885 QualType FieldType = Context.getBaseElementType(Field->getType());
5886
5887 const RecordType* RT = FieldType->getAs<RecordType>();
5888 if (!RT)
5889 continue;
5890
5891 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5892 if (FieldClassDecl->isInvalidDecl())
5893 continue;
5894 if (FieldClassDecl->hasIrrelevantDestructor())
5895 continue;
5896 // The destructor for an implicit anonymous union member is never invoked.
5897 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5898 continue;
5899
5900 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5901 // Dtor might still be missing, e.g because it's invalid.
5902 if (!Dtor)
5903 continue;
5904 CheckDestructorAccess(Field->getLocation(), Dtor,
5905 PDiag(diag::err_access_dtor_field)
5906 << Field->getDeclName()
5907 << FieldType);
5908
5909 MarkFunctionReferenced(Location, Dtor);
5910 DiagnoseUseOfDecl(Dtor, Location);
5911 }
5912
5913 // We only potentially invoke the destructors of potentially constructed
5914 // subobjects.
5915 bool VisitVirtualBases = !ClassDecl->isAbstract();
5916
5917 // If the destructor exists and has already been marked used in the MS ABI,
5918 // then virtual base destructors have already been checked and marked used.
5919 // Skip checking them again to avoid duplicate diagnostics.
5921 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5922 if (Dtor && Dtor->isUsed())
5923 VisitVirtualBases = false;
5924 }
5925
5927
5928 // Bases.
5929 for (const auto &Base : ClassDecl->bases()) {
5930 const RecordType *RT = Base.getType()->getAs<RecordType>();
5931 if (!RT)
5932 continue;
5933
5934 // Remember direct virtual bases.
5935 if (Base.isVirtual()) {
5936 if (!VisitVirtualBases)
5937 continue;
5938 DirectVirtualBases.insert(RT);
5939 }
5940
5941 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5942 // If our base class is invalid, we probably can't get its dtor anyway.
5943 if (BaseClassDecl->isInvalidDecl())
5944 continue;
5945 if (BaseClassDecl->hasIrrelevantDestructor())
5946 continue;
5947
5948 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5949 // Dtor might still be missing, e.g because it's invalid.
5950 if (!Dtor)
5951 continue;
5952
5953 // FIXME: caret should be on the start of the class name
5954 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5955 PDiag(diag::err_access_dtor_base)
5956 << Base.getType() << Base.getSourceRange(),
5957 Context.getTypeDeclType(ClassDecl));
5958
5959 MarkFunctionReferenced(Location, Dtor);
5960 DiagnoseUseOfDecl(Dtor, Location);
5961 }
5962
5963 if (VisitVirtualBases)
5964 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5965 &DirectVirtualBases);
5966}
5967
5969 SourceLocation Location, CXXRecordDecl *ClassDecl,
5970 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5971 // Virtual bases.
5972 for (const auto &VBase : ClassDecl->vbases()) {
5973 // Bases are always records in a well-formed non-dependent class.
5974 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5975
5976 // Ignore already visited direct virtual bases.
5977 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5978 continue;
5979
5980 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5981 // If our base class is invalid, we probably can't get its dtor anyway.
5982 if (BaseClassDecl->isInvalidDecl())
5983 continue;
5984 if (BaseClassDecl->hasIrrelevantDestructor())
5985 continue;
5986
5987 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5988 // Dtor might still be missing, e.g because it's invalid.
5989 if (!Dtor)
5990 continue;
5992 ClassDecl->getLocation(), Dtor,
5993 PDiag(diag::err_access_dtor_vbase)
5994 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5995 Context.getTypeDeclType(ClassDecl)) ==
5996 AR_accessible) {
5998 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5999 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
6000 SourceRange(), DeclarationName(), nullptr);
6001 }
6002
6003 MarkFunctionReferenced(Location, Dtor);
6004 DiagnoseUseOfDecl(Dtor, Location);
6005 }
6006}
6007
6009 if (!CDtorDecl)
6010 return;
6011
6012 if (CXXConstructorDecl *Constructor
6013 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6014 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6015 !ClassDecl || ClassDecl->isInvalidDecl()) {
6016 return;
6017 }
6018 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6019 DiagnoseUninitializedFields(*this, Constructor);
6020 }
6021}
6022
6024 if (!getLangOpts().CPlusPlus)
6025 return false;
6026
6027 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6028 if (!RD)
6029 return false;
6030
6031 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6032 // class template specialization here, but doing so breaks a lot of code.
6033
6034 // We can't answer whether something is abstract until it has a
6035 // definition. If it's currently being defined, we'll walk back
6036 // over all the declarations when we have a full definition.
6037 const CXXRecordDecl *Def = RD->getDefinition();
6038 if (!Def || Def->isBeingDefined())
6039 return false;
6040
6041 return RD->isAbstract();
6042}
6043
6045 TypeDiagnoser &Diagnoser) {
6046 if (!isAbstractType(Loc, T))
6047 return false;
6048
6050 Diagnoser.diagnose(*this, Loc, T);
6052 return true;
6053}
6054
6056 // Check if we've already emitted the list of pure virtual functions
6057 // for this class.
6059 return;
6060
6061 // If the diagnostic is suppressed, don't emit the notes. We're only
6062 // going to emit them once, so try to attach them to a diagnostic we're
6063 // actually going to show.
6065 return;
6066
6067 CXXFinalOverriderMap FinalOverriders;
6068 RD->getFinalOverriders(FinalOverriders);
6069
6070 // Keep a set of seen pure methods so we won't diagnose the same method
6071 // more than once.
6073
6074 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6075 MEnd = FinalOverriders.end();
6076 M != MEnd;
6077 ++M) {
6078 for (OverridingMethods::iterator SO = M->second.begin(),
6079 SOEnd = M->second.end();
6080 SO != SOEnd; ++SO) {
6081 // C++ [class.abstract]p4:
6082 // A class is abstract if it contains or inherits at least one
6083 // pure virtual function for which the final overrider is pure
6084 // virtual.
6085
6086 //
6087 if (SO->second.size() != 1)
6088 continue;
6089
6090 if (!SO->second.front().Method->isPureVirtual())
6091 continue;
6092
6093 if (!SeenPureMethods.insert(SO->second.front().Method).second)
6094 continue;
6095
6096 Diag(SO->second.front().Method->getLocation(),
6097 diag::note_pure_virtual_function)
6098 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6099 }
6100 }
6101
6104 PureVirtualClassDiagSet->insert(RD);
6105}
6106
6107namespace {
6108struct AbstractUsageInfo {
6109 Sema &S;
6111 CanQualType AbstractType;
6112 bool Invalid;
6113
6114 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6115 : S(S), Record(Record),
6116 AbstractType(S.Context.getCanonicalType(
6117 S.Context.getTypeDeclType(Record))),
6118 Invalid(false) {}
6119
6120 void DiagnoseAbstractType() {
6121 if (Invalid) return;
6123 Invalid = true;
6124 }
6125
6126 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6127};
6128
6129struct CheckAbstractUsage {
6130 AbstractUsageInfo &Info;
6131 const NamedDecl *Ctx;
6132
6133 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6134 : Info(Info), Ctx(Ctx) {}
6135
6136 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6137 switch (TL.getTypeLocClass()) {
6138#define ABSTRACT_TYPELOC(CLASS, PARENT)
6139#define TYPELOC(CLASS, PARENT) \
6140 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6141#include "clang/AST/TypeLocNodes.def"
6142 }
6143 }
6144
6145 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6147 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6148 if (!TL.getParam(I))
6149 continue;
6150
6152 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6153 }
6154 }
6155
6156 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6158 }
6159
6161 // Visit the type parameters from a permissive context.
6162 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6163 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6165 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6166 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6167 // TODO: other template argument types?
6168 }
6169 }
6170
6171 // Visit pointee types from a permissive context.
6172#define CheckPolymorphic(Type) \
6173 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6174 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6175 }
6181
6182 /// Handle all the types we haven't given a more specific
6183 /// implementation for above.
6184 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6185 // Every other kind of type that we haven't called out already
6186 // that has an inner type is either (1) sugar or (2) contains that
6187 // inner type in some way as a subobject.
6188 if (TypeLoc Next = TL.getNextTypeLoc())
6189 return Visit(Next, Sel);
6190
6191 // If there's no inner type and we're in a permissive context,
6192 // don't diagnose.
6193 if (Sel == Sema::AbstractNone) return;
6194
6195 // Check whether the type matches the abstract type.
6196 QualType T = TL.getType();
6197 if (T->isArrayType()) {
6199 T = Info.S.Context.getBaseElementType(T);
6200 }
6202 if (CT != Info.AbstractType) return;
6203
6204 // It matched; do some magic.
6205 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6206 if (Sel == Sema::AbstractArrayType) {
6207 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6208 << T << TL.getSourceRange();
6209 } else {
6210 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6211 << Sel << T << TL.getSourceRange();
6212 }
6213 Info.DiagnoseAbstractType();
6214 }
6215};
6216
6217void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6219 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6220}
6221
6222}
6223
6224/// Check for invalid uses of an abstract type in a function declaration.
6225static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6226 FunctionDecl *FD) {
6227 // Only definitions are required to refer to complete and
6228 // non-abstract types.
6230 return;
6231
6232 // For safety's sake, just ignore it if we don't have type source
6233 // information. This should never happen for non-implicit methods,
6234 // but...
6235 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6236 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6237}
6238
6239/// Check for invalid uses of an abstract type in a variable0 declaration.
6240static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6241 VarDecl *VD) {
6242 // No need to do the check on definitions, which require that
6243 // the type is complete.
6245 return;
6246
6247 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6249}
6250
6251/// Check for invalid uses of an abstract type within a class definition.
6252static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6253 CXXRecordDecl *RD) {
6254 for (auto *D : RD->decls()) {
6255 if (D->isImplicit()) continue;
6256
6257 // Step through friends to the befriended declaration.
6258 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6259 D = FD->getFriendDecl();
6260 if (!D) continue;
6261 }
6262
6263 // Functions and function templates.
6264 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6265 CheckAbstractClassUsage(Info, FD);
6266 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6267 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6268
6269 // Fields and static variables.
6270 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6271 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6272 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6273 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6274 CheckAbstractClassUsage(Info, VD);
6275 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6276 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6277
6278 // Nested classes and class templates.
6279 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6280 CheckAbstractClassUsage(Info, RD);
6281 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6282 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6283 }
6284 }
6285}
6286
6288 Attr *ClassAttr = getDLLAttr(Class);
6289 if (!ClassAttr)
6290 return;
6291
6292 assert(ClassAttr->getKind() == attr::DLLExport);
6293
6294 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6295
6297 // Don't go any further if this is just an explicit instantiation
6298 // declaration.
6299 return;
6300
6301 // Add a context note to explain how we got to any diagnostics produced below.
6302 struct MarkingClassDllexported {
6303 Sema &S;
6304 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6305 SourceLocation AttrLoc)
6306 : S(S) {
6309 Ctx.PointOfInstantiation = AttrLoc;
6310 Ctx.Entity = Class;
6312 }
6313 ~MarkingClassDllexported() {
6315 }
6316 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6317
6318 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6319 S.MarkVTableUsed(Class->getLocation(), Class, true);
6320
6321 for (Decl *Member : Class->decls()) {
6322 // Skip members that were not marked exported.
6323 if (!Member->hasAttr<DLLExportAttr>())
6324 continue;
6325
6326 // Defined static variables that are members of an exported base
6327 // class must be marked export too.
6328 auto *VD = dyn_cast<VarDecl>(Member);
6329 if (VD && VD->getStorageClass() == SC_Static &&
6331 S.MarkVariableReferenced(VD->getLocation(), VD);
6332
6333 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6334 if (!MD)
6335 continue;
6336
6337 if (MD->isUserProvided()) {
6338 // Instantiate non-default class member functions ...
6339
6340 // .. except for certain kinds of template specializations.
6341 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6342 continue;
6343
6344 // If this is an MS ABI dllexport default constructor, instantiate any
6345 // default arguments.
6347 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6348 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6350 }
6351 }
6352
6353 S.MarkFunctionReferenced(Class->getLocation(), MD);
6354
6355 // The function will be passed to the consumer when its definition is
6356 // encountered.
6357 } else if (MD->isExplicitlyDefaulted()) {
6358 // Synthesize and instantiate explicitly defaulted methods.
6359 S.MarkFunctionReferenced(Class->getLocation(), MD);
6360
6362 // Except for explicit instantiation defs, we will not see the
6363 // definition again later, so pass it to the consumer now.
6365 }
6366 } else if (!MD->isTrivial() ||
6367 MD->isCopyAssignmentOperator() ||
6368 MD->isMoveAssignmentOperator()) {
6369 // Synthesize and instantiate non-trivial implicit methods, and the copy
6370 // and move assignment operators. The latter are exported even if they
6371 // are trivial, because the address of an operator can be taken and
6372 // should compare equal across libraries.
6373 S.MarkFunctionReferenced(Class->getLocation(), MD);
6374
6375 // There is no later point when we will see the definition of this
6376 // function, so pass it to the consumer now.
6378 }
6379 }
6380}
6381
6384 // Only the MS ABI has default constructor closures, so we don't need to do
6385 // this semantic checking anywhere else.
6387 return;
6388
6389 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6390 for (Decl *Member : Class->decls()) {
6391 // Look for exported default constructors.
6392 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6393 if (!CD || !CD->isDefaultConstructor())
6394 continue;
6395 auto *Attr = CD->getAttr<DLLExportAttr>();
6396 if (!Attr)
6397 continue;
6398
6399 // If the class is non-dependent, mark the default arguments as ODR-used so
6400 // that we can properly codegen the constructor closure.
6401 if (!Class->isDependentContext()) {
6402 for (ParmVarDecl *PD : CD->parameters()) {
6403 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6405 }
6406 }
6407
6408 if (LastExportedDefaultCtor) {
6409 S.Diag(LastExportedDefaultCtor->getLocation(),
6410 diag::err_attribute_dll_ambiguous_default_ctor)
6411 << Class;
6412 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6413 << CD->getDeclName();
6414 return;
6415 }
6416 LastExportedDefaultCtor = CD;
6417 }
6418}
6419
6422 bool ErrorReported = false;
6423 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6424 ClassTemplateDecl *TD) {
6425 if (ErrorReported)
6426 return;
6427 S.Diag(TD->getLocation(),
6428 diag::err_cuda_device_builtin_surftex_cls_template)
6429 << /*surface*/ 0 << TD;
6430 ErrorReported = true;
6431 };
6432
6433 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6434 if (!TD) {
6435 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6436 if (!SD) {
6437 S.Diag(Class->getLocation(),
6438 diag::err_cuda_device_builtin_surftex_ref_decl)
6439 << /*surface*/ 0 << Class;
6440 S.Diag(Class->getLocation(),
6441 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6442 << Class;
6443 return;
6444 }
6445 TD = SD->getSpecializedTemplate();
6446 }
6447
6449 unsigned N = Params->size();
6450
6451 if (N != 2) {
6452 reportIllegalClassTemplate(S, TD);
6453 S.Diag(TD->getLocation(),
6454 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6455 << TD << 2;
6456 }
6457 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6458 reportIllegalClassTemplate(S, TD);
6459 S.Diag(TD->getLocation(),
6460 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6461 << TD << /*1st*/ 0 << /*type*/ 0;
6462 }
6463 if (N > 1) {
6464 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6465 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6466 reportIllegalClassTemplate(S, TD);
6467 S.Diag(TD->getLocation(),
6468 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6469 << TD << /*2nd*/ 1 << /*integer*/ 1;
6470 }
6471 }
6472}
6473
6476 bool ErrorReported = false;
6477 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6478 ClassTemplateDecl *TD) {
6479 if (ErrorReported)
6480 return;
6481 S.Diag(TD->getLocation(),
6482 diag::err_cuda_device_builtin_surftex_cls_template)
6483 << /*texture*/ 1 << TD;
6484 ErrorReported = true;
6485 };
6486
6487 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6488 if (!TD) {
6489 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6490 if (!SD) {
6491 S.Diag(Class->getLocation(),
6492 diag::err_cuda_device_builtin_surftex_ref_decl)
6493 << /*texture*/ 1 << Class;
6494 S.Diag(Class->getLocation(),
6495 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6496 << Class;
6497 return;
6498 }
6499 TD = SD->getSpecializedTemplate();
6500 }
6501
6503 unsigned N = Params->size();
6504
6505 if (N != 3) {
6506 reportIllegalClassTemplate(S, TD);
6507 S.Diag(TD->getLocation(),
6508 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6509 << TD << 3;
6510 }
6511 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6512 reportIllegalClassTemplate(S, TD);
6513 S.Diag(TD->getLocation(),
6514 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6515 << TD << /*1st*/ 0 << /*type*/ 0;
6516 }
6517 if (N > 1) {
6518 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6519 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6520 reportIllegalClassTemplate(S, TD);
6521 S.Diag(TD->getLocation(),
6522 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6523 << TD << /*2nd*/ 1 << /*integer*/ 1;
6524 }
6525 }
6526 if (N > 2) {
6527 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6528 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6529 reportIllegalClassTemplate(S, TD);
6530 S.Diag(TD->getLocation(),
6531 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6532 << TD << /*3rd*/ 2 << /*integer*/ 1;
6533 }
6534 }
6535}
6536
6538 // Mark any compiler-generated routines with the implicit code_seg attribute.
6539 for (auto *Method : Class->methods()) {
6540 if (Method->isUserProvided())
6541 continue;
6542 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6543 Method->addAttr(A);
6544 }
6545}
6546
6547/// Check class-level dllimport/dllexport attribute.
6549 Attr *ClassAttr = getDLLAttr(Class);
6550
6551 // MSVC inherits DLL attributes to partial class template specializations.
6552 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6553 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6554 if (Attr *TemplateAttr =
6555 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6556 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6557 A->setInherited(true);
6558 ClassAttr = A;
6559 }
6560 }
6561 }
6562
6563 if (!ClassAttr)
6564 return;
6565
6566 // MSVC allows imported or exported template classes that have UniqueExternal
6567 // linkage. This occurs when the template class has been instantiated with
6568 // a template parameter which itself has internal linkage.
6569 // We drop the attribute to avoid exporting or importing any members.
6571 Context.getTargetInfo().getTriple().isPS()) &&
6572 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6573 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6574 return;
6575 }
6576
6577 if (!Class->isExternallyVisible()) {
6578 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6579 << Class << ClassAttr;
6580 return;
6581 }
6582
6584 !ClassAttr->isInherited()) {
6585 // Diagnose dll attributes on members of class with dll attribute.
6586 for (Decl *Member : Class->decls()) {
6587 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6588 continue;
6589 InheritableAttr *MemberAttr = getDLLAttr(Member);
6590 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6591 continue;
6592
6593 Diag(MemberAttr->getLocation(),
6594 diag::err_attribute_dll_member_of_dll_class)
6595 << MemberAttr << ClassAttr;
6596 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6597 Member->setInvalidDecl();
6598 }
6599 }
6600
6601 if (Class->getDescribedClassTemplate())
6602 // Don't inherit dll attribute until the template is instantiated.
6603 return;
6604
6605 // The class is either imported or exported.
6606 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6607
6608 // Check if this was a dllimport attribute propagated from a derived class to
6609 // a base class template specialization. We don't apply these attributes to
6610 // static data members.
6611 const bool PropagatedImport =
6612 !ClassExported &&
6613 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6614
6615 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6616
6617 // Ignore explicit dllexport on explicit class template instantiation
6618 // declarations, except in MinGW mode.
6619 if (ClassExported && !ClassAttr->isInherited() &&
6621 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6622 Class->dropAttr<DLLExportAttr>();
6623 return;
6624 }
6625
6626 // Force declaration of implicit members so they can inherit the attribute.
6628
6629 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6630 // seem to be true in practice?
6631
6632 for (Decl *Member : Class->decls()) {
6633 VarDecl *VD = dyn_cast<VarDecl>(Member);
6634 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6635
6636 // Only methods and static fields inherit the attributes.
6637 if (!VD && !MD)
6638 continue;
6639
6640 if (MD) {
6641 // Don't process deleted methods.
6642 if (MD->isDeleted())
6643 continue;
6644
6645 if (MD->isInlined()) {
6646 // MinGW does not import or export inline methods. But do it for
6647 // template instantiations.
6651 continue;
6652
6653 // MSVC versions before 2015 don't export the move assignment operators
6654 // and move constructor, so don't attempt to import/export them if
6655 // we have a definition.
6656 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6657 if ((MD->isMoveAssignmentOperator() ||
6658 (Ctor && Ctor->isMoveConstructor())) &&
6659 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6660 continue;
6661
6662 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6663 // operator is exported anyway.
6664 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6665 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6666 continue;
6667 }
6668 }
6669
6670 // Don't apply dllimport attributes to static data members of class template
6671 // instantiations when the attribute is propagated from a derived class.
6672 if (VD && PropagatedImport)
6673 continue;
6674
6675 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6676 continue;
6677
6678 if (!getDLLAttr(Member)) {
6679 InheritableAttr *NewAttr = nullptr;
6680
6681 // Do not export/import inline function when -fno-dllexport-inlines is
6682 // passed. But add attribute for later local static var check.
6683 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6686 if (ClassExported) {
6687 NewAttr = ::new (getASTContext())
6688 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6689 } else {
6690 NewAttr = ::new (getASTContext())
6691 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6692 }
6693 } else {
6694 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6695 }
6696
6697 NewAttr->setInherited(true);
6698 Member->addAttr(NewAttr);
6699
6700 if (MD) {
6701 // Propagate DLLAttr to friend re-declarations of MD that have already
6702 // been constructed.
6703 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6704 FD = FD->getPreviousDecl()) {
6706 continue;
6707 assert(!getDLLAttr(FD) &&
6708 "friend re-decl should not already have a DLLAttr");
6709 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6710 NewAttr->setInherited(true);
6711 FD->addAttr(NewAttr);
6712 }
6713 }
6714 }
6715 }
6716
6717 if (ClassExported)
6718 DelayedDllExportClasses.push_back(Class);
6719}
6720
6721/// Perform propagation of DLL attributes from a derived class to a
6722/// templated base class for MS compatibility.
6724 CXXRecordDecl *Class, Attr *ClassAttr,
6725 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6726 if (getDLLAttr(
6727 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6728 // If the base class template has a DLL attribute, don't try to change it.
6729 return;
6730 }
6731
6732 auto TSK = BaseTemplateSpec->getSpecializationKind();
6733 if (!getDLLAttr(BaseTemplateSpec) &&
6735 TSK == TSK_ImplicitInstantiation)) {
6736 // The template hasn't been instantiated yet (or it has, but only as an
6737 // explicit instantiation declaration or implicit instantiation, which means
6738 // we haven't codegenned any members yet), so propagate the attribute.
6739 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6740 NewAttr->setInherited(true);
6741 BaseTemplateSpec->addAttr(NewAttr);
6742
6743 // If this was an import, mark that we propagated it from a derived class to
6744 // a base class template specialization.
6745 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6746 ImportAttr->setPropagatedToBaseTemplate();
6747
6748 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6749 // needs to be run again to work see the new attribute. Otherwise this will
6750 // get run whenever the template is instantiated.
6751 if (TSK != TSK_Undeclared)
6752 checkClassLevelDLLAttribute(BaseTemplateSpec);
6753
6754 return;
6755 }
6756
6757 if (getDLLAttr(BaseTemplateSpec)) {
6758 // The template has already been specialized or instantiated with an
6759 // attribute, explicitly or through propagation. We should not try to change
6760 // it.
6761 return;
6762 }
6763
6764 // The template was previously instantiated or explicitly specialized without
6765 // a dll attribute, It's too late for us to add an attribute, so warn that
6766 // this is unsupported.
6767 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6768 << BaseTemplateSpec->isExplicitSpecialization();
6769 Diag(ClassAttr->getLocation(), diag::note_attribute);
6770 if (BaseTemplateSpec->isExplicitSpecialization()) {
6771 Diag(BaseTemplateSpec->getLocation(),
6772 diag::note_template_class_explicit_specialization_was_here)
6773 << BaseTemplateSpec;
6774 } else {
6775 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6776 diag::note_template_class_instantiation_was_here)
6777 << BaseTemplateSpec;
6778 }
6779}
6780
6781/// Determine the kind of defaulting that would be done for a given function.
6782///
6783/// If the function is both a default constructor and a copy / move constructor
6784/// (due to having a default argument for the first parameter), this picks
6785/// CXXSpecialMemberKind::DefaultConstructor.
6786///
6787/// FIXME: Check that case is properly handled by all callers.
6790 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6791 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6792 if (Ctor->isDefaultConstructor())
6794
6795 if (Ctor->isCopyConstructor())
6797
6798 if (Ctor->isMoveConstructor())
6800 }
6801
6802 if (MD->isCopyAssignmentOperator())
6804
6805 if (MD->isMoveAssignmentOperator())
6807
6808 if (isa<CXXDestructorDecl>(FD))
6810 }
6811
6812 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6813 case OO_EqualEqual:
6815
6816 case OO_ExclaimEqual:
6818
6819 case OO_Spaceship:
6820 // No point allowing this if <=> doesn't exist in the current language mode.
6821 if (!getLangOpts().CPlusPlus20)
6822 break;
6824
6825 case OO_Less:
6826 case OO_LessEqual:
6827 case OO_Greater:
6828 case OO_GreaterEqual:
6829 // No point allowing this if <=> doesn't exist in the current language mode.
6830 if (!getLangOpts().CPlusPlus20)
6831 break;
6833
6834 default:
6835 break;
6836 }
6837
6838 // Not defaultable.
6839 return DefaultedFunctionKind();
6840}
6841
6843 SourceLocation DefaultLoc) {
6845 if (DFK.isComparison())
6846 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6847
6848 switch (DFK.asSpecialMember()) {
6851 cast<CXXConstructorDecl>(FD));
6852 break;
6854 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6855 break;
6857 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6858 break;
6860 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6861 break;
6863 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6864 break;
6866 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6867 break;
6869 llvm_unreachable("Invalid special member.");
6870 }
6871}
6872
6873/// Determine whether a type is permitted to be passed or returned in
6874/// registers, per C++ [class.temporary]p3.
6877 if (D->isDependentType() || D->isInvalidDecl())
6878 return false;
6879
6880 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6881 // The PS4 platform ABI follows the behavior of Clang 3.2.
6883 return !D->hasNonTrivialDestructorForCall() &&
6885
6886 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6887 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6888 bool DtorIsTrivialForCall = false;
6889
6890 // If a class has at least one eligible, trivial copy constructor, it
6891 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6892 //
6893 // Note: This permits classes with non-trivial copy or move ctors to be
6894 // passed in registers, so long as they *also* have a trivial copy ctor,
6895 // which is non-conforming.
6899 CopyCtorIsTrivial = true;
6901 CopyCtorIsTrivialForCall = true;
6902 }
6903 } else {
6904 for (const CXXConstructorDecl *CD : D->ctors()) {
6905 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6906 !CD->isIneligibleOrNotSelected()) {
6907 if (CD->isTrivial())
6908 CopyCtorIsTrivial = true;
6909 if (CD->isTrivialForCall())
6910 CopyCtorIsTrivialForCall = true;
6911 }
6912 }
6913 }
6914
6915 if (D->needsImplicitDestructor()) {
6916 if (!D->defaultedDestructorIsDeleted() &&
6918 DtorIsTrivialForCall = true;
6919 } else if (const auto *DD = D->getDestructor()) {
6920 if (!DD->isDeleted() && DD->isTrivialForCall())
6921 DtorIsTrivialForCall = true;
6922 }
6923
6924 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6925 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6926 return true;
6927
6928 // If a class has a destructor, we'd really like to pass it indirectly
6929 // because it allows us to elide copies. Unfortunately, MSVC makes that
6930 // impossible for small types, which it will pass in a single register or
6931 // stack slot. Most objects with dtors are large-ish, so handle that early.
6932 // We can't call out all large objects as being indirect because there are
6933 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6934 // how we pass large POD types.
6935
6936 // Note: This permits small classes with nontrivial destructors to be
6937 // passed in registers, which is non-conforming.
6938 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6939 uint64_t TypeSize = isAArch64 ? 128 : 64;
6940
6941 if (CopyCtorIsTrivial &&
6942 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6943 return true;
6944 return false;
6945 }
6946
6947 // Per C++ [class.temporary]p3, the relevant condition is:
6948 // each copy constructor, move constructor, and destructor of X is
6949 // either trivial or deleted, and X has at least one non-deleted copy
6950 // or move constructor
6951 bool HasNonDeletedCopyOrMove = false;
6952
6956 return false;
6957 HasNonDeletedCopyOrMove = true;
6958 }
6959
6960 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6963 return false;
6964 HasNonDeletedCopyOrMove = true;
6965 }
6966
6969 return false;
6970
6971 for (const CXXMethodDecl *MD : D->methods()) {
6972 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6973 continue;
6974
6975 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6976 if (CD && CD->isCopyOrMoveConstructor())
6977 HasNonDeletedCopyOrMove = true;
6978 else if (!isa<CXXDestructorDecl>(MD))
6979 continue;
6980
6981 if (!MD->isTrivialForCall())
6982 return false;
6983 }
6984
6985 return HasNonDeletedCopyOrMove;
6986}
6987
6988/// Report an error regarding overriding, along with any relevant
6989/// overridden methods.
6990///
6991/// \param DiagID the primary error to report.
6992/// \param MD the overriding method.
6993static bool
6994ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6995 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6996 bool IssuedDiagnostic = false;
6997 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6998 if (Report(O)) {
6999 if (!IssuedDiagnostic) {
7000 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7001 IssuedDiagnostic = true;
7002 }
7003 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7004 }
7005 }
7006 return IssuedDiagnostic;
7007}
7008
7009/// Perform semantic checks on a class definition that has been
7010/// completing, introducing implicitly-declared members, checking for
7011/// abstract types, etc.
7012///
7013/// \param S The scope in which the class was parsed. Null if we didn't just
7014/// parse a class definition.
7015/// \param Record The completed class.
7017 if (!Record)
7018 return;
7019
7020 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7021 AbstractUsageInfo Info(*this, Record);
7023 }
7024
7025 // If this is not an aggregate type and has no user-declared constructor,
7026 // complain about any non-static data members of reference or const scalar
7027 // type, since they will never get initializers.
7028 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7029 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7030 !Record->isLambda()) {
7031 bool Complained = false;
7032 for (const auto *F : Record->fields()) {
7033 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7034 continue;
7035
7036 if (F->getType()->isReferenceType() ||
7037 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7038 if (!Complained) {
7039 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7040 << llvm::to_underlying(Record->getTagKind()) << Record;
7041 Complained = true;
7042 }
7043
7044 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7045 << F->getType()->isReferenceType()
7046 << F->getDeclName();
7047 }
7048 }
7049 }
7050
7051 if (Record->getIdentifier()) {
7052 // C++ [class.mem]p13:
7053 // If T is the name of a class, then each of the following shall have a
7054 // name different from T:
7055 // - every member of every anonymous union that is a member of class T.
7056 //
7057 // C++ [class.mem]p14:
7058 // In addition, if class T has a user-declared constructor (12.1), every
7059 // non-static data member of class T shall have a name different from T.
7060 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7061 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7062 ++I) {
7063 NamedDecl *D = (*I)->getUnderlyingDecl();
7064 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7065 Record->hasUserDeclaredConstructor()) ||
7066 isa<IndirectFieldDecl>(D)) {
7067 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7068 << D->getDeclName();
7069 break;
7070 }
7071 }
7072 }
7073
7074 // Warn if the class has virtual methods but non-virtual public destructor.
7075 if (Record->isPolymorphic() && !Record->isDependentType()) {
7076 CXXDestructorDecl *dtor = Record->getDestructor();
7077 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7078 !Record->hasAttr<FinalAttr>())
7079 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7080 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7081 }
7082
7083 if (Record->isAbstract()) {
7084 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7085 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7086 << FA->isSpelledAsSealed();
7088 }
7089 }
7090
7091 // Warn if the class has a final destructor but is not itself marked final.
7092 if (!Record->hasAttr<FinalAttr>()) {
7093 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7094 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7095 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7096 << FA->isSpelledAsSealed()
7098 getLocForEndOfToken(Record->getLocation()),
7099 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7100 Diag(Record->getLocation(),
7101 diag::note_final_dtor_non_final_class_silence)
7102 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7103 }
7104 }
7105 }
7106
7107 // See if trivial_abi has to be dropped.
7108 if (Record->hasAttr<TrivialABIAttr>())
7110
7111 // Set HasTrivialSpecialMemberForCall if the record has attribute
7112 // "trivial_abi".
7113 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7114
7115 if (HasTrivialABI)
7116 Record->setHasTrivialSpecialMemberForCall();
7117
7118 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7119 // We check these last because they can depend on the properties of the
7120 // primary comparison functions (==, <=>).
7121 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7122
7123 // Perform checks that can't be done until we know all the properties of a
7124 // member function (whether it's defaulted, deleted, virtual, overriding,
7125 // ...).
7126 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7127 // A static function cannot override anything.
7128 if (MD->getStorageClass() == SC_Static) {
7129 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7130 [](const CXXMethodDecl *) { return true; }))
7131 return;
7132 }
7133
7134 // A deleted function cannot override a non-deleted function and vice
7135 // versa.
7136 if (ReportOverrides(*this,
7137 MD->isDeleted() ? diag::err_deleted_override
7138 : diag::err_non_deleted_override,
7139 MD, [&](const CXXMethodDecl *V) {
7140 return MD->isDeleted() != V->isDeleted();
7141 })) {
7142 if (MD->isDefaulted() && MD->isDeleted())
7143 // Explain why this defaulted function was deleted.
7145 return;
7146 }
7147
7148 // A consteval function cannot override a non-consteval function and vice
7149 // versa.
7150 if (ReportOverrides(*this,
7151 MD->isConsteval() ? diag::err_consteval_override
7152 : diag::err_non_consteval_override,
7153 MD, [&](const CXXMethodDecl *V) {
7154 return MD->isConsteval() != V->isConsteval();
7155 })) {
7156 if (MD->isDefaulted() && MD->isDeleted())
7157 // Explain why this defaulted function was deleted.
7159 return;
7160 }
7161 };
7162
7163 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7164 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7165 return false;
7166
7170 DefaultedSecondaryComparisons.push_back(FD);
7171 return true;
7172 }
7173
7175 return false;
7176 };
7177
7178 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7179 // Check whether the explicitly-defaulted members are valid.
7180 bool Incomplete = CheckForDefaultedFunction(M);
7181
7182 // Skip the rest of the checks for a member of a dependent class.
7183 if (Record->isDependentType())
7184 return;
7185
7186 // For an explicitly defaulted or deleted special member, we defer
7187 // determining triviality until the class is complete. That time is now!
7189 if (!M->isImplicit() && !M->isUserProvided()) {
7190 if (CSM != CXXSpecialMemberKind::Invalid) {
7191 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7192 // Inform the class that we've finished declaring this member.
7193 Record->finishedDefaultedOrDeletedMember(M);
7194 M->setTrivialForCall(
7195 HasTrivialABI ||
7197 Record->setTrivialForCallFlags(M);
7198 }
7199 }
7200
7201 // Set triviality for the purpose of calls if this is a user-provided
7202 // copy/move constructor or destructor.
7206 M->isUserProvided()) {
7207 M->setTrivialForCall(HasTrivialABI);
7208 Record->setTrivialForCallFlags(M);
7209 }
7210
7211 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7212 M->hasAttr<DLLExportAttr>()) {
7213 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7214 M->isTrivial() &&
7218 M->dropAttr<DLLExportAttr>();
7219
7220 if (M->hasAttr<DLLExportAttr>()) {
7221 // Define after any fields with in-class initializers have been parsed.
7223 }
7224 }
7225
7226 // Define defaulted constexpr virtual functions that override a base class
7227 // function right away.
7228 // FIXME: We can defer doing this until the vtable is marked as used.
7229 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7230 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
7231 DefineDefaultedFunction(*this, M, M->getLocation());
7232
7233 if (!Incomplete)
7234 CheckCompletedMemberFunction(M);
7235 };
7236
7237 // Check the destructor before any other member function. We need to
7238 // determine whether it's trivial in order to determine whether the claas
7239 // type is a literal type, which is a prerequisite for determining whether
7240 // other special member functions are valid and whether they're implicitly
7241 // 'constexpr'.
7242 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7243 CompleteMemberFunction(Dtor);
7244
7245 bool HasMethodWithOverrideControl = false,
7246 HasOverridingMethodWithoutOverrideControl = false;
7247 for (auto *D : Record->decls()) {
7248 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7249 // FIXME: We could do this check for dependent types with non-dependent
7250 // bases.
7251 if (!Record->isDependentType()) {
7252 // See if a method overloads virtual methods in a base
7253 // class without overriding any.
7254 if (!M->isStatic())
7256 if (M->hasAttr<OverrideAttr>())
7257 HasMethodWithOverrideControl = true;
7258 else if (M->size_overridden_methods() > 0)
7259 HasOverridingMethodWithoutOverrideControl = true;
7260 }
7261
7262 if (!isa<CXXDestructorDecl>(M))
7263 CompleteMemberFunction(M);
7264 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7265 CheckForDefaultedFunction(
7266 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7267 }
7268 }
7269
7270 if (HasOverridingMethodWithoutOverrideControl) {
7271 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7272 for (auto *M : Record->methods())
7273 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7274 }
7275
7276 // Check the defaulted secondary comparisons after any other member functions.
7277 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7279
7280 // If this is a member function, we deferred checking it until now.
7281 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7282 CheckCompletedMemberFunction(MD);
7283 }
7284
7285 // ms_struct is a request to use the same ABI rules as MSVC. Check
7286 // whether this class uses any C++ features that are implemented
7287 // completely differently in MSVC, and if so, emit a diagnostic.
7288 // That diagnostic defaults to an error, but we allow projects to
7289 // map it down to a warning (or ignore it). It's a fairly common
7290 // practice among users of the ms_struct pragma to mass-annotate
7291 // headers, sweeping up a bunch of types that the project doesn't
7292 // really rely on MSVC-compatible layout for. We must therefore
7293 // support "ms_struct except for C++ stuff" as a secondary ABI.
7294 // Don't emit this diagnostic if the feature was enabled as a
7295 // language option (as opposed to via a pragma or attribute), as
7296 // the option -mms-bitfields otherwise essentially makes it impossible
7297 // to build C++ code, unless this diagnostic is turned off.
7298 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7299 (Record->isPolymorphic() || Record->getNumBases())) {
7300 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7301 }
7302
7305
7306 bool ClangABICompat4 =
7307 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7309 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7310 bool CanPass = canPassInRegisters(*this, Record, CCK);
7311
7312 // Do not change ArgPassingRestrictions if it has already been set to
7313 // RecordArgPassingKind::CanNeverPassInRegs.
7314 if (Record->getArgPassingRestrictions() !=
7316 Record->setArgPassingRestrictions(
7319
7320 // If canPassInRegisters returns true despite the record having a non-trivial
7321 // destructor, the record is destructed in the callee. This happens only when
7322 // the record or one of its subobjects has a field annotated with trivial_abi
7323 // or a field qualified with ObjC __strong/__weak.
7325 Record->setParamDestroyedInCallee(true);
7326 else if (Record->hasNonTrivialDestructor())
7327 Record->setParamDestroyedInCallee(CanPass);
7328
7329 if (getLangOpts().ForceEmitVTables) {
7330 // If we want to emit all the vtables, we need to mark it as used. This
7331 // is especially required for cases like vtable assumption loads.
7332 MarkVTableUsed(Record->getInnerLocStart(), Record);
7333 }
7334
7335 if (getLangOpts().CUDA) {
7336 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7338 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7340 }
7341}
7342
7343/// Look up the special member function that would be called by a special
7344/// member function for a subobject of class type.
7345///
7346/// \param Class The class type of the subobject.
7347/// \param CSM The kind of special member function.
7348/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7349/// \param ConstRHS True if this is a copy operation with a const object
7350/// on its RHS, that is, if the argument to the outer special member
7351/// function is 'const' and this is not a field marked 'mutable'.
7354 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7355 bool ConstRHS) {
7356 unsigned LHSQuals = 0;
7359 LHSQuals = FieldQuals;
7360
7361 unsigned RHSQuals = FieldQuals;
7364 RHSQuals = 0;
7365 else if (ConstRHS)
7366 RHSQuals |= Qualifiers::Const;
7367
7368 return S.LookupSpecialMember(Class, CSM,
7369 RHSQuals & Qualifiers::Const,
7370 RHSQuals & Qualifiers::Volatile,
7371 false,
7372 LHSQuals & Qualifiers::Const,
7373 LHSQuals & Qualifiers::Volatile);
7374}
7375
7377 Sema &S;
7378 SourceLocation UseLoc;
7379
7380 /// A mapping from the base classes through which the constructor was
7381 /// inherited to the using shadow declaration in that base class (or a null
7382 /// pointer if the constructor was declared in that base class).
7383 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7384 InheritedFromBases;
7385
7386public:
7389 : S(S), UseLoc(UseLoc) {
7390 bool DiagnosedMultipleConstructedBases = false;
7391 CXXRecordDecl *ConstructedBase = nullptr;
7392 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7393
7394 // Find the set of such base class subobjects and check that there's a
7395 // unique constructed subobject.
7396 for (auto *D : Shadow->redecls()) {
7397 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7398 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7399 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7400
7401 InheritedFromBases.insert(
7402 std::make_pair(DNominatedBase->getCanonicalDecl(),
7403 DShadow->getNominatedBaseClassShadowDecl()));
7404 if (DShadow->constructsVirtualBase())
7405 InheritedFromBases.insert(
7406 std::make_pair(DConstructedBase->getCanonicalDecl(),
7407 DShadow->getConstructedBaseClassShadowDecl()));
7408 else
7409 assert(DNominatedBase == DConstructedBase);
7410
7411 // [class.inhctor.init]p2:
7412 // If the constructor was inherited from multiple base class subobjects
7413 // of type B, the program is ill-formed.
7414 if (!ConstructedBase) {
7415 ConstructedBase = DConstructedBase;
7416 ConstructedBaseIntroducer = D->getIntroducer();
7417 } else if (ConstructedBase != DConstructedBase &&
7418 !Shadow->isInvalidDecl()) {
7419 if (!DiagnosedMultipleConstructedBases) {
7420 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7421 << Shadow->getTargetDecl();
7422 S.Diag(ConstructedBaseIntroducer->getLocation(),
7423 diag::note_ambiguous_inherited_constructor_using)
7424 << ConstructedBase;
7425 DiagnosedMultipleConstructedBases = true;
7426 }
7427 S.Diag(D->getIntroducer()->getLocation(),
7428 diag::note_ambiguous_inherited_constructor_using)
7429 << DConstructedBase;
7430 }
7431 }
7432
7433 if (DiagnosedMultipleConstructedBases)
7434 Shadow->setInvalidDecl();
7435 }
7436
7437 /// Find the constructor to use for inherited construction of a base class,
7438 /// and whether that base class constructor inherits the constructor from a
7439 /// virtual base class (in which case it won't actually invoke it).
7440 std::pair<CXXConstructorDecl *, bool>
7442 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7443 if (It == InheritedFromBases.end())
7444 return std::make_pair(nullptr, false);
7445
7446 // This is an intermediary class.
7447 if (It->second)
7448 return std::make_pair(
7449 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7450 It->second->constructsVirtualBase());
7451
7452 // This is the base class from which the constructor was inherited.
7453 return std::make_pair(Ctor, false);
7454 }
7455};
7456
7457/// Is the special member function which would be selected to perform the
7458/// specified operation on the specified class type a constexpr constructor?
7460 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7461 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7462 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7463 // Suppress duplicate constraint checking here, in case a constraint check
7464 // caused us to decide to do this. Any truely recursive checks will get
7465 // caught during these checks anyway.
7467
7468 // If we're inheriting a constructor, see if we need to call it for this base
7469 // class.
7470 if (InheritedCtor) {
7472 auto BaseCtor =
7473 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7474 if (BaseCtor)
7475 return BaseCtor->isConstexpr();
7476 }
7477
7479 return ClassDecl->hasConstexprDefaultConstructor();
7481 return ClassDecl->hasConstexprDestructor();
7482
7484 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7485 if (!SMOR.getMethod())
7486 // A constructor we wouldn't select can't be "involved in initializing"
7487 // anything.
7488 return true;
7489 return SMOR.getMethod()->isConstexpr();
7490}
7491
7492/// Determine whether the specified special member function would be constexpr
7493/// if it were implicitly defined.
7495 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7496 CXXConstructorDecl *InheritedCtor = nullptr,
7497 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7498 if (!S.getLangOpts().CPlusPlus11)
7499 return false;
7500
7501 // C++11 [dcl.constexpr]p4:
7502 // In the definition of a constexpr constructor [...]
7503 bool Ctor = true;
7504 switch (CSM) {
7506 if (Inherited)
7507 break;
7508 // Since default constructor lookup is essentially trivial (and cannot
7509 // involve, for instance, template instantiation), we compute whether a
7510 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7511 //
7512 // This is important for performance; we need to know whether the default
7513 // constructor is constexpr to determine whether the type is a literal type.
7514 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7515
7518 // For copy or move constructors, we need to perform overload resolution.
7519 break;
7520
7523 if (!S.getLangOpts().CPlusPlus14)
7524 return false;
7525 // In C++1y, we need to perform overload resolution.
7526 Ctor = false;
7527 break;
7528
7530 return ClassDecl->defaultedDestructorIsConstexpr();
7531
7533 return false;
7534 }
7535
7536 // -- if the class is a non-empty union, or for each non-empty anonymous
7537 // union member of a non-union class, exactly one non-static data member
7538 // shall be initialized; [DR1359]
7539 //
7540 // If we squint, this is guaranteed, since exactly one non-static data member
7541 // will be initialized (if the constructor isn't deleted), we just don't know
7542 // which one.
7543 if (Ctor && ClassDecl->isUnion())
7545 ? ClassDecl->hasInClassInitializer() ||
7546 !ClassDecl->hasVariantMembers()
7547 : true;
7548
7549 // -- the class shall not have any virtual base classes;
7550 if (Ctor && ClassDecl->getNumVBases())
7551 return false;
7552
7553 // C++1y [class.copy]p26:
7554 // -- [the class] is a literal type, and
7555 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7556 return false;
7557
7558 // -- every constructor involved in initializing [...] base class
7559 // sub-objects shall be a constexpr constructor;
7560 // -- the assignment operator selected to copy/move each direct base
7561 // class is a constexpr function, and
7562 if (!S.getLangOpts().CPlusPlus23) {
7563 for (const auto &B : ClassDecl->bases()) {
7564 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7565 if (!BaseType)
7566 continue;
7567 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7568 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7569 InheritedCtor, Inherited))
7570 return false;
7571 }
7572 }
7573
7574 // -- every constructor involved in initializing non-static data members
7575 // [...] shall be a constexpr constructor;
7576 // -- every non-static data member and base class sub-object shall be
7577 // initialized
7578 // -- for each non-static data member of X that is of class type (or array
7579 // thereof), the assignment operator selected to copy/move that member is
7580 // a constexpr function
7581 if (!S.getLangOpts().CPlusPlus23) {
7582 for (const auto *F : ClassDecl->fields()) {
7583 if (F->isInvalidDecl())
7584 continue;
7586 F->hasInClassInitializer())
7587 continue;
7588 QualType BaseType = S.Context.getBaseElementType(F->getType());
7589 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7590 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7591 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7592 BaseType.getCVRQualifiers(),
7593 ConstArg && !F->isMutable()))
7594 return false;
7595 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7596 return false;
7597 }
7598 }
7599 }
7600
7601 // All OK, it's constexpr!
7602 return true;
7603}
7604
7605namespace {
7606/// RAII object to register a defaulted function as having its exception
7607/// specification computed.
7608struct ComputingExceptionSpec {
7609 Sema &S;
7610
7611 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7612 : S(S) {
7615 Ctx.PointOfInstantiation = Loc;
7616 Ctx.Entity = FD;
7618 }
7619 ~ComputingExceptionSpec() {
7621 }
7622};
7623}
7624
7627 CXXMethodDecl *MD,
7630
7633 FunctionDecl *FD,
7635
7638 auto DFK = S.getDefaultedFunctionKind(FD);
7639 if (DFK.isSpecialMember())
7641 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7642 if (DFK.isComparison())
7644 DFK.asComparison());
7645
7646 auto *CD = cast<CXXConstructorDecl>(FD);
7647 assert(CD->getInheritedConstructor() &&
7648 "only defaulted functions and inherited constructors have implicit "
7649 "exception specs");
7651 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7654}
7655
7657 CXXMethodDecl *MD) {
7659
7660 // Build an exception specification pointing back at this member.
7662 EPI.ExceptionSpec.SourceDecl = MD;
7663
7664 // Set the calling convention to the default for C++ instance methods.
7666 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7667 /*IsCXXMethod=*/true));
7668 return EPI;
7669}
7670
7672 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7674 return;
7675
7676 // Evaluate the exception specification.
7677 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7678 auto ESI = IES.getExceptionSpec();
7679
7680 // Update the type of the special member to use it.
7681 UpdateExceptionSpec(FD, ESI);
7682}
7683
7685 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7686
7688 if (!DefKind) {
7689 assert(FD->getDeclContext()->isDependentContext());
7690 return;
7691 }
7692
7693 if (DefKind.isComparison())
7694 UnusedPrivateFields.clear();
7695
7696 if (DefKind.isSpecialMember()
7697 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7698 DefKind.asSpecialMember(),
7699 FD->getDefaultLoc())
7701 FD->setInvalidDecl();
7702}
7703
7706 SourceLocation DefaultLoc) {
7707 CXXRecordDecl *RD = MD->getParent();
7708
7710 "not an explicitly-defaulted special member");
7711
7712 // Defer all checking for special members of a dependent type.
7713 if (RD->isDependentType())
7714 return false;
7715
7716 // Whether this was the first-declared instance of the constructor.
7717 // This affects whether we implicitly add an exception spec and constexpr.
7718 bool First = MD == MD->getCanonicalDecl();
7719
7720 bool HadError = false;
7721
7722 // C++11 [dcl.fct.def.default]p1:
7723 // A function that is explicitly defaulted shall
7724 // -- be a special member function [...] (checked elsewhere),
7725 // -- have the same type (except for ref-qualifiers, and except that a
7726 // copy operation can take a non-const reference) as an implicit
7727 // declaration, and
7728 // -- not have default arguments.
7729 // C++2a changes the second bullet to instead delete the function if it's
7730 // defaulted on its first declaration, unless it's "an assignment operator,
7731 // and its return type differs or its parameter type is not a reference".
7732 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7733 bool ShouldDeleteForTypeMismatch = false;
7734 unsigned ExpectedParams = 1;
7737 ExpectedParams = 0;
7738 if (MD->getNumExplicitParams() != ExpectedParams) {
7739 // This checks for default arguments: a copy or move constructor with a
7740 // default argument is classified as a default constructor, and assignment
7741 // operations and destructors can't have default arguments.
7742 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7743 << llvm::to_underlying(CSM) << MD->getSourceRange();
7744 HadError = true;
7745 } else if (MD->isVariadic()) {
7746 if (DeleteOnTypeMismatch)
7747 ShouldDeleteForTypeMismatch = true;
7748 else {
7749 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7750 << llvm::to_underlying(CSM) << MD->getSourceRange();
7751 HadError = true;
7752 }
7753 }
7754
7756
7757 bool CanHaveConstParam = false;
7759 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7761 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7762
7763 QualType ReturnType = Context.VoidTy;
7766 // Check for return type matching.
7767 ReturnType = Type->getReturnType();
7769
7770 QualType DeclType = Context.getTypeDeclType(RD);
7772 DeclType, nullptr);
7773 DeclType = Context.getAddrSpaceQualType(
7774 DeclType, ThisType.getQualifiers().getAddressSpace());
7775 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7776
7777 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7778 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7780 << ExpectedReturnType;
7781 HadError = true;
7782 }
7783
7784 // A defaulted special member cannot have cv-qualifiers.
7785 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7786 if (DeleteOnTypeMismatch)
7787 ShouldDeleteForTypeMismatch = true;
7788 else {
7789 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7791 << getLangOpts().CPlusPlus14;
7792 HadError = true;
7793 }
7794 }
7795 // [C++23][dcl.fct.def.default]/p2.2
7796 // if F2 has an implicit object parameter of type “reference to C”,
7797 // F1 may be an explicit object member function whose explicit object
7798 // parameter is of (possibly different) type “reference to C”,
7799 // in which case the type of F1 would differ from the type of F2
7800 // in that the type of F1 has an additional parameter;
7801 if (!Context.hasSameType(
7803 Context.getRecordType(RD))) {
7804 if (DeleteOnTypeMismatch)
7805 ShouldDeleteForTypeMismatch = true;
7806 else {
7807 Diag(MD->getLocation(),
7808 diag::err_defaulted_special_member_explicit_object_mismatch)
7809 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7810 << MD->getSourceRange();
7811 HadError = true;
7812 }
7813 }
7814 }
7815
7816 // Check for parameter type matching.
7817 QualType ArgType =
7818 ExpectedParams
7819 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7820 : QualType();
7821 bool HasConstParam = false;
7822 if (ExpectedParams && ArgType->isReferenceType()) {
7823 // Argument must be reference to possibly-const T.
7824 QualType ReferentType = ArgType->getPointeeType();
7825 HasConstParam = ReferentType.isConstQualified();
7826
7827 if (ReferentType.isVolatileQualified()) {
7828 if (DeleteOnTypeMismatch)
7829 ShouldDeleteForTypeMismatch = true;
7830 else {
7831 Diag(MD->getLocation(),
7832 diag::err_defaulted_special_member_volatile_param)
7833 << llvm::to_underlying(CSM);
7834 HadError = true;
7835 }
7836 }
7837
7838 if (HasConstParam && !CanHaveConstParam) {
7839 if (DeleteOnTypeMismatch)
7840 ShouldDeleteForTypeMismatch = true;
7841 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7843 Diag(MD->getLocation(),
7844 diag::err_defaulted_special_member_copy_const_param)
7846 // FIXME: Explain why this special member can't be const.
7847 HadError = true;
7848 } else {
7849 Diag(MD->getLocation(),
7850 diag::err_defaulted_special_member_move_const_param)
7852 HadError = true;
7853 }
7854 }
7855 } else if (ExpectedParams) {
7856 // A copy assignment operator can take its argument by value, but a
7857 // defaulted one cannot.
7859 "unexpected non-ref argument");
7860 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7861 HadError = true;
7862 }
7863
7864 // C++11 [dcl.fct.def.default]p2:
7865 // An explicitly-defaulted function may be declared constexpr only if it
7866 // would have been implicitly declared as constexpr,
7867 // Do not apply this rule to members of class templates, since core issue 1358
7868 // makes such functions always instantiate to constexpr functions. For
7869 // functions which cannot be constexpr (for non-constructors in C++11 and for
7870 // destructors in C++14 and C++17), this is checked elsewhere.
7871 //
7872 // FIXME: This should not apply if the member is deleted.
7873 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7874 HasConstParam);
7875
7876 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7877 // If the instantiated template specialization of a constexpr function
7878 // template or member function of a class template would fail to satisfy
7879 // the requirements for a constexpr function or constexpr constructor, that
7880 // specialization is still a constexpr function or constexpr constructor,
7881 // even though a call to such a function cannot appear in a constant
7882 // expression.
7883 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7884 Constexpr = true;
7885
7886 if ((getLangOpts().CPlusPlus20 ||
7887 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7888 : isa<CXXConstructorDecl>(MD))) &&
7889 MD->isConstexpr() && !Constexpr &&
7891 if (!MD->isConsteval() && RD->getNumVBases()) {
7892 Diag(MD->getBeginLoc(),
7893 diag::err_incorrect_defaulted_constexpr_with_vb)
7894 << llvm::to_underlying(CSM);
7895 for (const auto &I : RD->vbases())
7896 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7897 } else {
7898 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7899 << llvm::to_underlying(CSM) << MD->isConsteval();
7900 }
7901 HadError = true;
7902 // FIXME: Explain why the special member can't be constexpr.
7903 }
7904
7905 if (First) {
7906 // C++2a [dcl.fct.def.default]p3:
7907 // If a function is explicitly defaulted on its first declaration, it is
7908 // implicitly considered to be constexpr if the implicit declaration
7909 // would be.
7914
7915 if (!Type->hasExceptionSpec()) {
7916 // C++2a [except.spec]p3:
7917 // If a declaration of a function does not have a noexcept-specifier
7918 // [and] is defaulted on its first declaration, [...] the exception
7919 // specification is as specified below
7920 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7922 EPI.ExceptionSpec.SourceDecl = MD;
7923 MD->setType(
7924 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7925 }
7926 }
7927
7928 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7929 if (First) {
7930 SetDeclDeleted(MD, MD->getLocation());
7931 if (!inTemplateInstantiation() && !HadError) {
7932 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7933 << llvm::to_underlying(CSM);
7934 if (ShouldDeleteForTypeMismatch) {
7935 Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7936 << llvm::to_underlying(CSM);
7937 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7938 /*Diagnose*/ true) &&
7939 DefaultLoc.isValid()) {
7940 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7941 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7942 }
7943 }
7944 if (ShouldDeleteForTypeMismatch && !HadError) {
7945 Diag(MD->getLocation(),
7946 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7947 << llvm::to_underlying(CSM);
7948 }
7949 } else {
7950 // C++11 [dcl.fct.def.default]p4:
7951 // [For a] user-provided explicitly-defaulted function [...] if such a
7952 // function is implicitly defined as deleted, the program is ill-formed.
7953 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7954 << llvm::to_underlying(CSM);
7955 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7956 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7957 HadError = true;
7958 }
7959 }
7960
7961 return HadError;
7962}
7963
7964namespace {
7965/// Helper class for building and checking a defaulted comparison.
7966///
7967/// Defaulted functions are built in two phases:
7968///
7969/// * First, the set of operations that the function will perform are
7970/// identified, and some of them are checked. If any of the checked
7971/// operations is invalid in certain ways, the comparison function is
7972/// defined as deleted and no body is built.
7973/// * Then, if the function is not defined as deleted, the body is built.
7974///
7975/// This is accomplished by performing two visitation steps over the eventual
7976/// body of the function.
7977template<typename Derived, typename ResultList, typename Result,
7978 typename Subobject>
7979class DefaultedComparisonVisitor {
7980public:
7981 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7982
7983 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7984 DefaultedComparisonKind DCK)
7985 : S(S), RD(RD), FD(FD), DCK(DCK) {
7986 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7987 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7988 // UnresolvedSet to avoid this copy.
7989 Fns.assign(Info->getUnqualifiedLookups().begin(),
7990 Info->getUnqualifiedLookups().end());
7991 }
7992 }
7993
7994 ResultList visit() {
7995 // The type of an lvalue naming a parameter of this function.
7996 QualType ParamLvalType =
7998
7999 ResultList Results;
8000
8001 switch (DCK) {
8002 case DefaultedComparisonKind::None:
8003 llvm_unreachable("not a defaulted comparison");
8004
8005 case DefaultedComparisonKind::Equal:
8006 case DefaultedComparisonKind::ThreeWay:
8007 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8008 return Results;
8009
8010 case DefaultedComparisonKind::NotEqual:
8011 case DefaultedComparisonKind::Relational:
8012 Results.add(getDerived().visitExpandedSubobject(
8013 ParamLvalType, getDerived().getCompleteObject()));
8014 return Results;
8015 }
8016 llvm_unreachable("");
8017 }
8018
8019protected:
8020 Derived &getDerived() { return static_cast<Derived&>(*this); }
8021
8022 /// Visit the expanded list of subobjects of the given type, as specified in
8023 /// C++2a [class.compare.default].
8024 ///
8025 /// \return \c true if the ResultList object said we're done, \c false if not.
8026 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8027 Qualifiers Quals) {
8028 // C++2a [class.compare.default]p4:
8029 // The direct base class subobjects of C
8030 for (CXXBaseSpecifier &Base : Record->bases())
8031 if (Results.add(getDerived().visitSubobject(
8032 S.Context.getQualifiedType(Base.getType(), Quals),
8033 getDerived().getBase(&Base))))
8034 return true;
8035
8036 // followed by the non-static data members of C
8037 for (FieldDecl *Field : Record->fields()) {
8038 // C++23 [class.bit]p2:
8039 // Unnamed bit-fields are not members ...
8040 if (Field->isUnnamedBitField())
8041 continue;
8042 // Recursively expand anonymous structs.
8043 if (Field->isAnonymousStructOrUnion()) {
8044 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8045 Quals))
8046 return true;
8047 continue;
8048 }
8049
8050 // Figure out the type of an lvalue denoting this field.
8051 Qualifiers FieldQuals = Quals;
8052 if (Field->isMutable())
8053 FieldQuals.removeConst();
8054 QualType FieldType =
8055 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8056
8057 if (Results.add(getDerived().visitSubobject(
8058 FieldType, getDerived().getField(Field))))
8059 return true;
8060 }
8061
8062 // form a list of subobjects.
8063 return false;
8064 }
8065
8066 Result visitSubobject(QualType Type, Subobject Subobj) {
8067 // In that list, any subobject of array type is recursively expanded
8068 const ArrayType *AT = S.Context.getAsArrayType(Type);
8069 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8070 return getDerived().visitSubobjectArray(CAT->getElementType(),
8071 CAT->getSize(), Subobj);
8072 return getDerived().visitExpandedSubobject(Type, Subobj);
8073 }
8074
8075 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8076 Subobject Subobj) {
8077 return getDerived().visitSubobject(Type, Subobj);
8078 }
8079
8080protected:
8081 Sema &S;
8082 CXXRecordDecl *RD;
8083 FunctionDecl *FD;
8084 DefaultedComparisonKind DCK;
8086};
8087
8088/// Information about a defaulted comparison, as determined by
8089/// DefaultedComparisonAnalyzer.
8090struct DefaultedComparisonInfo {
8091 bool Deleted = false;
8092 bool Constexpr = true;
8093 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8094
8095 static DefaultedComparisonInfo deleted() {
8096 DefaultedComparisonInfo Deleted;
8097 Deleted.Deleted = true;
8098 return Deleted;
8099 }
8100
8101 bool add(const DefaultedComparisonInfo &R) {
8102 Deleted |= R.Deleted;
8103 Constexpr &= R.Constexpr;
8104 Category = commonComparisonType(Category, R.Category);
8105 return Deleted;
8106 }
8107};
8108
8109/// An element in the expanded list of subobjects of a defaulted comparison, as
8110/// specified in C++2a [class.compare.default]p4.
8111struct DefaultedComparisonSubobject {
8112 enum { CompleteObject, Member, Base } Kind;
8113 NamedDecl *Decl;
8114 SourceLocation Loc;
8115};
8116
8117/// A visitor over the notional body of a defaulted comparison that determines
8118/// whether that body would be deleted or constexpr.
8119class DefaultedComparisonAnalyzer
8120 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8121 DefaultedComparisonInfo,
8122 DefaultedComparisonInfo,
8123 DefaultedComparisonSubobject> {
8124public:
8125 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8126
8127private:
8128 DiagnosticKind Diagnose;
8129
8130public:
8131 using Base = DefaultedComparisonVisitor;
8132 using Result = DefaultedComparisonInfo;
8133 using Subobject = DefaultedComparisonSubobject;
8134
8135 friend Base;
8136
8137 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8138 DefaultedComparisonKind DCK,
8139 DiagnosticKind Diagnose = NoDiagnostics)
8140 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8141
8142 Result visit() {
8143 if ((DCK == DefaultedComparisonKind::Equal ||
8144 DCK == DefaultedComparisonKind::ThreeWay) &&
8145 RD->hasVariantMembers()) {
8146 // C++2a [class.compare.default]p2 [P2002R0]:
8147 // A defaulted comparison operator function for class C is defined as
8148 // deleted if [...] C has variant members.
8149 if (Diagnose == ExplainDeleted) {
8150 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8151 << FD << RD->isUnion() << RD;
8152 }
8153 return Result::deleted();
8154 }
8155
8156 return Base::visit();
8157 }
8158
8159private:
8160 Subobject getCompleteObject() {
8161 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8162 }
8163
8164 Subobject getBase(CXXBaseSpecifier *Base) {
8165 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8166 Base->getBaseTypeLoc()};
8167 }
8168
8169 Subobject getField(FieldDecl *Field) {
8170 return Subobject{Subobject::Member, Field, Field->getLocation()};
8171 }
8172
8173 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8174 // C++2a [class.compare.default]p2 [P2002R0]:
8175 // A defaulted <=> or == operator function for class C is defined as
8176 // deleted if any non-static data member of C is of reference type
8177 if (Type->isReferenceType()) {
8178 if (Diagnose == ExplainDeleted) {
8179 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8180 << FD << RD;
8181 }
8182 return Result::deleted();
8183 }
8184
8185 // [...] Let xi be an lvalue denoting the ith element [...]
8187 Expr *Args[] = {&Xi, &Xi};
8188
8189 // All operators start by trying to apply that same operator recursively.
8191 assert(OO != OO_None && "not an overloaded operator!");
8192 return visitBinaryOperator(OO, Args, Subobj);
8193 }
8194
8195 Result
8196 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8197 Subobject Subobj,
8198 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8199 // Note that there is no need to consider rewritten candidates here if
8200 // we've already found there is no viable 'operator<=>' candidate (and are
8201 // considering synthesizing a '<=>' from '==' and '<').
8202 OverloadCandidateSet CandidateSet(
8205 OO, FD->getLocation(),
8206 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8207
8208 /// C++2a [class.compare.default]p1 [P2002R0]:
8209 /// [...] the defaulted function itself is never a candidate for overload
8210 /// resolution [...]
8211 CandidateSet.exclude(FD);
8212
8213 if (Args[0]->getType()->isOverloadableType())
8214 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8215 else
8216 // FIXME: We determine whether this is a valid expression by checking to
8217 // see if there's a viable builtin operator candidate for it. That isn't
8218 // really what the rules ask us to do, but should give the right results.
8219 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8220
8221 Result R;
8222
8224 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8225 case OR_Success: {
8226 // C++2a [class.compare.secondary]p2 [P2002R0]:
8227 // The operator function [...] is defined as deleted if [...] the
8228 // candidate selected by overload resolution is not a rewritten
8229 // candidate.
8230 if ((DCK == DefaultedComparisonKind::NotEqual ||
8231 DCK == DefaultedComparisonKind::Relational) &&
8232 !Best->RewriteKind) {
8233 if (Diagnose == ExplainDeleted) {
8234 if (Best->Function) {
8235 S.Diag(Best->Function->getLocation(),
8236 diag::note_defaulted_comparison_not_rewritten_callee)
8237 << FD;
8238 } else {
8239 assert(Best->Conversions.size() == 2 &&
8240 Best->Conversions[0].isUserDefined() &&
8241 "non-user-defined conversion from class to built-in "
8242 "comparison");
8243 S.Diag(Best->Conversions[0]
8244 .UserDefined.FoundConversionFunction.getDecl()
8245 ->getLocation(),
8246 diag::note_defaulted_comparison_not_rewritten_conversion)
8247 << FD;
8248 }
8249 }
8250 return Result::deleted();
8251 }
8252
8253 // Throughout C++2a [class.compare]: if overload resolution does not
8254 // result in a usable function, the candidate function is defined as
8255 // deleted. This requires that we selected an accessible function.
8256 //
8257 // Note that this only considers the access of the function when named
8258 // within the type of the subobject, and not the access path for any
8259 // derived-to-base conversion.
8260 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8261 if (ArgClass && Best->FoundDecl.getDecl() &&
8262 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8263 QualType ObjectType = Subobj.Kind == Subobject::Member
8264 ? Args[0]->getType()
8265 : S.Context.getRecordType(RD);
8267 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8268 Diagnose == ExplainDeleted
8269 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8270 << FD << Subobj.Kind << Subobj.Decl
8271 : S.PDiag()))
8272 return Result::deleted();
8273 }
8274
8275 bool NeedsDeducing =
8276 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8277
8278 if (FunctionDecl *BestFD = Best->Function) {
8279 // C++2a [class.compare.default]p3 [P2002R0]:
8280 // A defaulted comparison function is constexpr-compatible if
8281 // [...] no overlod resolution performed [...] results in a
8282 // non-constexpr function.
8283 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8284 // If it's not constexpr, explain why not.
8285 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8286 if (Subobj.Kind != Subobject::CompleteObject)
8287 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8288 << Subobj.Kind << Subobj.Decl;
8289 S.Diag(BestFD->getLocation(),
8290 diag::note_defaulted_comparison_not_constexpr_here);
8291 // Bail out after explaining; we don't want any more notes.
8292 return Result::deleted();
8293 }
8294 R.Constexpr &= BestFD->isConstexpr();
8295
8296 if (NeedsDeducing) {
8297 // If any callee has an undeduced return type, deduce it now.
8298 // FIXME: It's not clear how a failure here should be handled. For
8299 // now, we produce an eager diagnostic, because that is forward
8300 // compatible with most (all?) other reasonable options.
8301 if (BestFD->getReturnType()->isUndeducedType() &&
8302 S.DeduceReturnType(BestFD, FD->getLocation(),
8303 /*Diagnose=*/false)) {
8304 // Don't produce a duplicate error when asked to explain why the
8305 // comparison is deleted: we diagnosed that when initially checking
8306 // the defaulted operator.
8307 if (Diagnose == NoDiagnostics) {
8308 S.Diag(
8309 FD->getLocation(),
8310 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8311 << Subobj.Kind << Subobj.Decl;
8312 S.Diag(
8313 Subobj.Loc,
8314 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8315 << Subobj.Kind << Subobj.Decl;
8316 S.Diag(BestFD->getLocation(),
8317 diag::note_defaulted_comparison_cannot_deduce_callee)
8318 << Subobj.Kind << Subobj.Decl;
8319 }
8320 return Result::deleted();
8321 }
8323 BestFD->getCallResultType());
8324 if (!Info) {
8325 if (Diagnose == ExplainDeleted) {
8326 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8327 << Subobj.Kind << Subobj.Decl
8328 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8329 S.Diag(BestFD->getLocation(),
8330 diag::note_defaulted_comparison_cannot_deduce_callee)
8331 << Subobj.Kind << Subobj.Decl;
8332 }
8333 return Result::deleted();
8334 }
8335 R.Category = Info->Kind;
8336 }
8337 } else {
8338 QualType T = Best->BuiltinParamTypes[0];
8339 assert(T == Best->BuiltinParamTypes[1] &&
8340 "builtin comparison for different types?");
8341 assert(Best->BuiltinParamTypes[2].isNull() &&
8342 "invalid builtin comparison");
8343
8344 if (NeedsDeducing) {
8345 std::optional<ComparisonCategoryType> Cat =
8347 assert(Cat && "no category for builtin comparison?");
8348 R.Category = *Cat;
8349 }
8350 }
8351
8352 // Note that we might be rewriting to a different operator. That call is
8353 // not considered until we come to actually build the comparison function.
8354 break;
8355 }
8356
8357 case OR_Ambiguous:
8358 if (Diagnose == ExplainDeleted) {
8359 unsigned Kind = 0;
8360 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8361 Kind = OO == OO_EqualEqual ? 1 : 2;
8362 CandidateSet.NoteCandidates(
8364 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8365 << FD << Kind << Subobj.Kind << Subobj.Decl),
8366 S, OCD_AmbiguousCandidates, Args);
8367 }
8368 R = Result::deleted();
8369 break;
8370
8371 case OR_Deleted:
8372 if (Diagnose == ExplainDeleted) {
8373 if ((DCK == DefaultedComparisonKind::NotEqual ||
8374 DCK == DefaultedComparisonKind::Relational) &&
8375 !Best->RewriteKind) {
8376 S.Diag(Best->Function->getLocation(),
8377 diag::note_defaulted_comparison_not_rewritten_callee)
8378 << FD;
8379 } else {
8380 S.Diag(Subobj.Loc,
8381 diag::note_defaulted_comparison_calls_deleted)
8382 << FD << Subobj.Kind << Subobj.Decl;
8383 S.NoteDeletedFunction(Best->Function);
8384 }
8385 }
8386 R = Result::deleted();
8387 break;
8388
8390 // If there's no usable candidate, we're done unless we can rewrite a
8391 // '<=>' in terms of '==' and '<'.
8392 if (OO == OO_Spaceship &&
8394 // For any kind of comparison category return type, we need a usable
8395 // '==' and a usable '<'.
8396 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8397 &CandidateSet)))
8398 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8399 break;
8400 }
8401
8402 if (Diagnose == ExplainDeleted) {
8403 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8404 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8405 << Subobj.Kind << Subobj.Decl;
8406
8407 // For a three-way comparison, list both the candidates for the
8408 // original operator and the candidates for the synthesized operator.
8409 if (SpaceshipCandidates) {
8410 SpaceshipCandidates->NoteCandidates(
8411 S, Args,
8412 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8413 Args, FD->getLocation()));
8414 S.Diag(Subobj.Loc,
8415 diag::note_defaulted_comparison_no_viable_function_synthesized)
8416 << (OO == OO_EqualEqual ? 0 : 1);
8417 }
8418
8419 CandidateSet.NoteCandidates(
8420 S, Args,
8421 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8422 FD->getLocation()));
8423 }
8424 R = Result::deleted();
8425 break;
8426 }
8427
8428 return R;
8429 }
8430};
8431
8432/// A list of statements.
8433struct StmtListResult {
8434 bool IsInvalid = false;
8436
8437 bool add(const StmtResult &S) {
8438 IsInvalid |= S.isInvalid();
8439 if (IsInvalid)
8440 return true;
8441 Stmts.push_back(S.get());
8442 return false;
8443 }
8444};
8445
8446/// A visitor over the notional body of a defaulted comparison that synthesizes
8447/// the actual body.
8448class DefaultedComparisonSynthesizer
8449 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8450 StmtListResult, StmtResult,
8451 std::pair<ExprResult, ExprResult>> {
8452 SourceLocation Loc;
8453 unsigned ArrayDepth = 0;
8454
8455public:
8456 using Base = DefaultedComparisonVisitor;
8457 using ExprPair = std::pair<ExprResult, ExprResult>;
8458
8459 friend Base;
8460
8461 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8462 DefaultedComparisonKind DCK,
8463 SourceLocation BodyLoc)
8464 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8465
8466 /// Build a suitable function body for this defaulted comparison operator.
8467 StmtResult build() {
8468 Sema::CompoundScopeRAII CompoundScope(S);
8469
8470 StmtListResult Stmts = visit();
8471 if (Stmts.IsInvalid)
8472 return StmtError();
8473
8474 ExprResult RetVal;
8475 switch (DCK) {
8476 case DefaultedComparisonKind::None:
8477 llvm_unreachable("not a defaulted comparison");
8478
8479 case DefaultedComparisonKind::Equal: {
8480 // C++2a [class.eq]p3:
8481 // [...] compar[e] the corresponding elements [...] until the first
8482 // index i where xi == yi yields [...] false. If no such index exists,
8483 // V is true. Otherwise, V is false.
8484 //
8485 // Join the comparisons with '&&'s and return the result. Use a right
8486 // fold (traversing the conditions right-to-left), because that
8487 // short-circuits more naturally.
8488 auto OldStmts = std::move(Stmts.Stmts);
8489 Stmts.Stmts.clear();
8490 ExprResult CmpSoFar;
8491 // Finish a particular comparison chain.
8492 auto FinishCmp = [&] {
8493 if (Expr *Prior = CmpSoFar.get()) {
8494 // Convert the last expression to 'return ...;'
8495 if (RetVal.isUnset() && Stmts.Stmts.empty())
8496 RetVal = CmpSoFar;
8497 // Convert any prior comparison to 'if (!(...)) return false;'
8498 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8499 return true;
8500 CmpSoFar = ExprResult();
8501 }
8502 return false;
8503 };
8504 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8505 Expr *E = dyn_cast<Expr>(EAsStmt);
8506 if (!E) {
8507 // Found an array comparison.
8508 if (FinishCmp() || Stmts.add(EAsStmt))
8509 return StmtError();
8510 continue;
8511 }
8512
8513 if (CmpSoFar.isUnset()) {
8514 CmpSoFar = E;
8515 continue;
8516 }
8517 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8518 if (CmpSoFar.isInvalid())
8519 return StmtError();
8520 }
8521 if (FinishCmp())
8522 return StmtError();
8523 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8524 // If no such index exists, V is true.
8525 if (RetVal.isUnset())
8526 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8527 break;
8528 }
8529
8530 case DefaultedComparisonKind::ThreeWay: {
8531 // Per C++2a [class.spaceship]p3, as a fallback add:
8532 // return static_cast<R>(std::strong_ordering::equal);
8534 ComparisonCategoryType::StrongOrdering, Loc,
8535 Sema::ComparisonCategoryUsage::DefaultedOperator);
8536 if (StrongOrdering.isNull())
8537 return StmtError();
8539 .getValueInfo(ComparisonCategoryResult::Equal)
8540 ->VD;
8541 RetVal = getDecl(EqualVD);
8542 if (RetVal.isInvalid())
8543 return StmtError();
8544 RetVal = buildStaticCastToR(RetVal.get());
8545 break;
8546 }
8547
8548 case DefaultedComparisonKind::NotEqual:
8549 case DefaultedComparisonKind::Relational:
8550 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8551 break;
8552 }
8553
8554 // Build the final return statement.
8555 if (RetVal.isInvalid())
8556 return StmtError();
8557 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8558 if (ReturnStmt.isInvalid())
8559 return StmtError();
8560 Stmts.Stmts.push_back(ReturnStmt.get());
8561
8562 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8563 }
8564
8565private:
8566 ExprResult getDecl(ValueDecl *VD) {
8567 return S.BuildDeclarationNameExpr(
8568 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8569 }
8570
8571 ExprResult getParam(unsigned I) {
8572 ParmVarDecl *PD = FD->getParamDecl(I);
8573 return getDecl(PD);
8574 }
8575
8576 ExprPair getCompleteObject() {
8577 unsigned Param = 0;
8578 ExprResult LHS;
8579 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8580 MD && MD->isImplicitObjectMemberFunction()) {
8581 // LHS is '*this'.
8582 LHS = S.ActOnCXXThis(Loc);
8583 if (!LHS.isInvalid())
8584 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8585 } else {
8586 LHS = getParam(Param++);
8587 }
8588 ExprResult RHS = getParam(Param++);
8589 assert(Param == FD->getNumParams());
8590 return {LHS, RHS};
8591 }
8592
8593 ExprPair getBase(CXXBaseSpecifier *Base) {
8594 ExprPair Obj = getCompleteObject();
8595 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8596 return {ExprError(), ExprError()};
8597 CXXCastPath Path = {Base};
8598 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8599 CK_DerivedToBase, VK_LValue, &Path),
8600 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8601 CK_DerivedToBase, VK_LValue, &Path)};
8602 }
8603
8604 ExprPair getField(FieldDecl *Field) {
8605 ExprPair Obj = getCompleteObject();
8606 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8607 return {ExprError(), ExprError()};
8608
8609 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8610 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8611 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8612 CXXScopeSpec(), Field, Found, NameInfo),
8613 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8614 CXXScopeSpec(), Field, Found, NameInfo)};
8615 }
8616
8617 // FIXME: When expanding a subobject, register a note in the code synthesis
8618 // stack to say which subobject we're comparing.
8619
8620 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8621 if (Cond.isInvalid())
8622 return StmtError();
8623
8624 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8625 if (NotCond.isInvalid())
8626 return StmtError();
8627
8628 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8629 assert(!False.isInvalid() && "should never fail");
8630 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8631 if (ReturnFalse.isInvalid())
8632 return StmtError();
8633
8634 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8635 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8636 Sema::ConditionKind::Boolean),
8637 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8638 }
8639
8640 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8641 ExprPair Subobj) {
8642 QualType SizeType = S.Context.getSizeType();
8643 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8644
8645 // Build 'size_t i$n = 0'.
8646 IdentifierInfo *IterationVarName = nullptr;
8647 {
8648 SmallString<8> Str;
8649 llvm::raw_svector_ostream OS(Str);
8650 OS << "i" << ArrayDepth;
8651 IterationVarName = &S.Context.Idents.get(OS.str());
8652 }
8653 VarDecl *IterationVar = VarDecl::Create(
8654 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8655 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8656 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8657 IterationVar->setInit(
8658 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8659 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8660
8661 auto IterRef = [&] {
8663 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8664 IterationVar);
8665 assert(!Ref.isInvalid() && "can't reference our own variable?");
8666 return Ref.get();
8667 };
8668
8669 // Build 'i$n != Size'.
8671 Loc, BO_NE, IterRef(),
8672 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8673 assert(!Cond.isInvalid() && "should never fail");
8674
8675 // Build '++i$n'.
8676 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8677 assert(!Inc.isInvalid() && "should never fail");
8678
8679 // Build 'a[i$n]' and 'b[i$n]'.
8680 auto Index = [&](ExprResult E) {
8681 if (E.isInvalid())
8682 return ExprError();
8683 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8684 };
8685 Subobj.first = Index(Subobj.first);
8686 Subobj.second = Index(Subobj.second);
8687
8688 // Compare the array elements.
8689 ++ArrayDepth;
8690 StmtResult Substmt = visitSubobject(Type, Subobj);
8691 --ArrayDepth;
8692
8693 if (Substmt.isInvalid())
8694 return StmtError();
8695
8696 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8697 // For outer levels or for an 'operator<=>' we already have a suitable
8698 // statement that returns as necessary.
8699 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8700 assert(DCK == DefaultedComparisonKind::Equal &&
8701 "should have non-expression statement");
8702 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8703 if (Substmt.isInvalid())
8704 return StmtError();
8705 }
8706
8707 // Build 'for (...) ...'
8708 return S.ActOnForStmt(Loc, Loc, Init,
8709 S.ActOnCondition(nullptr, Loc, Cond.get(),
8710 Sema::ConditionKind::Boolean),
8711 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8712 Substmt.get());
8713 }
8714
8715 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8716 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8717 return StmtError();
8718
8721 ExprResult Op;
8722 if (Type->isOverloadableType())
8723 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8724 Obj.second.get(), /*PerformADL=*/true,
8725 /*AllowRewrittenCandidates=*/true, FD);
8726 else
8727 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8728 if (Op.isInvalid())
8729 return StmtError();
8730
8731 switch (DCK) {
8732 case DefaultedComparisonKind::None:
8733 llvm_unreachable("not a defaulted comparison");
8734
8735 case DefaultedComparisonKind::Equal:
8736 // Per C++2a [class.eq]p2, each comparison is individually contextually
8737 // converted to bool.
8739 if (Op.isInvalid())
8740 return StmtError();
8741 return Op.get();
8742
8743 case DefaultedComparisonKind::ThreeWay: {
8744 // Per C++2a [class.spaceship]p3, form:
8745 // if (R cmp = static_cast<R>(op); cmp != 0)
8746 // return cmp;
8747 QualType R = FD->getReturnType();
8748 Op = buildStaticCastToR(Op.get());
8749 if (Op.isInvalid())
8750 return StmtError();
8751
8752 // R cmp = ...;
8753 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8754 VarDecl *VD =
8755 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8757 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8758 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8759
8760 // cmp != 0
8761 ExprResult VDRef = getDecl(VD);
8762 if (VDRef.isInvalid())
8763 return StmtError();
8764 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8765 Expr *Zero =
8766 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8768 if (VDRef.get()->getType()->isOverloadableType())
8769 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8770 true, FD);
8771 else
8772 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8773 if (Comp.isInvalid())
8774 return StmtError();
8776 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8777 if (Cond.isInvalid())
8778 return StmtError();
8779
8780 // return cmp;
8781 VDRef = getDecl(VD);
8782 if (VDRef.isInvalid())
8783 return StmtError();
8784 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8785 if (ReturnStmt.isInvalid())
8786 return StmtError();
8787
8788 // if (...)
8789 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8790 Loc, ReturnStmt.get(),
8791 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8792 }
8793
8794 case DefaultedComparisonKind::NotEqual:
8795 case DefaultedComparisonKind::Relational:
8796 // C++2a [class.compare.secondary]p2:
8797 // Otherwise, the operator function yields x @ y.
8798 return Op.get();
8799 }
8800 llvm_unreachable("");
8801 }
8802
8803 /// Build "static_cast<R>(E)".
8804 ExprResult buildStaticCastToR(Expr *E) {
8805 QualType R = FD->getReturnType();
8806 assert(!R->isUndeducedType() && "type should have been deduced already");
8807
8808 // Don't bother forming a no-op cast in the common case.
8809 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8810 return E;
8811 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8812 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8813 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8814 }
8815};
8816}
8817
8818/// Perform the unqualified lookups that might be needed to form a defaulted
8819/// comparison function for the given operator.
8821 UnresolvedSetImpl &Operators,
8823 auto Lookup = [&](OverloadedOperatorKind OO) {
8824 Self.LookupOverloadedOperatorName(OO, S, Operators);
8825 };
8826
8827 // Every defaulted operator looks up itself.
8828 Lookup(Op);
8829 // ... and the rewritten form of itself, if any.
8831 Lookup(ExtraOp);
8832
8833 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8834 // synthesize a three-way comparison from '<' and '=='. In a dependent
8835 // context, we also need to look up '==' in case we implicitly declare a
8836 // defaulted 'operator=='.
8837 if (Op == OO_Spaceship) {
8838 Lookup(OO_ExclaimEqual);
8839 Lookup(OO_Less);
8840 Lookup(OO_EqualEqual);
8841 }
8842}
8843
8846 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8847
8848 // Perform any unqualified lookups we're going to need to default this
8849 // function.
8850 if (S) {
8851 UnresolvedSet<32> Operators;
8852 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8853 FD->getOverloadedOperator());
8856 Context, Operators.pairs()));
8857 }
8858
8859 // C++2a [class.compare.default]p1:
8860 // A defaulted comparison operator function for some class C shall be a
8861 // non-template function declared in the member-specification of C that is
8862 // -- a non-static const non-volatile member of C having one parameter of
8863 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8864 // -- a friend of C having two parameters of type const C& or two
8865 // parameters of type C.
8866
8867 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8868 bool IsMethod = isa<CXXMethodDecl>(FD);
8869 if (IsMethod) {
8870 auto *MD = cast<CXXMethodDecl>(FD);
8871 assert(!MD->isStatic() && "comparison function cannot be a static member");
8872
8873 if (MD->getRefQualifier() == RQ_RValue) {
8874 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8875
8876 // Remove the ref qualifier to recover.
8877 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8878 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8879 EPI.RefQualifier = RQ_None;
8880 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8881 FPT->getParamTypes(), EPI));
8882 }
8883
8884 // If we're out-of-class, this is the class we're comparing.
8885 if (!RD)
8886 RD = MD->getParent();
8888 if (!T.isConstQualified()) {
8889 SourceLocation Loc, InsertLoc;
8891 Loc = MD->getParamDecl(0)->getBeginLoc();
8892 InsertLoc = getLocForEndOfToken(
8894 } else {
8895 Loc = MD->getLocation();
8896 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8897 InsertLoc = Loc.getRParenLoc();
8898 }
8899 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8900 // corresponding defaulted 'operator<=>' already.
8901 if (!MD->isImplicit()) {
8902 Diag(Loc, diag::err_defaulted_comparison_non_const)
8903 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8904 }
8905
8906 // Add the 'const' to the type to recover.
8907 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8908 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8909 EPI.TypeQuals.addConst();
8910 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8911 FPT->getParamTypes(), EPI));
8912 }
8913
8914 if (MD->isVolatile()) {
8915 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8916
8917 // Remove the 'volatile' from the type to recover.
8918 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8919 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8921 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8922 FPT->getParamTypes(), EPI));
8923 }
8924 }
8925
8926 if ((FD->getNumParams() -
8927 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8928 (IsMethod ? 1 : 2)) {
8929 // Let's not worry about using a variadic template pack here -- who would do
8930 // such a thing?
8931 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8932 << int(IsMethod) << int(DCK);
8933 return true;
8934 }
8935
8936 const ParmVarDecl *KnownParm = nullptr;
8937 for (const ParmVarDecl *Param : FD->parameters()) {
8938 if (Param->isExplicitObjectParameter())
8939 continue;
8940 QualType ParmTy = Param->getType();
8941
8942 if (!KnownParm) {
8943 auto CTy = ParmTy;
8944 // Is it `T const &`?
8945 bool Ok = !IsMethod;
8946 QualType ExpectedTy;
8947 if (RD)
8948 ExpectedTy = Context.getRecordType(RD);
8949 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8950 CTy = Ref->getPointeeType();
8951 if (RD)
8952 ExpectedTy.addConst();
8953 Ok = true;
8954 }
8955
8956 // Is T a class?
8957 if (!Ok) {
8958 } else if (RD) {
8959 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8960 Ok = false;
8961 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8962 RD = cast<CXXRecordDecl>(CRD);
8963 } else {
8964 Ok = false;
8965 }
8966
8967 if (Ok) {
8968 KnownParm = Param;
8969 } else {
8970 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8971 // corresponding defaulted 'operator<=>' already.
8972 if (!FD->isImplicit()) {
8973 if (RD) {
8974 QualType PlainTy = Context.getRecordType(RD);
8975 QualType RefTy =
8977 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8978 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8979 << Param->getSourceRange();
8980 } else {
8981 assert(!IsMethod && "should know expected type for method");
8982 Diag(FD->getLocation(),
8983 diag::err_defaulted_comparison_param_unknown)
8984 << int(DCK) << ParmTy << Param->getSourceRange();
8985 }
8986 }
8987 return true;
8988 }
8989 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8990 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8991 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8992 << ParmTy << Param->getSourceRange();
8993 return true;
8994 }
8995 }
8996
8997 assert(RD && "must have determined class");
8998 if (IsMethod) {
8999 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9000 // In-class, must be a friend decl.
9001 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9002 } else {
9003 // Out of class, require the defaulted comparison to be a friend (of a
9004 // complete type).
9006 diag::err_defaulted_comparison_not_friend, int(DCK),
9007 int(1)))
9008 return true;
9009
9010 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9011 return FD->getCanonicalDecl() ==
9012 F->getFriendDecl()->getCanonicalDecl();
9013 })) {
9014 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9015 << int(DCK) << int(0) << RD;
9016 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9017 return true;
9018 }
9019 }
9020
9021 // C++2a [class.eq]p1, [class.rel]p1:
9022 // A [defaulted comparison other than <=>] shall have a declared return
9023 // type bool.
9027 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9028 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9029 << FD->getReturnTypeSourceRange();
9030 return true;
9031 }
9032 // C++2a [class.spaceship]p2 [P2002R0]:
9033 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9034 // R shall not contain a placeholder type.
9035 if (QualType RT = FD->getDeclaredReturnType();
9037 RT->getContainedDeducedType() &&
9039 RT->getContainedAutoType()->isConstrained())) {
9040 Diag(FD->getLocation(),
9041 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9042 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9043 << FD->getReturnTypeSourceRange();
9044 return true;
9045 }
9046
9047 // For a defaulted function in a dependent class, defer all remaining checks
9048 // until instantiation.
9049 if (RD->isDependentType())
9050 return false;
9051
9052 // Determine whether the function should be defined as deleted.
9053 DefaultedComparisonInfo Info =
9054 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9055
9056 bool First = FD == FD->getCanonicalDecl();
9057
9058 if (!First) {
9059 if (Info.Deleted) {
9060 // C++11 [dcl.fct.def.default]p4:
9061 // [For a] user-provided explicitly-defaulted function [...] if such a
9062 // function is implicitly defined as deleted, the program is ill-formed.
9063 //
9064 // This is really just a consequence of the general rule that you can
9065 // only delete a function on its first declaration.
9066 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9067 << FD->isImplicit() << (int)DCK;
9068 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9069 DefaultedComparisonAnalyzer::ExplainDeleted)
9070 .visit();
9071 return true;
9072 }
9073 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9074 // C++20 [class.compare.default]p1:
9075 // [...] A definition of a comparison operator as defaulted that appears
9076 // in a class shall be the first declaration of that function.
9077 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9078 << (int)DCK;
9080 diag::note_previous_declaration);
9081 return true;
9082 }
9083 }
9084
9085 // If we want to delete the function, then do so; there's nothing else to
9086 // check in that case.
9087 if (Info.Deleted) {
9088 SetDeclDeleted(FD, FD->getLocation());
9089 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9090 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9091 << (int)DCK;
9092 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9093 DefaultedComparisonAnalyzer::ExplainDeleted)
9094 .visit();
9095 if (FD->getDefaultLoc().isValid())
9096 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9097 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9098 }
9099 return false;
9100 }
9101
9102 // C++2a [class.spaceship]p2:
9103 // The return type is deduced as the common comparison type of R0, R1, ...
9107 if (RetLoc.isInvalid())
9108 RetLoc = FD->getBeginLoc();
9109 // FIXME: Should we really care whether we have the complete type and the
9110 // 'enumerator' constants here? A forward declaration seems sufficient.
9112 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9113 if (Cat.isNull())
9114 return true;
9116 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9117 }
9118
9119 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9120 // An explicitly-defaulted function that is not defined as deleted may be
9121 // declared constexpr or consteval only if it is constexpr-compatible.
9122 // C++2a [class.compare.default]p3 [P2002R0]:
9123 // A defaulted comparison function is constexpr-compatible if it satisfies
9124 // the requirements for a constexpr function [...]
9125 // The only relevant requirements are that the parameter and return types are
9126 // literal types. The remaining conditions are checked by the analyzer.
9127 //
9128 // We support P2448R2 in language modes earlier than C++23 as an extension.
9129 // The concept of constexpr-compatible was removed.
9130 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9131 // A function explicitly defaulted on its first declaration is implicitly
9132 // inline, and is implicitly constexpr if it is constexpr-suitable.
9133 // C++23 [dcl.constexpr]p3
9134 // A function is constexpr-suitable if
9135 // - it is not a coroutine, and
9136 // - if the function is a constructor or destructor, its class does not
9137 // have any virtual base classes.
9138 if (FD->isConstexpr()) {
9139 if (!getLangOpts().CPlusPlus23 &&
9142 !Info.Constexpr) {
9143 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9144 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9145 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9146 DefaultedComparisonAnalyzer::ExplainConstexpr)
9147 .visit();
9148 }
9149 }
9150
9151 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9152 // If a constexpr-compatible function is explicitly defaulted on its first
9153 // declaration, it is implicitly considered to be constexpr.
9154 // FIXME: Only applying this to the first declaration seems problematic, as
9155 // simple reorderings can affect the meaning of the program.
9156 if (First && !FD->isConstexpr() && Info.Constexpr)
9158
9159 // C++2a [except.spec]p3:
9160 // If a declaration of a function does not have a noexcept-specifier
9161 // [and] is defaulted on its first declaration, [...] the exception
9162 // specification is as specified below
9163 if (FD->getExceptionSpecType() == EST_None) {
9164 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9165 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9167 EPI.ExceptionSpec.SourceDecl = FD;
9168 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9169 FPT->getParamTypes(), EPI));
9170 }
9171
9172 return false;
9173}
9174
9176 FunctionDecl *Spaceship) {
9179 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9180 Ctx.Entity = Spaceship;
9182
9183 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9184 EqualEqual->setImplicit();
9185
9187}
9188
9191 assert(FD->isDefaulted() && !FD->isDeleted() &&
9193 if (FD->willHaveBody() || FD->isInvalidDecl())
9194 return;
9195
9197
9198 // Add a context note for diagnostics produced after this point.
9199 Scope.addContextNote(UseLoc);
9200
9201 {
9202 // Build and set up the function body.
9203 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9204 // the type of the class being compared.
9205 auto PT = FD->getParamDecl(0)->getType();
9206 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9207 SourceLocation BodyLoc =
9208 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9209 StmtResult Body =
9210 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9211 if (Body.isInvalid()) {
9212 FD->setInvalidDecl();
9213 return;
9214 }
9215 FD->setBody(Body.get());
9216 FD->markUsed(Context);
9217 }
9218
9219 // The exception specification is needed because we are defining the
9220 // function. Note that this will reuse the body we just built.
9222
9224 L->CompletedImplicitDefinition(FD);
9225}
9226
9229 FunctionDecl *FD,
9231 ComputingExceptionSpec CES(S, FD, Loc);
9233
9234 if (FD->isInvalidDecl())
9235 return ExceptSpec;
9236
9237 // The common case is that we just defined the comparison function. In that
9238 // case, just look at whether the body can throw.
9239 if (FD->hasBody()) {
9240 ExceptSpec.CalledStmt(FD->getBody());
9241 } else {
9242 // Otherwise, build a body so we can check it. This should ideally only
9243 // happen when we're not actually marking the function referenced. (This is
9244 // only really important for efficiency: we don't want to build and throw
9245 // away bodies for comparison functions more than we strictly need to.)
9246
9247 // Pretend to synthesize the function body in an unevaluated context.
9248 // Note that we can't actually just go ahead and define the function here:
9249 // we are not permitted to mark its callees as referenced.
9253
9254 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9255 SourceLocation BodyLoc =
9256 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9257 StmtResult Body =
9258 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9259 if (!Body.isInvalid())
9260 ExceptSpec.CalledStmt(Body.get());
9261
9262 // FIXME: Can we hold onto this body and just transform it to potentially
9263 // evaluated when we're asked to define the function rather than rebuilding
9264 // it? Either that, or we should only build the bits of the body that we
9265 // need (the expressions, not the statements).
9266 }
9267
9268 return ExceptSpec;
9269}
9270
9272 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9274
9275 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9277
9278 // Perform any deferred checking of exception specifications for virtual
9279 // destructors.
9280 for (auto &Check : Overriding)
9281 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9282
9283 // Perform any deferred checking of exception specifications for befriended
9284 // special members.
9285 for (auto &Check : Equivalent)
9286 CheckEquivalentExceptionSpec(Check.second, Check.first);
9287}
9288
9289namespace {
9290/// CRTP base class for visiting operations performed by a special member
9291/// function (or inherited constructor).
9292template<typename Derived>
9293struct SpecialMemberVisitor {
9294 Sema &S;
9295 CXXMethodDecl *MD;
9298
9299 // Properties of the special member, computed for convenience.
9300 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9301
9302 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9304 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9305 switch (CSM) {
9306 case CXXSpecialMemberKind::DefaultConstructor:
9307 case CXXSpecialMemberKind::CopyConstructor:
9308 case CXXSpecialMemberKind::MoveConstructor:
9309 IsConstructor = true;
9310 break;
9311 case CXXSpecialMemberKind::CopyAssignment:
9312 case CXXSpecialMemberKind::MoveAssignment:
9313 IsAssignment = true;
9314 break;
9315 case CXXSpecialMemberKind::Destructor:
9316 break;
9317 case CXXSpecialMemberKind::Invalid:
9318 llvm_unreachable("invalid special member kind");
9319 }
9320
9321 if (MD->getNumExplicitParams()) {
9322 if (const ReferenceType *RT =
9324 ConstArg = RT->getPointeeType().isConstQualified();
9325 }
9326 }
9327
9328 Derived &getDerived() { return static_cast<Derived&>(*this); }
9329
9330 /// Is this a "move" special member?
9331 bool isMove() const {
9332 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9333 CSM == CXXSpecialMemberKind::MoveAssignment;
9334 }
9335
9336 /// Look up the corresponding special member in the given class.
9338 unsigned Quals, bool IsMutable) {
9339 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9340 ConstArg && !IsMutable);
9341 }
9342
9343 /// Look up the constructor for the specified base class to see if it's
9344 /// overridden due to this being an inherited constructor.
9345 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9346 if (!ICI)
9347 return {};
9348 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9349 auto *BaseCtor =
9350 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9351 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9352 return MD;
9353 return {};
9354 }
9355
9356 /// A base or member subobject.
9357 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9358
9359 /// Get the location to use for a subobject in diagnostics.
9360 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9361 // FIXME: For an indirect virtual base, the direct base leading to
9362 // the indirect virtual base would be a more useful choice.
9363 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9364 return B->getBaseTypeLoc();
9365 else
9366 return Subobj.get<FieldDecl*>()->getLocation();
9367 }
9368
9369 enum BasesToVisit {
9370 /// Visit all non-virtual (direct) bases.
9371 VisitNonVirtualBases,
9372 /// Visit all direct bases, virtual or not.
9373 VisitDirectBases,
9374 /// Visit all non-virtual bases, and all virtual bases if the class
9375 /// is not abstract.
9376 VisitPotentiallyConstructedBases,
9377 /// Visit all direct or virtual bases.
9378 VisitAllBases
9379 };
9380
9381 // Visit the bases and members of the class.
9382 bool visit(BasesToVisit Bases) {
9383 CXXRecordDecl *RD = MD->getParent();
9384
9385 if (Bases == VisitPotentiallyConstructedBases)
9386 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9387
9388 for (auto &B : RD->bases())
9389 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9390 getDerived().visitBase(&B))
9391 return true;
9392
9393 if (Bases == VisitAllBases)
9394 for (auto &B : RD->vbases())
9395 if (getDerived().visitBase(&B))
9396 return true;
9397
9398 for (auto *F : RD->fields())
9399 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9400 getDerived().visitField(F))
9401 return true;
9402
9403 return false;
9404 }
9405};
9406}
9407
9408namespace {
9409struct SpecialMemberDeletionInfo
9410 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9411 bool Diagnose;
9412
9413 SourceLocation Loc;
9414
9415 bool AllFieldsAreConst;
9416
9417 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9419 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9420 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9421 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9422
9423 bool inUnion() const { return MD->getParent()->isUnion(); }
9424
9425 CXXSpecialMemberKind getEffectiveCSM() {
9426 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9427 }
9428
9429 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9430
9431 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9432 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9433
9434 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9435 bool shouldDeleteForField(FieldDecl *FD);
9436 bool shouldDeleteForAllConstMembers();
9437
9438 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9439 unsigned Quals);
9440 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9442 bool IsDtorCallInCtor);
9443
9444 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9445};
9446}
9447
9448/// Is the given special member inaccessible when used on the given
9449/// sub-object.
9450bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9451 CXXMethodDecl *target) {
9452 /// If we're operating on a base class, the object type is the
9453 /// type of this special member.
9454 QualType objectTy;
9455 AccessSpecifier access = target->getAccess();
9456 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9457 objectTy = S.Context.getTypeDeclType(MD->getParent());
9458 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9459
9460 // If we're operating on a field, the object type is the type of the field.
9461 } else {
9462 objectTy = S.Context.getTypeDeclType(target->getParent());
9463 }
9464
9466 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9467}
9468
9469/// Check whether we should delete a special member due to the implicit
9470/// definition containing a call to a special member of a subobject.
9471bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9472 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9473 bool IsDtorCallInCtor) {
9474 CXXMethodDecl *Decl = SMOR.getMethod();
9475 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9476
9477 int DiagKind = -1;
9478
9480 DiagKind = !Decl ? 0 : 1;
9482 DiagKind = 2;
9483 else if (!isAccessible(Subobj, Decl))
9484 DiagKind = 3;
9485 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9486 !Decl->isTrivial()) {
9487 // A member of a union must have a trivial corresponding special member.
9488 // As a weird special case, a destructor call from a union's constructor
9489 // must be accessible and non-deleted, but need not be trivial. Such a
9490 // destructor is never actually called, but is semantically checked as
9491 // if it were.
9493 // [class.default.ctor]p2:
9494 // A defaulted default constructor for class X is defined as deleted if
9495 // - X is a union that has a variant member with a non-trivial default
9496 // constructor and no variant member of X has a default member
9497 // initializer
9498 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9499 if (!RD->hasInClassInitializer())
9500 DiagKind = 4;
9501 } else {
9502 DiagKind = 4;
9503 }
9504 }
9505
9506 if (DiagKind == -1)
9507 return false;
9508
9509 if (Diagnose) {
9510 if (Field) {
9511 S.Diag(Field->getLocation(),
9512 diag::note_deleted_special_member_class_subobject)
9513 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9514 << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9515 << /*IsObjCPtr*/ false;
9516 } else {
9517 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9518 S.Diag(Base->getBeginLoc(),
9519 diag::note_deleted_special_member_class_subobject)
9520 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9521 << /*IsField*/ false << Base->getType() << DiagKind
9522 << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9523 }
9524
9525 if (DiagKind == 1)
9527 // FIXME: Explain inaccessibility if DiagKind == 3.
9528 }
9529
9530 return true;
9531}
9532
9533/// Check whether we should delete a special member function due to having a
9534/// direct or virtual base class or non-static data member of class type M.
9535bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9536 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9537 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9538 bool IsMutable = Field && Field->isMutable();
9539
9540 // C++11 [class.ctor]p5:
9541 // -- any direct or virtual base class, or non-static data member with no
9542 // brace-or-equal-initializer, has class type M (or array thereof) and
9543 // either M has no default constructor or overload resolution as applied
9544 // to M's default constructor results in an ambiguity or in a function
9545 // that is deleted or inaccessible
9546 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9547 // -- a direct or virtual base class B that cannot be copied/moved because
9548 // overload resolution, as applied to B's corresponding special member,
9549 // results in an ambiguity or a function that is deleted or inaccessible
9550 // from the defaulted special member
9551 // C++11 [class.dtor]p5:
9552 // -- any direct or virtual base class [...] has a type with a destructor
9553 // that is deleted or inaccessible
9554 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9555 Field->hasInClassInitializer()) &&
9556 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9557 false))
9558 return true;
9559
9560 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9561 // -- any direct or virtual base class or non-static data member has a
9562 // type with a destructor that is deleted or inaccessible
9563 if (IsConstructor) {
9566 false, false, false, false);
9567 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9568 return true;
9569 }
9570
9571 return false;
9572}
9573
9574bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9575 FieldDecl *FD, QualType FieldType) {
9576 // The defaulted special functions are defined as deleted if this is a variant
9577 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9578 // type under ARC.
9579 if (!FieldType.hasNonTrivialObjCLifetime())
9580 return false;
9581
9582 // Don't make the defaulted default constructor defined as deleted if the
9583 // member has an in-class initializer.
9586 return false;
9587
9588 if (Diagnose) {
9589 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9590 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9591 << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9592 << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9593 << /*IsObjCPtr*/ true;
9594 }
9595
9596 return true;
9597}
9598
9599/// Check whether we should delete a special member function due to the class
9600/// having a particular direct or virtual base class.
9601bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9602 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9603 // If program is correct, BaseClass cannot be null, but if it is, the error
9604 // must be reported elsewhere.
9605 if (!BaseClass)
9606 return false;
9607 // If we have an inheriting constructor, check whether we're calling an
9608 // inherited constructor instead of a default constructor.
9609 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9610 if (auto *BaseCtor = SMOR.getMethod()) {
9611 // Note that we do not check access along this path; other than that,
9612 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9613 // FIXME: Check that the base has a usable destructor! Sink this into
9614 // shouldDeleteForClassSubobject.
9615 if (BaseCtor->isDeleted() && Diagnose) {
9616 S.Diag(Base->getBeginLoc(),
9617 diag::note_deleted_special_member_class_subobject)
9618 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9619 << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9620 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9621 S.NoteDeletedFunction(BaseCtor);
9622 }
9623 return BaseCtor->isDeleted();
9624 }
9625 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9626}
9627
9628/// Check whether we should delete a special member function due to the class
9629/// having a particular non-static data member.
9630bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9631 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9632 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9633
9634 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9635 return true;
9636
9638 // For a default constructor, all references must be initialized in-class
9639 // and, if a union, it must have a non-const member.
9640 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9641 if (Diagnose)
9642 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9643 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9644 return true;
9645 }
9646 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9647 // data member of const-qualified type (or array thereof) with no
9648 // brace-or-equal-initializer is not const-default-constructible.
9649 if (!inUnion() && FieldType.isConstQualified() &&
9650 !FD->hasInClassInitializer() &&
9651 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9652 if (Diagnose)
9653 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9654 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9655 return true;
9656 }
9657
9658 if (inUnion() && !FieldType.isConstQualified())
9659 AllFieldsAreConst = false;
9660 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9661 // For a copy constructor, data members must not be of rvalue reference
9662 // type.
9663 if (FieldType->isRValueReferenceType()) {
9664 if (Diagnose)
9665 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9666 << MD->getParent() << FD << FieldType;
9667 return true;
9668 }
9669 } else if (IsAssignment) {
9670 // For an assignment operator, data members must not be of reference type.
9671 if (FieldType->isReferenceType()) {
9672 if (Diagnose)
9673 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9674 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9675 return true;
9676 }
9677 if (!FieldRecord && FieldType.isConstQualified()) {
9678 // C++11 [class.copy]p23:
9679 // -- a non-static data member of const non-class type (or array thereof)
9680 if (Diagnose)
9681 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9682 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9683 return true;
9684 }
9685 }
9686
9687 if (FieldRecord) {
9688 // Some additional restrictions exist on the variant members.
9689 if (!inUnion() && FieldRecord->isUnion() &&
9690 FieldRecord->isAnonymousStructOrUnion()) {
9691 bool AllVariantFieldsAreConst = true;
9692
9693 // FIXME: Handle anonymous unions declared within anonymous unions.
9694 for (auto *UI : FieldRecord->fields()) {
9695 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9696
9697 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9698 return true;
9699
9700 if (!UnionFieldType.isConstQualified())
9701 AllVariantFieldsAreConst = false;
9702
9703 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9704 if (UnionFieldRecord &&
9705 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9706 UnionFieldType.getCVRQualifiers()))
9707 return true;
9708 }
9709
9710 // At least one member in each anonymous union must be non-const
9712 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9713 if (Diagnose)
9714 S.Diag(FieldRecord->getLocation(),
9715 diag::note_deleted_default_ctor_all_const)
9716 << !!ICI << MD->getParent() << /*anonymous union*/1;
9717 return true;
9718 }
9719
9720 // Don't check the implicit member of the anonymous union type.
9721 // This is technically non-conformant but supported, and we have a
9722 // diagnostic for this elsewhere.
9723 return false;
9724 }
9725
9726 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9727 FieldType.getCVRQualifiers()))
9728 return true;
9729 }
9730
9731 return false;
9732}
9733
9734/// C++11 [class.ctor] p5:
9735/// A defaulted default constructor for a class X is defined as deleted if
9736/// X is a union and all of its variant members are of const-qualified type.
9737bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9738 // This is a silly definition, because it gives an empty union a deleted
9739 // default constructor. Don't do that.
9740 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9741 AllFieldsAreConst) {
9742 bool AnyFields = false;
9743 for (auto *F : MD->getParent()->fields())
9744 if ((AnyFields = !F->isUnnamedBitField()))
9745 break;
9746 if (!AnyFields)
9747 return false;
9748 if (Diagnose)
9749 S.Diag(MD->getParent()->getLocation(),
9750 diag::note_deleted_default_ctor_all_const)
9751 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9752 return true;
9753 }
9754 return false;
9755}
9756
9757/// Determine whether a defaulted special member function should be defined as
9758/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9759/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9763 bool Diagnose) {
9764 if (MD->isInvalidDecl())
9765 return false;
9766 CXXRecordDecl *RD = MD->getParent();
9767 assert(!RD->isDependentType() && "do deletion after instantiation");
9768 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9769 RD->isInvalidDecl())
9770 return false;
9771
9772 // C++11 [expr.lambda.prim]p19:
9773 // The closure type associated with a lambda-expression has a
9774 // deleted (8.4.3) default constructor and a deleted copy
9775 // assignment operator.
9776 // C++2a adds back these operators if the lambda has no lambda-capture.
9780 if (Diagnose)
9781 Diag(RD->getLocation(), diag::note_lambda_decl);
9782 return true;
9783 }
9784
9785 // For an anonymous struct or union, the copy and assignment special members
9786 // will never be used, so skip the check. For an anonymous union declared at
9787 // namespace scope, the constructor and destructor are used.
9790 return false;
9791
9792 // C++11 [class.copy]p7, p18:
9793 // If the class definition declares a move constructor or move assignment
9794 // operator, an implicitly declared copy constructor or copy assignment
9795 // operator is defined as deleted.
9798 CXXMethodDecl *UserDeclaredMove = nullptr;
9799
9800 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9801 // deletion of the corresponding copy operation, not both copy operations.
9802 // MSVC 2015 has adopted the standards conforming behavior.
9803 bool DeletesOnlyMatchingCopy =
9804 getLangOpts().MSVCCompat &&
9806
9808 (!DeletesOnlyMatchingCopy ||
9810 if (!Diagnose) return true;
9811
9812 // Find any user-declared move constructor.
9813 for (auto *I : RD->ctors()) {
9814 if (I->isMoveConstructor()) {
9815 UserDeclaredMove = I;
9816 break;
9817 }
9818 }
9819 assert(UserDeclaredMove);
9820 } else if (RD->hasUserDeclaredMoveAssignment() &&
9821 (!DeletesOnlyMatchingCopy ||
9823 if (!Diagnose) return true;
9824
9825 // Find any user-declared move assignment operator.
9826 for (auto *I : RD->methods()) {
9827 if (I->isMoveAssignmentOperator()) {
9828 UserDeclaredMove = I;
9829 break;
9830 }
9831 }
9832 assert(UserDeclaredMove);
9833 }
9834
9835 if (UserDeclaredMove) {
9836 Diag(UserDeclaredMove->getLocation(),
9837 diag::note_deleted_copy_user_declared_move)
9838 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9839 << UserDeclaredMove->isMoveAssignmentOperator();
9840 return true;
9841 }
9842 }
9843
9844 // Do access control from the special member function
9845 ContextRAII MethodContext(*this, MD);
9846
9847 // C++11 [class.dtor]p5:
9848 // -- for a virtual destructor, lookup of the non-array deallocation function
9849 // results in an ambiguity or in a function that is deleted or inaccessible
9850 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9851 FunctionDecl *OperatorDelete = nullptr;
9852 DeclarationName Name =
9854 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9855 OperatorDelete, /*Diagnose*/false)) {
9856 if (Diagnose)
9857 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9858 return true;
9859 }
9860 }
9861
9862 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9863
9864 // Per DR1611, do not consider virtual bases of constructors of abstract
9865 // classes, since we are not going to construct them.
9866 // Per DR1658, do not consider virtual bases of destructors of abstract
9867 // classes either.
9868 // Per DR2180, for assignment operators we only assign (and thus only
9869 // consider) direct bases.
9870 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9871 : SMI.VisitPotentiallyConstructedBases))
9872 return true;
9873
9874 if (SMI.shouldDeleteForAllConstMembers())
9875 return true;
9876
9877 if (getLangOpts().CUDA) {
9878 // We should delete the special member in CUDA mode if target inference
9879 // failed.
9880 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9881 // is treated as certain special member, which may not reflect what special
9882 // member MD really is. However inferTargetForImplicitSpecialMember
9883 // expects CSM to match MD, therefore recalculate CSM.
9884 assert(ICI || CSM == getSpecialMember(MD));
9885 auto RealCSM = CSM;
9886 if (ICI)
9887 RealCSM = getSpecialMember(MD);
9888
9889 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9890 SMI.ConstArg, Diagnose);
9891 }
9892
9893 return false;
9894}
9895
9898 assert(DFK && "not a defaultable function");
9899 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9900
9901 if (DFK.isSpecialMember()) {
9902 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9903 nullptr, /*Diagnose=*/true);
9904 } else {
9905 DefaultedComparisonAnalyzer(
9906 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9907 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9908 .visit();
9909 }
9910}
9911
9912/// Perform lookup for a special member of the specified kind, and determine
9913/// whether it is trivial. If the triviality can be determined without the
9914/// lookup, skip it. This is intended for use when determining whether a
9915/// special member of a containing object is trivial, and thus does not ever
9916/// perform overload resolution for default constructors.
9917///
9918/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9919/// member that was most likely to be intended to be trivial, if any.
9920///
9921/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9922/// determine whether the special member is trivial.
9924 CXXSpecialMemberKind CSM, unsigned Quals,
9925 bool ConstRHS,
9927 CXXMethodDecl **Selected) {
9928 if (Selected)
9929 *Selected = nullptr;
9930
9931 switch (CSM) {
9933 llvm_unreachable("not a special member");
9934
9936 // C++11 [class.ctor]p5:
9937 // A default constructor is trivial if:
9938 // - all the [direct subobjects] have trivial default constructors
9939 //
9940 // Note, no overload resolution is performed in this case.
9942 return true;
9943
9944 if (Selected) {
9945 // If there's a default constructor which could have been trivial, dig it
9946 // out. Otherwise, if there's any user-provided default constructor, point
9947 // to that as an example of why there's not a trivial one.
9948 CXXConstructorDecl *DefCtor = nullptr;
9951 for (auto *CI : RD->ctors()) {
9952 if (!CI->isDefaultConstructor())
9953 continue;
9954 DefCtor = CI;
9955 if (!DefCtor->isUserProvided())
9956 break;
9957 }
9958
9959 *Selected = DefCtor;
9960 }
9961
9962 return false;
9963
9965 // C++11 [class.dtor]p5:
9966 // A destructor is trivial if:
9967 // - all the direct [subobjects] have trivial destructors
9968 if (RD->hasTrivialDestructor() ||
9971 return true;
9972
9973 if (Selected) {
9974 if (RD->needsImplicitDestructor())
9976 *Selected = RD->getDestructor();
9977 }
9978
9979 return false;
9980
9982 // C++11 [class.copy]p12:
9983 // A copy constructor is trivial if:
9984 // - the constructor selected to copy each direct [subobject] is trivial
9985 if (RD->hasTrivialCopyConstructor() ||
9988 if (Quals == Qualifiers::Const)
9989 // We must either select the trivial copy constructor or reach an
9990 // ambiguity; no need to actually perform overload resolution.
9991 return true;
9992 } else if (!Selected) {
9993 return false;
9994 }
9995 // In C++98, we are not supposed to perform overload resolution here, but we
9996 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9997 // cases like B as having a non-trivial copy constructor:
9998 // struct A { template<typename T> A(T&); };
9999 // struct B { mutable A a; };
10000 goto NeedOverloadResolution;
10001
10003 // C++11 [class.copy]p25:
10004 // A copy assignment operator is trivial if:
10005 // - the assignment operator selected to copy each direct [subobject] is
10006 // trivial
10007 if (RD->hasTrivialCopyAssignment()) {
10008 if (Quals == Qualifiers::Const)
10009 return true;
10010 } else if (!Selected) {
10011 return false;
10012 }
10013 // In C++98, we are not supposed to perform overload resolution here, but we
10014 // treat that as a language defect.
10015 goto NeedOverloadResolution;
10016
10019 NeedOverloadResolution:
10021 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10022
10023 // The standard doesn't describe how to behave if the lookup is ambiguous.
10024 // We treat it as not making the member non-trivial, just like the standard
10025 // mandates for the default constructor. This should rarely matter, because
10026 // the member will also be deleted.
10028 return true;
10029
10030 if (!SMOR.getMethod()) {
10031 assert(SMOR.getKind() ==
10033 return false;
10034 }
10035
10036 // We deliberately don't check if we found a deleted special member. We're
10037 // not supposed to!
10038 if (Selected)
10039 *Selected = SMOR.getMethod();
10040
10041 if (TAH == Sema::TAH_ConsiderTrivialABI &&
10044 return SMOR.getMethod()->isTrivialForCall();
10045 return SMOR.getMethod()->isTrivial();
10046 }
10047
10048 llvm_unreachable("unknown special method kind");
10049}
10050
10052 for (auto *CI : RD->ctors())
10053 if (!CI->isImplicit())
10054 return CI;
10055
10056 // Look for constructor templates.
10058 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10059 if (CXXConstructorDecl *CD =
10060 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10061 return CD;
10062 }
10063
10064 return nullptr;
10065}
10066
10067/// The kind of subobject we are checking for triviality. The values of this
10068/// enumeration are used in diagnostics.
10070 /// The subobject is a base class.
10072 /// The subobject is a non-static data member.
10074 /// The object is actually the complete object.
10077
10078/// Check whether the special member selected for a given type would be trivial.
10080 QualType SubType, bool ConstRHS,
10084 bool Diagnose) {
10085 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10086 if (!SubRD)
10087 return true;
10088
10089 CXXMethodDecl *Selected;
10090 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10091 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10092 return true;
10093
10094 if (Diagnose) {
10095 if (ConstRHS)
10096 SubType.addConst();
10097
10098 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10099 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10100 << Kind << SubType.getUnqualifiedType();
10102 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10103 } else if (!Selected)
10104 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10105 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
10106 << SubType;
10107 else if (Selected->isUserProvided()) {
10108 if (Kind == TSK_CompleteObject)
10109 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10110 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10111 else {
10112 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10113 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10114 S.Diag(Selected->getLocation(), diag::note_declared_at);
10115 }
10116 } else {
10117 if (Kind != TSK_CompleteObject)
10118 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10119 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10120
10121 // Explain why the defaulted or deleted special member isn't trivial.
10123 Diagnose);
10124 }
10125 }
10126
10127 return false;
10128}
10129
10130/// Check whether the members of a class type allow a special member to be
10131/// trivial.
10133 CXXSpecialMemberKind CSM, bool ConstArg,
10135 bool Diagnose) {
10136 for (const auto *FI : RD->fields()) {
10137 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10138 continue;
10139
10140 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10141
10142 // Pretend anonymous struct or union members are members of this class.
10143 if (FI->isAnonymousStructOrUnion()) {
10144 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10145 CSM, ConstArg, TAH, Diagnose))
10146 return false;
10147 continue;
10148 }
10149
10150 // C++11 [class.ctor]p5:
10151 // A default constructor is trivial if [...]
10152 // -- no non-static data member of its class has a
10153 // brace-or-equal-initializer
10155 FI->hasInClassInitializer()) {
10156 if (Diagnose)
10157 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10158 << FI;
10159 return false;
10160 }
10161
10162 // Objective C ARC 4.3.5:
10163 // [...] nontrivally ownership-qualified types are [...] not trivially
10164 // default constructible, copy constructible, move constructible, copy
10165 // assignable, move assignable, or destructible [...]
10166 if (FieldType.hasNonTrivialObjCLifetime()) {
10167 if (Diagnose)
10168 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10169 << RD << FieldType.getObjCLifetime();
10170 return false;
10171 }
10172
10173 bool ConstRHS = ConstArg && !FI->isMutable();
10174 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10175 CSM, TSK_Field, TAH, Diagnose))
10176 return false;
10177 }
10178
10179 return true;
10180}
10181
10182/// Diagnose why the specified class does not have a trivial special member of
10183/// the given kind.
10187
10188 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10190 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10192 /*Diagnose*/true);
10193}
10194
10195/// Determine whether a defaulted or deleted special member function is trivial,
10196/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10197/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10199 TrivialABIHandling TAH, bool Diagnose) {
10200 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10201 "not special enough");
10202
10203 CXXRecordDecl *RD = MD->getParent();
10204
10205 bool ConstArg = false;
10206
10207 // C++11 [class.copy]p12, p25: [DR1593]
10208 // A [special member] is trivial if [...] its parameter-type-list is
10209 // equivalent to the parameter-type-list of an implicit declaration [...]
10210 switch (CSM) {
10213 // Trivial default constructors and destructors cannot have parameters.
10214 break;
10215
10218 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10219 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10220
10221 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10222 // if they are not user-provided and their parameter-type-list is equivalent
10223 // to the parameter-type-list of an implicit declaration. This maintains the
10224 // behavior before dr2171 was implemented.
10225 //
10226 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10227 // trivial, if they are not user-provided, regardless of the qualifiers on
10228 // the reference type.
10229 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10231 if (!RT ||
10233 ClangABICompat14)) {
10234 if (Diagnose)
10235 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10236 << Param0->getSourceRange() << Param0->getType()
10239 return false;
10240 }
10241
10242 ConstArg = RT->getPointeeType().isConstQualified();
10243 break;
10244 }
10245
10248 // Trivial move operations always have non-cv-qualified parameters.
10249 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10250 const RValueReferenceType *RT =
10251 Param0->getType()->getAs<RValueReferenceType>();
10252 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10253 if (Diagnose)
10254 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10255 << Param0->getSourceRange() << Param0->getType()
10257 return false;
10258 }
10259 break;
10260 }
10261
10263 llvm_unreachable("not a special member");
10264 }
10265
10266 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10267 if (Diagnose)
10269 diag::note_nontrivial_default_arg)
10271 return false;
10272 }
10273 if (MD->isVariadic()) {
10274 if (Diagnose)
10275 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10276 return false;
10277 }
10278
10279 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10280 // A copy/move [constructor or assignment operator] is trivial if
10281 // -- the [member] selected to copy/move each direct base class subobject
10282 // is trivial
10283 //
10284 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10285 // A [default constructor or destructor] is trivial if
10286 // -- all the direct base classes have trivial [default constructors or
10287 // destructors]
10288 for (const auto &BI : RD->bases())
10289 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10290 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10291 return false;
10292
10293 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10294 // A copy/move [constructor or assignment operator] for a class X is
10295 // trivial if
10296 // -- for each non-static data member of X that is of class type (or array
10297 // thereof), the constructor selected to copy/move that member is
10298 // trivial
10299 //
10300 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10301 // A [default constructor or destructor] is trivial if
10302 // -- for all of the non-static data members of its class that are of class
10303 // type (or array thereof), each such class has a trivial [default
10304 // constructor or destructor]
10305 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10306 return false;
10307
10308 // C++11 [class.dtor]p5:
10309 // A destructor is trivial if [...]
10310 // -- the destructor is not virtual
10311 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10312 if (Diagnose)
10313 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10314 return false;
10315 }
10316
10317 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10318 // A [special member] for class X is trivial if [...]
10319 // -- class X has no virtual functions and no virtual base classes
10321 MD->getParent()->isDynamicClass()) {
10322 if (!Diagnose)
10323 return false;
10324
10325 if (RD->getNumVBases()) {
10326 // Check for virtual bases. We already know that the corresponding
10327 // member in all bases is trivial, so vbases must all be direct.
10328 CXXBaseSpecifier &BS = *RD->vbases_begin();
10329 assert(BS.isVirtual());
10330 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10331 return false;
10332 }
10333
10334 // Must have a virtual method.
10335 for (const auto *MI : RD->methods()) {
10336 if (MI->isVirtual()) {
10337 SourceLocation MLoc = MI->getBeginLoc();
10338 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10339 return false;
10340 }
10341 }
10342
10343 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10344 }
10345
10346 // Looks like it's trivial!
10347 return true;
10348}
10349
10350namespace {
10351struct FindHiddenVirtualMethod {
10352 Sema *S;
10353 CXXMethodDecl *Method;
10354 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10355 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10356
10357private:
10358 /// Check whether any most overridden method from MD in Methods
10359 static bool CheckMostOverridenMethods(
10360 const CXXMethodDecl *MD,
10361 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10362 if (MD->size_overridden_methods() == 0)
10363 return Methods.count(MD->getCanonicalDecl());
10364 for (const CXXMethodDecl *O : MD->overridden_methods())
10365 if (CheckMostOverridenMethods(O, Methods))
10366 return true;
10367 return false;
10368 }
10369
10370public:
10371 /// Member lookup function that determines whether a given C++
10372 /// method overloads virtual methods in a base class without overriding any,
10373 /// to be used with CXXRecordDecl::lookupInBases().
10374 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10375 RecordDecl *BaseRecord =
10376 Specifier->getType()->castAs<RecordType>()->getDecl();
10377
10378 DeclarationName Name = Method->getDeclName();
10379 assert(Name.getNameKind() == DeclarationName::Identifier);
10380
10381 bool foundSameNameMethod = false;
10382 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10383 for (Path.Decls = BaseRecord->lookup(Name).begin();
10384 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10385 NamedDecl *D = *Path.Decls;
10386 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10387 MD = MD->getCanonicalDecl();
10388 foundSameNameMethod = true;
10389 // Interested only in hidden virtual methods.
10390 if (!MD->isVirtual())
10391 continue;
10392 // If the method we are checking overrides a method from its base
10393 // don't warn about the other overloaded methods. Clang deviates from
10394 // GCC by only diagnosing overloads of inherited virtual functions that
10395 // do not override any other virtual functions in the base. GCC's
10396 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10397 // function from a base class. These cases may be better served by a
10398 // warning (not specific to virtual functions) on call sites when the
10399 // call would select a different function from the base class, were it
10400 // visible.
10401 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10402 if (!S->IsOverload(Method, MD, false))
10403 return true;
10404 // Collect the overload only if its hidden.
10405 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10406 overloadedMethods.push_back(MD);
10407 }
10408 }
10409
10410 if (foundSameNameMethod)
10411 OverloadedMethods.append(overloadedMethods.begin(),
10412 overloadedMethods.end());
10413 return foundSameNameMethod;
10414 }
10415};
10416} // end anonymous namespace
10417
10418/// Add the most overridden methods from MD to Methods
10420 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10421 if (MD->size_overridden_methods() == 0)
10422 Methods.insert(MD->getCanonicalDecl());
10423 else
10424 for (const CXXMethodDecl *O : MD->overridden_methods())
10425 AddMostOverridenMethods(O, Methods);
10426}
10427
10428/// Check if a method overloads virtual methods in a base class without
10429/// overriding any.
10431 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10432 if (!MD->getDeclName().isIdentifier())
10433 return;
10434
10435 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10436 /*bool RecordPaths=*/false,
10437 /*bool DetectVirtual=*/false);
10438 FindHiddenVirtualMethod FHVM;
10439 FHVM.Method = MD;
10440 FHVM.S = this;
10441
10442 // Keep the base methods that were overridden or introduced in the subclass
10443 // by 'using' in a set. A base method not in this set is hidden.
10444 CXXRecordDecl *DC = MD->getParent();
10446 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10447 NamedDecl *ND = *I;
10448 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10449 ND = shad->getTargetDecl();
10450 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10451 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10452 }
10453
10454 if (DC->lookupInBases(FHVM, Paths))
10455 OverloadedMethods = FHVM.OverloadedMethods;
10456}
10457
10459 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10460 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10461 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10463 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10464 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10465 Diag(overloadedMD->getLocation(), PD);
10466 }
10467}
10468
10469/// Diagnose methods which overload virtual methods in a base class
10470/// without overriding any.
10472 if (MD->isInvalidDecl())
10473 return;
10474
10475 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10476 return;
10477
10478 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10479 FindHiddenVirtualMethods(MD, OverloadedMethods);
10480 if (!OverloadedMethods.empty()) {
10481 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10482 << MD << (OverloadedMethods.size() > 1);
10483
10484 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10485 }
10486}
10487
10489 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10490 // No diagnostics if this is a template instantiation.
10492 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10493 diag::ext_cannot_use_trivial_abi) << &RD;
10494 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10495 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10496 }
10497 RD.dropAttr<TrivialABIAttr>();
10498 };
10499
10500 // Ill-formed if the copy and move constructors are deleted.
10501 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10502 // If the type is dependent, then assume it might have
10503 // implicit copy or move ctor because we won't know yet at this point.
10504 if (RD.isDependentType())
10505 return true;
10508 return true;
10511 return true;
10512 for (const CXXConstructorDecl *CD : RD.ctors())
10513 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10514 return true;
10515 return false;
10516 };
10517
10518 if (!HasNonDeletedCopyOrMoveConstructor()) {
10519 PrintDiagAndRemoveAttr(0);
10520 return;
10521 }
10522
10523 // Ill-formed if the struct has virtual functions.
10524 if (RD.isPolymorphic()) {
10525 PrintDiagAndRemoveAttr(1);
10526 return;
10527 }
10528
10529 for (const auto &B : RD.bases()) {
10530 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10531 // virtual base.
10532 if (!B.getType()->isDependentType() &&
10533 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10534 PrintDiagAndRemoveAttr(2);
10535 return;
10536 }
10537
10538 if (B.isVirtual()) {
10539 PrintDiagAndRemoveAttr(3);
10540 return;
10541 }
10542 }
10543
10544 for (const auto *FD : RD.fields()) {
10545 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10546 // non-trivial for the purpose of calls.
10547 QualType FT = FD->getType();
10549 PrintDiagAndRemoveAttr(4);
10550 return;
10551 }
10552
10553 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10554 if (!RT->isDependentType() &&
10555 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10556 PrintDiagAndRemoveAttr(5);
10557 return;
10558 }
10559 }
10560}
10561
10564 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10565 if (!TagDecl)
10566 return;
10567
10569
10570 for (const ParsedAttr &AL : AttrList) {
10571 if (AL.getKind() != ParsedAttr::AT_Visibility)
10572 continue;
10573 AL.setInvalid();
10574 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10575 }
10576
10577 ActOnFields(S, RLoc, TagDecl,
10579 // strict aliasing violation!
10580 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10581 FieldCollector->getCurNumFields()),
10582 LBrac, RBrac, AttrList);
10583
10584 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10585}
10586
10587/// Find the equality comparison functions that should be implicitly declared
10588/// in a given class definition, per C++2a [class.compare.default]p3.
10590 ASTContext &Ctx, CXXRecordDecl *RD,
10592 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10593 if (!RD->lookup(EqEq).empty())
10594 // Member operator== explicitly declared: no implicit operator==s.
10595 return;
10596
10597 // Traverse friends looking for an '==' or a '<=>'.
10598 for (FriendDecl *Friend : RD->friends()) {
10599 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10600 if (!FD) continue;
10601
10602 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10603 // Friend operator== explicitly declared: no implicit operator==s.
10604 Spaceships.clear();
10605 return;
10606 }
10607
10608 if (FD->getOverloadedOperator() == OO_Spaceship &&
10610 Spaceships.push_back(FD);
10611 }
10612
10613 // Look for members named 'operator<=>'.
10614 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10615 for (NamedDecl *ND : RD->lookup(Cmp)) {
10616 // Note that we could find a non-function here (either a function template
10617 // or a using-declaration). Neither case results in an implicit
10618 // 'operator=='.
10619 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10620 if (FD->isExplicitlyDefaulted())
10621 Spaceships.push_back(FD);
10622 }
10623}
10624
10625/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10626/// special functions, such as the default constructor, copy
10627/// constructor, or destructor, to the given C++ class (C++
10628/// [special]p1). This routine can only be executed just before the
10629/// definition of the class is complete.
10631 // Don't add implicit special members to templated classes.
10632 // FIXME: This means unqualified lookups for 'operator=' within a class
10633 // template don't work properly.
10634 if (!ClassDecl->isDependentType()) {
10635 if (ClassDecl->needsImplicitDefaultConstructor()) {
10637
10638 if (ClassDecl->hasInheritedConstructor())
10640 }
10641
10642 if (ClassDecl->needsImplicitCopyConstructor()) {
10644
10645 // If the properties or semantics of the copy constructor couldn't be
10646 // determined while the class was being declared, force a declaration
10647 // of it now.
10649 ClassDecl->hasInheritedConstructor())
10651 // For the MS ABI we need to know whether the copy ctor is deleted. A
10652 // prerequisite for deleting the implicit copy ctor is that the class has
10653 // a move ctor or move assignment that is either user-declared or whose
10654 // semantics are inherited from a subobject. FIXME: We should provide a
10655 // more direct way for CodeGen to ask whether the constructor was deleted.
10656 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10657 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10659 ClassDecl->hasUserDeclaredMoveAssignment() ||
10662 }
10663
10664 if (getLangOpts().CPlusPlus11 &&
10665 ClassDecl->needsImplicitMoveConstructor()) {
10667
10669 ClassDecl->hasInheritedConstructor())
10671 }
10672
10673 if (ClassDecl->needsImplicitCopyAssignment()) {
10675
10676 // If we have a dynamic class, then the copy assignment operator may be
10677 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10678 // it shows up in the right place in the vtable and that we diagnose
10679 // problems with the implicit exception specification.
10680 if (ClassDecl->isDynamicClass() ||
10682 ClassDecl->hasInheritedAssignment())
10684 }
10685
10686 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10688
10689 // Likewise for the move assignment operator.
10690 if (ClassDecl->isDynamicClass() ||
10692 ClassDecl->hasInheritedAssignment())
10694 }
10695
10696 if (ClassDecl->needsImplicitDestructor()) {
10698
10699 // If we have a dynamic class, then the destructor may be virtual, so we
10700 // have to declare the destructor immediately. This ensures that, e.g., it
10701 // shows up in the right place in the vtable and that we diagnose problems
10702 // with the implicit exception specification.
10703 if (ClassDecl->isDynamicClass() ||
10705 DeclareImplicitDestructor(ClassDecl);
10706 }
10707 }
10708
10709 // C++2a [class.compare.default]p3:
10710 // If the member-specification does not explicitly declare any member or
10711 // friend named operator==, an == operator function is declared implicitly
10712 // for each defaulted three-way comparison operator function defined in
10713 // the member-specification
10714 // FIXME: Consider doing this lazily.
10715 // We do this during the initial parse for a class template, not during
10716 // instantiation, so that we can handle unqualified lookups for 'operator=='
10717 // when parsing the template.
10719 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10721 DefaultedSpaceships);
10722 for (auto *FD : DefaultedSpaceships)
10723 DeclareImplicitEqualityComparison(ClassDecl, FD);
10724 }
10725}
10726
10727unsigned
10729 llvm::function_ref<Scope *()> EnterScope) {
10730 if (!D)
10731 return 0;
10733
10734 // In order to get name lookup right, reenter template scopes in order from
10735 // outermost to innermost.
10737 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10738
10739 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10740 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10741 ParameterLists.push_back(DD->getTemplateParameterList(i));
10742
10743 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10744 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10745 ParameterLists.push_back(FTD->getTemplateParameters());
10746 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10747 LookupDC = VD->getDeclContext();
10748
10750 ParameterLists.push_back(VTD->getTemplateParameters());
10751 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10752 ParameterLists.push_back(PSD->getTemplateParameters());
10753 }
10754 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10755 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10756 ParameterLists.push_back(TD->getTemplateParameterList(i));
10757
10758 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10760 ParameterLists.push_back(CTD->getTemplateParameters());
10761 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10762 ParameterLists.push_back(PSD->getTemplateParameters());
10763 }
10764 }
10765 // FIXME: Alias declarations and concepts.
10766
10767 unsigned Count = 0;
10768 Scope *InnermostTemplateScope = nullptr;
10769 for (TemplateParameterList *Params : ParameterLists) {
10770 // Ignore explicit specializations; they don't contribute to the template
10771 // depth.
10772 if (Params->size() == 0)
10773 continue;
10774
10775 InnermostTemplateScope = EnterScope();
10776 for (NamedDecl *Param : *Params) {
10777 if (Param->getDeclName()) {
10778 InnermostTemplateScope->AddDecl(Param);
10779 IdResolver.AddDecl(Param);
10780 }
10781 }
10782 ++Count;
10783 }
10784
10785 // Associate the new template scopes with the corresponding entities.
10786 if (InnermostTemplateScope) {
10787 assert(LookupDC && "no enclosing DeclContext for template lookup");
10788 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10789 }
10790
10791 return Count;
10792}
10793
10795 if (!RecordD) return;
10796 AdjustDeclIfTemplate(RecordD);
10797 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10799}
10800
10802 if (!RecordD) return;
10804}
10805
10806/// This is used to implement the constant expression evaluation part of the
10807/// attribute enable_if extension. There is nothing in standard C++ which would
10808/// require reentering parameters.
10810 if (!Param)
10811 return;
10812
10813 S->AddDecl(Param);
10814 if (Param->getDeclName())
10815 IdResolver.AddDecl(Param);
10816}
10817
10818/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10819/// parsing a top-level (non-nested) C++ class, and we are now
10820/// parsing those parts of the given Method declaration that could
10821/// not be parsed earlier (C++ [class.mem]p2), such as default
10822/// arguments. This action should enter the scope of the given
10823/// Method declaration as if we had just parsed the qualified method
10824/// name. However, it should not bring the parameters into scope;
10825/// that will be performed by ActOnDelayedCXXMethodParameter.
10827}
10828
10829/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10830/// C++ method declaration. We're (re-)introducing the given
10831/// function parameter into scope for use in parsing later parts of
10832/// the method declaration. For example, we could see an
10833/// ActOnParamDefaultArgument event for this parameter.
10835 if (!ParamD)
10836 return;
10837
10838 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10839
10840 S->AddDecl(Param);
10841 if (Param->getDeclName())
10842 IdResolver.AddDecl(Param);
10843}
10844
10845/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10846/// processing the delayed method declaration for Method. The method
10847/// declaration is now considered finished. There may be a separate
10848/// ActOnStartOfFunctionDef action later (not necessarily
10849/// immediately!) for this method, if it was also defined inside the
10850/// class body.
10852 if (!MethodD)
10853 return;
10854
10855 AdjustDeclIfTemplate(MethodD);
10856
10857 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10858
10859 // Now that we have our default arguments, check the constructor
10860 // again. It could produce additional diagnostics or affect whether
10861 // the class has implicitly-declared destructors, among other
10862 // things.
10863 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10864 CheckConstructor(Constructor);
10865
10866 // Check the default arguments, which we may have added.
10867 if (!Method->isInvalidDecl())
10869}
10870
10871// Emit the given diagnostic for each non-address-space qualifier.
10872// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10873static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10875 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10876 bool DiagOccured = false;
10878 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10879 SourceLocation SL) {
10880 // This diagnostic should be emitted on any qualifier except an addr
10881 // space qualifier. However, forEachQualifier currently doesn't visit
10882 // addr space qualifiers, so there's no way to write this condition
10883 // right now; we just diagnose on everything.
10884 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10885 DiagOccured = true;
10886 });
10887 if (DiagOccured)
10888 D.setInvalidType();
10889 }
10890}
10891
10892/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10893/// the well-formedness of the constructor declarator @p D with type @p
10894/// R. If there are any errors in the declarator, this routine will
10895/// emit diagnostics and set the invalid bit to true. In any case, the type
10896/// will be updated to reflect a well-formed type for the constructor and
10897/// returned.
10899 StorageClass &SC) {
10900 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10901
10902 // C++ [class.ctor]p3:
10903 // A constructor shall not be virtual (10.3) or static (9.4). A
10904 // constructor can be invoked for a const, volatile or const
10905 // volatile object. A constructor shall not be declared const,
10906 // volatile, or const volatile (9.3.2).
10907 if (isVirtual) {
10908 if (!D.isInvalidType())
10909 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10910 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10912 D.setInvalidType();
10913 }
10914 if (SC == SC_Static) {
10915 if (!D.isInvalidType())
10916 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10917 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10919 D.setInvalidType();
10920 SC = SC_None;
10921 }
10922
10923 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10925 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10929 D.setInvalidType();
10930 }
10931
10932 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10933
10934 // C++0x [class.ctor]p4:
10935 // A constructor shall not be declared with a ref-qualifier.
10937 if (FTI.hasRefQualifier()) {
10938 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10941 D.setInvalidType();
10942 }
10943
10944 // Rebuild the function type "R" without any type qualifiers (in
10945 // case any of the errors above fired) and with "void" as the
10946 // return type, since constructors don't have return types.
10947 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10948 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10949 return R;
10950
10952 EPI.TypeQuals = Qualifiers();
10953 EPI.RefQualifier = RQ_None;
10954
10955 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10956}
10957
10958/// CheckConstructor - Checks a fully-formed constructor for
10959/// well-formedness, issuing any diagnostics required. Returns true if
10960/// the constructor declarator is invalid.
10962 CXXRecordDecl *ClassDecl
10963 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10964 if (!ClassDecl)
10965 return Constructor->setInvalidDecl();
10966
10967 // C++ [class.copy]p3:
10968 // A declaration of a constructor for a class X is ill-formed if
10969 // its first parameter is of type (optionally cv-qualified) X and
10970 // either there are no other parameters or else all other
10971 // parameters have default arguments.
10972 if (!Constructor->isInvalidDecl() &&
10973 Constructor->hasOneParamOrDefaultArgs() &&
10974 Constructor->getTemplateSpecializationKind() !=
10976 QualType ParamType = Constructor->getParamDecl(0)->getType();
10977 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10978 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10979 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10980 const char *ConstRef
10981 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10982 : " const &";
10983 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10984 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10985
10986 // FIXME: Rather that making the constructor invalid, we should endeavor
10987 // to fix the type.
10988 Constructor->setInvalidDecl();
10989 }
10990 }
10991}
10992
10993/// CheckDestructor - Checks a fully-formed destructor definition for
10994/// well-formedness, issuing any diagnostics required. Returns true
10995/// on error.
10997 CXXRecordDecl *RD = Destructor->getParent();
10998
10999 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11000 SourceLocation Loc;
11001
11002 if (!Destructor->isImplicit())
11003 Loc = Destructor->getLocation();
11004 else
11005 Loc = RD->getLocation();
11006
11007 // If we have a virtual destructor, look up the deallocation function
11008 if (FunctionDecl *OperatorDelete =
11010 Expr *ThisArg = nullptr;
11011
11012 // If the notional 'delete this' expression requires a non-trivial
11013 // conversion from 'this' to the type of a destroying operator delete's
11014 // first parameter, perform that conversion now.
11015 if (OperatorDelete->isDestroyingOperatorDelete()) {
11016 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
11017 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11018 // C++ [class.dtor]p13:
11019 // ... as if for the expression 'delete this' appearing in a
11020 // non-virtual destructor of the destructor's class.
11021 ContextRAII SwitchContext(*this, Destructor);
11022 ExprResult This =
11023 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
11024 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11025 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
11026 if (This.isInvalid()) {
11027 // FIXME: Register this as a context note so that it comes out
11028 // in the right order.
11029 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11030 return true;
11031 }
11032 ThisArg = This.get();
11033 }
11034 }
11035
11036 DiagnoseUseOfDecl(OperatorDelete, Loc);
11037 MarkFunctionReferenced(Loc, OperatorDelete);
11038 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11039 }
11040 }
11041
11042 return false;
11043}
11044
11045/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
11046/// the well-formednes of the destructor declarator @p D with type @p
11047/// R. If there are any errors in the declarator, this routine will
11048/// emit diagnostics and set the declarator to invalid. Even if this happens,
11049/// will be updated to reflect a well-formed type for the destructor and
11050/// returned.
11052 StorageClass& SC) {
11053 // C++ [class.dtor]p1:
11054 // [...] A typedef-name that names a class is a class-name
11055 // (7.1.3); however, a typedef-name that names a class shall not
11056 // be used as the identifier in the declarator for a destructor
11057 // declaration.
11058 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11059 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11060 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11061 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11062 else if (const TemplateSpecializationType *TST =
11063 DeclaratorType->getAs<TemplateSpecializationType>())
11064 if (TST->isTypeAlias())
11065 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11066 << DeclaratorType << 1;
11067
11068 // C++ [class.dtor]p2:
11069 // A destructor is used to destroy objects of its class type. A
11070 // destructor takes no parameters, and no return type can be
11071 // specified for it (not even void). The address of a destructor
11072 // shall not be taken. A destructor shall not be static. A
11073 // destructor can be invoked for a const, volatile or const
11074 // volatile object. A destructor shall not be declared const,
11075 // volatile or const volatile (9.3.2).
11076 if (SC == SC_Static) {
11077 if (!D.isInvalidType())
11078 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11079 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11082
11083 SC = SC_None;
11084 }
11085 if (!D.isInvalidType()) {
11086 // Destructors don't have return types, but the parser will
11087 // happily parse something like:
11088 //
11089 // class X {
11090 // float ~X();
11091 // };
11092 //
11093 // The return type will be eliminated later.
11094 if (D.getDeclSpec().hasTypeSpecifier())
11095 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11098 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11099 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11105 D.setInvalidType();
11106 }
11107 }
11108
11109 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11110
11111 // C++0x [class.dtor]p2:
11112 // A destructor shall not be declared with a ref-qualifier.
11114 if (FTI.hasRefQualifier()) {
11115 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11118 D.setInvalidType();
11119 }
11120
11121 // Make sure we don't have any parameters.
11122 if (FTIHasNonVoidParameters(FTI)) {
11123 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11124
11125 // Delete the parameters.
11126 FTI.freeParams();
11127 D.setInvalidType();
11128 }
11129
11130 // Make sure the destructor isn't variadic.
11131 if (FTI.isVariadic) {
11132 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11133 D.setInvalidType();
11134 }
11135
11136 // Rebuild the function type "R" without any type qualifiers or
11137 // parameters (in case any of the errors above fired) and with
11138 // "void" as the return type, since destructors don't have return
11139 // types.
11140 if (!D.isInvalidType())
11141 return R;
11142
11143 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11145 EPI.Variadic = false;
11146 EPI.TypeQuals = Qualifiers();
11147 EPI.RefQualifier = RQ_None;
11148 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
11149}
11150
11151static void extendLeft(SourceRange &R, SourceRange Before) {
11152 if (Before.isInvalid())
11153 return;
11154 R.setBegin(Before.getBegin());
11155 if (R.getEnd().isInvalid())
11156 R.setEnd(Before.getEnd());
11157}
11158
11159static void extendRight(SourceRange &R, SourceRange After) {
11160 if (After.isInvalid())
11161 return;
11162 if (R.getBegin().isInvalid())
11163 R.setBegin(After.getBegin());
11164 R.setEnd(After.getEnd());
11165}
11166
11167/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11168/// well-formednes of the conversion function declarator @p D with
11169/// type @p R. If there are any errors in the declarator, this routine
11170/// will emit diagnostics and return true. Otherwise, it will return
11171/// false. Either way, the type @p R will be updated to reflect a
11172/// well-formed type for the conversion operator.
11174 StorageClass& SC) {
11175 // C++ [class.conv.fct]p1:
11176 // Neither parameter types nor return type can be specified. The
11177 // type of a conversion function (8.3.5) is "function taking no
11178 // parameter returning conversion-type-id."
11179 if (SC == SC_Static) {
11180 if (!D.isInvalidType())
11181 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11183 << D.getName().getSourceRange();
11184 D.setInvalidType();
11185 SC = SC_None;
11186 }
11187
11188 TypeSourceInfo *ConvTSI = nullptr;
11189 QualType ConvType =
11191
11192 const DeclSpec &DS = D.getDeclSpec();
11193 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11194 // Conversion functions don't have return types, but the parser will
11195 // happily parse something like:
11196 //
11197 // class X {
11198 // float operator bool();
11199 // };
11200 //
11201 // The return type will be changed later anyway.
11202 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11205 D.setInvalidType();
11206 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11207 // It's also plausible that the user writes type qualifiers in the wrong
11208 // place, such as:
11209 // struct S { const operator int(); };
11210 // FIXME: we could provide a fixit to move the qualifiers onto the
11211 // conversion type.
11212 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11213 << SourceRange(D.getIdentifierLoc()) << 0;
11214 D.setInvalidType();
11215 }
11216 const auto *Proto = R->castAs<FunctionProtoType>();
11217 // Make sure we don't have any parameters.
11219 unsigned NumParam = Proto->getNumParams();
11220
11221 // [C++2b]
11222 // A conversion function shall have no non-object parameters.
11223 if (NumParam == 1) {
11225 if (const auto *First =
11226 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11227 First && First->isExplicitObjectParameter())
11228 NumParam--;
11229 }
11230
11231 if (NumParam != 0) {
11232 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11233 // Delete the parameters.
11234 FTI.freeParams();
11235 D.setInvalidType();
11236 } else if (Proto->isVariadic()) {
11237 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11238 D.setInvalidType();
11239 }
11240
11241 // Diagnose "&operator bool()" and other such nonsense. This
11242 // is actually a gcc extension which we don't support.
11243 if (Proto->getReturnType() != ConvType) {
11244 bool NeedsTypedef = false;
11245 SourceRange Before, After;
11246
11247 // Walk the chunks and extract information on them for our diagnostic.
11248 bool PastFunctionChunk = false;
11249 for (auto &Chunk : D.type_objects()) {
11250 switch (Chunk.Kind) {
11252 if (!PastFunctionChunk) {
11253 if (Chunk.Fun.HasTrailingReturnType) {
11254 TypeSourceInfo *TRT = nullptr;
11255 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11256 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11257 }
11258 PastFunctionChunk = true;
11259 break;
11260 }
11261 [[fallthrough]];
11263 NeedsTypedef = true;
11264 extendRight(After, Chunk.getSourceRange());
11265 break;
11266
11272 extendLeft(Before, Chunk.getSourceRange());
11273 break;
11274
11276 extendLeft(Before, Chunk.Loc);
11277 extendRight(After, Chunk.EndLoc);
11278 break;
11279 }
11280 }
11281
11282 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11283 After.isValid() ? After.getBegin() :
11284 D.getIdentifierLoc();
11285 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11286 DB << Before << After;
11287
11288 if (!NeedsTypedef) {
11289 DB << /*don't need a typedef*/0;
11290
11291 // If we can provide a correct fix-it hint, do so.
11292 if (After.isInvalid() && ConvTSI) {
11293 SourceLocation InsertLoc =
11295 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11297 InsertLoc, CharSourceRange::getTokenRange(Before))
11298 << FixItHint::CreateRemoval(Before);
11299 }
11300 } else if (!Proto->getReturnType()->isDependentType()) {
11301 DB << /*typedef*/1 << Proto->getReturnType();
11302 } else if (getLangOpts().CPlusPlus11) {
11303 DB << /*alias template*/2 << Proto->getReturnType();
11304 } else {
11305 DB << /*might not be fixable*/3;
11306 }
11307
11308 // Recover by incorporating the other type chunks into the result type.
11309 // Note, this does *not* change the name of the function. This is compatible
11310 // with the GCC extension:
11311 // struct S { &operator int(); } s;
11312 // int &r = s.operator int(); // ok in GCC
11313 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11314 ConvType = Proto->getReturnType();
11315 }
11316
11317 // C++ [class.conv.fct]p4:
11318 // The conversion-type-id shall not represent a function type nor
11319 // an array type.
11320 if (ConvType->isArrayType()) {
11321 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11322 ConvType = Context.getPointerType(ConvType);
11323 D.setInvalidType();
11324 } else if (ConvType->isFunctionType()) {
11325 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11326 ConvType = Context.getPointerType(ConvType);
11327 D.setInvalidType();
11328 }
11329
11330 // Rebuild the function type "R" without any parameters (in case any
11331 // of the errors above fired) and with the conversion type as the
11332 // return type.
11333 if (D.isInvalidType())
11334 R = Context.getFunctionType(ConvType, std::nullopt,
11335 Proto->getExtProtoInfo());
11336
11337 // C++0x explicit conversion operators.
11341 ? diag::warn_cxx98_compat_explicit_conversion_functions
11342 : diag::ext_explicit_conversion_functions)
11344}
11345
11346/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11347/// the declaration of the given C++ conversion function. This routine
11348/// is responsible for recording the conversion function in the C++
11349/// class, if possible.
11351 assert(Conversion && "Expected to receive a conversion function declaration");
11352
11353 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11354
11355 // Make sure we aren't redeclaring the conversion function.
11356 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11357 // C++ [class.conv.fct]p1:
11358 // [...] A conversion function is never used to convert a
11359 // (possibly cv-qualified) object to the (possibly cv-qualified)
11360 // same object type (or a reference to it), to a (possibly
11361 // cv-qualified) base class of that type (or a reference to it),
11362 // or to (possibly cv-qualified) void.
11363 QualType ClassType
11365 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11366 ConvType = ConvTypeRef->getPointeeType();
11367 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11369 /* Suppress diagnostics for instantiations. */;
11370 else if (Conversion->size_overridden_methods() != 0)
11371 /* Suppress diagnostics for overriding virtual function in a base class. */;
11372 else if (ConvType->isRecordType()) {
11373 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11374 if (ConvType == ClassType)
11375 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11376 << ClassType;
11377 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11378 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11379 << ClassType << ConvType;
11380 } else if (ConvType->isVoidType()) {
11381 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11382 << ClassType << ConvType;
11383 }
11384
11385 if (FunctionTemplateDecl *ConversionTemplate =
11386 Conversion->getDescribedFunctionTemplate()) {
11387 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11388 ConvType = ConvTypePtr->getPointeeType();
11389 }
11390 if (ConvType->isUndeducedAutoType()) {
11391 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11392 << getReturnTypeLoc(Conversion).getSourceRange()
11393 << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11394 << /* in declaration of conversion function template= */ 24;
11395 }
11396
11397 return ConversionTemplate;
11398 }
11399
11400 return Conversion;
11401}
11402
11404 DeclarationName Name, QualType R) {
11405 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11406}
11407
11409 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11410}
11411
11413 DeclarationName Name, QualType R,
11414 bool IsLambda, DeclContext *DC) {
11415 if (!D.isFunctionDeclarator())
11416 return;
11417
11419 if (FTI.NumParams == 0)
11420 return;
11421 ParmVarDecl *ExplicitObjectParam = nullptr;
11422 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11423 const auto &ParamInfo = FTI.Params[Idx];
11424 if (!ParamInfo.Param)
11425 continue;
11426 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11427 if (!Param->isExplicitObjectParameter())
11428 continue;
11429 if (Idx == 0) {
11430 ExplicitObjectParam = Param;
11431 continue;
11432 } else {
11433 Diag(Param->getLocation(),
11434 diag::err_explicit_object_parameter_must_be_first)
11435 << IsLambda << Param->getSourceRange();
11436 }
11437 }
11438 if (!ExplicitObjectParam)
11439 return;
11440
11441 if (ExplicitObjectParam->hasDefaultArg()) {
11442 Diag(ExplicitObjectParam->getLocation(),
11443 diag::err_explicit_object_default_arg)
11444 << ExplicitObjectParam->getSourceRange();
11445 }
11446
11449 D.isStaticMember())) {
11450 Diag(ExplicitObjectParam->getBeginLoc(),
11451 diag::err_explicit_object_parameter_nonmember)
11452 << D.getSourceRange() << /*static=*/0 << IsLambda;
11453 D.setInvalidType();
11454 }
11455
11456 if (D.getDeclSpec().isVirtualSpecified()) {
11457 Diag(ExplicitObjectParam->getBeginLoc(),
11458 diag::err_explicit_object_parameter_nonmember)
11459 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11460 D.setInvalidType();
11461 }
11462
11463 if (IsLambda && FTI.hasMutableQualifier()) {
11464 Diag(ExplicitObjectParam->getBeginLoc(),
11465 diag::err_explicit_object_parameter_mutable)
11466 << D.getSourceRange();
11467 }
11468
11469 if (IsLambda)
11470 return;
11471
11472 if (!DC || !DC->isRecord()) {
11473 Diag(ExplicitObjectParam->getLocation(),
11474 diag::err_explicit_object_parameter_nonmember)
11475 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11476 D.setInvalidType();
11477 return;
11478 }
11479
11480 // CWG2674: constructors and destructors cannot have explicit parameters.
11481 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11482 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11483 Diag(ExplicitObjectParam->getBeginLoc(),
11484 diag::err_explicit_object_parameter_constructor)
11485 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11486 << D.getSourceRange();
11487 D.setInvalidType();
11488 }
11489}
11490
11491namespace {
11492/// Utility class to accumulate and print a diagnostic listing the invalid
11493/// specifier(s) on a declaration.
11494struct BadSpecifierDiagnoser {
11495 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11496 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11497 ~BadSpecifierDiagnoser() {
11498 Diagnostic << Specifiers;
11499 }
11500
11501 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11502 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11503 }
11504 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11505 return check(SpecLoc,
11507 }
11508 void check(SourceLocation SpecLoc, const char *Spec) {
11509 if (SpecLoc.isInvalid()) return;
11510 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11511 if (!Specifiers.empty()) Specifiers += " ";
11512 Specifiers += Spec;
11513 }
11514
11515 Sema &S;
11517 std::string Specifiers;
11518};
11519}
11520
11521/// Check the validity of a declarator that we parsed for a deduction-guide.
11522/// These aren't actually declarators in the grammar, so we need to check that
11523/// the user didn't specify any pieces that are not part of the deduction-guide
11524/// grammar. Return true on invalid deduction-guide.
11526 StorageClass &SC) {
11527 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11528 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11529 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11530
11531 // C++ [temp.deduct.guide]p3:
11532 // A deduction-gide shall be declared in the same scope as the
11533 // corresponding class template.
11535 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11536 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11537 << GuidedTemplateDecl;
11538 NoteTemplateLocation(*GuidedTemplateDecl);
11539 }
11540
11541 auto &DS = D.getMutableDeclSpec();
11542 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11543 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11544 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11545 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11546 BadSpecifierDiagnoser Diagnoser(
11547 *this, D.getIdentifierLoc(),
11548 diag::err_deduction_guide_invalid_specifier);
11549
11550 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11551 DS.ClearStorageClassSpecs();
11552 SC = SC_None;
11553
11554 // 'explicit' is permitted.
11555 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11556 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11557 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11558 DS.ClearConstexprSpec();
11559
11560 Diagnoser.check(DS.getConstSpecLoc(), "const");
11561 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11562 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11563 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11564 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11565 DS.ClearTypeQualifiers();
11566
11567 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11568 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11569 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11570 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11571 DS.ClearTypeSpecType();
11572 }
11573
11574 if (D.isInvalidType())
11575 return true;
11576
11577 // Check the declarator is simple enough.
11578 bool FoundFunction = false;
11579 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11580 if (Chunk.Kind == DeclaratorChunk::Paren)
11581 continue;
11582 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11584 diag::err_deduction_guide_with_complex_decl)
11585 << D.getSourceRange();
11586 break;
11587 }
11588 if (!Chunk.Fun.hasTrailingReturnType())
11589 return Diag(D.getName().getBeginLoc(),
11590 diag::err_deduction_guide_no_trailing_return_type);
11591
11592 // Check that the return type is written as a specialization of
11593 // the template specified as the deduction-guide's name.
11594 // The template name may not be qualified. [temp.deduct.guide]
11595 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11596 TypeSourceInfo *TSI = nullptr;
11597 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11598 assert(TSI && "deduction guide has valid type but invalid return type?");
11599 bool AcceptableReturnType = false;
11600 bool MightInstantiateToSpecialization = false;
11601 if (auto RetTST =
11603 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11604 bool TemplateMatches =
11605 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11606 auto TKind = SpecifiedName.getKind();
11607 // A Using TemplateName can't actually be valid (either it's qualified, or
11608 // we're in the wrong scope). But we have diagnosed these problems
11609 // already.
11610 bool SimplyWritten = TKind == TemplateName::Template ||
11612 if (SimplyWritten && TemplateMatches)
11613 AcceptableReturnType = true;
11614 else {
11615 // This could still instantiate to the right type, unless we know it
11616 // names the wrong class template.
11617 auto *TD = SpecifiedName.getAsTemplateDecl();
11618 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11619 !TemplateMatches);
11620 }
11621 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11622 MightInstantiateToSpecialization = true;
11623 }
11624
11625 if (!AcceptableReturnType)
11626 return Diag(TSI->getTypeLoc().getBeginLoc(),
11627 diag::err_deduction_guide_bad_trailing_return_type)
11628 << GuidedTemplate << TSI->getType()
11629 << MightInstantiateToSpecialization
11630 << TSI->getTypeLoc().getSourceRange();
11631
11632 // Keep going to check that we don't have any inner declarator pieces (we
11633 // could still have a function returning a pointer to a function).
11634 FoundFunction = true;
11635 }
11636
11637 if (D.isFunctionDefinition())
11638 // we can still create a valid deduction guide here.
11639 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11640 return false;
11641}
11642
11643//===----------------------------------------------------------------------===//
11644// Namespace Handling
11645//===----------------------------------------------------------------------===//
11646
11647/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11648/// reopened.
11650 SourceLocation Loc,
11651 IdentifierInfo *II, bool *IsInline,
11652 NamespaceDecl *PrevNS) {
11653 assert(*IsInline != PrevNS->isInline());
11654
11655 // 'inline' must appear on the original definition, but not necessarily
11656 // on all extension definitions, so the note should point to the first
11657 // definition to avoid confusion.
11658 PrevNS = PrevNS->getFirstDecl();
11659
11660 if (PrevNS->isInline())
11661 // The user probably just forgot the 'inline', so suggest that it
11662 // be added back.
11663 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11664 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11665 else
11666 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11667
11668 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11669 *IsInline = PrevNS->isInline();
11670}
11671
11672/// ActOnStartNamespaceDef - This is called at the start of a namespace
11673/// definition.
11675 SourceLocation InlineLoc,
11676 SourceLocation NamespaceLoc,
11677 SourceLocation IdentLoc, IdentifierInfo *II,
11678 SourceLocation LBrace,
11679 const ParsedAttributesView &AttrList,
11680 UsingDirectiveDecl *&UD, bool IsNested) {
11681 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11682 // For anonymous namespace, take the location of the left brace.
11683 SourceLocation Loc = II ? IdentLoc : LBrace;
11684 bool IsInline = InlineLoc.isValid();
11685 bool IsInvalid = false;
11686 bool IsStd = false;
11687 bool AddToKnown = false;
11688 Scope *DeclRegionScope = NamespcScope->getParent();
11689
11690 NamespaceDecl *PrevNS = nullptr;
11691 if (II) {
11692 // C++ [namespace.std]p7:
11693 // A translation unit shall not declare namespace std to be an inline
11694 // namespace (9.8.2).
11695 //
11696 // Precondition: the std namespace is in the file scope and is declared to
11697 // be inline
11698 auto DiagnoseInlineStdNS = [&]() {
11699 assert(IsInline && II->isStr("std") &&
11701 "Precondition of DiagnoseInlineStdNS not met");
11702 Diag(InlineLoc, diag::err_inline_namespace_std)
11703 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11704 IsInline = false;
11705 };
11706 // C++ [namespace.def]p2:
11707 // The identifier in an original-namespace-definition shall not
11708 // have been previously defined in the declarative region in
11709 // which the original-namespace-definition appears. The
11710 // identifier in an original-namespace-definition is the name of
11711 // the namespace. Subsequently in that declarative region, it is
11712 // treated as an original-namespace-name.
11713 //
11714 // Since namespace names are unique in their scope, and we don't
11715 // look through using directives, just look for any ordinary names
11716 // as if by qualified name lookup.
11717 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11718 RedeclarationKind::ForExternalRedeclaration);
11720 NamedDecl *PrevDecl =
11721 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11722 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11723
11724 if (PrevNS) {
11725 // This is an extended namespace definition.
11726 if (IsInline && II->isStr("std") &&
11728 DiagnoseInlineStdNS();
11729 else if (IsInline != PrevNS->isInline())
11730 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11731 &IsInline, PrevNS);
11732 } else if (PrevDecl) {
11733 // This is an invalid name redefinition.
11734 Diag(Loc, diag::err_redefinition_different_kind)
11735 << II;
11736 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11737 IsInvalid = true;
11738 // Continue on to push Namespc as current DeclContext and return it.
11739 } else if (II->isStr("std") &&
11741 if (IsInline)
11742 DiagnoseInlineStdNS();
11743 // This is the first "real" definition of the namespace "std", so update
11744 // our cache of the "std" namespace to point at this definition.
11745 PrevNS = getStdNamespace();
11746 IsStd = true;
11747 AddToKnown = !IsInline;
11748 } else {
11749 // We've seen this namespace for the first time.
11750 AddToKnown = !IsInline;
11751 }
11752 } else {
11753 // Anonymous namespaces.
11754
11755 // Determine whether the parent already has an anonymous namespace.
11757 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11758 PrevNS = TU->getAnonymousNamespace();
11759 } else {
11760 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11761 PrevNS = ND->getAnonymousNamespace();
11762 }
11763
11764 if (PrevNS && IsInline != PrevNS->isInline())
11765 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11766 &IsInline, PrevNS);
11767 }
11768
11770 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11771 if (IsInvalid)
11772 Namespc->setInvalidDecl();
11773
11774 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11775 AddPragmaAttributes(DeclRegionScope, Namespc);
11776 ProcessAPINotes(Namespc);
11777
11778 // FIXME: Should we be merging attributes?
11779 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11781
11782 if (IsStd)
11783 StdNamespace = Namespc;
11784 if (AddToKnown)
11785 KnownNamespaces[Namespc] = false;
11786
11787 if (II) {
11788 PushOnScopeChains(Namespc, DeclRegionScope);
11789 } else {
11790 // Link the anonymous namespace into its parent.
11792 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11793 TU->setAnonymousNamespace(Namespc);
11794 } else {
11795 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11796 }
11797
11798 CurContext->addDecl(Namespc);
11799
11800 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11801 // behaves as if it were replaced by
11802 // namespace unique { /* empty body */ }
11803 // using namespace unique;
11804 // namespace unique { namespace-body }
11805 // where all occurrences of 'unique' in a translation unit are
11806 // replaced by the same identifier and this identifier differs
11807 // from all other identifiers in the entire program.
11808
11809 // We just create the namespace with an empty name and then add an
11810 // implicit using declaration, just like the standard suggests.
11811 //
11812 // CodeGen enforces the "universally unique" aspect by giving all
11813 // declarations semantically contained within an anonymous
11814 // namespace internal linkage.
11815
11816 if (!PrevNS) {
11818 /* 'using' */ LBrace,
11819 /* 'namespace' */ SourceLocation(),
11820 /* qualifier */ NestedNameSpecifierLoc(),
11821 /* identifier */ SourceLocation(),
11822 Namespc,
11823 /* Ancestor */ Parent);
11824 UD->setImplicit();
11825 Parent->addDecl(UD);
11826 }
11827 }
11828
11829 ActOnDocumentableDecl(Namespc);
11830
11831 // Although we could have an invalid decl (i.e. the namespace name is a
11832 // redefinition), push it as current DeclContext and try to continue parsing.
11833 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11834 // for the namespace has the declarations that showed up in that particular
11835 // namespace definition.
11836 PushDeclContext(NamespcScope, Namespc);
11837 return Namespc;
11838}
11839
11840/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11841/// is a namespace alias, returns the namespace it points to.
11843 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11844 return AD->getNamespace();
11845 return dyn_cast_or_null<NamespaceDecl>(D);
11846}
11847
11848/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11849/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11851 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11852 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11853 Namespc->setRBraceLoc(RBrace);
11855 if (Namespc->hasAttr<VisibilityAttr>())
11856 PopPragmaVisibility(true, RBrace);
11857 // If this namespace contains an export-declaration, export it now.
11858 if (DeferredExportedNamespaces.erase(Namespc))
11860}
11861
11863 return cast_or_null<CXXRecordDecl>(
11865}
11866
11868 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11869}
11870
11872 return cast_or_null<NamespaceDecl>(
11874}
11875namespace {
11876
11877enum UnsupportedSTLSelect {
11878 USS_InvalidMember,
11879 USS_MissingMember,
11880 USS_NonTrivial,
11881 USS_Other
11882};
11883
11884struct InvalidSTLDiagnoser {
11885 Sema &S;
11886 SourceLocation Loc;
11887 QualType TyForDiags;
11888
11889 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11890 const VarDecl *VD = nullptr) {
11891 {
11892 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11893 << TyForDiags << ((int)Sel);
11894 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11895 assert(!Name.empty());
11896 D << Name;
11897 }
11898 }
11899 if (Sel == USS_InvalidMember) {
11900 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11901 << VD << VD->getSourceRange();
11902 }
11903 return QualType();
11904 }
11905};
11906} // namespace
11907
11909 SourceLocation Loc,
11911 assert(getLangOpts().CPlusPlus &&
11912 "Looking for comparison category type outside of C++.");
11913
11914 // Use an elaborated type for diagnostics which has a name containing the
11915 // prepended 'std' namespace but not any inline namespace names.
11916 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11917 auto *NNS =
11920 Info->getType());
11921 };
11922
11923 // Check if we've already successfully checked the comparison category type
11924 // before. If so, skip checking it again.
11926 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11927 // The only thing we need to check is that the type has a reachable
11928 // definition in the current context.
11929 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11930 return QualType();
11931
11932 return Info->getType();
11933 }
11934
11935 // If lookup failed
11936 if (!Info) {
11937 std::string NameForDiags = "std::";
11938 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11939 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11940 << NameForDiags << (int)Usage;
11941 return QualType();
11942 }
11943
11944 assert(Info->Kind == Kind);
11945 assert(Info->Record);
11946
11947 // Update the Record decl in case we encountered a forward declaration on our
11948 // first pass. FIXME: This is a bit of a hack.
11949 if (Info->Record->hasDefinition())
11950 Info->Record = Info->Record->getDefinition();
11951
11952 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11953 return QualType();
11954
11955 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11956
11957 if (!Info->Record->isTriviallyCopyable())
11958 return UnsupportedSTLError(USS_NonTrivial);
11959
11960 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11961 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11962 // Tolerate empty base classes.
11963 if (Base->isEmpty())
11964 continue;
11965 // Reject STL implementations which have at least one non-empty base.
11966 return UnsupportedSTLError();
11967 }
11968
11969 // Check that the STL has implemented the types using a single integer field.
11970 // This expectation allows better codegen for builtin operators. We require:
11971 // (1) The class has exactly one field.
11972 // (2) The field is an integral or enumeration type.
11973 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11974 if (std::distance(FIt, FEnd) != 1 ||
11975 !FIt->getType()->isIntegralOrEnumerationType()) {
11976 return UnsupportedSTLError();
11977 }
11978
11979 // Build each of the require values and store them in Info.
11980 for (ComparisonCategoryResult CCR :
11982 StringRef MemName = ComparisonCategories::getResultString(CCR);
11983 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11984
11985 if (!ValInfo)
11986 return UnsupportedSTLError(USS_MissingMember, MemName);
11987
11988 VarDecl *VD = ValInfo->VD;
11989 assert(VD && "should not be null!");
11990
11991 // Attempt to diagnose reasons why the STL definition of this type
11992 // might be foobar, including it failing to be a constant expression.
11993 // TODO Handle more ways the lookup or result can be invalid.
11994 if (!VD->isStaticDataMember() ||
11996 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11997
11998 // Attempt to evaluate the var decl as a constant expression and extract
11999 // the value of its first field as a ICE. If this fails, the STL
12000 // implementation is not supported.
12001 if (!ValInfo->hasValidIntValue())
12002 return UnsupportedSTLError();
12003
12004 MarkVariableReferenced(Loc, VD);
12005 }
12006
12007 // We've successfully built the required types and expressions. Update
12008 // the cache and return the newly cached value.
12009 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12010 return Info->getType();
12011}
12012
12013/// Retrieve the special "std" namespace, which may require us to
12014/// implicitly define the namespace.
12016 if (!StdNamespace) {
12017 // The "std" namespace has not yet been defined, so build one implicitly.
12020 /*Inline=*/false, SourceLocation(), SourceLocation(),
12021 &PP.getIdentifierTable().get("std"),
12022 /*PrevDecl=*/nullptr, /*Nested=*/false);
12024 // We want the created NamespaceDecl to be available for redeclaration
12025 // lookups, but not for regular name lookups.
12028 }
12029
12030 return getStdNamespace();
12031}
12032
12034 assert(getLangOpts().CPlusPlus &&
12035 "Looking for std::initializer_list outside of C++.");
12036
12037 // We're looking for implicit instantiations of
12038 // template <typename E> class std::initializer_list.
12039
12040 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
12041 return false;
12042
12043 ClassTemplateDecl *Template = nullptr;
12044 const TemplateArgument *Arguments = nullptr;
12045
12046 if (const RecordType *RT = Ty->getAs<RecordType>()) {
12047
12049 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
12050 if (!Specialization)
12051 return false;
12052
12053 Template = Specialization->getSpecializedTemplate();
12054 Arguments = Specialization->getTemplateArgs().data();
12055 } else if (const TemplateSpecializationType *TST =
12057 Template = dyn_cast_or_null<ClassTemplateDecl>(
12058 TST->getTemplateName().getAsTemplateDecl());
12059 Arguments = TST->template_arguments().begin();
12060 }
12061 if (!Template)
12062 return false;
12063
12064 if (!StdInitializerList) {
12065 // Haven't recognized std::initializer_list yet, maybe this is it.
12066 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12067 if (TemplateClass->getIdentifier() !=
12068 &PP.getIdentifierTable().get("initializer_list") ||
12069 !getStdNamespace()->InEnclosingNamespaceSetOf(
12070 TemplateClass->getDeclContext()))
12071 return false;
12072 // This is a template called std::initializer_list, but is it the right
12073 // template?
12074 TemplateParameterList *Params = Template->getTemplateParameters();
12075 if (Params->getMinRequiredArguments() != 1)
12076 return false;
12077 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
12078 return false;
12079
12080 // It's the right template.
12081 StdInitializerList = Template;
12082 }
12083
12085 return false;
12086
12087 // This is an instance of std::initializer_list. Find the argument type.
12088 if (Element)
12089 *Element = Arguments[0].getAsType();
12090 return true;
12091}
12092
12095 if (!Std) {
12096 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12097 return nullptr;
12098 }
12099
12100 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
12102 if (!S.LookupQualifiedName(Result, Std)) {
12103 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12104 return nullptr;
12105 }
12106 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12107 if (!Template) {
12108 Result.suppressDiagnostics();
12109 // We found something weird. Complain about the first thing we found.
12110 NamedDecl *Found = *Result.begin();
12111 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12112 return nullptr;
12113 }
12114
12115 // We found some template called std::initializer_list. Now verify that it's
12116 // correct.
12117 TemplateParameterList *Params = Template->getTemplateParameters();
12118 if (Params->getMinRequiredArguments() != 1 ||
12119 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12120 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12121 return nullptr;
12122 }
12123
12124 return Template;
12125}
12126
12128 if (!StdInitializerList) {
12130 if (!StdInitializerList)
12131 return QualType();
12132 }
12133
12134 TemplateArgumentListInfo Args(Loc, Loc);
12137 Loc)));
12142}
12143
12145 // C++ [dcl.init.list]p2:
12146 // A constructor is an initializer-list constructor if its first parameter
12147 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12148 // std::initializer_list<E> for some type E, and either there are no other
12149 // parameters or else all other parameters have default arguments.
12150 if (!Ctor->hasOneParamOrDefaultArgs())
12151 return false;
12152
12153 QualType ArgType = Ctor->getParamDecl(0)->getType();
12154 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12155 ArgType = RT->getPointeeType().getUnqualifiedType();
12156
12157 return isStdInitializerList(ArgType, nullptr);
12158}
12159
12160/// Determine whether a using statement is in a context where it will be
12161/// apply in all contexts.
12163 switch (CurContext->getDeclKind()) {
12164 case Decl::TranslationUnit:
12165 return true;
12166 case Decl::LinkageSpec:
12168 default:
12169 return false;
12170 }
12171}
12172
12173namespace {
12174
12175// Callback to only accept typo corrections that are namespaces.
12176class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12177public:
12178 bool ValidateCandidate(const TypoCorrection &candidate) override {
12179 if (NamedDecl *ND = candidate.getCorrectionDecl())
12180 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12181 return false;
12182 }
12183
12184 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12185 return std::make_unique<NamespaceValidatorCCC>(*this);
12186 }
12187};
12188
12189}
12190
12191static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12192 Sema &S) {
12193 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12194 Module *M = ND->getOwningModule();
12195 assert(M && "hidden namespace definition not in a module?");
12196
12197 if (M->isExplicitGlobalModule())
12198 S.Diag(Corrected.getCorrectionRange().getBegin(),
12199 diag::err_module_unimported_use_header)
12201 << /*Header Name*/ false;
12202 else
12203 S.Diag(Corrected.getCorrectionRange().getBegin(),
12204 diag::err_module_unimported_use)
12206 << M->getTopLevelModuleName();
12207}
12208
12210 CXXScopeSpec &SS,
12211 SourceLocation IdentLoc,
12212 IdentifierInfo *Ident) {
12213 R.clear();
12214 NamespaceValidatorCCC CCC{};
12215 if (TypoCorrection Corrected =
12216 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12218 // Generally we find it is confusing more than helpful to diagnose the
12219 // invisible namespace.
12220 // See https://github.com/llvm/llvm-project/issues/73893.
12221 //
12222 // However, we should diagnose when the users are trying to using an
12223 // invisible namespace. So we handle the case specially here.
12224 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12225 Corrected.requiresImport()) {
12226 DiagnoseInvisibleNamespace(Corrected, S);
12227 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12228 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12229 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
12230 Ident->getName().equals(CorrectedStr);
12231 S.diagnoseTypo(Corrected,
12232 S.PDiag(diag::err_using_directive_member_suggest)
12233 << Ident << DC << DroppedSpecifier << SS.getRange(),
12234 S.PDiag(diag::note_namespace_defined_here));
12235 } else {
12236 S.diagnoseTypo(Corrected,
12237 S.PDiag(diag::err_using_directive_suggest) << Ident,
12238 S.PDiag(diag::note_namespace_defined_here));
12239 }
12240 R.addDecl(Corrected.getFoundDecl());
12241 return true;
12242 }
12243 return false;
12244}
12245
12247 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12248 SourceLocation IdentLoc,
12249 IdentifierInfo *NamespcName,
12250 const ParsedAttributesView &AttrList) {
12251 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12252 assert(NamespcName && "Invalid NamespcName.");
12253 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12254
12255 // Get the innermost enclosing declaration scope.
12256 S = S->getDeclParent();
12257
12258 UsingDirectiveDecl *UDir = nullptr;
12259 NestedNameSpecifier *Qualifier = nullptr;
12260 if (SS.isSet())
12261 Qualifier = SS.getScopeRep();
12262
12263 // Lookup namespace name.
12264 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12265 LookupParsedName(R, S, &SS);
12266 if (R.isAmbiguous())
12267 return nullptr;
12268
12269 if (R.empty()) {
12270 R.clear();
12271 // Allow "using namespace std;" or "using namespace ::std;" even if
12272 // "std" hasn't been defined yet, for GCC compatibility.
12273 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12274 NamespcName->isStr("std")) {
12275 Diag(IdentLoc, diag::ext_using_undefined_std);
12277 R.resolveKind();
12278 }
12279 // Otherwise, attempt typo correction.
12280 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12281 }
12282
12283 if (!R.empty()) {
12284 NamedDecl *Named = R.getRepresentativeDecl();
12286 assert(NS && "expected namespace decl");
12287
12288 // The use of a nested name specifier may trigger deprecation warnings.
12289 DiagnoseUseOfDecl(Named, IdentLoc);
12290
12291 // C++ [namespace.udir]p1:
12292 // A using-directive specifies that the names in the nominated
12293 // namespace can be used in the scope in which the
12294 // using-directive appears after the using-directive. During
12295 // unqualified name lookup (3.4.1), the names appear as if they
12296 // were declared in the nearest enclosing namespace which
12297 // contains both the using-directive and the nominated
12298 // namespace. [Note: in this context, "contains" means "contains
12299 // directly or indirectly". ]
12300
12301 // Find enclosing context containing both using-directive and
12302 // nominated namespace.
12303 DeclContext *CommonAncestor = NS;
12304 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12305 CommonAncestor = CommonAncestor->getParent();
12306
12307 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12309 IdentLoc, Named, CommonAncestor);
12310
12313 Diag(IdentLoc, diag::warn_using_directive_in_header);
12314 }
12315
12316 PushUsingDirective(S, UDir);
12317 } else {
12318 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12319 }
12320
12321 if (UDir) {
12322 ProcessDeclAttributeList(S, UDir, AttrList);
12323 ProcessAPINotes(UDir);
12324 }
12325
12326 return UDir;
12327}
12328
12330 // If the scope has an associated entity and the using directive is at
12331 // namespace or translation unit scope, add the UsingDirectiveDecl into
12332 // its lookup structure so qualified name lookup can find it.
12333 DeclContext *Ctx = S->getEntity();
12334 if (Ctx && !Ctx->isFunctionOrMethod())
12335 Ctx->addDecl(UDir);
12336 else
12337 // Otherwise, it is at block scope. The using-directives will affect lookup
12338 // only to the end of the scope.
12339 S->PushUsingDirective(UDir);
12340}
12341
12343 SourceLocation UsingLoc,
12344 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12345 UnqualifiedId &Name,
12346 SourceLocation EllipsisLoc,
12347 const ParsedAttributesView &AttrList) {
12348 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12349
12350 if (SS.isEmpty()) {
12351 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12352 return nullptr;
12353 }
12354
12355 switch (Name.getKind()) {
12361 break;
12362
12365 // C++11 inheriting constructors.
12366 Diag(Name.getBeginLoc(),
12368 ? diag::warn_cxx98_compat_using_decl_constructor
12369 : diag::err_using_decl_constructor)
12370 << SS.getRange();
12371
12372 if (getLangOpts().CPlusPlus11) break;
12373
12374 return nullptr;
12375
12377 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12378 return nullptr;
12379
12381 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12382 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12383 return nullptr;
12384
12386 llvm_unreachable("cannot parse qualified deduction guide name");
12387 }
12388
12389 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12390 DeclarationName TargetName = TargetNameInfo.getName();
12391 if (!TargetName)
12392 return nullptr;
12393
12394 // Warn about access declarations.
12395 if (UsingLoc.isInvalid()) {
12396 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12397 ? diag::err_access_decl
12398 : diag::warn_access_decl_deprecated)
12399 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12400 }
12401
12402 if (EllipsisLoc.isInvalid()) {
12405 return nullptr;
12406 } else {
12408 !TargetNameInfo.containsUnexpandedParameterPack()) {
12409 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12410 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12411 EllipsisLoc = SourceLocation();
12412 }
12413 }
12414
12415 NamedDecl *UD =
12416 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12417 SS, TargetNameInfo, EllipsisLoc, AttrList,
12418 /*IsInstantiation*/ false,
12419 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12420 if (UD)
12421 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12422
12423 return UD;
12424}
12425
12427 SourceLocation UsingLoc,
12428 SourceLocation EnumLoc,
12429 SourceLocation IdentLoc,
12430 IdentifierInfo &II, CXXScopeSpec *SS) {
12431 assert(!SS->isInvalid() && "ScopeSpec is invalid");
12432 TypeSourceInfo *TSI = nullptr;
12433 QualType EnumTy = GetTypeFromParser(
12434 getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12435 /*HasTrailingDot=*/false,
12436 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12437 /*WantNontrivialTypeSourceInfo=*/true),
12438 &TSI);
12439 if (EnumTy.isNull()) {
12440 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12441 ? diag::err_using_enum_is_dependent
12442 : diag::err_unknown_typename)
12443 << II.getName()
12444 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12445 return nullptr;
12446 }
12447
12448 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12449 if (!Enum) {
12450 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12451 return nullptr;
12452 }
12453
12454 if (auto *Def = Enum->getDefinition())
12455 Enum = Def;
12456
12457 if (TSI == nullptr)
12458 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12459
12460 auto *UD =
12461 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12462
12463 if (UD)
12464 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12465
12466 return UD;
12467}
12468
12469/// Determine whether a using declaration considers the given
12470/// declarations as "equivalent", e.g., if they are redeclarations of
12471/// the same entity or are both typedefs of the same type.
12472static bool
12474 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12475 return true;
12476
12477 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12478 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12479 return Context.hasSameType(TD1->getUnderlyingType(),
12480 TD2->getUnderlyingType());
12481
12482 // Two using_if_exists using-declarations are equivalent if both are
12483 // unresolved.
12484 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12485 isa<UnresolvedUsingIfExistsDecl>(D2))
12486 return true;
12487
12488 return false;
12489}
12490
12491
12492/// Determines whether to create a using shadow decl for a particular
12493/// decl, given the set of decls existing prior to this using lookup.
12495 const LookupResult &Previous,
12496 UsingShadowDecl *&PrevShadow) {
12497 // Diagnose finding a decl which is not from a base class of the
12498 // current class. We do this now because there are cases where this
12499 // function will silently decide not to build a shadow decl, which
12500 // will pre-empt further diagnostics.
12501 //
12502 // We don't need to do this in C++11 because we do the check once on
12503 // the qualifier.
12504 //
12505 // FIXME: diagnose the following if we care enough:
12506 // struct A { int foo; };
12507 // struct B : A { using A::foo; };
12508 // template <class T> struct C : A {};
12509 // template <class T> struct D : C<T> { using B::foo; } // <---
12510 // This is invalid (during instantiation) in C++03 because B::foo
12511 // resolves to the using decl in B, which is not a base class of D<T>.
12512 // We can't diagnose it immediately because C<T> is an unknown
12513 // specialization. The UsingShadowDecl in D<T> then points directly
12514 // to A::foo, which will look well-formed when we instantiate.
12515 // The right solution is to not collapse the shadow-decl chain.
12517 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12518 DeclContext *OrigDC = Orig->getDeclContext();
12519
12520 // Handle enums and anonymous structs.
12521 if (isa<EnumDecl>(OrigDC))
12522 OrigDC = OrigDC->getParent();
12523 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12524 while (OrigRec->isAnonymousStructOrUnion())
12525 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12526
12527 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12528 if (OrigDC == CurContext) {
12529 Diag(Using->getLocation(),
12530 diag::err_using_decl_nested_name_specifier_is_current_class)
12531 << Using->getQualifierLoc().getSourceRange();
12532 Diag(Orig->getLocation(), diag::note_using_decl_target);
12533 Using->setInvalidDecl();
12534 return true;
12535 }
12536
12537 Diag(Using->getQualifierLoc().getBeginLoc(),
12538 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12539 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12540 << Using->getQualifierLoc().getSourceRange();
12541 Diag(Orig->getLocation(), diag::note_using_decl_target);
12542 Using->setInvalidDecl();
12543 return true;
12544 }
12545 }
12546
12547 if (Previous.empty()) return false;
12548
12549 NamedDecl *Target = Orig;
12550 if (isa<UsingShadowDecl>(Target))
12551 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12552
12553 // If the target happens to be one of the previous declarations, we
12554 // don't have a conflict.
12555 //
12556 // FIXME: but we might be increasing its access, in which case we
12557 // should redeclare it.
12558 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12559 bool FoundEquivalentDecl = false;
12560 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12561 I != E; ++I) {
12562 NamedDecl *D = (*I)->getUnderlyingDecl();
12563 // We can have UsingDecls in our Previous results because we use the same
12564 // LookupResult for checking whether the UsingDecl itself is a valid
12565 // redeclaration.
12566 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12567 continue;
12568
12569 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12570 // C++ [class.mem]p19:
12571 // If T is the name of a class, then [every named member other than
12572 // a non-static data member] shall have a name different from T
12573 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12574 !isa<IndirectFieldDecl>(Target) &&
12575 !isa<UnresolvedUsingValueDecl>(Target) &&
12577 CurContext,
12579 return true;
12580 }
12581
12583 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12584 PrevShadow = Shadow;
12585 FoundEquivalentDecl = true;
12587 // We don't conflict with an existing using shadow decl of an equivalent
12588 // declaration, but we're not a redeclaration of it.
12589 FoundEquivalentDecl = true;
12590 }
12591
12592 if (isVisible(D))
12593 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12594 }
12595
12596 if (FoundEquivalentDecl)
12597 return false;
12598
12599 // Always emit a diagnostic for a mismatch between an unresolved
12600 // using_if_exists and a resolved using declaration in either direction.
12601 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12602 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12603 if (!NonTag && !Tag)
12604 return false;
12605 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12606 Diag(Target->getLocation(), diag::note_using_decl_target);
12607 Diag((NonTag ? NonTag : Tag)->getLocation(),
12608 diag::note_using_decl_conflict);
12609 BUD->setInvalidDecl();
12610 return true;
12611 }
12612
12613 if (FunctionDecl *FD = Target->getAsFunction()) {
12614 NamedDecl *OldDecl = nullptr;
12615 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12616 /*IsForUsingDecl*/ true)) {
12617 case Ovl_Overload:
12618 return false;
12619
12620 case Ovl_NonFunction:
12621 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12622 break;
12623
12624 // We found a decl with the exact signature.
12625 case Ovl_Match:
12626 // If we're in a record, we want to hide the target, so we
12627 // return true (without a diagnostic) to tell the caller not to
12628 // build a shadow decl.
12629 if (CurContext->isRecord())
12630 return true;
12631
12632 // If we're not in a record, this is an error.
12633 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12634 break;
12635 }
12636
12637 Diag(Target->getLocation(), diag::note_using_decl_target);
12638 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12639 BUD->setInvalidDecl();
12640 return true;
12641 }
12642
12643 // Target is not a function.
12644
12645 if (isa<TagDecl>(Target)) {
12646 // No conflict between a tag and a non-tag.
12647 if (!Tag) return false;
12648
12649 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12650 Diag(Target->getLocation(), diag::note_using_decl_target);
12651 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12652 BUD->setInvalidDecl();
12653 return true;
12654 }
12655
12656 // No conflict between a tag and a non-tag.
12657 if (!NonTag) return false;
12658
12659 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12660 Diag(Target->getLocation(), diag::note_using_decl_target);
12661 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12662 BUD->setInvalidDecl();
12663 return true;
12664}
12665
12666/// Determine whether a direct base class is a virtual base class.
12668 if (!Derived->getNumVBases())
12669 return false;
12670 for (auto &B : Derived->bases())
12671 if (B.getType()->getAsCXXRecordDecl() == Base)
12672 return B.isVirtual();
12673 llvm_unreachable("not a direct base class");
12674}
12675
12676/// Builds a shadow declaration corresponding to a 'using' declaration.
12678 NamedDecl *Orig,
12679 UsingShadowDecl *PrevDecl) {
12680 // If we resolved to another shadow declaration, just coalesce them.
12681 NamedDecl *Target = Orig;
12682 if (isa<UsingShadowDecl>(Target)) {
12683 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12684 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12685 }
12686
12687 NamedDecl *NonTemplateTarget = Target;
12688 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12689 NonTemplateTarget = TargetTD->getTemplatedDecl();
12690
12691 UsingShadowDecl *Shadow;
12692 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12693 UsingDecl *Using = cast<UsingDecl>(BUD);
12694 bool IsVirtualBase =
12695 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12696 Using->getQualifier()->getAsRecordDecl());
12698 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12699 } else {
12701 Target->getDeclName(), BUD, Target);
12702 }
12703 BUD->addShadowDecl(Shadow);
12704
12705 Shadow->setAccess(BUD->getAccess());
12706 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12707 Shadow->setInvalidDecl();
12708
12709 Shadow->setPreviousDecl(PrevDecl);
12710
12711 if (S)
12712 PushOnScopeChains(Shadow, S);
12713 else
12714 CurContext->addDecl(Shadow);
12715
12716
12717 return Shadow;
12718}
12719
12720/// Hides a using shadow declaration. This is required by the current
12721/// using-decl implementation when a resolvable using declaration in a
12722/// class is followed by a declaration which would hide or override
12723/// one or more of the using decl's targets; for example:
12724///
12725/// struct Base { void foo(int); };
12726/// struct Derived : Base {
12727/// using Base::foo;
12728/// void foo(int);
12729/// };
12730///
12731/// The governing language is C++03 [namespace.udecl]p12:
12732///
12733/// When a using-declaration brings names from a base class into a
12734/// derived class scope, member functions in the derived class
12735/// override and/or hide member functions with the same name and
12736/// parameter types in a base class (rather than conflicting).
12737///
12738/// There are two ways to implement this:
12739/// (1) optimistically create shadow decls when they're not hidden
12740/// by existing declarations, or
12741/// (2) don't create any shadow decls (or at least don't make them
12742/// visible) until we've fully parsed/instantiated the class.
12743/// The problem with (1) is that we might have to retroactively remove
12744/// a shadow decl, which requires several O(n) operations because the
12745/// decl structures are (very reasonably) not designed for removal.
12746/// (2) avoids this but is very fiddly and phase-dependent.
12748 if (Shadow->getDeclName().getNameKind() ==
12750 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12751
12752 // Remove it from the DeclContext...
12753 Shadow->getDeclContext()->removeDecl(Shadow);
12754
12755 // ...and the scope, if applicable...
12756 if (S) {
12757 S->RemoveDecl(Shadow);
12758 IdResolver.RemoveDecl(Shadow);
12759 }
12760
12761 // ...and the using decl.
12762 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12763
12764 // TODO: complain somehow if Shadow was used. It shouldn't
12765 // be possible for this to happen, because...?
12766}
12767
12768/// Find the base specifier for a base class with the given type.
12770 QualType DesiredBase,
12771 bool &AnyDependentBases) {
12772 // Check whether the named type is a direct base class.
12773 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12775 for (auto &Base : Derived->bases()) {
12776 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12777 if (CanonicalDesiredBase == BaseType)
12778 return &Base;
12779 if (BaseType->isDependentType())
12780 AnyDependentBases = true;
12781 }
12782 return nullptr;
12783}
12784
12785namespace {
12786class UsingValidatorCCC final : public CorrectionCandidateCallback {
12787public:
12788 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12789 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12790 : HasTypenameKeyword(HasTypenameKeyword),
12791 IsInstantiation(IsInstantiation), OldNNS(NNS),
12792 RequireMemberOf(RequireMemberOf) {}
12793
12794 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12795 NamedDecl *ND = Candidate.getCorrectionDecl();
12796
12797 // Keywords are not valid here.
12798 if (!ND || isa<NamespaceDecl>(ND))
12799 return false;
12800
12801 // Completely unqualified names are invalid for a 'using' declaration.
12802 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12803 return false;
12804
12805 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12806 // reject.
12807
12808 if (RequireMemberOf) {
12809 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12810 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12811 // No-one ever wants a using-declaration to name an injected-class-name
12812 // of a base class, unless they're declaring an inheriting constructor.
12813 ASTContext &Ctx = ND->getASTContext();
12814 if (!Ctx.getLangOpts().CPlusPlus11)
12815 return false;
12816 QualType FoundType = Ctx.getRecordType(FoundRecord);
12817
12818 // Check that the injected-class-name is named as a member of its own
12819 // type; we don't want to suggest 'using Derived::Base;', since that
12820 // means something else.
12822 Candidate.WillReplaceSpecifier()
12823 ? Candidate.getCorrectionSpecifier()
12824 : OldNNS;
12825 if (!Specifier->getAsType() ||
12826 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12827 return false;
12828
12829 // Check that this inheriting constructor declaration actually names a
12830 // direct base class of the current class.
12831 bool AnyDependentBases = false;
12832 if (!findDirectBaseWithType(RequireMemberOf,
12833 Ctx.getRecordType(FoundRecord),
12834 AnyDependentBases) &&
12835 !AnyDependentBases)
12836 return false;
12837 } else {
12838 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12839 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12840 return false;
12841
12842 // FIXME: Check that the base class member is accessible?
12843 }
12844 } else {
12845 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12846 if (FoundRecord && FoundRecord->isInjectedClassName())
12847 return false;
12848 }
12849
12850 if (isa<TypeDecl>(ND))
12851 return HasTypenameKeyword || !IsInstantiation;
12852
12853 return !HasTypenameKeyword;
12854 }
12855
12856 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12857 return std::make_unique<UsingValidatorCCC>(*this);
12858 }
12859
12860private:
12861 bool HasTypenameKeyword;
12862 bool IsInstantiation;
12863 NestedNameSpecifier *OldNNS;
12864 CXXRecordDecl *RequireMemberOf;
12865};
12866} // end anonymous namespace
12867
12868/// Remove decls we can't actually see from a lookup being used to declare
12869/// shadow using decls.
12870///
12871/// \param S - The scope of the potential shadow decl
12872/// \param Previous - The lookup of a potential shadow decl's name.
12874 // It is really dumb that we have to do this.
12875 LookupResult::Filter F = Previous.makeFilter();
12876 while (F.hasNext()) {
12877 NamedDecl *D = F.next();
12878 if (!isDeclInScope(D, CurContext, S))
12879 F.erase();
12880 // If we found a local extern declaration that's not ordinarily visible,
12881 // and this declaration is being added to a non-block scope, ignore it.
12882 // We're only checking for scope conflicts here, not also for violations
12883 // of the linkage rules.
12884 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12886 F.erase();
12887 }
12888 F.done();
12889}
12890
12891/// Builds a using declaration.
12892///
12893/// \param IsInstantiation - Whether this call arises from an
12894/// instantiation of an unresolved using declaration. We treat
12895/// the lookup differently for these declarations.
12897 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12898 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12899 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12900 const ParsedAttributesView &AttrList, bool IsInstantiation,
12901 bool IsUsingIfExists) {
12902 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12903 SourceLocation IdentLoc = NameInfo.getLoc();
12904 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12905
12906 // FIXME: We ignore attributes for now.
12907
12908 // For an inheriting constructor declaration, the name of the using
12909 // declaration is the name of a constructor in this class, not in the
12910 // base class.
12911 DeclarationNameInfo UsingName = NameInfo;
12913 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12916
12917 // Do the redeclaration lookup in the current scope.
12918 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12919 RedeclarationKind::ForVisibleRedeclaration);
12920 Previous.setHideTags(false);
12921 if (S) {
12922 LookupName(Previous, S);
12923
12925 } else {
12926 assert(IsInstantiation && "no scope in non-instantiation");
12927 if (CurContext->isRecord())
12929 else {
12930 // No redeclaration check is needed here; in non-member contexts we
12931 // diagnosed all possible conflicts with other using-declarations when
12932 // building the template:
12933 //
12934 // For a dependent non-type using declaration, the only valid case is
12935 // if we instantiate to a single enumerator. We check for conflicts
12936 // between shadow declarations we introduce, and we check in the template
12937 // definition for conflicts between a non-type using declaration and any
12938 // other declaration, which together covers all cases.
12939 //
12940 // A dependent typename using declaration will never successfully
12941 // instantiate, since it will always name a class member, so we reject
12942 // that in the template definition.
12943 }
12944 }
12945
12946 // Check for invalid redeclarations.
12947 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12948 SS, IdentLoc, Previous))
12949 return nullptr;
12950
12951 // 'using_if_exists' doesn't make sense on an inherited constructor.
12952 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12954 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12955 return nullptr;
12956 }
12957
12958 DeclContext *LookupContext = computeDeclContext(SS);
12960 if (!LookupContext || EllipsisLoc.isValid()) {
12961 NamedDecl *D;
12962 // Dependent scope, or an unexpanded pack
12963 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12964 SS, NameInfo, IdentLoc))
12965 return nullptr;
12966
12967 if (HasTypenameKeyword) {
12968 // FIXME: not all declaration name kinds are legal here
12970 UsingLoc, TypenameLoc,
12971 QualifierLoc,
12972 IdentLoc, NameInfo.getName(),
12973 EllipsisLoc);
12974 } else {
12976 QualifierLoc, NameInfo, EllipsisLoc);
12977 }
12978 D->setAccess(AS);
12979 CurContext->addDecl(D);
12980 ProcessDeclAttributeList(S, D, AttrList);
12981 return D;
12982 }
12983
12984 auto Build = [&](bool Invalid) {
12985 UsingDecl *UD =
12986 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12987 UsingName, HasTypenameKeyword);
12988 UD->setAccess(AS);
12989 CurContext->addDecl(UD);
12990 ProcessDeclAttributeList(S, UD, AttrList);
12992 return UD;
12993 };
12994 auto BuildInvalid = [&]{ return Build(true); };
12995 auto BuildValid = [&]{ return Build(false); };
12996
12997 if (RequireCompleteDeclContext(SS, LookupContext))
12998 return BuildInvalid();
12999
13000 // Look up the target name.
13001 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13002
13003 // Unlike most lookups, we don't always want to hide tag
13004 // declarations: tag names are visible through the using declaration
13005 // even if hidden by ordinary names, *except* in a dependent context
13006 // where they may be used by two-phase lookup.
13007 if (!IsInstantiation)
13008 R.setHideTags(false);
13009
13010 // For the purposes of this lookup, we have a base object type
13011 // equal to that of the current context.
13012 if (CurContext->isRecord()) {
13014 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
13015 }
13016
13017 LookupQualifiedName(R, LookupContext);
13018
13019 // Validate the context, now we have a lookup
13020 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13021 IdentLoc, &R))
13022 return nullptr;
13023
13024 if (R.empty() && IsUsingIfExists)
13026 UsingName.getName()),
13027 AS_public);
13028
13029 // Try to correct typos if possible. If constructor name lookup finds no
13030 // results, that means the named class has no explicit constructors, and we
13031 // suppressed declaring implicit ones (probably because it's dependent or
13032 // invalid).
13033 if (R.empty() &&
13035 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13036 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13037 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13038 auto *II = NameInfo.getName().getAsIdentifierInfo();
13039 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13041 isa<TranslationUnitDecl>(LookupContext) &&
13042 getSourceManager().isInSystemHeader(UsingLoc))
13043 return nullptr;
13044 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13045 dyn_cast<CXXRecordDecl>(CurContext));
13046 if (TypoCorrection Corrected =
13047 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13049 // We reject candidates where DroppedSpecifier == true, hence the
13050 // literal '0' below.
13051 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13052 << NameInfo.getName() << LookupContext << 0
13053 << SS.getRange());
13054
13055 // If we picked a correction with no attached Decl we can't do anything
13056 // useful with it, bail out.
13057 NamedDecl *ND = Corrected.getCorrectionDecl();
13058 if (!ND)
13059 return BuildInvalid();
13060
13061 // If we corrected to an inheriting constructor, handle it as one.
13062 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13063 if (RD && RD->isInjectedClassName()) {
13064 // The parent of the injected class name is the class itself.
13065 RD = cast<CXXRecordDecl>(RD->getParent());
13066
13067 // Fix up the information we'll use to build the using declaration.
13068 if (Corrected.WillReplaceSpecifier()) {
13070 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13071 QualifierLoc.getSourceRange());
13072 QualifierLoc = Builder.getWithLocInContext(Context);
13073 }
13074
13075 // In this case, the name we introduce is the name of a derived class
13076 // constructor.
13077 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13080 UsingName.setNamedTypeInfo(nullptr);
13081 for (auto *Ctor : LookupConstructors(RD))
13082 R.addDecl(Ctor);
13083 R.resolveKind();
13084 } else {
13085 // FIXME: Pick up all the declarations if we found an overloaded
13086 // function.
13087 UsingName.setName(ND->getDeclName());
13088 R.addDecl(ND);
13089 }
13090 } else {
13091 Diag(IdentLoc, diag::err_no_member)
13092 << NameInfo.getName() << LookupContext << SS.getRange();
13093 return BuildInvalid();
13094 }
13095 }
13096
13097 if (R.isAmbiguous())
13098 return BuildInvalid();
13099
13100 if (HasTypenameKeyword) {
13101 // If we asked for a typename and got a non-type decl, error out.
13102 if (!R.getAsSingle<TypeDecl>() &&
13104 Diag(IdentLoc, diag::err_using_typename_non_type);
13105 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13106 Diag((*I)->getUnderlyingDecl()->getLocation(),
13107 diag::note_using_decl_target);
13108 return BuildInvalid();
13109 }
13110 } else {
13111 // If we asked for a non-typename and we got a type, error out,
13112 // but only if this is an instantiation of an unresolved using
13113 // decl. Otherwise just silently find the type name.
13114 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13115 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13116 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13117 return BuildInvalid();
13118 }
13119 }
13120
13121 // C++14 [namespace.udecl]p6:
13122 // A using-declaration shall not name a namespace.
13123 if (R.getAsSingle<NamespaceDecl>()) {
13124 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13125 << SS.getRange();
13126 return BuildInvalid();
13127 }
13128
13129 UsingDecl *UD = BuildValid();
13130
13131 // Some additional rules apply to inheriting constructors.
13132 if (UsingName.getName().getNameKind() ==
13134 // Suppress access diagnostics; the access check is instead performed at the
13135 // point of use for an inheriting constructor.
13138 return UD;
13139 }
13140
13141 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13142 UsingShadowDecl *PrevDecl = nullptr;
13143 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13144 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13145 }
13146
13147 return UD;
13148}
13149
13151 SourceLocation UsingLoc,
13152 SourceLocation EnumLoc,
13153 SourceLocation NameLoc,
13155 EnumDecl *ED) {
13156 bool Invalid = false;
13157
13159 /// In class scope, check if this is a duplicate, for better a diagnostic.
13160 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13161 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13162 RedeclarationKind::ForVisibleRedeclaration);
13163
13164 LookupName(Previous, S);
13165
13166 for (NamedDecl *D : Previous)
13167 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13168 if (UED->getEnumDecl() == ED) {
13169 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13170 << SourceRange(EnumLoc, NameLoc);
13171 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13172 Invalid = true;
13173 break;
13174 }
13175 }
13176
13177 if (RequireCompleteEnumDecl(ED, NameLoc))
13178 Invalid = true;
13179
13181 EnumLoc, NameLoc, EnumType);
13182 UD->setAccess(AS);
13183 CurContext->addDecl(UD);
13184
13185 if (Invalid) {
13186 UD->setInvalidDecl();
13187 return UD;
13188 }
13189
13190 // Create the shadow decls for each enumerator
13191 for (EnumConstantDecl *EC : ED->enumerators()) {
13192 UsingShadowDecl *PrevDecl = nullptr;
13193 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13195 RedeclarationKind::ForVisibleRedeclaration);
13196 LookupName(Previous, S);
13198
13199 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13200 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13201 }
13202
13203 return UD;
13204}
13205
13207 ArrayRef<NamedDecl *> Expansions) {
13208 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13209 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13210 isa<UsingPackDecl>(InstantiatedFrom));
13211
13212 auto *UPD =
13213 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13214 UPD->setAccess(InstantiatedFrom->getAccess());
13215 CurContext->addDecl(UPD);
13216 return UPD;
13217}
13218
13219/// Additional checks for a using declaration referring to a constructor name.
13221 assert(!UD->hasTypename() && "expecting a constructor name");
13222
13223 const Type *SourceType = UD->getQualifier()->getAsType();
13224 assert(SourceType &&
13225 "Using decl naming constructor doesn't have type in scope spec.");
13226 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13227
13228 // Check whether the named type is a direct base class.
13229 bool AnyDependentBases = false;
13230 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13231 AnyDependentBases);
13232 if (!Base && !AnyDependentBases) {
13233 Diag(UD->getUsingLoc(),
13234 diag::err_using_decl_constructor_not_in_direct_base)
13235 << UD->getNameInfo().getSourceRange()
13236 << QualType(SourceType, 0) << TargetClass;
13237 UD->setInvalidDecl();
13238 return true;
13239 }
13240
13241 if (Base)
13242 Base->setInheritConstructors();
13243
13244 return false;
13245}
13246
13247/// Checks that the given using declaration is not an invalid
13248/// redeclaration. Note that this is checking only for the using decl
13249/// itself, not for any ill-formedness among the UsingShadowDecls.
13251 bool HasTypenameKeyword,
13252 const CXXScopeSpec &SS,
13253 SourceLocation NameLoc,
13254 const LookupResult &Prev) {
13255 NestedNameSpecifier *Qual = SS.getScopeRep();
13256
13257 // C++03 [namespace.udecl]p8:
13258 // C++0x [namespace.udecl]p10:
13259 // A using-declaration is a declaration and can therefore be used
13260 // repeatedly where (and only where) multiple declarations are
13261 // allowed.
13262 //
13263 // That's in non-member contexts.
13265 // A dependent qualifier outside a class can only ever resolve to an
13266 // enumeration type. Therefore it conflicts with any other non-type
13267 // declaration in the same scope.
13268 // FIXME: How should we check for dependent type-type conflicts at block
13269 // scope?
13270 if (Qual->isDependent() && !HasTypenameKeyword) {
13271 for (auto *D : Prev) {
13272 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13273 bool OldCouldBeEnumerator =
13274 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13275 Diag(NameLoc,
13276 OldCouldBeEnumerator ? diag::err_redefinition
13277 : diag::err_redefinition_different_kind)
13278 << Prev.getLookupName();
13279 Diag(D->getLocation(), diag::note_previous_definition);
13280 return true;
13281 }
13282 }
13283 }
13284 return false;
13285 }
13286
13287 const NestedNameSpecifier *CNNS =
13289 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13290 NamedDecl *D = *I;
13291
13292 bool DTypename;
13293 NestedNameSpecifier *DQual;
13294 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13295 DTypename = UD->hasTypename();
13296 DQual = UD->getQualifier();
13297 } else if (UnresolvedUsingValueDecl *UD
13298 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13299 DTypename = false;
13300 DQual = UD->getQualifier();
13301 } else if (UnresolvedUsingTypenameDecl *UD
13302 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13303 DTypename = true;
13304 DQual = UD->getQualifier();
13305 } else continue;
13306
13307 // using decls differ if one says 'typename' and the other doesn't.
13308 // FIXME: non-dependent using decls?
13309 if (HasTypenameKeyword != DTypename) continue;
13310
13311 // using decls differ if they name different scopes (but note that
13312 // template instantiation can cause this check to trigger when it
13313 // didn't before instantiation).
13314 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13315 continue;
13316
13317 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13318 Diag(D->getLocation(), diag::note_using_decl) << 1;
13319 return true;
13320 }
13321
13322 return false;
13323}
13324
13325/// Checks that the given nested-name qualifier used in a using decl
13326/// in the current context is appropriately related to the current
13327/// scope. If an error is found, diagnoses it and returns true.
13328/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13329/// result of that lookup. UD is likewise nullptr, except when we have an
13330/// already-populated UsingDecl whose shadow decls contain the same information
13331/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13332bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13333 const CXXScopeSpec &SS,
13334 const DeclarationNameInfo &NameInfo,
13335 SourceLocation NameLoc,
13336 const LookupResult *R, const UsingDecl *UD) {
13337 DeclContext *NamedContext = computeDeclContext(SS);
13338 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13339 "resolvable context must have exactly one set of decls");
13340
13341 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13342 // relationship.
13343 bool Cxx20Enumerator = false;
13344 if (NamedContext) {
13345 EnumConstantDecl *EC = nullptr;
13346 if (R)
13347 EC = R->getAsSingle<EnumConstantDecl>();
13348 else if (UD && UD->shadow_size() == 1)
13349 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13350 if (EC)
13351 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13352
13353 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13354 // C++14 [namespace.udecl]p7:
13355 // A using-declaration shall not name a scoped enumerator.
13356 // C++20 p1099 permits enumerators.
13357 if (EC && R && ED->isScoped())
13358 Diag(SS.getBeginLoc(),
13360 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13361 : diag::ext_using_decl_scoped_enumerator)
13362 << SS.getRange();
13363
13364 // We want to consider the scope of the enumerator
13365 NamedContext = ED->getDeclContext();
13366 }
13367 }
13368
13369 if (!CurContext->isRecord()) {
13370 // C++03 [namespace.udecl]p3:
13371 // C++0x [namespace.udecl]p8:
13372 // A using-declaration for a class member shall be a member-declaration.
13373 // C++20 [namespace.udecl]p7
13374 // ... other than an enumerator ...
13375
13376 // If we weren't able to compute a valid scope, it might validly be a
13377 // dependent class or enumeration scope. If we have a 'typename' keyword,
13378 // the scope must resolve to a class type.
13379 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13380 : !HasTypename)
13381 return false; // OK
13382
13383 Diag(NameLoc,
13384 Cxx20Enumerator
13385 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13386 : diag::err_using_decl_can_not_refer_to_class_member)
13387 << SS.getRange();
13388
13389 if (Cxx20Enumerator)
13390 return false; // OK
13391
13392 auto *RD = NamedContext
13393 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13394 : nullptr;
13395 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13396 // See if there's a helpful fixit
13397
13398 if (!R) {
13399 // We will have already diagnosed the problem on the template
13400 // definition, Maybe we should do so again?
13401 } else if (R->getAsSingle<TypeDecl>()) {
13402 if (getLangOpts().CPlusPlus11) {
13403 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13404 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13405 << 0 // alias declaration
13407 NameInfo.getName().getAsString() +
13408 " = ");
13409 } else {
13410 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13411 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13412 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13413 << 1 // typedef declaration
13414 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13416 InsertLoc, " " + NameInfo.getName().getAsString());
13417 }
13418 } else if (R->getAsSingle<VarDecl>()) {
13419 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13420 // repeating the type of the static data member here.
13421 FixItHint FixIt;
13422 if (getLangOpts().CPlusPlus11) {
13423 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13425 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13426 }
13427
13428 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13429 << 2 // reference declaration
13430 << FixIt;
13431 } else if (R->getAsSingle<EnumConstantDecl>()) {
13432 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13433 // repeating the type of the enumeration here, and we can't do so if
13434 // the type is anonymous.
13435 FixItHint FixIt;
13436 if (getLangOpts().CPlusPlus11) {
13437 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13439 UsingLoc,
13440 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13441 }
13442
13443 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13444 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13445 << FixIt;
13446 }
13447 }
13448
13449 return true; // Fail
13450 }
13451
13452 // If the named context is dependent, we can't decide much.
13453 if (!NamedContext) {
13454 // FIXME: in C++0x, we can diagnose if we can prove that the
13455 // nested-name-specifier does not refer to a base class, which is
13456 // still possible in some cases.
13457
13458 // Otherwise we have to conservatively report that things might be
13459 // okay.
13460 return false;
13461 }
13462
13463 // The current scope is a record.
13464 if (!NamedContext->isRecord()) {
13465 // Ideally this would point at the last name in the specifier,
13466 // but we don't have that level of source info.
13467 Diag(SS.getBeginLoc(),
13468 Cxx20Enumerator
13469 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13470 : diag::err_using_decl_nested_name_specifier_is_not_class)
13471 << SS.getScopeRep() << SS.getRange();
13472
13473 if (Cxx20Enumerator)
13474 return false; // OK
13475
13476 return true;
13477 }
13478
13479 if (!NamedContext->isDependentContext() &&
13480 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13481 return true;
13482
13483 if (getLangOpts().CPlusPlus11) {
13484 // C++11 [namespace.udecl]p3:
13485 // In a using-declaration used as a member-declaration, the
13486 // nested-name-specifier shall name a base class of the class
13487 // being defined.
13488
13489 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13490 cast<CXXRecordDecl>(NamedContext))) {
13491
13492 if (Cxx20Enumerator) {
13493 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13494 << SS.getRange();
13495 return false;
13496 }
13497
13498 if (CurContext == NamedContext) {
13499 Diag(SS.getBeginLoc(),
13500 diag::err_using_decl_nested_name_specifier_is_current_class)
13501 << SS.getRange();
13502 return !getLangOpts().CPlusPlus20;
13503 }
13504
13505 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13506 Diag(SS.getBeginLoc(),
13507 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13508 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13509 << SS.getRange();
13510 }
13511 return true;
13512 }
13513
13514 return false;
13515 }
13516
13517 // C++03 [namespace.udecl]p4:
13518 // A using-declaration used as a member-declaration shall refer
13519 // to a member of a base class of the class being defined [etc.].
13520
13521 // Salient point: SS doesn't have to name a base class as long as
13522 // lookup only finds members from base classes. Therefore we can
13523 // diagnose here only if we can prove that can't happen,
13524 // i.e. if the class hierarchies provably don't intersect.
13525
13526 // TODO: it would be nice if "definitely valid" results were cached
13527 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13528 // need to be repeated.
13529
13531 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13532 Bases.insert(Base);
13533 return true;
13534 };
13535
13536 // Collect all bases. Return false if we find a dependent base.
13537 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13538 return false;
13539
13540 // Returns true if the base is dependent or is one of the accumulated base
13541 // classes.
13542 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13543 return !Bases.count(Base);
13544 };
13545
13546 // Return false if the class has a dependent base or if it or one
13547 // of its bases is present in the base set of the current context.
13548 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13549 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13550 return false;
13551
13552 Diag(SS.getRange().getBegin(),
13553 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13554 << SS.getScopeRep()
13555 << cast<CXXRecordDecl>(CurContext)
13556 << SS.getRange();
13557
13558 return true;
13559}
13560
13562 MultiTemplateParamsArg TemplateParamLists,
13563 SourceLocation UsingLoc, UnqualifiedId &Name,
13564 const ParsedAttributesView &AttrList,
13565 TypeResult Type, Decl *DeclFromDeclSpec) {
13566 // Get the innermost enclosing declaration scope.
13567 S = S->getDeclParent();
13568
13569 if (Type.isInvalid())
13570 return nullptr;
13571
13572 bool Invalid = false;
13574 TypeSourceInfo *TInfo = nullptr;
13575 GetTypeFromParser(Type.get(), &TInfo);
13576
13577 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13578 return nullptr;
13579
13580 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13582 Invalid = true;
13584 TInfo->getTypeLoc().getBeginLoc());
13585 }
13586
13587 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13588 TemplateParamLists.size()
13590 : RedeclarationKind::ForVisibleRedeclaration);
13591 LookupName(Previous, S);
13592
13593 // Warn about shadowing the name of a template parameter.
13594 if (Previous.isSingleResult() &&
13595 Previous.getFoundDecl()->isTemplateParameter()) {
13596 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13597 Previous.clear();
13598 }
13599
13600 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13601 "name in alias declaration must be an identifier");
13603 Name.StartLocation,
13604 Name.Identifier, TInfo);
13605
13606 NewTD->setAccess(AS);
13607
13608 if (Invalid)
13609 NewTD->setInvalidDecl();
13610
13611 ProcessDeclAttributeList(S, NewTD, AttrList);
13612 AddPragmaAttributes(S, NewTD);
13613 ProcessAPINotes(NewTD);
13614
13616 Invalid |= NewTD->isInvalidDecl();
13617
13618 bool Redeclaration = false;
13619
13620 NamedDecl *NewND;
13621 if (TemplateParamLists.size()) {
13622 TypeAliasTemplateDecl *OldDecl = nullptr;
13623 TemplateParameterList *OldTemplateParams = nullptr;
13624
13625 if (TemplateParamLists.size() != 1) {
13626 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13627 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13628 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13629 Invalid = true;
13630 }
13631 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13632
13633 // Check that we can declare a template here.
13634 if (CheckTemplateDeclScope(S, TemplateParams))
13635 return nullptr;
13636
13637 // Only consider previous declarations in the same scope.
13638 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13639 /*ExplicitInstantiationOrSpecialization*/false);
13640 if (!Previous.empty()) {
13641 Redeclaration = true;
13642
13643 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13644 if (!OldDecl && !Invalid) {
13645 Diag(UsingLoc, diag::err_redefinition_different_kind)
13646 << Name.Identifier;
13647
13648 NamedDecl *OldD = Previous.getRepresentativeDecl();
13649 if (OldD->getLocation().isValid())
13650 Diag(OldD->getLocation(), diag::note_previous_definition);
13651
13652 Invalid = true;
13653 }
13654
13655 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13656 if (TemplateParameterListsAreEqual(TemplateParams,
13657 OldDecl->getTemplateParameters(),
13658 /*Complain=*/true,
13660 OldTemplateParams =
13662 else
13663 Invalid = true;
13664
13665 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13666 if (!Invalid &&
13668 NewTD->getUnderlyingType())) {
13669 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13670 // but we can't reasonably accept it.
13671 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13672 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13673 if (OldTD->getLocation().isValid())
13674 Diag(OldTD->getLocation(), diag::note_previous_definition);
13675 Invalid = true;
13676 }
13677 }
13678 }
13679
13680 // Merge any previous default template arguments into our parameters,
13681 // and check the parameter list.
13682 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13684 return nullptr;
13685
13686 TypeAliasTemplateDecl *NewDecl =
13688 Name.Identifier, TemplateParams,
13689 NewTD);
13690 NewTD->setDescribedAliasTemplate(NewDecl);
13691
13692 NewDecl->setAccess(AS);
13693
13694 if (Invalid)
13695 NewDecl->setInvalidDecl();
13696 else if (OldDecl) {
13697 NewDecl->setPreviousDecl(OldDecl);
13698 CheckRedeclarationInModule(NewDecl, OldDecl);
13699 }
13700
13701 NewND = NewDecl;
13702 } else {
13703 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13705 handleTagNumbering(TD, S);
13706 }
13707 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13708 NewND = NewTD;
13709 }
13710
13711 PushOnScopeChains(NewND, S);
13712 ActOnDocumentableDecl(NewND);
13713 return NewND;
13714}
13715
13717 SourceLocation AliasLoc,
13718 IdentifierInfo *Alias, CXXScopeSpec &SS,
13719 SourceLocation IdentLoc,
13720 IdentifierInfo *Ident) {
13721
13722 // Lookup the namespace name.
13723 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13724 LookupParsedName(R, S, &SS);
13725
13726 if (R.isAmbiguous())
13727 return nullptr;
13728
13729 if (R.empty()) {
13730 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13731 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13732 return nullptr;
13733 }
13734 }
13735 assert(!R.isAmbiguous() && !R.empty());
13737
13738 // Check if we have a previous declaration with the same name.
13739 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13740 RedeclarationKind::ForVisibleRedeclaration);
13741 LookupName(PrevR, S);
13742
13743 // Check we're not shadowing a template parameter.
13744 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13746 PrevR.clear();
13747 }
13748
13749 // Filter out any other lookup result from an enclosing scope.
13750 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13751 /*AllowInlineNamespace*/false);
13752
13753 // Find the previous declaration and check that we can redeclare it.
13754 NamespaceAliasDecl *Prev = nullptr;
13755 if (PrevR.isSingleResult()) {
13756 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13757 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13758 // We already have an alias with the same name that points to the same
13759 // namespace; check that it matches.
13760 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13761 Prev = AD;
13762 } else if (isVisible(PrevDecl)) {
13763 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13764 << Alias;
13765 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13766 << AD->getNamespace();
13767 return nullptr;
13768 }
13769 } else if (isVisible(PrevDecl)) {
13770 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13771 ? diag::err_redefinition
13772 : diag::err_redefinition_different_kind;
13773 Diag(AliasLoc, DiagID) << Alias;
13774 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13775 return nullptr;
13776 }
13777 }
13778
13779 // The use of a nested name specifier may trigger deprecation warnings.
13780 DiagnoseUseOfDecl(ND, IdentLoc);
13781
13783 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13784 Alias, SS.getWithLocInContext(Context),
13785 IdentLoc, ND);
13786 if (Prev)
13787 AliasDecl->setPreviousDecl(Prev);
13788
13790 return AliasDecl;
13791}
13792
13793namespace {
13794struct SpecialMemberExceptionSpecInfo
13795 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13796 SourceLocation Loc;
13798
13799 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13802 SourceLocation Loc)
13803 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13804
13805 bool visitBase(CXXBaseSpecifier *Base);
13806 bool visitField(FieldDecl *FD);
13807
13808 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13809 unsigned Quals);
13810
13811 void visitSubobjectCall(Subobject Subobj,
13813};
13814}
13815
13816bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13817 auto *RT = Base->getType()->getAs<RecordType>();
13818 if (!RT)
13819 return false;
13820
13821 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13822 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13823 if (auto *BaseCtor = SMOR.getMethod()) {
13824 visitSubobjectCall(Base, BaseCtor);
13825 return false;
13826 }
13827
13828 visitClassSubobject(BaseClass, Base, 0);
13829 return false;
13830}
13831
13832bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13834 FD->hasInClassInitializer()) {
13835 Expr *E = FD->getInClassInitializer();
13836 if (!E)
13837 // FIXME: It's a little wasteful to build and throw away a
13838 // CXXDefaultInitExpr here.
13839 // FIXME: We should have a single context note pointing at Loc, and
13840 // this location should be MD->getLocation() instead, since that's
13841 // the location where we actually use the default init expression.
13842 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13843 if (E)
13844 ExceptSpec.CalledExpr(E);
13845 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13846 ->getAs<RecordType>()) {
13847 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13848 FD->getType().getCVRQualifiers());
13849 }
13850 return false;
13851}
13852
13853void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13854 Subobject Subobj,
13855 unsigned Quals) {
13856 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13857 bool IsMutable = Field && Field->isMutable();
13858 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13859}
13860
13861void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13862 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13863 // Note, if lookup fails, it doesn't matter what exception specification we
13864 // choose because the special member will be deleted.
13865 if (CXXMethodDecl *MD = SMOR.getMethod())
13866 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13867}
13868
13870 llvm::APSInt Result;
13872 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13873 ExplicitSpec.setExpr(Converted.get());
13874 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13875 ExplicitSpec.setKind(Result.getBoolValue()
13878 return true;
13879 }
13881 return false;
13882}
13883
13886 if (!ExplicitExpr->isTypeDependent())
13888 return ES;
13889}
13890
13895 ComputingExceptionSpec CES(S, MD, Loc);
13896
13897 CXXRecordDecl *ClassDecl = MD->getParent();
13898
13899 // C++ [except.spec]p14:
13900 // An implicitly declared special member function (Clause 12) shall have an
13901 // exception-specification. [...]
13902 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13903 if (ClassDecl->isInvalidDecl())
13904 return Info.ExceptSpec;
13905
13906 // FIXME: If this diagnostic fires, we're probably missing a check for
13907 // attempting to resolve an exception specification before it's known
13908 // at a higher level.
13909 if (S.RequireCompleteType(MD->getLocation(),
13910 S.Context.getRecordType(ClassDecl),
13911 diag::err_exception_spec_incomplete_type))
13912 return Info.ExceptSpec;
13913
13914 // C++1z [except.spec]p7:
13915 // [Look for exceptions thrown by] a constructor selected [...] to
13916 // initialize a potentially constructed subobject,
13917 // C++1z [except.spec]p8:
13918 // The exception specification for an implicitly-declared destructor, or a
13919 // destructor without a noexcept-specifier, is potentially-throwing if and
13920 // only if any of the destructors for any of its potentially constructed
13921 // subojects is potentially throwing.
13922 // FIXME: We respect the first rule but ignore the "potentially constructed"
13923 // in the second rule to resolve a core issue (no number yet) that would have
13924 // us reject:
13925 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13926 // struct B : A {};
13927 // struct C : B { void f(); };
13928 // ... due to giving B::~B() a non-throwing exception specification.
13929 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13930 : Info.VisitAllBases);
13931
13932 return Info.ExceptSpec;
13933}
13934
13935namespace {
13936/// RAII object to register a special member as being currently declared.
13937struct DeclaringSpecialMember {
13938 Sema &S;
13940 Sema::ContextRAII SavedContext;
13941 bool WasAlreadyBeingDeclared;
13942
13943 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13944 : S(S), D(RD, CSM), SavedContext(S, RD) {
13945 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13946 if (WasAlreadyBeingDeclared)
13947 // This almost never happens, but if it does, ensure that our cache
13948 // doesn't contain a stale result.
13949 S.SpecialMemberCache.clear();
13950 else {
13951 // Register a note to be produced if we encounter an error while
13952 // declaring the special member.
13955 // FIXME: We don't have a location to use here. Using the class's
13956 // location maintains the fiction that we declare all special members
13957 // with the class, but (1) it's not clear that lying about that helps our
13958 // users understand what's going on, and (2) there may be outer contexts
13959 // on the stack (some of which are relevant) and printing them exposes
13960 // our lies.
13962 Ctx.Entity = RD;
13963 Ctx.SpecialMember = CSM;
13965 }
13966 }
13967 ~DeclaringSpecialMember() {
13968 if (!WasAlreadyBeingDeclared) {
13969 S.SpecialMembersBeingDeclared.erase(D);
13971 }
13972 }
13973
13974 /// Are we already trying to declare this special member?
13975 bool isAlreadyBeingDeclared() const {
13976 return WasAlreadyBeingDeclared;
13977 }
13978};
13979}
13980
13982 // Look up any existing declarations, but don't trigger declaration of all
13983 // implicit special members with this name.
13984 DeclarationName Name = FD->getDeclName();
13986 RedeclarationKind::ForExternalRedeclaration);
13987 for (auto *D : FD->getParent()->lookup(Name))
13988 if (auto *Acceptable = R.getAcceptableDecl(D))
13989 R.addDecl(Acceptable);
13990 R.resolveKind();
13992
13993 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13995}
13996
13997void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13998 QualType ResultTy,
13999 ArrayRef<QualType> Args) {
14000 // Build an exception specification pointing back at this constructor.
14002
14004 if (AS != LangAS::Default) {
14005 EPI.TypeQuals.addAddressSpace(AS);
14006 }
14007
14008 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14009 SpecialMem->setType(QT);
14010
14011 // During template instantiation of implicit special member functions we need
14012 // a reliable TypeSourceInfo for the function prototype in order to allow
14013 // functions to be substituted.
14015 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
14016 TypeSourceInfo *TSI =
14018 SpecialMem->setTypeSourceInfo(TSI);
14019 }
14020}
14021
14023 CXXRecordDecl *ClassDecl) {
14024 // C++ [class.ctor]p5:
14025 // A default constructor for a class X is a constructor of class X
14026 // that can be called without an argument. If there is no
14027 // user-declared constructor for class X, a default constructor is
14028 // implicitly declared. An implicitly-declared default constructor
14029 // is an inline public member of its class.
14030 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14031 "Should not build implicit default constructor!");
14032
14033 DeclaringSpecialMember DSM(*this, ClassDecl,
14035 if (DSM.isAlreadyBeingDeclared())
14036 return nullptr;
14037
14039 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14040
14041 // Create the actual constructor declaration.
14042 CanQualType ClassType
14044 SourceLocation ClassLoc = ClassDecl->getLocation();
14045 DeclarationName Name
14047 DeclarationNameInfo NameInfo(Name, ClassLoc);
14049 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14050 /*TInfo=*/nullptr, ExplicitSpecifier(),
14051 getCurFPFeatures().isFPConstrained(),
14052 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14055 DefaultCon->setAccess(AS_public);
14056 DefaultCon->setDefaulted();
14057
14058 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
14059
14060 if (getLangOpts().CUDA)
14062 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14063 /* ConstRHS */ false,
14064 /* Diagnose */ false);
14065
14066 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14067 // constructors is easy to compute.
14068 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14069
14070 // Note that we have declared this constructor.
14072
14073 Scope *S = getScopeForContext(ClassDecl);
14075
14076 if (ShouldDeleteSpecialMember(DefaultCon,
14078 SetDeclDeleted(DefaultCon, ClassLoc);
14079
14080 if (S)
14081 PushOnScopeChains(DefaultCon, S, false);
14082 ClassDecl->addDecl(DefaultCon);
14083
14084 return DefaultCon;
14085}
14086
14088 CXXConstructorDecl *Constructor) {
14089 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14090 !Constructor->doesThisDeclarationHaveABody() &&
14091 !Constructor->isDeleted()) &&
14092 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14093 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14094 return;
14095
14096 CXXRecordDecl *ClassDecl = Constructor->getParent();
14097 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14098 if (ClassDecl->isInvalidDecl()) {
14099 return;
14100 }
14101
14102 SynthesizedFunctionScope Scope(*this, Constructor);
14103
14104 // The exception specification is needed because we are defining the
14105 // function.
14106 ResolveExceptionSpec(CurrentLocation,
14107 Constructor->getType()->castAs<FunctionProtoType>());
14108 MarkVTableUsed(CurrentLocation, ClassDecl);
14109
14110 // Add a context note for diagnostics produced after this point.
14111 Scope.addContextNote(CurrentLocation);
14112
14113 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14114 Constructor->setInvalidDecl();
14115 return;
14116 }
14117
14118 SourceLocation Loc = Constructor->getEndLoc().isValid()
14119 ? Constructor->getEndLoc()
14120 : Constructor->getLocation();
14121 Constructor->setBody(new (Context) CompoundStmt(Loc));
14122 Constructor->markUsed(Context);
14123
14125 L->CompletedImplicitDefinition(Constructor);
14126 }
14127
14128 DiagnoseUninitializedFields(*this, Constructor);
14129}
14130
14132 // Perform any delayed checks on exception specifications.
14134}
14135
14136/// Find or create the fake constructor we synthesize to model constructing an
14137/// object of a derived class via a constructor of a base class.
14140 CXXConstructorDecl *BaseCtor,
14142 CXXRecordDecl *Derived = Shadow->getParent();
14143 SourceLocation UsingLoc = Shadow->getLocation();
14144
14145 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14146 // For now we use the name of the base class constructor as a member of the
14147 // derived class to indicate a (fake) inherited constructor name.
14148 DeclarationName Name = BaseCtor->getDeclName();
14149
14150 // Check to see if we already have a fake constructor for this inherited
14151 // constructor call.
14152 for (NamedDecl *Ctor : Derived->lookup(Name))
14153 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14154 ->getInheritedConstructor()
14155 .getConstructor(),
14156 BaseCtor))
14157 return cast<CXXConstructorDecl>(Ctor);
14158
14159 DeclarationNameInfo NameInfo(Name, UsingLoc);
14160 TypeSourceInfo *TInfo =
14161 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14162 FunctionProtoTypeLoc ProtoLoc =
14164
14165 // Check the inherited constructor is valid and find the list of base classes
14166 // from which it was inherited.
14167 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14168
14169 bool Constexpr = BaseCtor->isConstexpr() &&
14172 false, BaseCtor, &ICI);
14173
14175 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14176 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14177 /*isInline=*/true,
14178 /*isImplicitlyDeclared=*/true,
14180 InheritedConstructor(Shadow, BaseCtor),
14181 BaseCtor->getTrailingRequiresClause());
14182 if (Shadow->isInvalidDecl())
14183 DerivedCtor->setInvalidDecl();
14184
14185 // Build an unevaluated exception specification for this fake constructor.
14186 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14189 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14190 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14191 FPT->getParamTypes(), EPI));
14192
14193 // Build the parameter declarations.
14195 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14196 TypeSourceInfo *TInfo =
14199 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14200 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14201 PD->setScopeInfo(0, I);
14202 PD->setImplicit();
14203 // Ensure attributes are propagated onto parameters (this matters for
14204 // format, pass_object_size, ...).
14205 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14206 ParamDecls.push_back(PD);
14207 ProtoLoc.setParam(I, PD);
14208 }
14209
14210 // Set up the new constructor.
14211 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14212 DerivedCtor->setAccess(BaseCtor->getAccess());
14213 DerivedCtor->setParams(ParamDecls);
14214 Derived->addDecl(DerivedCtor);
14215
14216 if (ShouldDeleteSpecialMember(DerivedCtor,
14218 SetDeclDeleted(DerivedCtor, UsingLoc);
14219
14220 return DerivedCtor;
14221}
14222
14224 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14227 &ICI,
14228 /*Diagnose*/ true);
14229}
14230
14232 CXXConstructorDecl *Constructor) {
14233 CXXRecordDecl *ClassDecl = Constructor->getParent();
14234 assert(Constructor->getInheritedConstructor() &&
14235 !Constructor->doesThisDeclarationHaveABody() &&
14236 !Constructor->isDeleted());
14237 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14238 return;
14239
14240 // Initializations are performed "as if by a defaulted default constructor",
14241 // so enter the appropriate scope.
14242 SynthesizedFunctionScope Scope(*this, Constructor);
14243
14244 // The exception specification is needed because we are defining the
14245 // function.
14246 ResolveExceptionSpec(CurrentLocation,
14247 Constructor->getType()->castAs<FunctionProtoType>());
14248 MarkVTableUsed(CurrentLocation, ClassDecl);
14249
14250 // Add a context note for diagnostics produced after this point.
14251 Scope.addContextNote(CurrentLocation);
14252
14254 Constructor->getInheritedConstructor().getShadowDecl();
14255 CXXConstructorDecl *InheritedCtor =
14256 Constructor->getInheritedConstructor().getConstructor();
14257
14258 // [class.inhctor.init]p1:
14259 // initialization proceeds as if a defaulted default constructor is used to
14260 // initialize the D object and each base class subobject from which the
14261 // constructor was inherited
14262
14263 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14264 CXXRecordDecl *RD = Shadow->getParent();
14265 SourceLocation InitLoc = Shadow->getLocation();
14266
14267 // Build explicit initializers for all base classes from which the
14268 // constructor was inherited.
14270 for (bool VBase : {false, true}) {
14271 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14272 if (B.isVirtual() != VBase)
14273 continue;
14274
14275 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14276 if (!BaseRD)
14277 continue;
14278
14279 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14280 if (!BaseCtor.first)
14281 continue;
14282
14283 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14285 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14286
14287 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14288 Inits.push_back(new (Context) CXXCtorInitializer(
14289 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14290 SourceLocation()));
14291 }
14292 }
14293
14294 // We now proceed as if for a defaulted default constructor, with the relevant
14295 // initializers replaced.
14296
14297 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14298 Constructor->setInvalidDecl();
14299 return;
14300 }
14301
14302 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14303 Constructor->markUsed(Context);
14304
14306 L->CompletedImplicitDefinition(Constructor);
14307 }
14308
14309 DiagnoseUninitializedFields(*this, Constructor);
14310}
14311
14313 // C++ [class.dtor]p2:
14314 // If a class has no user-declared destructor, a destructor is
14315 // declared implicitly. An implicitly-declared destructor is an
14316 // inline public member of its class.
14317 assert(ClassDecl->needsImplicitDestructor());
14318
14319 DeclaringSpecialMember DSM(*this, ClassDecl,
14321 if (DSM.isAlreadyBeingDeclared())
14322 return nullptr;
14323
14325 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14326
14327 // Create the actual destructor declaration.
14328 CanQualType ClassType
14330 SourceLocation ClassLoc = ClassDecl->getLocation();
14331 DeclarationName Name
14333 DeclarationNameInfo NameInfo(Name, ClassLoc);
14335 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14336 getCurFPFeatures().isFPConstrained(),
14337 /*isInline=*/true,
14338 /*isImplicitlyDeclared=*/true,
14341 Destructor->setAccess(AS_public);
14342 Destructor->setDefaulted();
14343
14344 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14345
14346 if (getLangOpts().CUDA)
14349 /* ConstRHS */ false,
14350 /* Diagnose */ false);
14351
14352 // We don't need to use SpecialMemberIsTrivial here; triviality for
14353 // destructors is easy to compute.
14354 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14355 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14356 ClassDecl->hasTrivialDestructorForCall());
14357
14358 // Note that we have declared this destructor.
14360
14361 Scope *S = getScopeForContext(ClassDecl);
14363
14364 // We can't check whether an implicit destructor is deleted before we complete
14365 // the definition of the class, because its validity depends on the alignment
14366 // of the class. We'll check this from ActOnFields once the class is complete.
14367 if (ClassDecl->isCompleteDefinition() &&
14369 SetDeclDeleted(Destructor, ClassLoc);
14370
14371 // Introduce this destructor into its scope.
14372 if (S)
14373 PushOnScopeChains(Destructor, S, false);
14374 ClassDecl->addDecl(Destructor);
14375
14376 return Destructor;
14377}
14378
14381 assert((Destructor->isDefaulted() &&
14382 !Destructor->doesThisDeclarationHaveABody() &&
14383 !Destructor->isDeleted()) &&
14384 "DefineImplicitDestructor - call it for implicit default dtor");
14385 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14386 return;
14387
14388 CXXRecordDecl *ClassDecl = Destructor->getParent();
14389 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14390
14392
14393 // The exception specification is needed because we are defining the
14394 // function.
14395 ResolveExceptionSpec(CurrentLocation,
14396 Destructor->getType()->castAs<FunctionProtoType>());
14397 MarkVTableUsed(CurrentLocation, ClassDecl);
14398
14399 // Add a context note for diagnostics produced after this point.
14400 Scope.addContextNote(CurrentLocation);
14401
14403 Destructor->getParent());
14404
14406 Destructor->setInvalidDecl();
14407 return;
14408 }
14409
14410 SourceLocation Loc = Destructor->getEndLoc().isValid()
14411 ? Destructor->getEndLoc()
14412 : Destructor->getLocation();
14413 Destructor->setBody(new (Context) CompoundStmt(Loc));
14414 Destructor->markUsed(Context);
14415
14417 L->CompletedImplicitDefinition(Destructor);
14418 }
14419}
14420
14423 if (Destructor->isInvalidDecl())
14424 return;
14425
14426 CXXRecordDecl *ClassDecl = Destructor->getParent();
14428 "implicit complete dtors unneeded outside MS ABI");
14429 assert(ClassDecl->getNumVBases() > 0 &&
14430 "complete dtor only exists for classes with vbases");
14431
14433
14434 // Add a context note for diagnostics produced after this point.
14435 Scope.addContextNote(CurrentLocation);
14436
14437 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14438}
14439
14440/// Perform any semantic analysis which needs to be delayed until all
14441/// pending class member declarations have been parsed.
14443 // If the context is an invalid C++ class, just suppress these checks.
14444 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14445 if (Record->isInvalidDecl()) {
14448 return;
14449 }
14451 }
14452}
14453
14456
14457 if (!DelayedDllExportMemberFunctions.empty()) {
14459 std::swap(DelayedDllExportMemberFunctions, WorkList);
14460 for (CXXMethodDecl *M : WorkList) {
14461 DefineDefaultedFunction(*this, M, M->getLocation());
14462
14463 // Pass the method to the consumer to get emitted. This is not necessary
14464 // for explicit instantiation definitions, as they will get emitted
14465 // anyway.
14466 if (M->getParent()->getTemplateSpecializationKind() !=
14469 }
14470 }
14471}
14472
14474 if (!DelayedDllExportClasses.empty()) {
14475 // Calling ReferenceDllExportedMembers might cause the current function to
14476 // be called again, so use a local copy of DelayedDllExportClasses.
14478 std::swap(DelayedDllExportClasses, WorkList);
14479 for (CXXRecordDecl *Class : WorkList)
14481 }
14482}
14483
14485 assert(getLangOpts().CPlusPlus11 &&
14486 "adjusting dtor exception specs was introduced in c++11");
14487
14488 if (Destructor->isDependentContext())
14489 return;
14490
14491 // C++11 [class.dtor]p3:
14492 // A declaration of a destructor that does not have an exception-
14493 // specification is implicitly considered to have the same exception-
14494 // specification as an implicit declaration.
14495 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14496 if (DtorType->hasExceptionSpec())
14497 return;
14498
14499 // Replace the destructor's type, building off the existing one. Fortunately,
14500 // the only thing of interest in the destructor type is its extended info.
14501 // The return and arguments are fixed.
14502 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14505 Destructor->setType(
14506 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14507
14508 // FIXME: If the destructor has a body that could throw, and the newly created
14509 // spec doesn't allow exceptions, we should emit a warning, because this
14510 // change in behavior can break conforming C++03 programs at runtime.
14511 // However, we don't have a body or an exception specification yet, so it
14512 // needs to be done somewhere else.
14513}
14514
14515namespace {
14516/// An abstract base class for all helper classes used in building the
14517// copy/move operators. These classes serve as factory functions and help us
14518// avoid using the same Expr* in the AST twice.
14519class ExprBuilder {
14520 ExprBuilder(const ExprBuilder&) = delete;
14521 ExprBuilder &operator=(const ExprBuilder&) = delete;
14522
14523protected:
14524 static Expr *assertNotNull(Expr *E) {
14525 assert(E && "Expression construction must not fail.");
14526 return E;
14527 }
14528
14529public:
14530 ExprBuilder() {}
14531 virtual ~ExprBuilder() {}
14532
14533 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14534};
14535
14536class RefBuilder: public ExprBuilder {
14537 VarDecl *Var;
14538 QualType VarType;
14539
14540public:
14541 Expr *build(Sema &S, SourceLocation Loc) const override {
14542 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14543 }
14544
14545 RefBuilder(VarDecl *Var, QualType VarType)
14546 : Var(Var), VarType(VarType) {}
14547};
14548
14549class ThisBuilder: public ExprBuilder {
14550public:
14551 Expr *build(Sema &S, SourceLocation Loc) const override {
14552 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14553 }
14554};
14555
14556class CastBuilder: public ExprBuilder {
14557 const ExprBuilder &Builder;
14558 QualType Type;
14560 const CXXCastPath &Path;
14561
14562public:
14563 Expr *build(Sema &S, SourceLocation Loc) const override {
14564 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14565 CK_UncheckedDerivedToBase, Kind,
14566 &Path).get());
14567 }
14568
14569 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14570 const CXXCastPath &Path)
14571 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14572};
14573
14574class DerefBuilder: public ExprBuilder {
14575 const ExprBuilder &Builder;
14576
14577public:
14578 Expr *build(Sema &S, SourceLocation Loc) const override {
14579 return assertNotNull(
14580 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14581 }
14582
14583 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14584};
14585
14586class MemberBuilder: public ExprBuilder {
14587 const ExprBuilder &Builder;
14588 QualType Type;
14589 CXXScopeSpec SS;
14590 bool IsArrow;
14591 LookupResult &MemberLookup;
14592
14593public:
14594 Expr *build(Sema &S, SourceLocation Loc) const override {
14595 return assertNotNull(S.BuildMemberReferenceExpr(
14596 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14597 nullptr, MemberLookup, nullptr, nullptr).get());
14598 }
14599
14600 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14601 LookupResult &MemberLookup)
14602 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14603 MemberLookup(MemberLookup) {}
14604};
14605
14606class MoveCastBuilder: public ExprBuilder {
14607 const ExprBuilder &Builder;
14608
14609public:
14610 Expr *build(Sema &S, SourceLocation Loc) const override {
14611 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14612 }
14613
14614 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14615};
14616
14617class LvalueConvBuilder: public ExprBuilder {
14618 const ExprBuilder &Builder;
14619
14620public:
14621 Expr *build(Sema &S, SourceLocation Loc) const override {
14622 return assertNotNull(
14623 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14624 }
14625
14626 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14627};
14628
14629class SubscriptBuilder: public ExprBuilder {
14630 const ExprBuilder &Base;
14631 const ExprBuilder &Index;
14632
14633public:
14634 Expr *build(Sema &S, SourceLocation Loc) const override {
14635 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14636 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14637 }
14638
14639 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14640 : Base(Base), Index(Index) {}
14641};
14642
14643} // end anonymous namespace
14644
14645/// When generating a defaulted copy or move assignment operator, if a field
14646/// should be copied with __builtin_memcpy rather than via explicit assignments,
14647/// do so. This optimization only applies for arrays of scalars, and for arrays
14648/// of class type where the selected copy/move-assignment operator is trivial.
14649static StmtResult
14651 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14652 // Compute the size of the memory buffer to be copied.
14653 QualType SizeType = S.Context.getSizeType();
14654 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14656
14657 // Take the address of the field references for "from" and "to". We
14658 // directly construct UnaryOperators here because semantic analysis
14659 // does not permit us to take the address of an xvalue.
14660 Expr *From = FromB.build(S, Loc);
14661 From = UnaryOperator::Create(
14662 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14663 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14664 Expr *To = ToB.build(S, Loc);
14666 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14667 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14668
14669 const Type *E = T->getBaseElementTypeUnsafe();
14670 bool NeedsCollectableMemCpy =
14671 E->isRecordType() &&
14672 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14673
14674 // Create a reference to the __builtin_objc_memmove_collectable function
14675 StringRef MemCpyName = NeedsCollectableMemCpy ?
14676 "__builtin_objc_memmove_collectable" :
14677 "__builtin_memcpy";
14678 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14680 S.LookupName(R, S.TUScope, true);
14681
14682 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14683 if (!MemCpy)
14684 // Something went horribly wrong earlier, and we will have complained
14685 // about it.
14686 return StmtError();
14687
14688 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14689 VK_PRValue, Loc, nullptr);
14690 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14691
14692 Expr *CallArgs[] = {
14693 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14694 };
14695 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14696 Loc, CallArgs, Loc);
14697
14698 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14699 return Call.getAs<Stmt>();
14700}
14701
14702/// Builds a statement that copies/moves the given entity from \p From to
14703/// \c To.
14704///
14705/// This routine is used to copy/move the members of a class with an
14706/// implicitly-declared copy/move assignment operator. When the entities being
14707/// copied are arrays, this routine builds for loops to copy them.
14708///
14709/// \param S The Sema object used for type-checking.
14710///
14711/// \param Loc The location where the implicit copy/move is being generated.
14712///
14713/// \param T The type of the expressions being copied/moved. Both expressions
14714/// must have this type.
14715///
14716/// \param To The expression we are copying/moving to.
14717///
14718/// \param From The expression we are copying/moving from.
14719///
14720/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14721/// Otherwise, it's a non-static member subobject.
14722///
14723/// \param Copying Whether we're copying or moving.
14724///
14725/// \param Depth Internal parameter recording the depth of the recursion.
14726///
14727/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14728/// if a memcpy should be used instead.
14729static StmtResult
14731 const ExprBuilder &To, const ExprBuilder &From,
14732 bool CopyingBaseSubobject, bool Copying,
14733 unsigned Depth = 0) {
14734 // C++11 [class.copy]p28:
14735 // Each subobject is assigned in the manner appropriate to its type:
14736 //
14737 // - if the subobject is of class type, as if by a call to operator= with
14738 // the subobject as the object expression and the corresponding
14739 // subobject of x as a single function argument (as if by explicit
14740 // qualification; that is, ignoring any possible virtual overriding
14741 // functions in more derived classes);
14742 //
14743 // C++03 [class.copy]p13:
14744 // - if the subobject is of class type, the copy assignment operator for
14745 // the class is used (as if by explicit qualification; that is,
14746 // ignoring any possible virtual overriding functions in more derived
14747 // classes);
14748 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14749 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14750
14751 // Look for operator=.
14752 DeclarationName Name
14754 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14755 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14756
14757 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14758 // operator.
14759 if (!S.getLangOpts().CPlusPlus11) {
14760 LookupResult::Filter F = OpLookup.makeFilter();
14761 while (F.hasNext()) {
14762 NamedDecl *D = F.next();
14763 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14764 if (Method->isCopyAssignmentOperator() ||
14765 (!Copying && Method->isMoveAssignmentOperator()))
14766 continue;
14767
14768 F.erase();
14769 }
14770 F.done();
14771 }
14772
14773 // Suppress the protected check (C++ [class.protected]) for each of the
14774 // assignment operators we found. This strange dance is required when
14775 // we're assigning via a base classes's copy-assignment operator. To
14776 // ensure that we're getting the right base class subobject (without
14777 // ambiguities), we need to cast "this" to that subobject type; to
14778 // ensure that we don't go through the virtual call mechanism, we need
14779 // to qualify the operator= name with the base class (see below). However,
14780 // this means that if the base class has a protected copy assignment
14781 // operator, the protected member access check will fail. So, we
14782 // rewrite "protected" access to "public" access in this case, since we
14783 // know by construction that we're calling from a derived class.
14784 if (CopyingBaseSubobject) {
14785 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14786 L != LEnd; ++L) {
14787 if (L.getAccess() == AS_protected)
14788 L.setAccess(AS_public);
14789 }
14790 }
14791
14792 // Create the nested-name-specifier that will be used to qualify the
14793 // reference to operator=; this is required to suppress the virtual
14794 // call mechanism.
14795 CXXScopeSpec SS;
14796 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14797 SS.MakeTrivial(S.Context,
14798 NestedNameSpecifier::Create(S.Context, nullptr, false,
14799 CanonicalT),
14800 Loc);
14801
14802 // Create the reference to operator=.
14803 ExprResult OpEqualRef
14804 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14805 SS, /*TemplateKWLoc=*/SourceLocation(),
14806 /*FirstQualifierInScope=*/nullptr,
14807 OpLookup,
14808 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14809 /*SuppressQualifierCheck=*/true);
14810 if (OpEqualRef.isInvalid())
14811 return StmtError();
14812
14813 // Build the call to the assignment operator.
14814
14815 Expr *FromInst = From.build(S, Loc);
14816 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14817 OpEqualRef.getAs<Expr>(),
14818 Loc, FromInst, Loc);
14819 if (Call.isInvalid())
14820 return StmtError();
14821
14822 // If we built a call to a trivial 'operator=' while copying an array,
14823 // bail out. We'll replace the whole shebang with a memcpy.
14824 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14825 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14826 return StmtResult((Stmt*)nullptr);
14827
14828 // Convert to an expression-statement, and clean up any produced
14829 // temporaries.
14830 return S.ActOnExprStmt(Call);
14831 }
14832
14833 // - if the subobject is of scalar type, the built-in assignment
14834 // operator is used.
14836 if (!ArrayTy) {
14837 ExprResult Assignment = S.CreateBuiltinBinOp(
14838 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14839 if (Assignment.isInvalid())
14840 return StmtError();
14841 return S.ActOnExprStmt(Assignment);
14842 }
14843
14844 // - if the subobject is an array, each element is assigned, in the
14845 // manner appropriate to the element type;
14846
14847 // Construct a loop over the array bounds, e.g.,
14848 //
14849 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14850 //
14851 // that will copy each of the array elements.
14852 QualType SizeType = S.Context.getSizeType();
14853
14854 // Create the iteration variable.
14855 IdentifierInfo *IterationVarName = nullptr;
14856 {
14857 SmallString<8> Str;
14858 llvm::raw_svector_ostream OS(Str);
14859 OS << "__i" << Depth;
14860 IterationVarName = &S.Context.Idents.get(OS.str());
14861 }
14862 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14863 IterationVarName, SizeType,
14864 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14865 SC_None);
14866
14867 // Initialize the iteration variable to zero.
14868 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14869 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14870
14871 // Creates a reference to the iteration variable.
14872 RefBuilder IterationVarRef(IterationVar, SizeType);
14873 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14874
14875 // Create the DeclStmt that holds the iteration variable.
14876 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14877
14878 // Subscript the "from" and "to" expressions with the iteration variable.
14879 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14880 MoveCastBuilder FromIndexMove(FromIndexCopy);
14881 const ExprBuilder *FromIndex;
14882 if (Copying)
14883 FromIndex = &FromIndexCopy;
14884 else
14885 FromIndex = &FromIndexMove;
14886
14887 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14888
14889 // Build the copy/move for an individual element of the array.
14892 ToIndex, *FromIndex, CopyingBaseSubobject,
14893 Copying, Depth + 1);
14894 // Bail out if copying fails or if we determined that we should use memcpy.
14895 if (Copy.isInvalid() || !Copy.get())
14896 return Copy;
14897
14898 // Create the comparison against the array bound.
14899 llvm::APInt Upper
14900 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14901 Expr *Comparison = BinaryOperator::Create(
14902 S.Context, IterationVarRefRVal.build(S, Loc),
14903 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14906
14907 // Create the pre-increment of the iteration variable. We can determine
14908 // whether the increment will overflow based on the value of the array
14909 // bound.
14910 Expr *Increment = UnaryOperator::Create(
14911 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14912 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14913
14914 // Construct the loop that copies all elements of this array.
14915 return S.ActOnForStmt(
14916 Loc, Loc, InitStmt,
14917 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14918 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14919}
14920
14921static StmtResult
14923 const ExprBuilder &To, const ExprBuilder &From,
14924 bool CopyingBaseSubobject, bool Copying) {
14925 // Maybe we should use a memcpy?
14926 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14927 T.isTriviallyCopyableType(S.Context))
14928 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14929
14931 CopyingBaseSubobject,
14932 Copying, 0));
14933
14934 // If we ended up picking a trivial assignment operator for an array of a
14935 // non-trivially-copyable class type, just emit a memcpy.
14936 if (!Result.isInvalid() && !Result.get())
14937 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14938
14939 return Result;
14940}
14941
14943 // Note: The following rules are largely analoguous to the copy
14944 // constructor rules. Note that virtual bases are not taken into account
14945 // for determining the argument type of the operator. Note also that
14946 // operators taking an object instead of a reference are allowed.
14947 assert(ClassDecl->needsImplicitCopyAssignment());
14948
14949 DeclaringSpecialMember DSM(*this, ClassDecl,
14951 if (DSM.isAlreadyBeingDeclared())
14952 return nullptr;
14953
14954 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14956 ArgType, nullptr);
14958 if (AS != LangAS::Default)
14959 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14960 QualType RetType = Context.getLValueReferenceType(ArgType);
14961 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14962 if (Const)
14963 ArgType = ArgType.withConst();
14964
14965 ArgType = Context.getLValueReferenceType(ArgType);
14966
14968 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14969
14970 // An implicitly-declared copy assignment operator is an inline public
14971 // member of its class.
14973 SourceLocation ClassLoc = ClassDecl->getLocation();
14974 DeclarationNameInfo NameInfo(Name, ClassLoc);
14976 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14977 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14978 getCurFPFeatures().isFPConstrained(),
14979 /*isInline=*/true,
14981 SourceLocation());
14982 CopyAssignment->setAccess(AS_public);
14983 CopyAssignment->setDefaulted();
14984 CopyAssignment->setImplicit();
14985
14986 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14987
14988 if (getLangOpts().CUDA)
14991 /* ConstRHS */ Const,
14992 /* Diagnose */ false);
14993
14994 // Add the parameter to the operator.
14996 ClassLoc, ClassLoc,
14997 /*Id=*/nullptr, ArgType,
14998 /*TInfo=*/nullptr, SC_None,
14999 nullptr);
15000 CopyAssignment->setParams(FromParam);
15001
15002 CopyAssignment->setTrivial(
15006 : ClassDecl->hasTrivialCopyAssignment());
15007
15008 // Note that we have added this copy-assignment operator.
15010
15011 Scope *S = getScopeForContext(ClassDecl);
15013
15017 SetDeclDeleted(CopyAssignment, ClassLoc);
15018 }
15019
15020 if (S)
15022 ClassDecl->addDecl(CopyAssignment);
15023
15024 return CopyAssignment;
15025}
15026
15027/// Diagnose an implicit copy operation for a class which is odr-used, but
15028/// which is deprecated because the class has a user-declared copy constructor,
15029/// copy assignment operator, or destructor.
15031 assert(CopyOp->isImplicit());
15032
15033 CXXRecordDecl *RD = CopyOp->getParent();
15034 CXXMethodDecl *UserDeclaredOperation = nullptr;
15035
15036 if (RD->hasUserDeclaredDestructor()) {
15037 UserDeclaredOperation = RD->getDestructor();
15038 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15040 // Find any user-declared copy constructor.
15041 for (auto *I : RD->ctors()) {
15042 if (I->isCopyConstructor()) {
15043 UserDeclaredOperation = I;
15044 break;
15045 }
15046 }
15047 assert(UserDeclaredOperation);
15048 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15050 // Find any user-declared move assignment operator.
15051 for (auto *I : RD->methods()) {
15052 if (I->isCopyAssignmentOperator()) {
15053 UserDeclaredOperation = I;
15054 break;
15055 }
15056 }
15057 assert(UserDeclaredOperation);
15058 }
15059
15060 if (UserDeclaredOperation) {
15061 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15062 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15063 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15064 unsigned DiagID =
15065 (UDOIsUserProvided && UDOIsDestructor)
15066 ? diag::warn_deprecated_copy_with_user_provided_dtor
15067 : (UDOIsUserProvided && !UDOIsDestructor)
15068 ? diag::warn_deprecated_copy_with_user_provided_copy
15069 : (!UDOIsUserProvided && UDOIsDestructor)
15070 ? diag::warn_deprecated_copy_with_dtor
15071 : diag::warn_deprecated_copy;
15072 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15073 << RD << IsCopyAssignment;
15074 }
15075}
15076
15078 CXXMethodDecl *CopyAssignOperator) {
15079 assert((CopyAssignOperator->isDefaulted() &&
15080 CopyAssignOperator->isOverloadedOperator() &&
15081 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15082 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15083 !CopyAssignOperator->isDeleted()) &&
15084 "DefineImplicitCopyAssignment called for wrong function");
15085 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15086 return;
15087
15088 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15089 if (ClassDecl->isInvalidDecl()) {
15090 CopyAssignOperator->setInvalidDecl();
15091 return;
15092 }
15093
15094 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15095
15096 // The exception specification is needed because we are defining the
15097 // function.
15098 ResolveExceptionSpec(CurrentLocation,
15099 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15100
15101 // Add a context note for diagnostics produced after this point.
15102 Scope.addContextNote(CurrentLocation);
15103
15104 // C++11 [class.copy]p18:
15105 // The [definition of an implicitly declared copy assignment operator] is
15106 // deprecated if the class has a user-declared copy constructor or a
15107 // user-declared destructor.
15108 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15109 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15110
15111 // C++0x [class.copy]p30:
15112 // The implicitly-defined or explicitly-defaulted copy assignment operator
15113 // for a non-union class X performs memberwise copy assignment of its
15114 // subobjects. The direct base classes of X are assigned first, in the
15115 // order of their declaration in the base-specifier-list, and then the
15116 // immediate non-static data members of X are assigned, in the order in
15117 // which they were declared in the class definition.
15118
15119 // The statements that form the synthesized function body.
15120 SmallVector<Stmt*, 8> Statements;
15121
15122 // The parameter for the "other" object, which we are copying from.
15123 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15124 Qualifiers OtherQuals = Other->getType().getQualifiers();
15125 QualType OtherRefType = Other->getType();
15126 if (OtherRefType->isLValueReferenceType()) {
15127 OtherRefType = OtherRefType->getPointeeType();
15128 OtherQuals = OtherRefType.getQualifiers();
15129 }
15130
15131 // Our location for everything implicitly-generated.
15132 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15133 ? CopyAssignOperator->getEndLoc()
15134 : CopyAssignOperator->getLocation();
15135
15136 // Builds a DeclRefExpr for the "other" object.
15137 RefBuilder OtherRef(Other, OtherRefType);
15138
15139 // Builds the function object parameter.
15140 std::optional<ThisBuilder> This;
15141 std::optional<DerefBuilder> DerefThis;
15142 std::optional<RefBuilder> ExplicitObject;
15143 bool IsArrow = false;
15144 QualType ObjectType;
15145 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15146 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15147 if (ObjectType->isReferenceType())
15148 ObjectType = ObjectType->getPointeeType();
15149 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15150 } else {
15151 ObjectType = getCurrentThisType();
15152 This.emplace();
15153 DerefThis.emplace(*This);
15154 IsArrow = !LangOpts.HLSL;
15155 }
15156 ExprBuilder &ObjectParameter =
15157 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15158 : static_cast<ExprBuilder &>(*This);
15159
15160 // Assign base classes.
15161 bool Invalid = false;
15162 for (auto &Base : ClassDecl->bases()) {
15163 // Form the assignment:
15164 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15165 QualType BaseType = Base.getType().getUnqualifiedType();
15166 if (!BaseType->isRecordType()) {
15167 Invalid = true;
15168 continue;
15169 }
15170
15171 CXXCastPath BasePath;
15172 BasePath.push_back(&Base);
15173
15174 // Construct the "from" expression, which is an implicit cast to the
15175 // appropriately-qualified base type.
15176 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15177 VK_LValue, BasePath);
15178
15179 // Dereference "this".
15180 CastBuilder To(
15181 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15182 : static_cast<ExprBuilder &>(*DerefThis),
15183 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15184 VK_LValue, BasePath);
15185
15186 // Build the copy.
15187 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15188 To, From,
15189 /*CopyingBaseSubobject=*/true,
15190 /*Copying=*/true);
15191 if (Copy.isInvalid()) {
15192 CopyAssignOperator->setInvalidDecl();
15193 return;
15194 }
15195
15196 // Success! Record the copy.
15197 Statements.push_back(Copy.getAs<Expr>());
15198 }
15199
15200 // Assign non-static members.
15201 for (auto *Field : ClassDecl->fields()) {
15202 // FIXME: We should form some kind of AST representation for the implied
15203 // memcpy in a union copy operation.
15204 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15205 continue;
15206
15207 if (Field->isInvalidDecl()) {
15208 Invalid = true;
15209 continue;
15210 }
15211
15212 // Check for members of reference type; we can't copy those.
15213 if (Field->getType()->isReferenceType()) {
15214 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15215 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15216 Diag(Field->getLocation(), diag::note_declared_at);
15217 Invalid = true;
15218 continue;
15219 }
15220
15221 // Check for members of const-qualified, non-class type.
15222 QualType BaseType = Context.getBaseElementType(Field->getType());
15223 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15224 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15225 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15226 Diag(Field->getLocation(), diag::note_declared_at);
15227 Invalid = true;
15228 continue;
15229 }
15230
15231 // Suppress assigning zero-width bitfields.
15232 if (Field->isZeroLengthBitField(Context))
15233 continue;
15234
15235 QualType FieldType = Field->getType().getNonReferenceType();
15236 if (FieldType->isIncompleteArrayType()) {
15237 assert(ClassDecl->hasFlexibleArrayMember() &&
15238 "Incomplete array type is not valid");
15239 continue;
15240 }
15241
15242 // Build references to the field in the object we're copying from and to.
15243 CXXScopeSpec SS; // Intentionally empty
15244 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15246 MemberLookup.addDecl(Field);
15247 MemberLookup.resolveKind();
15248
15249 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15250 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15251 // Build the copy of this field.
15252 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15253 To, From,
15254 /*CopyingBaseSubobject=*/false,
15255 /*Copying=*/true);
15256 if (Copy.isInvalid()) {
15257 CopyAssignOperator->setInvalidDecl();
15258 return;
15259 }
15260
15261 // Success! Record the copy.
15262 Statements.push_back(Copy.getAs<Stmt>());
15263 }
15264
15265 if (!Invalid) {
15266 // Add a "return *this;"
15267 Expr *ThisExpr =
15268 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15269 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15270 : static_cast<ExprBuilder &>(*DerefThis))
15271 .build(*this, Loc);
15272 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15273 if (Return.isInvalid())
15274 Invalid = true;
15275 else
15276 Statements.push_back(Return.getAs<Stmt>());
15277 }
15278
15279 if (Invalid) {
15280 CopyAssignOperator->setInvalidDecl();
15281 return;
15282 }
15283
15284 StmtResult Body;
15285 {
15286 CompoundScopeRAII CompoundScope(*this);
15287 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15288 /*isStmtExpr=*/false);
15289 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15290 }
15291 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15292 CopyAssignOperator->markUsed(Context);
15293
15295 L->CompletedImplicitDefinition(CopyAssignOperator);
15296 }
15297}
15298
15300 assert(ClassDecl->needsImplicitMoveAssignment());
15301
15302 DeclaringSpecialMember DSM(*this, ClassDecl,
15304 if (DSM.isAlreadyBeingDeclared())
15305 return nullptr;
15306
15307 // Note: The following rules are largely analoguous to the move
15308 // constructor rules.
15309
15310 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15312 ArgType, nullptr);
15314 if (AS != LangAS::Default)
15315 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15316 QualType RetType = Context.getLValueReferenceType(ArgType);
15317 ArgType = Context.getRValueReferenceType(ArgType);
15318
15320 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15321
15322 // An implicitly-declared move assignment operator is an inline public
15323 // member of its class.
15325 SourceLocation ClassLoc = ClassDecl->getLocation();
15326 DeclarationNameInfo NameInfo(Name, ClassLoc);
15328 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15329 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15330 getCurFPFeatures().isFPConstrained(),
15331 /*isInline=*/true,
15333 SourceLocation());
15334 MoveAssignment->setAccess(AS_public);
15335 MoveAssignment->setDefaulted();
15336 MoveAssignment->setImplicit();
15337
15338 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15339
15340 if (getLangOpts().CUDA)
15343 /* ConstRHS */ false,
15344 /* Diagnose */ false);
15345
15346 // Add the parameter to the operator.
15348 ClassLoc, ClassLoc,
15349 /*Id=*/nullptr, ArgType,
15350 /*TInfo=*/nullptr, SC_None,
15351 nullptr);
15352 MoveAssignment->setParams(FromParam);
15353
15354 MoveAssignment->setTrivial(
15358 : ClassDecl->hasTrivialMoveAssignment());
15359
15360 // Note that we have added this copy-assignment operator.
15362
15363 Scope *S = getScopeForContext(ClassDecl);
15365
15369 SetDeclDeleted(MoveAssignment, ClassLoc);
15370 }
15371
15372 if (S)
15374 ClassDecl->addDecl(MoveAssignment);
15375
15376 return MoveAssignment;
15377}
15378
15379/// Check if we're implicitly defining a move assignment operator for a class
15380/// with virtual bases. Such a move assignment might move-assign the virtual
15381/// base multiple times.
15383 SourceLocation CurrentLocation) {
15384 assert(!Class->isDependentContext() && "should not define dependent move");
15385
15386 // Only a virtual base could get implicitly move-assigned multiple times.
15387 // Only a non-trivial move assignment can observe this. We only want to
15388 // diagnose if we implicitly define an assignment operator that assigns
15389 // two base classes, both of which move-assign the same virtual base.
15390 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15391 Class->getNumBases() < 2)
15392 return;
15393
15395 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15396 VBaseMap VBases;
15397
15398 for (auto &BI : Class->bases()) {
15399 Worklist.push_back(&BI);
15400 while (!Worklist.empty()) {
15401 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15402 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15403
15404 // If the base has no non-trivial move assignment operators,
15405 // we don't care about moves from it.
15406 if (!Base->hasNonTrivialMoveAssignment())
15407 continue;
15408
15409 // If there's nothing virtual here, skip it.
15410 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15411 continue;
15412
15413 // If we're not actually going to call a move assignment for this base,
15414 // or the selected move assignment is trivial, skip it.
15417 /*ConstArg*/ false, /*VolatileArg*/ false,
15418 /*RValueThis*/ true, /*ConstThis*/ false,
15419 /*VolatileThis*/ false);
15420 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15422 continue;
15423
15424 if (BaseSpec->isVirtual()) {
15425 // We're going to move-assign this virtual base, and its move
15426 // assignment operator is not trivial. If this can happen for
15427 // multiple distinct direct bases of Class, diagnose it. (If it
15428 // only happens in one base, we'll diagnose it when synthesizing
15429 // that base class's move assignment operator.)
15430 CXXBaseSpecifier *&Existing =
15431 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15432 .first->second;
15433 if (Existing && Existing != &BI) {
15434 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15435 << Class << Base;
15436 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15437 << (Base->getCanonicalDecl() ==
15439 << Base << Existing->getType() << Existing->getSourceRange();
15440 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15441 << (Base->getCanonicalDecl() ==
15442 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15443 << Base << BI.getType() << BaseSpec->getSourceRange();
15444
15445 // Only diagnose each vbase once.
15446 Existing = nullptr;
15447 }
15448 } else {
15449 // Only walk over bases that have defaulted move assignment operators.
15450 // We assume that any user-provided move assignment operator handles
15451 // the multiple-moves-of-vbase case itself somehow.
15452 if (!SMOR.getMethod()->isDefaulted())
15453 continue;
15454
15455 // We're going to move the base classes of Base. Add them to the list.
15456 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15457 }
15458 }
15459 }
15460}
15461
15463 CXXMethodDecl *MoveAssignOperator) {
15464 assert((MoveAssignOperator->isDefaulted() &&
15465 MoveAssignOperator->isOverloadedOperator() &&
15466 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15467 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15468 !MoveAssignOperator->isDeleted()) &&
15469 "DefineImplicitMoveAssignment called for wrong function");
15470 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15471 return;
15472
15473 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15474 if (ClassDecl->isInvalidDecl()) {
15475 MoveAssignOperator->setInvalidDecl();
15476 return;
15477 }
15478
15479 // C++0x [class.copy]p28:
15480 // The implicitly-defined or move assignment operator for a non-union class
15481 // X performs memberwise move assignment of its subobjects. The direct base
15482 // classes of X are assigned first, in the order of their declaration in the
15483 // base-specifier-list, and then the immediate non-static data members of X
15484 // are assigned, in the order in which they were declared in the class
15485 // definition.
15486
15487 // Issue a warning if our implicit move assignment operator will move
15488 // from a virtual base more than once.
15489 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15490
15491 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15492
15493 // The exception specification is needed because we are defining the
15494 // function.
15495 ResolveExceptionSpec(CurrentLocation,
15496 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15497
15498 // Add a context note for diagnostics produced after this point.
15499 Scope.addContextNote(CurrentLocation);
15500
15501 // The statements that form the synthesized function body.
15502 SmallVector<Stmt*, 8> Statements;
15503
15504 // The parameter for the "other" object, which we are move from.
15505 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15506 QualType OtherRefType =
15507 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15508
15509 // Our location for everything implicitly-generated.
15510 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15511 ? MoveAssignOperator->getEndLoc()
15512 : MoveAssignOperator->getLocation();
15513
15514 // Builds a reference to the "other" object.
15515 RefBuilder OtherRef(Other, OtherRefType);
15516 // Cast to rvalue.
15517 MoveCastBuilder MoveOther(OtherRef);
15518
15519 // Builds the function object parameter.
15520 std::optional<ThisBuilder> This;
15521 std::optional<DerefBuilder> DerefThis;
15522 std::optional<RefBuilder> ExplicitObject;
15523 QualType ObjectType;
15524 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15525 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15526 if (ObjectType->isReferenceType())
15527 ObjectType = ObjectType->getPointeeType();
15528 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15529 } else {
15530 ObjectType = getCurrentThisType();
15531 This.emplace();
15532 DerefThis.emplace(*This);
15533 }
15534 ExprBuilder &ObjectParameter =
15535 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15536
15537 // Assign base classes.
15538 bool Invalid = false;
15539 for (auto &Base : ClassDecl->bases()) {
15540 // C++11 [class.copy]p28:
15541 // It is unspecified whether subobjects representing virtual base classes
15542 // are assigned more than once by the implicitly-defined copy assignment
15543 // operator.
15544 // FIXME: Do not assign to a vbase that will be assigned by some other base
15545 // class. For a move-assignment, this can result in the vbase being moved
15546 // multiple times.
15547
15548 // Form the assignment:
15549 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15550 QualType BaseType = Base.getType().getUnqualifiedType();
15551 if (!BaseType->isRecordType()) {
15552 Invalid = true;
15553 continue;
15554 }
15555
15556 CXXCastPath BasePath;
15557 BasePath.push_back(&Base);
15558
15559 // Construct the "from" expression, which is an implicit cast to the
15560 // appropriately-qualified base type.
15561 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15562
15563 // Implicitly cast "this" to the appropriately-qualified base type.
15564 // Dereference "this".
15565 CastBuilder To(
15566 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15567 : static_cast<ExprBuilder &>(*DerefThis),
15568 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15569 VK_LValue, BasePath);
15570
15571 // Build the move.
15572 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15573 To, From,
15574 /*CopyingBaseSubobject=*/true,
15575 /*Copying=*/false);
15576 if (Move.isInvalid()) {
15577 MoveAssignOperator->setInvalidDecl();
15578 return;
15579 }
15580
15581 // Success! Record the move.
15582 Statements.push_back(Move.getAs<Expr>());
15583 }
15584
15585 // Assign non-static members.
15586 for (auto *Field : ClassDecl->fields()) {
15587 // FIXME: We should form some kind of AST representation for the implied
15588 // memcpy in a union copy operation.
15589 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15590 continue;
15591
15592 if (Field->isInvalidDecl()) {
15593 Invalid = true;
15594 continue;
15595 }
15596
15597 // Check for members of reference type; we can't move those.
15598 if (Field->getType()->isReferenceType()) {
15599 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15600 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15601 Diag(Field->getLocation(), diag::note_declared_at);
15602 Invalid = true;
15603 continue;
15604 }
15605
15606 // Check for members of const-qualified, non-class type.
15607 QualType BaseType = Context.getBaseElementType(Field->getType());
15608 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15609 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15610 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15611 Diag(Field->getLocation(), diag::note_declared_at);
15612 Invalid = true;
15613 continue;
15614 }
15615
15616 // Suppress assigning zero-width bitfields.
15617 if (Field->isZeroLengthBitField(Context))
15618 continue;
15619
15620 QualType FieldType = Field->getType().getNonReferenceType();
15621 if (FieldType->isIncompleteArrayType()) {
15622 assert(ClassDecl->hasFlexibleArrayMember() &&
15623 "Incomplete array type is not valid");
15624 continue;
15625 }
15626
15627 // Build references to the field in the object we're copying from and to.
15628 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15630 MemberLookup.addDecl(Field);
15631 MemberLookup.resolveKind();
15632 MemberBuilder From(MoveOther, OtherRefType,
15633 /*IsArrow=*/false, MemberLookup);
15634 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15635 MemberLookup);
15636
15637 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15638 "Member reference with rvalue base must be rvalue except for reference "
15639 "members, which aren't allowed for move assignment.");
15640
15641 // Build the move of this field.
15642 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15643 To, From,
15644 /*CopyingBaseSubobject=*/false,
15645 /*Copying=*/false);
15646 if (Move.isInvalid()) {
15647 MoveAssignOperator->setInvalidDecl();
15648 return;
15649 }
15650
15651 // Success! Record the copy.
15652 Statements.push_back(Move.getAs<Stmt>());
15653 }
15654
15655 if (!Invalid) {
15656 // Add a "return *this;"
15657 Expr *ThisExpr =
15658 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15659 : static_cast<ExprBuilder &>(*DerefThis))
15660 .build(*this, Loc);
15661
15662 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15663 if (Return.isInvalid())
15664 Invalid = true;
15665 else
15666 Statements.push_back(Return.getAs<Stmt>());
15667 }
15668
15669 if (Invalid) {
15670 MoveAssignOperator->setInvalidDecl();
15671 return;
15672 }
15673
15674 StmtResult Body;
15675 {
15676 CompoundScopeRAII CompoundScope(*this);
15677 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15678 /*isStmtExpr=*/false);
15679 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15680 }
15681 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15682 MoveAssignOperator->markUsed(Context);
15683
15685 L->CompletedImplicitDefinition(MoveAssignOperator);
15686 }
15687}
15688
15690 CXXRecordDecl *ClassDecl) {
15691 // C++ [class.copy]p4:
15692 // If the class definition does not explicitly declare a copy
15693 // constructor, one is declared implicitly.
15694 assert(ClassDecl->needsImplicitCopyConstructor());
15695
15696 DeclaringSpecialMember DSM(*this, ClassDecl,
15698 if (DSM.isAlreadyBeingDeclared())
15699 return nullptr;
15700
15701 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15702 QualType ArgType = ClassType;
15704 ArgType, nullptr);
15705 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15706 if (Const)
15707 ArgType = ArgType.withConst();
15708
15710 if (AS != LangAS::Default)
15711 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15712
15713 ArgType = Context.getLValueReferenceType(ArgType);
15714
15716 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15717
15718 DeclarationName Name
15720 Context.getCanonicalType(ClassType));
15721 SourceLocation ClassLoc = ClassDecl->getLocation();
15722 DeclarationNameInfo NameInfo(Name, ClassLoc);
15723
15724 // An implicitly-declared copy constructor is an inline public
15725 // member of its class.
15727 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15728 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15729 /*isInline=*/true,
15730 /*isImplicitlyDeclared=*/true,
15733 CopyConstructor->setAccess(AS_public);
15734 CopyConstructor->setDefaulted();
15735
15736 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15737
15738 if (getLangOpts().CUDA)
15741 /* ConstRHS */ Const,
15742 /* Diagnose */ false);
15743
15744 // During template instantiation of special member functions we need a
15745 // reliable TypeSourceInfo for the parameter types in order to allow functions
15746 // to be substituted.
15747 TypeSourceInfo *TSI = nullptr;
15748 if (inTemplateInstantiation() && ClassDecl->isLambda())
15749 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15750
15751 // Add the parameter to the constructor.
15752 ParmVarDecl *FromParam =
15753 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15754 /*IdentifierInfo=*/nullptr, ArgType,
15755 /*TInfo=*/TSI, SC_None, nullptr);
15756 CopyConstructor->setParams(FromParam);
15757
15758 CopyConstructor->setTrivial(
15762 : ClassDecl->hasTrivialCopyConstructor());
15763
15764 CopyConstructor->setTrivialForCall(
15765 ClassDecl->hasAttr<TrivialABIAttr>() ||
15770 : ClassDecl->hasTrivialCopyConstructorForCall()));
15771
15772 // Note that we have declared this constructor.
15774
15775 Scope *S = getScopeForContext(ClassDecl);
15777
15782 }
15783
15784 if (S)
15786 ClassDecl->addDecl(CopyConstructor);
15787
15788 return CopyConstructor;
15789}
15790
15793 assert((CopyConstructor->isDefaulted() &&
15794 CopyConstructor->isCopyConstructor() &&
15795 !CopyConstructor->doesThisDeclarationHaveABody() &&
15796 !CopyConstructor->isDeleted()) &&
15797 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15798 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15799 return;
15800
15801 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15802 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15803
15805
15806 // The exception specification is needed because we are defining the
15807 // function.
15808 ResolveExceptionSpec(CurrentLocation,
15809 CopyConstructor->getType()->castAs<FunctionProtoType>());
15810 MarkVTableUsed(CurrentLocation, ClassDecl);
15811
15812 // Add a context note for diagnostics produced after this point.
15813 Scope.addContextNote(CurrentLocation);
15814
15815 // C++11 [class.copy]p7:
15816 // The [definition of an implicitly declared copy constructor] is
15817 // deprecated if the class has a user-declared copy assignment operator
15818 // or a user-declared destructor.
15819 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15821
15822 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15823 CopyConstructor->setInvalidDecl();
15824 } else {
15825 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15826 ? CopyConstructor->getEndLoc()
15827 : CopyConstructor->getLocation();
15828 Sema::CompoundScopeRAII CompoundScope(*this);
15829 CopyConstructor->setBody(
15830 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15831 .getAs<Stmt>());
15832 CopyConstructor->markUsed(Context);
15833 }
15834
15836 L->CompletedImplicitDefinition(CopyConstructor);
15837 }
15838}
15839
15841 CXXRecordDecl *ClassDecl) {
15842 assert(ClassDecl->needsImplicitMoveConstructor());
15843
15844 DeclaringSpecialMember DSM(*this, ClassDecl,
15846 if (DSM.isAlreadyBeingDeclared())
15847 return nullptr;
15848
15849 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15850
15851 QualType ArgType = ClassType;
15853 ArgType, nullptr);
15855 if (AS != LangAS::Default)
15856 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15857 ArgType = Context.getRValueReferenceType(ArgType);
15858
15860 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15861
15862 DeclarationName Name
15864 Context.getCanonicalType(ClassType));
15865 SourceLocation ClassLoc = ClassDecl->getLocation();
15866 DeclarationNameInfo NameInfo(Name, ClassLoc);
15867
15868 // C++11 [class.copy]p11:
15869 // An implicitly-declared copy/move constructor is an inline public
15870 // member of its class.
15872 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15873 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15874 /*isInline=*/true,
15875 /*isImplicitlyDeclared=*/true,
15878 MoveConstructor->setAccess(AS_public);
15879 MoveConstructor->setDefaulted();
15880
15881 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15882
15883 if (getLangOpts().CUDA)
15886 /* ConstRHS */ false,
15887 /* Diagnose */ false);
15888
15889 // Add the parameter to the constructor.
15891 ClassLoc, ClassLoc,
15892 /*IdentifierInfo=*/nullptr,
15893 ArgType, /*TInfo=*/nullptr,
15894 SC_None, nullptr);
15895 MoveConstructor->setParams(FromParam);
15896
15897 MoveConstructor->setTrivial(
15901 : ClassDecl->hasTrivialMoveConstructor());
15902
15903 MoveConstructor->setTrivialForCall(
15904 ClassDecl->hasAttr<TrivialABIAttr>() ||
15909 : ClassDecl->hasTrivialMoveConstructorForCall()));
15910
15911 // Note that we have declared this constructor.
15913
15914 Scope *S = getScopeForContext(ClassDecl);
15916
15921 }
15922
15923 if (S)
15925 ClassDecl->addDecl(MoveConstructor);
15926
15927 return MoveConstructor;
15928}
15929
15932 assert((MoveConstructor->isDefaulted() &&
15933 MoveConstructor->isMoveConstructor() &&
15934 !MoveConstructor->doesThisDeclarationHaveABody() &&
15935 !MoveConstructor->isDeleted()) &&
15936 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15937 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15938 return;
15939
15940 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15941 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15942
15944
15945 // The exception specification is needed because we are defining the
15946 // function.
15947 ResolveExceptionSpec(CurrentLocation,
15948 MoveConstructor->getType()->castAs<FunctionProtoType>());
15949 MarkVTableUsed(CurrentLocation, ClassDecl);
15950
15951 // Add a context note for diagnostics produced after this point.
15952 Scope.addContextNote(CurrentLocation);
15953
15954 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15955 MoveConstructor->setInvalidDecl();
15956 } else {
15957 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15958 ? MoveConstructor->getEndLoc()
15959 : MoveConstructor->getLocation();
15960 Sema::CompoundScopeRAII CompoundScope(*this);
15961 MoveConstructor->setBody(
15962 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15963 .getAs<Stmt>());
15964 MoveConstructor->markUsed(Context);
15965 }
15966
15968 L->CompletedImplicitDefinition(MoveConstructor);
15969 }
15970}
15971
15973 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15974}
15975
15977 SourceLocation CurrentLocation,
15978 CXXConversionDecl *Conv) {
15979 SynthesizedFunctionScope Scope(*this, Conv);
15980 assert(!Conv->getReturnType()->isUndeducedType());
15981
15982 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15983 CallingConv CC =
15984 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15985
15986 CXXRecordDecl *Lambda = Conv->getParent();
15987 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15988 FunctionDecl *Invoker =
15989 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15990 ? CallOp
15991 : Lambda->getLambdaStaticInvoker(CC);
15992
15993 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15995 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15996 if (!CallOp)
15997 return;
15998
15999 if (CallOp != Invoker) {
16001 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16002 CurrentLocation);
16003 if (!Invoker)
16004 return;
16005 }
16006 }
16007
16008 if (CallOp->isInvalidDecl())
16009 return;
16010
16011 // Mark the call operator referenced (and add to pending instantiations
16012 // if necessary).
16013 // For both the conversion and static-invoker template specializations
16014 // we construct their body's in this function, so no need to add them
16015 // to the PendingInstantiations.
16016 MarkFunctionReferenced(CurrentLocation, CallOp);
16017
16018 if (Invoker != CallOp) {
16019 // Fill in the __invoke function with a dummy implementation. IR generation
16020 // will fill in the actual details. Update its type in case it contained
16021 // an 'auto'.
16022 Invoker->markUsed(Context);
16023 Invoker->setReferenced();
16024 Invoker->setType(Conv->getReturnType()->getPointeeType());
16025 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16026 }
16027
16028 // Construct the body of the conversion function { return __invoke; }.
16029 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16030 Conv->getLocation());
16031 assert(FunctionRef && "Can't refer to __invoke function?");
16032 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16034 Conv->getLocation(), Conv->getLocation()));
16035 Conv->markUsed(Context);
16036 Conv->setReferenced();
16037
16039 L->CompletedImplicitDefinition(Conv);
16040 if (Invoker != CallOp)
16041 L->CompletedImplicitDefinition(Invoker);
16042 }
16043}
16044
16046 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16047 assert(!Conv->getParent()->isGenericLambda());
16048
16049 SynthesizedFunctionScope Scope(*this, Conv);
16050
16051 // Copy-initialize the lambda object as needed to capture it.
16052 Expr *This = ActOnCXXThis(CurrentLocation).get();
16053 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16054
16055 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16056 Conv->getLocation(),
16057 Conv, DerefThis);
16058
16059 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16060 // behavior. Note that only the general conversion function does this
16061 // (since it's unusable otherwise); in the case where we inline the
16062 // block literal, it has block literal lifetime semantics.
16063 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16064 BuildBlock = ImplicitCastExpr::Create(
16065 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16066 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16067
16068 if (BuildBlock.isInvalid()) {
16069 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16070 Conv->setInvalidDecl();
16071 return;
16072 }
16073
16074 // Create the return statement that returns the block from the conversion
16075 // function.
16076 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16077 if (Return.isInvalid()) {
16078 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16079 Conv->setInvalidDecl();
16080 return;
16081 }
16082
16083 // Set the body of the conversion function.
16084 Stmt *ReturnS = Return.get();
16086 Conv->getLocation(), Conv->getLocation()));
16087 Conv->markUsed(Context);
16088
16089 // We're done; notify the mutation listener, if any.
16091 L->CompletedImplicitDefinition(Conv);
16092 }
16093}
16094
16095/// Determine whether the given list arguments contains exactly one
16096/// "real" (non-default) argument.
16098 switch (Args.size()) {
16099 case 0:
16100 return false;
16101
16102 default:
16103 if (!Args[1]->isDefaultArgument())
16104 return false;
16105
16106 [[fallthrough]];
16107 case 1:
16108 return !Args[0]->isDefaultArgument();
16109 }
16110
16111 return false;
16112}
16113
16115 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16116 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16117 bool HadMultipleCandidates, bool IsListInitialization,
16118 bool IsStdInitListInitialization, bool RequiresZeroInit,
16119 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16120 bool Elidable = false;
16121
16122 // C++0x [class.copy]p34:
16123 // When certain criteria are met, an implementation is allowed to
16124 // omit the copy/move construction of a class object, even if the
16125 // copy/move constructor and/or destructor for the object have
16126 // side effects. [...]
16127 // - when a temporary class object that has not been bound to a
16128 // reference (12.2) would be copied/moved to a class object
16129 // with the same cv-unqualified type, the copy/move operation
16130 // can be omitted by constructing the temporary object
16131 // directly into the target of the omitted copy/move
16132 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16133 // FIXME: Converting constructors should also be accepted.
16134 // But to fix this, the logic that digs down into a CXXConstructExpr
16135 // to find the source object needs to handle it.
16136 // Right now it assumes the source object is passed directly as the
16137 // first argument.
16138 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16139 Expr *SubExpr = ExprArgs[0];
16140 // FIXME: Per above, this is also incorrect if we want to accept
16141 // converting constructors, as isTemporaryObject will
16142 // reject temporaries with different type from the
16143 // CXXRecord itself.
16144 Elidable = SubExpr->isTemporaryObject(
16145 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16146 }
16147
16148 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16149 FoundDecl, Constructor,
16150 Elidable, ExprArgs, HadMultipleCandidates,
16151 IsListInitialization,
16152 IsStdInitListInitialization, RequiresZeroInit,
16153 ConstructKind, ParenRange);
16154}
16155
16157 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16158 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16159 bool HadMultipleCandidates, bool IsListInitialization,
16160 bool IsStdInitListInitialization, bool RequiresZeroInit,
16161 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16162 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16163 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16164 // The only way to get here is if we did overlaod resolution to find the
16165 // shadow decl, so we don't need to worry about re-checking the trailing
16166 // requires clause.
16167 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16168 return ExprError();
16169 }
16170
16171 return BuildCXXConstructExpr(
16172 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16173 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16174 RequiresZeroInit, ConstructKind, ParenRange);
16175}
16176
16177/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16178/// including handling of its default argument expressions.
16180 SourceLocation ConstructLoc, QualType DeclInitType,
16181 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16182 bool HadMultipleCandidates, bool IsListInitialization,
16183 bool IsStdInitListInitialization, bool RequiresZeroInit,
16184 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16185 assert(declaresSameEntity(
16186 Constructor->getParent(),
16187 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16188 "given constructor for wrong type");
16189 MarkFunctionReferenced(ConstructLoc, Constructor);
16190 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16191 return ExprError();
16192
16195 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16196 HadMultipleCandidates, IsListInitialization,
16197 IsStdInitListInitialization, RequiresZeroInit,
16198 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16199 Constructor);
16200}
16201
16203 if (VD->isInvalidDecl()) return;
16204 // If initializing the variable failed, don't also diagnose problems with
16205 // the destructor, they're likely related.
16206 if (VD->getInit() && VD->getInit()->containsErrors())
16207 return;
16208
16209 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16210 if (ClassDecl->isInvalidDecl()) return;
16211 if (ClassDecl->hasIrrelevantDestructor()) return;
16212 if (ClassDecl->isDependentContext()) return;
16213
16214 if (VD->isNoDestroy(getASTContext()))
16215 return;
16216
16218 // The result of `LookupDestructor` might be nullptr if the destructor is
16219 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16220 // will not be selected by `CXXRecordDecl::getDestructor()`.
16221 if (!Destructor)
16222 return;
16223 // If this is an array, we'll require the destructor during initialization, so
16224 // we can skip over this. We still want to emit exit-time destructor warnings
16225 // though.
16226 if (!VD->getType()->isArrayType()) {
16229 PDiag(diag::err_access_dtor_var)
16230 << VD->getDeclName() << VD->getType());
16232 }
16233
16234 if (Destructor->isTrivial()) return;
16235
16236 // If the destructor is constexpr, check whether the variable has constant
16237 // destruction now.
16238 if (Destructor->isConstexpr()) {
16239 bool HasConstantInit = false;
16240 if (VD->getInit() && !VD->getInit()->isValueDependent())
16241 HasConstantInit = VD->evaluateValue();
16243 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16244 HasConstantInit) {
16245 Diag(VD->getLocation(),
16246 diag::err_constexpr_var_requires_const_destruction) << VD;
16247 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16248 Diag(Notes[I].first, Notes[I].second);
16249 }
16250 }
16251
16252 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16253 return;
16254
16255 // Emit warning for non-trivial dtor in global scope (a real global,
16256 // class-static, function-static).
16257 if (!VD->hasAttr<AlwaysDestroyAttr>())
16258 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16259
16260 // TODO: this should be re-enabled for static locals by !CXAAtExit
16261 if (!VD->isStaticLocal())
16262 Diag(VD->getLocation(), diag::warn_global_destructor);
16263}
16264
16265/// Given a constructor and the set of arguments provided for the
16266/// constructor, convert the arguments and add any required default arguments
16267/// to form a proper call to this constructor.
16268///
16269/// \returns true if an error occurred, false otherwise.
16271 QualType DeclInitType, MultiExprArg ArgsPtr,
16272 SourceLocation Loc,
16273 SmallVectorImpl<Expr *> &ConvertedArgs,
16274 bool AllowExplicit,
16275 bool IsListInitialization) {
16276 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16277 unsigned NumArgs = ArgsPtr.size();
16278 Expr **Args = ArgsPtr.data();
16279
16280 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16281 unsigned NumParams = Proto->getNumParams();
16282
16283 // If too few arguments are available, we'll fill in the rest with defaults.
16284 if (NumArgs < NumParams)
16285 ConvertedArgs.reserve(NumParams);
16286 else
16287 ConvertedArgs.reserve(NumArgs);
16288
16289 VariadicCallType CallType =
16290 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16291 SmallVector<Expr *, 8> AllArgs;
16293 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16294 CallType, AllowExplicit, IsListInitialization);
16295 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16296
16297 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16298
16299 CheckConstructorCall(Constructor, DeclInitType,
16300 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16301 Loc);
16302
16303 return Invalid;
16304}
16305
16306static inline bool
16308 const FunctionDecl *FnDecl) {
16309 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16310 if (isa<NamespaceDecl>(DC)) {
16311 return SemaRef.Diag(FnDecl->getLocation(),
16312 diag::err_operator_new_delete_declared_in_namespace)
16313 << FnDecl->getDeclName();
16314 }
16315
16316 if (isa<TranslationUnitDecl>(DC) &&
16317 FnDecl->getStorageClass() == SC_Static) {
16318 return SemaRef.Diag(FnDecl->getLocation(),
16319 diag::err_operator_new_delete_declared_static)
16320 << FnDecl->getDeclName();
16321 }
16322
16323 return false;
16324}
16325
16327 const PointerType *PtrTy) {
16328 auto &Ctx = SemaRef.Context;
16329 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16330 PtrQuals.removeAddressSpace();
16331 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16332 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16333}
16334
16335static inline bool
16337 CanQualType ExpectedResultType,
16338 CanQualType ExpectedFirstParamType,
16339 unsigned DependentParamTypeDiag,
16340 unsigned InvalidParamTypeDiag) {
16341 QualType ResultType =
16342 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16343
16344 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16345 // The operator is valid on any address space for OpenCL.
16346 // Drop address space from actual and expected result types.
16347 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16348 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16349
16350 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16351 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16352 }
16353
16354 // Check that the result type is what we expect.
16355 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16356 // Reject even if the type is dependent; an operator delete function is
16357 // required to have a non-dependent result type.
16358 return SemaRef.Diag(
16359 FnDecl->getLocation(),
16360 ResultType->isDependentType()
16361 ? diag::err_operator_new_delete_dependent_result_type
16362 : diag::err_operator_new_delete_invalid_result_type)
16363 << FnDecl->getDeclName() << ExpectedResultType;
16364 }
16365
16366 // A function template must have at least 2 parameters.
16367 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16368 return SemaRef.Diag(FnDecl->getLocation(),
16369 diag::err_operator_new_delete_template_too_few_parameters)
16370 << FnDecl->getDeclName();
16371
16372 // The function decl must have at least 1 parameter.
16373 if (FnDecl->getNumParams() == 0)
16374 return SemaRef.Diag(FnDecl->getLocation(),
16375 diag::err_operator_new_delete_too_few_parameters)
16376 << FnDecl->getDeclName();
16377
16378 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16379 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16380 // The operator is valid on any address space for OpenCL.
16381 // Drop address space from actual and expected first parameter types.
16382 if (const auto *PtrTy =
16383 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16384 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16385
16386 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16387 ExpectedFirstParamType =
16388 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16389 }
16390
16391 // Check that the first parameter type is what we expect.
16392 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16393 ExpectedFirstParamType) {
16394 // The first parameter type is not allowed to be dependent. As a tentative
16395 // DR resolution, we allow a dependent parameter type if it is the right
16396 // type anyway, to allow destroying operator delete in class templates.
16397 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16398 ? DependentParamTypeDiag
16399 : InvalidParamTypeDiag)
16400 << FnDecl->getDeclName() << ExpectedFirstParamType;
16401 }
16402
16403 return false;
16404}
16405
16406static bool
16408 // C++ [basic.stc.dynamic.allocation]p1:
16409 // A program is ill-formed if an allocation function is declared in a
16410 // namespace scope other than global scope or declared static in global
16411 // scope.
16413 return true;
16414
16415 CanQualType SizeTy =
16417
16418 // C++ [basic.stc.dynamic.allocation]p1:
16419 // The return type shall be void*. The first parameter shall have type
16420 // std::size_t.
16422 SizeTy,
16423 diag::err_operator_new_dependent_param_type,
16424 diag::err_operator_new_param_type))
16425 return true;
16426
16427 // C++ [basic.stc.dynamic.allocation]p1:
16428 // The first parameter shall not have an associated default argument.
16429 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16430 return SemaRef.Diag(FnDecl->getLocation(),
16431 diag::err_operator_new_default_arg)
16432 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16433
16434 return false;
16435}
16436
16437static bool
16439 // C++ [basic.stc.dynamic.deallocation]p1:
16440 // A program is ill-formed if deallocation functions are declared in a
16441 // namespace scope other than global scope or declared static in global
16442 // scope.
16444 return true;
16445
16446 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16447
16448 // C++ P0722:
16449 // Within a class C, the first parameter of a destroying operator delete
16450 // shall be of type C *. The first parameter of any other deallocation
16451 // function shall be of type void *.
16452 CanQualType ExpectedFirstParamType =
16453 MD && MD->isDestroyingOperatorDelete()
16457
16458 // C++ [basic.stc.dynamic.deallocation]p2:
16459 // Each deallocation function shall return void
16461 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16462 diag::err_operator_delete_dependent_param_type,
16463 diag::err_operator_delete_param_type))
16464 return true;
16465
16466 // C++ P0722:
16467 // A destroying operator delete shall be a usual deallocation function.
16468 if (MD && !MD->getParent()->isDependentContext() &&
16471 SemaRef.Diag(MD->getLocation(),
16472 diag::err_destroying_operator_delete_not_usual);
16473 return true;
16474 }
16475
16476 return false;
16477}
16478
16479/// CheckOverloadedOperatorDeclaration - Check whether the declaration
16480/// of this overloaded operator is well-formed. If so, returns false;
16481/// otherwise, emits appropriate diagnostics and returns true.
16483 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16484 "Expected an overloaded operator declaration");
16485
16487
16488 // C++ [over.oper]p5:
16489 // The allocation and deallocation functions, operator new,
16490 // operator new[], operator delete and operator delete[], are
16491 // described completely in 3.7.3. The attributes and restrictions
16492 // found in the rest of this subclause do not apply to them unless
16493 // explicitly stated in 3.7.3.
16494 if (Op == OO_Delete || Op == OO_Array_Delete)
16495 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16496
16497 if (Op == OO_New || Op == OO_Array_New)
16498 return CheckOperatorNewDeclaration(*this, FnDecl);
16499
16500 // C++ [over.oper]p7:
16501 // An operator function shall either be a member function or
16502 // be a non-member function and have at least one parameter
16503 // whose type is a class, a reference to a class, an enumeration,
16504 // or a reference to an enumeration.
16505 // Note: Before C++23, a member function could not be static. The only member
16506 // function allowed to be static is the call operator function.
16507 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16508 if (MethodDecl->isStatic()) {
16509 if (Op == OO_Call || Op == OO_Subscript)
16510 Diag(FnDecl->getLocation(),
16511 (LangOpts.CPlusPlus23
16512 ? diag::warn_cxx20_compat_operator_overload_static
16513 : diag::ext_operator_overload_static))
16514 << FnDecl;
16515 else
16516 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16517 << FnDecl;
16518 }
16519 } else {
16520 bool ClassOrEnumParam = false;
16521 for (auto *Param : FnDecl->parameters()) {
16522 QualType ParamType = Param->getType().getNonReferenceType();
16523 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16524 ParamType->isEnumeralType()) {
16525 ClassOrEnumParam = true;
16526 break;
16527 }
16528 }
16529
16530 if (!ClassOrEnumParam)
16531 return Diag(FnDecl->getLocation(),
16532 diag::err_operator_overload_needs_class_or_enum)
16533 << FnDecl->getDeclName();
16534 }
16535
16536 // C++ [over.oper]p8:
16537 // An operator function cannot have default arguments (8.3.6),
16538 // except where explicitly stated below.
16539 //
16540 // Only the function-call operator (C++ [over.call]p1) and the subscript
16541 // operator (CWG2507) allow default arguments.
16542 if (Op != OO_Call) {
16543 ParmVarDecl *FirstDefaultedParam = nullptr;
16544 for (auto *Param : FnDecl->parameters()) {
16545 if (Param->hasDefaultArg()) {
16546 FirstDefaultedParam = Param;
16547 break;
16548 }
16549 }
16550 if (FirstDefaultedParam) {
16551 if (Op == OO_Subscript) {
16552 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16553 ? diag::ext_subscript_overload
16554 : diag::error_subscript_overload)
16555 << FnDecl->getDeclName() << 1
16556 << FirstDefaultedParam->getDefaultArgRange();
16557 } else {
16558 return Diag(FirstDefaultedParam->getLocation(),
16559 diag::err_operator_overload_default_arg)
16560 << FnDecl->getDeclName()
16561 << FirstDefaultedParam->getDefaultArgRange();
16562 }
16563 }
16564 }
16565
16566 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16567 { false, false, false }
16568#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16569 , { Unary, Binary, MemberOnly }
16570#include "clang/Basic/OperatorKinds.def"
16571 };
16572
16573 bool CanBeUnaryOperator = OperatorUses[Op][0];
16574 bool CanBeBinaryOperator = OperatorUses[Op][1];
16575 bool MustBeMemberOperator = OperatorUses[Op][2];
16576
16577 // C++ [over.oper]p8:
16578 // [...] Operator functions cannot have more or fewer parameters
16579 // than the number required for the corresponding operator, as
16580 // described in the rest of this subclause.
16581 unsigned NumParams = FnDecl->getNumParams() +
16582 (isa<CXXMethodDecl>(FnDecl) &&
16584 ? 1
16585 : 0);
16586 if (Op != OO_Call && Op != OO_Subscript &&
16587 ((NumParams == 1 && !CanBeUnaryOperator) ||
16588 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16589 (NumParams > 2))) {
16590 // We have the wrong number of parameters.
16591 unsigned ErrorKind;
16592 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16593 ErrorKind = 2; // 2 -> unary or binary.
16594 } else if (CanBeUnaryOperator) {
16595 ErrorKind = 0; // 0 -> unary
16596 } else {
16597 assert(CanBeBinaryOperator &&
16598 "All non-call overloaded operators are unary or binary!");
16599 ErrorKind = 1; // 1 -> binary
16600 }
16601 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16602 << FnDecl->getDeclName() << NumParams << ErrorKind;
16603 }
16604
16605 if (Op == OO_Subscript && NumParams != 2) {
16606 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16607 ? diag::ext_subscript_overload
16608 : diag::error_subscript_overload)
16609 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16610 }
16611
16612 // Overloaded operators other than operator() and operator[] cannot be
16613 // variadic.
16614 if (Op != OO_Call &&
16615 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16616 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16617 << FnDecl->getDeclName();
16618 }
16619
16620 // Some operators must be member functions.
16621 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16622 return Diag(FnDecl->getLocation(),
16623 diag::err_operator_overload_must_be_member)
16624 << FnDecl->getDeclName();
16625 }
16626
16627 // C++ [over.inc]p1:
16628 // The user-defined function called operator++ implements the
16629 // prefix and postfix ++ operator. If this function is a member
16630 // function with no parameters, or a non-member function with one
16631 // parameter of class or enumeration type, it defines the prefix
16632 // increment operator ++ for objects of that type. If the function
16633 // is a member function with one parameter (which shall be of type
16634 // int) or a non-member function with two parameters (the second
16635 // of which shall be of type int), it defines the postfix
16636 // increment operator ++ for objects of that type.
16637 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16638 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16639 QualType ParamType = LastParam->getType();
16640
16641 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16642 !ParamType->isDependentType())
16643 return Diag(LastParam->getLocation(),
16644 diag::err_operator_overload_post_incdec_must_be_int)
16645 << LastParam->getType() << (Op == OO_MinusMinus);
16646 }
16647
16648 return false;
16649}
16650
16651static bool
16653 FunctionTemplateDecl *TpDecl) {
16654 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16655
16656 // Must have one or two template parameters.
16657 if (TemplateParams->size() == 1) {
16658 NonTypeTemplateParmDecl *PmDecl =
16659 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16660
16661 // The template parameter must be a char parameter pack.
16662 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16664 return false;
16665
16666 // C++20 [over.literal]p5:
16667 // A string literal operator template is a literal operator template
16668 // whose template-parameter-list comprises a single non-type
16669 // template-parameter of class type.
16670 //
16671 // As a DR resolution, we also allow placeholders for deduced class
16672 // template specializations.
16673 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16674 !PmDecl->isTemplateParameterPack() &&
16675 (PmDecl->getType()->isRecordType() ||
16677 return false;
16678 } else if (TemplateParams->size() == 2) {
16679 TemplateTypeParmDecl *PmType =
16680 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16681 NonTypeTemplateParmDecl *PmArgs =
16682 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16683
16684 // The second template parameter must be a parameter pack with the
16685 // first template parameter as its type.
16686 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16687 PmArgs->isTemplateParameterPack()) {
16688 const TemplateTypeParmType *TArgs =
16689 PmArgs->getType()->getAs<TemplateTypeParmType>();
16690 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16691 TArgs->getIndex() == PmType->getIndex()) {
16693 SemaRef.Diag(TpDecl->getLocation(),
16694 diag::ext_string_literal_operator_template);
16695 return false;
16696 }
16697 }
16698 }
16699
16701 diag::err_literal_operator_template)
16702 << TpDecl->getTemplateParameters()->getSourceRange();
16703 return true;
16704}
16705
16706/// CheckLiteralOperatorDeclaration - Check whether the declaration
16707/// of this literal operator function is well-formed. If so, returns
16708/// false; otherwise, emits appropriate diagnostics and returns true.
16710 if (isa<CXXMethodDecl>(FnDecl)) {
16711 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16712 << FnDecl->getDeclName();
16713 return true;
16714 }
16715
16716 if (FnDecl->isExternC()) {
16717 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16718 if (const LinkageSpecDecl *LSD =
16719 FnDecl->getDeclContext()->getExternCContext())
16720 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16721 return true;
16722 }
16723
16724 // This might be the definition of a literal operator template.
16726
16727 // This might be a specialization of a literal operator template.
16728 if (!TpDecl)
16729 TpDecl = FnDecl->getPrimaryTemplate();
16730
16731 // template <char...> type operator "" name() and
16732 // template <class T, T...> type operator "" name() are the only valid
16733 // template signatures, and the only valid signatures with no parameters.
16734 //
16735 // C++20 also allows template <SomeClass T> type operator "" name().
16736 if (TpDecl) {
16737 if (FnDecl->param_size() != 0) {
16738 Diag(FnDecl->getLocation(),
16739 diag::err_literal_operator_template_with_params);
16740 return true;
16741 }
16742
16744 return true;
16745
16746 } else if (FnDecl->param_size() == 1) {
16747 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16748
16749 QualType ParamType = Param->getType().getUnqualifiedType();
16750
16751 // Only unsigned long long int, long double, any character type, and const
16752 // char * are allowed as the only parameters.
16753 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16754 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16755 Context.hasSameType(ParamType, Context.CharTy) ||
16756 Context.hasSameType(ParamType, Context.WideCharTy) ||
16757 Context.hasSameType(ParamType, Context.Char8Ty) ||
16758 Context.hasSameType(ParamType, Context.Char16Ty) ||
16759 Context.hasSameType(ParamType, Context.Char32Ty)) {
16760 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16761 QualType InnerType = Ptr->getPointeeType();
16762
16763 // Pointer parameter must be a const char *.
16764 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16765 Context.CharTy) &&
16766 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16767 Diag(Param->getSourceRange().getBegin(),
16768 diag::err_literal_operator_param)
16769 << ParamType << "'const char *'" << Param->getSourceRange();
16770 return true;
16771 }
16772
16773 } else if (ParamType->isRealFloatingType()) {
16774 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16775 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16776 return true;
16777
16778 } else if (ParamType->isIntegerType()) {
16779 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16780 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16781 return true;
16782
16783 } else {
16784 Diag(Param->getSourceRange().getBegin(),
16785 diag::err_literal_operator_invalid_param)
16786 << ParamType << Param->getSourceRange();
16787 return true;
16788 }
16789
16790 } else if (FnDecl->param_size() == 2) {
16791 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16792
16793 // First, verify that the first parameter is correct.
16794
16795 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16796
16797 // Two parameter function must have a pointer to const as a
16798 // first parameter; let's strip those qualifiers.
16799 const PointerType *PT = FirstParamType->getAs<PointerType>();
16800
16801 if (!PT) {
16802 Diag((*Param)->getSourceRange().getBegin(),
16803 diag::err_literal_operator_param)
16804 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16805 return true;
16806 }
16807
16808 QualType PointeeType = PT->getPointeeType();
16809 // First parameter must be const
16810 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16811 Diag((*Param)->getSourceRange().getBegin(),
16812 diag::err_literal_operator_param)
16813 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16814 return true;
16815 }
16816
16817 QualType InnerType = PointeeType.getUnqualifiedType();
16818 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16819 // const char32_t* are allowed as the first parameter to a two-parameter
16820 // function
16821 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16822 Context.hasSameType(InnerType, Context.WideCharTy) ||
16823 Context.hasSameType(InnerType, Context.Char8Ty) ||
16824 Context.hasSameType(InnerType, Context.Char16Ty) ||
16825 Context.hasSameType(InnerType, Context.Char32Ty))) {
16826 Diag((*Param)->getSourceRange().getBegin(),
16827 diag::err_literal_operator_param)
16828 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16829 return true;
16830 }
16831
16832 // Move on to the second and final parameter.
16833 ++Param;
16834
16835 // The second parameter must be a std::size_t.
16836 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16837 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16838 Diag((*Param)->getSourceRange().getBegin(),
16839 diag::err_literal_operator_param)
16840 << SecondParamType << Context.getSizeType()
16841 << (*Param)->getSourceRange();
16842 return true;
16843 }
16844 } else {
16845 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16846 return true;
16847 }
16848
16849 // Parameters are good.
16850
16851 // A parameter-declaration-clause containing a default argument is not
16852 // equivalent to any of the permitted forms.
16853 for (auto *Param : FnDecl->parameters()) {
16854 if (Param->hasDefaultArg()) {
16855 Diag(Param->getDefaultArgRange().getBegin(),
16856 diag::err_literal_operator_default_argument)
16857 << Param->getDefaultArgRange();
16858 break;
16859 }
16860 }
16861
16862 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16865 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16866 // C++23 [usrlit.suffix]p1:
16867 // Literal suffix identifiers that do not start with an underscore are
16868 // reserved for future standardization. Literal suffix identifiers that
16869 // contain a double underscore __ are reserved for use by C++
16870 // implementations.
16871 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16872 << static_cast<int>(Status)
16874 }
16875
16876 return false;
16877}
16878
16879/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16880/// linkage specification, including the language and (if present)
16881/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16882/// language string literal. LBraceLoc, if valid, provides the location of
16883/// the '{' brace. Otherwise, this linkage specification does not
16884/// have any braces.
16886 Expr *LangStr,
16887 SourceLocation LBraceLoc) {
16888 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16889 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16890
16891 StringRef Lang = Lit->getString();
16893 if (Lang == "C")
16895 else if (Lang == "C++")
16897 else {
16898 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16899 << LangStr->getSourceRange();
16900 return nullptr;
16901 }
16902
16903 // FIXME: Add all the various semantics of linkage specifications
16904
16906 LangStr->getExprLoc(), Language,
16907 LBraceLoc.isValid());
16908
16909 /// C++ [module.unit]p7.2.3
16910 /// - Otherwise, if the declaration
16911 /// - ...
16912 /// - ...
16913 /// - appears within a linkage-specification,
16914 /// it is attached to the global module.
16915 ///
16916 /// If the declaration is already in global module fragment, we don't
16917 /// need to attach it again.
16918 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16919 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16920 D->setLocalOwningModule(GlobalModule);
16921 }
16922
16923 CurContext->addDecl(D);
16924 PushDeclContext(S, D);
16925 return D;
16926}
16927
16928/// ActOnFinishLinkageSpecification - Complete the definition of
16929/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16930/// valid, it's the position of the closing '}' brace in a linkage
16931/// specification that uses braces.
16933 Decl *LinkageSpec,
16934 SourceLocation RBraceLoc) {
16935 if (RBraceLoc.isValid()) {
16936 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16937 LSDecl->setRBraceLoc(RBraceLoc);
16938 }
16939
16940 // If the current module doesn't has Parent, it implies that the
16941 // LinkageSpec isn't in the module created by itself. So we don't
16942 // need to pop it.
16943 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16944 getCurrentModule()->isImplicitGlobalModule() &&
16946 PopImplicitGlobalModuleFragment();
16947
16949 return LinkageSpec;
16950}
16951
16953 const ParsedAttributesView &AttrList,
16954 SourceLocation SemiLoc) {
16955 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16956 // Attribute declarations appertain to empty declaration so we handle
16957 // them here.
16958 ProcessDeclAttributeList(S, ED, AttrList);
16959
16960 CurContext->addDecl(ED);
16961 return ED;
16962}
16963
16964/// Perform semantic analysis for the variable declaration that
16965/// occurs within a C++ catch clause, returning the newly-created
16966/// variable.
16968 SourceLocation StartLoc,
16969 SourceLocation Loc,
16970 const IdentifierInfo *Name) {
16971 bool Invalid = false;
16972 QualType ExDeclType = TInfo->getType();
16973
16974 // Arrays and functions decay.
16975 if (ExDeclType->isArrayType())
16976 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16977 else if (ExDeclType->isFunctionType())
16978 ExDeclType = Context.getPointerType(ExDeclType);
16979
16980 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16981 // The exception-declaration shall not denote a pointer or reference to an
16982 // incomplete type, other than [cv] void*.
16983 // N2844 forbids rvalue references.
16984 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16985 Diag(Loc, diag::err_catch_rvalue_ref);
16986 Invalid = true;
16987 }
16988
16989 if (ExDeclType->isVariablyModifiedType()) {
16990 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16991 Invalid = true;
16992 }
16993
16994 QualType BaseType = ExDeclType;
16995 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16996 unsigned DK = diag::err_catch_incomplete;
16997 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16998 BaseType = Ptr->getPointeeType();
16999 Mode = 1;
17000 DK = diag::err_catch_incomplete_ptr;
17001 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17002 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17003 BaseType = Ref->getPointeeType();
17004 Mode = 2;
17005 DK = diag::err_catch_incomplete_ref;
17006 }
17007 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17008 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17009 Invalid = true;
17010
17011 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17012 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17013 Invalid = true;
17014 }
17015
17016 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17017 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17018 Invalid = true;
17019 }
17020
17021 if (!Invalid && !ExDeclType->isDependentType() &&
17022 RequireNonAbstractType(Loc, ExDeclType,
17023 diag::err_abstract_type_in_decl,
17025 Invalid = true;
17026
17027 // Only the non-fragile NeXT runtime currently supports C++ catches
17028 // of ObjC types, and no runtime supports catching ObjC types by value.
17029 if (!Invalid && getLangOpts().ObjC) {
17030 QualType T = ExDeclType;
17031 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17032 T = RT->getPointeeType();
17033
17034 if (T->isObjCObjectType()) {
17035 Diag(Loc, diag::err_objc_object_catch);
17036 Invalid = true;
17037 } else if (T->isObjCObjectPointerType()) {
17038 // FIXME: should this be a test for macosx-fragile specifically?
17040 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17041 }
17042 }
17043
17044 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17045 ExDeclType, TInfo, SC_None);
17046 ExDecl->setExceptionVariable(true);
17047
17048 // In ARC, infer 'retaining' for variables of retainable type.
17049 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
17050 Invalid = true;
17051
17052 if (!Invalid && !ExDeclType->isDependentType()) {
17053 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
17054 // Insulate this from anything else we might currently be parsing.
17057
17058 // C++ [except.handle]p16:
17059 // The object declared in an exception-declaration or, if the
17060 // exception-declaration does not specify a name, a temporary (12.2) is
17061 // copy-initialized (8.5) from the exception object. [...]
17062 // The object is destroyed when the handler exits, after the destruction
17063 // of any automatic objects initialized within the handler.
17064 //
17065 // We just pretend to initialize the object with itself, then make sure
17066 // it can be destroyed later.
17067 QualType initType = Context.getExceptionObjectType(ExDeclType);
17068
17069 InitializedEntity entity =
17071 InitializationKind initKind =
17073
17074 Expr *opaqueValue =
17075 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17076 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17077 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17078 if (result.isInvalid())
17079 Invalid = true;
17080 else {
17081 // If the constructor used was non-trivial, set this as the
17082 // "initializer".
17083 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17084 if (!construct->getConstructor()->isTrivial()) {
17085 Expr *init = MaybeCreateExprWithCleanups(construct);
17086 ExDecl->setInit(init);
17087 }
17088
17089 // And make sure it's destructable.
17091 }
17092 }
17093 }
17094
17095 if (Invalid)
17096 ExDecl->setInvalidDecl();
17097
17098 return ExDecl;
17099}
17100
17101/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17102/// handler.
17105 bool Invalid = D.isInvalidType();
17106
17107 // Check for unexpanded parameter packs.
17111 D.getIdentifierLoc());
17112 Invalid = true;
17113 }
17114
17115 const IdentifierInfo *II = D.getIdentifier();
17116 if (NamedDecl *PrevDecl =
17118 RedeclarationKind::ForVisibleRedeclaration)) {
17119 // The scope should be freshly made just for us. There is just no way
17120 // it contains any previous declaration, except for function parameters in
17121 // a function-try-block's catch statement.
17122 assert(!S->isDeclScope(PrevDecl));
17123 if (isDeclInScope(PrevDecl, CurContext, S)) {
17124 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17125 << D.getIdentifier();
17126 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17127 Invalid = true;
17128 } else if (PrevDecl->isTemplateParameter())
17129 // Maybe we will complain about the shadowed template parameter.
17131 }
17132
17133 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17134 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17135 << D.getCXXScopeSpec().getRange();
17136 Invalid = true;
17137 }
17138
17140 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17141 if (Invalid)
17142 ExDecl->setInvalidDecl();
17143
17144 // Add the exception declaration into this scope.
17145 if (II)
17146 PushOnScopeChains(ExDecl, S);
17147 else
17148 CurContext->addDecl(ExDecl);
17149
17150 ProcessDeclAttributes(S, ExDecl, D);
17151 return ExDecl;
17152}
17153
17155 Expr *AssertExpr,
17156 Expr *AssertMessageExpr,
17157 SourceLocation RParenLoc) {
17159 return nullptr;
17160
17161 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17162 AssertMessageExpr, RParenLoc, false);
17163}
17164
17165static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17166 switch (BTK) {
17167 case BuiltinType::Char_S:
17168 case BuiltinType::Char_U:
17169 break;
17170 case BuiltinType::Char8:
17171 OS << "u8";
17172 break;
17173 case BuiltinType::Char16:
17174 OS << 'u';
17175 break;
17176 case BuiltinType::Char32:
17177 OS << 'U';
17178 break;
17179 case BuiltinType::WChar_S:
17180 case BuiltinType::WChar_U:
17181 OS << 'L';
17182 break;
17183 default:
17184 llvm_unreachable("Non-character type");
17185 }
17186}
17187
17188/// Convert character's value, interpreted as a code unit, to a string.
17189/// The value needs to be zero-extended to 32-bits.
17190/// FIXME: This assumes Unicode literal encodings
17191static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17192 unsigned TyWidth,
17193 SmallVectorImpl<char> &Str) {
17194 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17195 char *Ptr = Arr;
17196 BuiltinType::Kind K = BTy->getKind();
17197 llvm::raw_svector_ostream OS(Str);
17198
17199 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17200 // other types.
17201 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17202 K == BuiltinType::Char8 || Value <= 0x7F) {
17203 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17204 if (!Escaped.empty())
17205 EscapeStringForDiagnostic(Escaped, Str);
17206 else
17207 OS << static_cast<char>(Value);
17208 return;
17209 }
17210
17211 switch (K) {
17212 case BuiltinType::Char16:
17213 case BuiltinType::Char32:
17214 case BuiltinType::WChar_S:
17215 case BuiltinType::WChar_U: {
17216 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17217 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17218 else
17219 OS << "\\x"
17220 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17221 break;
17222 }
17223 default:
17224 llvm_unreachable("Non-character type is passed");
17225 }
17226}
17227
17228/// Convert \V to a string we can present to the user in a diagnostic
17229/// \T is the type of the expression that has been evaluated into \V
17233 if (!V.hasValue())
17234 return false;
17235
17236 switch (V.getKind()) {
17238 if (T->isBooleanType()) {
17239 // Bools are reduced to ints during evaluation, but for
17240 // diagnostic purposes we want to print them as
17241 // true or false.
17242 int64_t BoolValue = V.getInt().getExtValue();
17243 assert((BoolValue == 0 || BoolValue == 1) &&
17244 "Bool type, but value is not 0 or 1");
17245 llvm::raw_svector_ostream OS(Str);
17246 OS << (BoolValue ? "true" : "false");
17247 } else {
17248 llvm::raw_svector_ostream OS(Str);
17249 // Same is true for chars.
17250 // We want to print the character representation for textual types
17251 const auto *BTy = T->getAs<BuiltinType>();
17252 if (BTy) {
17253 switch (BTy->getKind()) {
17254 case BuiltinType::Char_S:
17255 case BuiltinType::Char_U:
17256 case BuiltinType::Char8:
17257 case BuiltinType::Char16:
17258 case BuiltinType::Char32:
17259 case BuiltinType::WChar_S:
17260 case BuiltinType::WChar_U: {
17261 unsigned TyWidth = Context.getIntWidth(T);
17262 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17263 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17264 WriteCharTypePrefix(BTy->getKind(), OS);
17265 OS << '\'';
17266 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17267 OS << "' (0x"
17268 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17269 /*Upper=*/true)
17270 << ", " << V.getInt() << ')';
17271 return true;
17272 }
17273 default:
17274 break;
17275 }
17276 }
17277 V.getInt().toString(Str);
17278 }
17279
17280 break;
17281
17283 V.getFloat().toString(Str);
17284 break;
17285
17287 if (V.isNullPointer()) {
17288 llvm::raw_svector_ostream OS(Str);
17289 OS << "nullptr";
17290 } else
17291 return false;
17292 break;
17293
17295 llvm::raw_svector_ostream OS(Str);
17296 OS << '(';
17297 V.getComplexFloatReal().toString(Str);
17298 OS << " + ";
17299 V.getComplexFloatImag().toString(Str);
17300 OS << "i)";
17301 } break;
17302
17304 llvm::raw_svector_ostream OS(Str);
17305 OS << '(';
17306 V.getComplexIntReal().toString(Str);
17307 OS << " + ";
17308 V.getComplexIntImag().toString(Str);
17309 OS << "i)";
17310 } break;
17311
17312 default:
17313 return false;
17314 }
17315
17316 return true;
17317}
17318
17319/// Some Expression types are not useful to print notes about,
17320/// e.g. literals and values that have already been expanded
17321/// before such as int-valued template parameters.
17322static bool UsefulToPrintExpr(const Expr *E) {
17323 E = E->IgnoreParenImpCasts();
17324 // Literals are pretty easy for humans to understand.
17327 return false;
17328
17329 // These have been substituted from template parameters
17330 // and appear as literals in the static assert error.
17331 if (isa<SubstNonTypeTemplateParmExpr>(E))
17332 return false;
17333
17334 // -5 is also simple to understand.
17335 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17336 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17337
17338 // Only print nested arithmetic operators.
17339 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17340 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17341 BO->isBitwiseOp());
17342
17343 return true;
17344}
17345
17346/// Try to print more useful information about a failed static_assert
17347/// with expression \E
17349 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17350 Op && Op->getOpcode() != BO_LOr) {
17351 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17352 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17353
17354 // Ignore comparisons of boolean expressions with a boolean literal.
17355 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17356 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17357 return;
17358
17359 // Don't print obvious expressions.
17360 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17361 return;
17362
17363 struct {
17364 const clang::Expr *Cond;
17366 SmallString<12> ValueString;
17367 bool Print;
17368 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17369 {RHS, Expr::EvalResult(), {}, false}};
17370 for (unsigned I = 0; I < 2; I++) {
17371 const Expr *Side = DiagSide[I].Cond;
17372
17373 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17374
17375 DiagSide[I].Print =
17376 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17377 DiagSide[I].ValueString, Context);
17378 }
17379 if (DiagSide[0].Print && DiagSide[1].Print) {
17380 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17381 << DiagSide[0].ValueString << Op->getOpcodeStr()
17382 << DiagSide[1].ValueString << Op->getSourceRange();
17383 }
17384 }
17385}
17386
17388 std::string &Result,
17389 ASTContext &Ctx,
17390 bool ErrorOnInvalidMessage) {
17391 assert(Message);
17392 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17393 "can't evaluate a dependant static assert message");
17394
17395 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17396 assert(SL->isUnevaluated() && "expected an unevaluated string");
17397 Result.assign(SL->getString().begin(), SL->getString().end());
17398 return true;
17399 }
17400
17401 SourceLocation Loc = Message->getBeginLoc();
17402 QualType T = Message->getType().getNonReferenceType();
17403 auto *RD = T->getAsCXXRecordDecl();
17404 if (!RD) {
17405 Diag(Loc, diag::err_static_assert_invalid_message);
17406 return false;
17407 }
17408
17409 auto FindMember = [&](StringRef Member, bool &Empty,
17410 bool Diag = false) -> std::optional<LookupResult> {
17412 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17413 LookupQualifiedName(MemberLookup, RD);
17414 Empty = MemberLookup.empty();
17415 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17417 if (MemberLookup.empty())
17418 return std::nullopt;
17419 return std::move(MemberLookup);
17420 };
17421
17422 bool SizeNotFound, DataNotFound;
17423 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17424 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17425 if (SizeNotFound || DataNotFound) {
17426 Diag(Loc, diag::err_static_assert_missing_member_function)
17427 << ((SizeNotFound && DataNotFound) ? 2
17428 : SizeNotFound ? 0
17429 : 1);
17430 return false;
17431 }
17432
17433 if (!SizeMember || !DataMember) {
17434 if (!SizeMember)
17435 FindMember("size", SizeNotFound, /*Diag=*/true);
17436 if (!DataMember)
17437 FindMember("data", DataNotFound, /*Diag=*/true);
17438 return false;
17439 }
17440
17441 auto BuildExpr = [&](LookupResult &LR) {
17443 Message, Message->getType(), Message->getBeginLoc(), false,
17444 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17445 if (Res.isInvalid())
17446 return ExprError();
17447 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17448 false, true);
17449 if (Res.isInvalid())
17450 return ExprError();
17451 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17452 return ExprError();
17454 };
17455
17456 ExprResult SizeE = BuildExpr(*SizeMember);
17457 ExprResult DataE = BuildExpr(*DataMember);
17458
17459 QualType SizeT = Context.getSizeType();
17460 QualType ConstCharPtr =
17462
17463 ExprResult EvaluatedSize =
17464 SizeE.isInvalid() ? ExprError()
17466 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17467 if (EvaluatedSize.isInvalid()) {
17468 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17469 return false;
17470 }
17471
17472 ExprResult EvaluatedData =
17473 DataE.isInvalid()
17474 ? ExprError()
17475 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17477 if (EvaluatedData.isInvalid()) {
17478 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17479 return false;
17480 }
17481
17482 if (!ErrorOnInvalidMessage &&
17483 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17484 return true;
17485
17486 Expr::EvalResult Status;
17488 Status.Diag = &Notes;
17489 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17490 EvaluatedData.get(), Ctx, Status) ||
17491 !Notes.empty()) {
17492 Diag(Message->getBeginLoc(),
17493 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17494 : diag::warn_static_assert_message_constexpr);
17495 for (const auto &Note : Notes)
17496 Diag(Note.first, Note.second);
17497 return !ErrorOnInvalidMessage;
17498 }
17499 return true;
17500}
17501
17503 Expr *AssertExpr, Expr *AssertMessage,
17504 SourceLocation RParenLoc,
17505 bool Failed) {
17506 assert(AssertExpr != nullptr && "Expected non-null condition");
17507 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17508 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17509 !AssertMessage->isValueDependent())) &&
17510 !Failed) {
17511 // In a static_assert-declaration, the constant-expression shall be a
17512 // constant expression that can be contextually converted to bool.
17513 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17514 if (Converted.isInvalid())
17515 Failed = true;
17516
17517 ExprResult FullAssertExpr =
17518 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17519 /*DiscardedValue*/ false,
17520 /*IsConstexpr*/ true);
17521 if (FullAssertExpr.isInvalid())
17522 Failed = true;
17523 else
17524 AssertExpr = FullAssertExpr.get();
17525
17526 llvm::APSInt Cond;
17527 Expr *BaseExpr = AssertExpr;
17528 AllowFoldKind FoldKind = NoFold;
17529
17530 if (!getLangOpts().CPlusPlus) {
17531 // In C mode, allow folding as an extension for better compatibility with
17532 // C++ in terms of expressions like static_assert("test") or
17533 // static_assert(nullptr).
17534 FoldKind = AllowFold;
17535 }
17536
17537 if (!Failed && VerifyIntegerConstantExpression(
17538 BaseExpr, &Cond,
17539 diag::err_static_assert_expression_is_not_constant,
17540 FoldKind).isInvalid())
17541 Failed = true;
17542
17543 // If the static_assert passes, only verify that
17544 // the message is grammatically valid without evaluating it.
17545 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17546 std::string Str;
17547 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17548 /*ErrorOnInvalidMessage=*/false);
17549 }
17550
17551 // CWG2518
17552 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17553 // template definition, the declaration has no effect.
17554 bool InTemplateDefinition =
17555 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17556
17557 if (!Failed && !Cond && !InTemplateDefinition) {
17558 SmallString<256> MsgBuffer;
17559 llvm::raw_svector_ostream Msg(MsgBuffer);
17560 bool HasMessage = AssertMessage;
17561 if (AssertMessage) {
17562 std::string Str;
17563 HasMessage =
17565 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17566 !Str.empty();
17567 Msg << Str;
17568 }
17569 Expr *InnerCond = nullptr;
17570 std::string InnerCondDescription;
17571 std::tie(InnerCond, InnerCondDescription) =
17572 findFailedBooleanCondition(Converted.get());
17573 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17574 // Drill down into concept specialization expressions to see why they
17575 // weren't satisfied.
17576 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17577 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17578 ConstraintSatisfaction Satisfaction;
17579 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17580 DiagnoseUnsatisfiedConstraint(Satisfaction);
17581 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17582 && !isa<IntegerLiteral>(InnerCond)) {
17583 Diag(InnerCond->getBeginLoc(),
17584 diag::err_static_assert_requirement_failed)
17585 << InnerCondDescription << !HasMessage << Msg.str()
17586 << InnerCond->getSourceRange();
17587 DiagnoseStaticAssertDetails(InnerCond);
17588 } else {
17589 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17590 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17592 }
17593 Failed = true;
17594 }
17595 } else {
17596 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17597 /*DiscardedValue*/false,
17598 /*IsConstexpr*/true);
17599 if (FullAssertExpr.isInvalid())
17600 Failed = true;
17601 else
17602 AssertExpr = FullAssertExpr.get();
17603 }
17604
17606 AssertExpr, AssertMessage, RParenLoc,
17607 Failed);
17608
17610 return Decl;
17611}
17612
17613/// Handle a friend tag declaration where the scope specifier was
17614/// templated.
17616 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17617 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17618 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17620
17621 bool IsMemberSpecialization = false;
17622 bool Invalid = false;
17623
17624 if (TemplateParameterList *TemplateParams =
17626 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17627 IsMemberSpecialization, Invalid)) {
17628 if (TemplateParams->size() > 0) {
17629 // This is a declaration of a class template.
17630 if (Invalid)
17631 return true;
17632
17633 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17634 NameLoc, Attr, TemplateParams, AS_public,
17635 /*ModulePrivateLoc=*/SourceLocation(),
17636 FriendLoc, TempParamLists.size() - 1,
17637 TempParamLists.data()).get();
17638 } else {
17639 // The "template<>" header is extraneous.
17640 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17641 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17642 IsMemberSpecialization = true;
17643 }
17644 }
17645
17646 if (Invalid) return true;
17647
17648 bool isAllExplicitSpecializations = true;
17649 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17650 if (TempParamLists[I]->size()) {
17651 isAllExplicitSpecializations = false;
17652 break;
17653 }
17654 }
17655
17656 // FIXME: don't ignore attributes.
17657
17658 // If it's explicit specializations all the way down, just forget
17659 // about the template header and build an appropriate non-templated
17660 // friend. TODO: for source fidelity, remember the headers.
17661 if (isAllExplicitSpecializations) {
17662 if (SS.isEmpty()) {
17663 bool Owned = false;
17664 bool IsDependent = false;
17665 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17666 AS_public,
17667 /*ModulePrivateLoc=*/SourceLocation(),
17668 MultiTemplateParamsArg(), Owned, IsDependent,
17669 /*ScopedEnumKWLoc=*/SourceLocation(),
17670 /*ScopedEnumUsesClassTag=*/false,
17671 /*UnderlyingType=*/TypeResult(),
17672 /*IsTypeSpecifier=*/false,
17673 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17674 }
17675
17677 ElaboratedTypeKeyword Keyword
17679 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17680 *Name, NameLoc);
17681 if (T.isNull())
17682 return true;
17683
17685 if (isa<DependentNameType>(T)) {
17688 TL.setElaboratedKeywordLoc(TagLoc);
17689 TL.setQualifierLoc(QualifierLoc);
17690 TL.setNameLoc(NameLoc);
17691 } else {
17693 TL.setElaboratedKeywordLoc(TagLoc);
17694 TL.setQualifierLoc(QualifierLoc);
17695 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17696 }
17697
17698 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17699 TSI, FriendLoc, TempParamLists);
17700 Friend->setAccess(AS_public);
17701 CurContext->addDecl(Friend);
17702 return Friend;
17703 }
17704
17705 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17706
17707
17708
17709 // Handle the case of a templated-scope friend class. e.g.
17710 // template <class T> class A<T>::B;
17711 // FIXME: we don't support these right now.
17712 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17713 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17718 TL.setElaboratedKeywordLoc(TagLoc);
17720 TL.setNameLoc(NameLoc);
17721
17722 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17723 TSI, FriendLoc, TempParamLists);
17724 Friend->setAccess(AS_public);
17725 Friend->setUnsupportedFriend(true);
17726 CurContext->addDecl(Friend);
17727 return Friend;
17728}
17729
17730/// Handle a friend type declaration. This works in tandem with
17731/// ActOnTag.
17732///
17733/// Notes on friend class templates:
17734///
17735/// We generally treat friend class declarations as if they were
17736/// declaring a class. So, for example, the elaborated type specifier
17737/// in a friend declaration is required to obey the restrictions of a
17738/// class-head (i.e. no typedefs in the scope chain), template
17739/// parameters are required to match up with simple template-ids, &c.
17740/// However, unlike when declaring a template specialization, it's
17741/// okay to refer to a template specialization without an empty
17742/// template parameter declaration, e.g.
17743/// friend class A<T>::B<unsigned>;
17744/// We permit this as a special case; if there are any template
17745/// parameters present at all, require proper matching, i.e.
17746/// template <> template <class T> friend class A<int>::B;
17748 MultiTemplateParamsArg TempParams) {
17749 SourceLocation Loc = DS.getBeginLoc();
17750 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17751
17752 assert(DS.isFriendSpecified());
17754
17755 // C++ [class.friend]p3:
17756 // A friend declaration that does not declare a function shall have one of
17757 // the following forms:
17758 // friend elaborated-type-specifier ;
17759 // friend simple-type-specifier ;
17760 // friend typename-specifier ;
17761 //
17762 // If the friend keyword isn't first, or if the declarations has any type
17763 // qualifiers, then the declaration doesn't have that form.
17765 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17766 if (DS.getTypeQualifiers()) {
17768 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17770 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17772 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17774 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17776 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17777 }
17778
17779 // Try to convert the decl specifier to a type. This works for
17780 // friend templates because ActOnTag never produces a ClassTemplateDecl
17781 // for a TUK_Friend.
17782 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17784 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17785 QualType T = TSI->getType();
17786 if (TheDeclarator.isInvalidType())
17787 return nullptr;
17788
17790 return nullptr;
17791
17792 if (!T->isElaboratedTypeSpecifier()) {
17793 if (TempParams.size()) {
17794 // C++23 [dcl.pre]p5:
17795 // In a simple-declaration, the optional init-declarator-list can be
17796 // omitted only when declaring a class or enumeration, that is, when
17797 // the decl-specifier-seq contains either a class-specifier, an
17798 // elaborated-type-specifier with a class-key, or an enum-specifier.
17799 //
17800 // The declaration of a template-declaration or explicit-specialization
17801 // is never a member-declaration, so this must be a simple-declaration
17802 // with no init-declarator-list. Therefore, this is ill-formed.
17803 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17804 return nullptr;
17805 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17806 SmallString<16> InsertionText(" ");
17807 InsertionText += RD->getKindName();
17808
17810 ? diag::warn_cxx98_compat_unelaborated_friend_type
17811 : diag::ext_unelaborated_friend_type)
17812 << (unsigned)RD->getTagKind() << T
17814 InsertionText);
17815 } else {
17816 Diag(FriendLoc, getLangOpts().CPlusPlus11
17817 ? diag::warn_cxx98_compat_nonclass_type_friend
17818 : diag::ext_nonclass_type_friend)
17819 << T << DS.getSourceRange();
17820 }
17821 }
17822
17823 // C++98 [class.friend]p1: A friend of a class is a function
17824 // or class that is not a member of the class . . .
17825 // This is fixed in DR77, which just barely didn't make the C++03
17826 // deadline. It's also a very silly restriction that seriously
17827 // affects inner classes and which nobody else seems to implement;
17828 // thus we never diagnose it, not even in -pedantic.
17829 //
17830 // But note that we could warn about it: it's always useless to
17831 // friend one of your own members (it's not, however, worthless to
17832 // friend a member of an arbitrary specialization of your template).
17833
17834 Decl *D;
17835 if (!TempParams.empty())
17836 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17837 FriendLoc);
17838 else
17840 TSI, FriendLoc);
17841
17842 if (!D)
17843 return nullptr;
17844
17845 D->setAccess(AS_public);
17846 CurContext->addDecl(D);
17847
17848 return D;
17849}
17850
17852 MultiTemplateParamsArg TemplateParams) {
17853 const DeclSpec &DS = D.getDeclSpec();
17854
17855 assert(DS.isFriendSpecified());
17857
17860
17861 // C++ [class.friend]p1
17862 // A friend of a class is a function or class....
17863 // Note that this sees through typedefs, which is intended.
17864 // It *doesn't* see through dependent types, which is correct
17865 // according to [temp.arg.type]p3:
17866 // If a declaration acquires a function type through a
17867 // type dependent on a template-parameter and this causes
17868 // a declaration that does not use the syntactic form of a
17869 // function declarator to have a function type, the program
17870 // is ill-formed.
17871 if (!TInfo->getType()->isFunctionType()) {
17872 Diag(Loc, diag::err_unexpected_friend);
17873
17874 // It might be worthwhile to try to recover by creating an
17875 // appropriate declaration.
17876 return nullptr;
17877 }
17878
17879 // C++ [namespace.memdef]p3
17880 // - If a friend declaration in a non-local class first declares a
17881 // class or function, the friend class or function is a member
17882 // of the innermost enclosing namespace.
17883 // - The name of the friend is not found by simple name lookup
17884 // until a matching declaration is provided in that namespace
17885 // scope (either before or after the class declaration granting
17886 // friendship).
17887 // - If a friend function is called, its name may be found by the
17888 // name lookup that considers functions from namespaces and
17889 // classes associated with the types of the function arguments.
17890 // - When looking for a prior declaration of a class or a function
17891 // declared as a friend, scopes outside the innermost enclosing
17892 // namespace scope are not considered.
17893
17894 CXXScopeSpec &SS = D.getCXXScopeSpec();
17896 assert(NameInfo.getName());
17897
17898 // Check for unexpanded parameter packs.
17902 return nullptr;
17903
17904 // The context we found the declaration in, or in which we should
17905 // create the declaration.
17906 DeclContext *DC;
17907 Scope *DCScope = S;
17908 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17909 RedeclarationKind::ForExternalRedeclaration);
17910
17911 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17912
17913 // There are five cases here.
17914 // - There's no scope specifier and we're in a local class. Only look
17915 // for functions declared in the immediately-enclosing block scope.
17916 // We recover from invalid scope qualifiers as if they just weren't there.
17917 FunctionDecl *FunctionContainingLocalClass = nullptr;
17918 if ((SS.isInvalid() || !SS.isSet()) &&
17919 (FunctionContainingLocalClass =
17920 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17921 // C++11 [class.friend]p11:
17922 // If a friend declaration appears in a local class and the name
17923 // specified is an unqualified name, a prior declaration is
17924 // looked up without considering scopes that are outside the
17925 // innermost enclosing non-class scope. For a friend function
17926 // declaration, if there is no prior declaration, the program is
17927 // ill-formed.
17928
17929 // Find the innermost enclosing non-class scope. This is the block
17930 // scope containing the local class definition (or for a nested class,
17931 // the outer local class).
17932 DCScope = S->getFnParent();
17933
17934 // Look up the function name in the scope.
17936 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17937
17938 if (!Previous.empty()) {
17939 // All possible previous declarations must have the same context:
17940 // either they were declared at block scope or they are members of
17941 // one of the enclosing local classes.
17942 DC = Previous.getRepresentativeDecl()->getDeclContext();
17943 } else {
17944 // This is ill-formed, but provide the context that we would have
17945 // declared the function in, if we were permitted to, for error recovery.
17946 DC = FunctionContainingLocalClass;
17947 }
17949
17950 // - There's no scope specifier, in which case we just go to the
17951 // appropriate scope and look for a function or function template
17952 // there as appropriate.
17953 } else if (SS.isInvalid() || !SS.isSet()) {
17954 // C++11 [namespace.memdef]p3:
17955 // If the name in a friend declaration is neither qualified nor
17956 // a template-id and the declaration is a function or an
17957 // elaborated-type-specifier, the lookup to determine whether
17958 // the entity has been previously declared shall not consider
17959 // any scopes outside the innermost enclosing namespace.
17960
17961 // Find the appropriate context according to the above.
17962 DC = CurContext;
17963
17964 // Skip class contexts. If someone can cite chapter and verse
17965 // for this behavior, that would be nice --- it's what GCC and
17966 // EDG do, and it seems like a reasonable intent, but the spec
17967 // really only says that checks for unqualified existing
17968 // declarations should stop at the nearest enclosing namespace,
17969 // not that they should only consider the nearest enclosing
17970 // namespace.
17971 while (DC->isRecord())
17972 DC = DC->getParent();
17973
17974 DeclContext *LookupDC = DC->getNonTransparentContext();
17975 while (true) {
17976 LookupQualifiedName(Previous, LookupDC);
17977
17978 if (!Previous.empty()) {
17979 DC = LookupDC;
17980 break;
17981 }
17982
17983 if (isTemplateId) {
17984 if (isa<TranslationUnitDecl>(LookupDC)) break;
17985 } else {
17986 if (LookupDC->isFileContext()) break;
17987 }
17988 LookupDC = LookupDC->getParent();
17989 }
17990
17991 DCScope = getScopeForDeclContext(S, DC);
17992
17993 // - There's a non-dependent scope specifier, in which case we
17994 // compute it and do a previous lookup there for a function
17995 // or function template.
17996 } else if (!SS.getScopeRep()->isDependent()) {
17997 DC = computeDeclContext(SS);
17998 if (!DC) return nullptr;
17999
18000 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18001
18003
18004 // C++ [class.friend]p1: A friend of a class is a function or
18005 // class that is not a member of the class . . .
18006 if (DC->Equals(CurContext))
18009 diag::warn_cxx98_compat_friend_is_member :
18010 diag::err_friend_is_member);
18011
18012 // - There's a scope specifier that does not match any template
18013 // parameter lists, in which case we use some arbitrary context,
18014 // create a method or method template, and wait for instantiation.
18015 // - There's a scope specifier that does match some template
18016 // parameter lists, which we don't handle right now.
18017 } else {
18018 DC = CurContext;
18019 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18020 }
18021
18022 if (!DC->isRecord()) {
18023 int DiagArg = -1;
18024 switch (D.getName().getKind()) {
18027 DiagArg = 0;
18028 break;
18030 DiagArg = 1;
18031 break;
18033 DiagArg = 2;
18034 break;
18036 DiagArg = 3;
18037 break;
18043 break;
18044 }
18045 // This implies that it has to be an operator or function.
18046 if (DiagArg >= 0) {
18047 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18048 return nullptr;
18049 }
18050 }
18051
18052 // FIXME: This is an egregious hack to cope with cases where the scope stack
18053 // does not contain the declaration context, i.e., in an out-of-line
18054 // definition of a class.
18055 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18056 if (!DCScope) {
18057 FakeDCScope.setEntity(DC);
18058 DCScope = &FakeDCScope;
18059 }
18060
18061 bool AddToScope = true;
18062 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18063 TemplateParams, AddToScope);
18064 if (!ND) return nullptr;
18065
18066 assert(ND->getLexicalDeclContext() == CurContext);
18067
18068 // If we performed typo correction, we might have added a scope specifier
18069 // and changed the decl context.
18070 DC = ND->getDeclContext();
18071
18072 // Add the function declaration to the appropriate lookup tables,
18073 // adjusting the redeclarations list as necessary. We don't
18074 // want to do this yet if the friending class is dependent.
18075 //
18076 // Also update the scope-based lookup if the target context's
18077 // lookup context is in lexical scope.
18079 DC = DC->getRedeclContext();
18081 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18082 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18083 }
18084
18086 D.getIdentifierLoc(), ND,
18087 DS.getFriendSpecLoc());
18088 FrD->setAccess(AS_public);
18089 CurContext->addDecl(FrD);
18090
18091 if (ND->isInvalidDecl()) {
18092 FrD->setInvalidDecl();
18093 } else {
18094 if (DC->isRecord()) CheckFriendAccess(ND);
18095
18096 FunctionDecl *FD;
18097 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18098 FD = FTD->getTemplatedDecl();
18099 else
18100 FD = cast<FunctionDecl>(ND);
18101
18102 // C++ [class.friend]p6:
18103 // A function may be defined in a friend declaration of a class if and
18104 // only if the class is a non-local class, and the function name is
18105 // unqualified.
18106 if (D.isFunctionDefinition()) {
18107 // Qualified friend function definition.
18108 if (SS.isNotEmpty()) {
18109 // FIXME: We should only do this if the scope specifier names the
18110 // innermost enclosing namespace; otherwise the fixit changes the
18111 // meaning of the code.
18113 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18114
18115 DB << SS.getScopeRep();
18116 if (DC->isFileContext())
18118
18119 // Friend function defined in a local class.
18120 } else if (FunctionContainingLocalClass) {
18121 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18122
18123 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18124 // a template-id, the function name is not unqualified because these is
18125 // no name. While the wording requires some reading in-between the
18126 // lines, GCC, MSVC, and EDG all consider a friend function
18127 // specialization definitions // to be de facto explicit specialization
18128 // and diagnose them as such.
18129 } else if (isTemplateId) {
18130 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18131 }
18132 }
18133
18134 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18135 // default argument expression, that declaration shall be a definition
18136 // and shall be the only declaration of the function or function
18137 // template in the translation unit.
18139 // We can't look at FD->getPreviousDecl() because it may not have been set
18140 // if we're in a dependent context. If the function is known to be a
18141 // redeclaration, we will have narrowed Previous down to the right decl.
18142 if (D.isRedeclaration()) {
18143 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18144 Diag(Previous.getRepresentativeDecl()->getLocation(),
18145 diag::note_previous_declaration);
18146 } else if (!D.isFunctionDefinition())
18147 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18148 }
18149
18150 // Mark templated-scope function declarations as unsupported.
18151 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18152 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18153 << SS.getScopeRep() << SS.getRange()
18154 << cast<CXXRecordDecl>(CurContext);
18155 FrD->setUnsupportedFriend(true);
18156 }
18157 }
18158
18160
18161 return ND;
18162}
18163
18165 StringLiteral *Message) {
18167
18168 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18169 if (!Fn) {
18170 Diag(DelLoc, diag::err_deleted_non_function);
18171 return;
18172 }
18173
18174 // Deleted function does not have a body.
18175 Fn->setWillHaveBody(false);
18176
18177 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18178 // Don't consider the implicit declaration we generate for explicit
18179 // specializations. FIXME: Do not generate these implicit declarations.
18180 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18181 Prev->getPreviousDecl()) &&
18182 !Prev->isDefined()) {
18183 Diag(DelLoc, diag::err_deleted_decl_not_first);
18184 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18185 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18186 : diag::note_previous_declaration);
18187 // We can't recover from this; the declaration might have already
18188 // been used.
18189 Fn->setInvalidDecl();
18190 return;
18191 }
18192
18193 // To maintain the invariant that functions are only deleted on their first
18194 // declaration, mark the implicitly-instantiated declaration of the
18195 // explicitly-specialized function as deleted instead of marking the
18196 // instantiated redeclaration.
18197 Fn = Fn->getCanonicalDecl();
18198 }
18199
18200 // dllimport/dllexport cannot be deleted.
18201 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18202 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18203 Fn->setInvalidDecl();
18204 }
18205
18206 // C++11 [basic.start.main]p3:
18207 // A program that defines main as deleted [...] is ill-formed.
18208 if (Fn->isMain())
18209 Diag(DelLoc, diag::err_deleted_main);
18210
18211 // C++11 [dcl.fct.def.delete]p4:
18212 // A deleted function is implicitly inline.
18213 Fn->setImplicitlyInline();
18214 Fn->setDeletedAsWritten(true, Message);
18215}
18216
18218 if (!Dcl || Dcl->isInvalidDecl())
18219 return;
18220
18221 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18222 if (!FD) {
18223 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18224 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18225 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18226 return;
18227 }
18228 }
18229
18230 Diag(DefaultLoc, diag::err_default_special_members)
18231 << getLangOpts().CPlusPlus20;
18232 return;
18233 }
18234
18235 // Reject if this can't possibly be a defaultable function.
18237 if (!DefKind &&
18238 // A dependent function that doesn't locally look defaultable can
18239 // still instantiate to a defaultable function if it's a constructor
18240 // or assignment operator.
18241 (!FD->isDependentContext() ||
18242 (!isa<CXXConstructorDecl>(FD) &&
18243 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18244 Diag(DefaultLoc, diag::err_default_special_members)
18245 << getLangOpts().CPlusPlus20;
18246 return;
18247 }
18248
18249 // Issue compatibility warning. We already warned if the operator is
18250 // 'operator<=>' when parsing the '<=>' token.
18251 if (DefKind.isComparison() &&
18253 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18254 ? diag::warn_cxx17_compat_defaulted_comparison
18255 : diag::ext_defaulted_comparison);
18256 }
18257
18258 FD->setDefaulted();
18259 FD->setExplicitlyDefaulted();
18260 FD->setDefaultLoc(DefaultLoc);
18261
18262 // Defer checking functions that are defaulted in a dependent context.
18263 if (FD->isDependentContext())
18264 return;
18265
18266 // Unset that we will have a body for this function. We might not,
18267 // if it turns out to be trivial, and we don't need this marking now
18268 // that we've marked it as defaulted.
18269 FD->setWillHaveBody(false);
18270
18271 if (DefKind.isComparison()) {
18272 // If this comparison's defaulting occurs within the definition of its
18273 // lexical class context, we have to do the checking when complete.
18274 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18275 if (!RD->isCompleteDefinition())
18276 return;
18277 }
18278
18279 // If this member fn was defaulted on its first declaration, we will have
18280 // already performed the checking in CheckCompletedCXXClass. Such a
18281 // declaration doesn't trigger an implicit definition.
18282 if (isa<CXXMethodDecl>(FD)) {
18283 const FunctionDecl *Primary = FD;
18284 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18285 // Ask the template instantiation pattern that actually had the
18286 // '= default' on it.
18287 Primary = Pattern;
18288 if (Primary->getCanonicalDecl()->isDefaulted())
18289 return;
18290 }
18291
18292 if (DefKind.isComparison()) {
18293 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18294 FD->setInvalidDecl();
18295 else
18296 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18297 } else {
18298 auto *MD = cast<CXXMethodDecl>(FD);
18299
18301 DefaultLoc))
18302 MD->setInvalidDecl();
18303 else
18304 DefineDefaultedFunction(*this, MD, DefaultLoc);
18305 }
18306}
18307
18309 for (Stmt *SubStmt : S->children()) {
18310 if (!SubStmt)
18311 continue;
18312 if (isa<ReturnStmt>(SubStmt))
18313 Self.Diag(SubStmt->getBeginLoc(),
18314 diag::err_return_in_constructor_handler);
18315 if (!isa<Expr>(SubStmt))
18316 SearchForReturnInStmt(Self, SubStmt);
18317 }
18318}
18319
18321 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18322 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18323 SearchForReturnInStmt(*this, Handler);
18324 }
18325}
18326
18328 StringLiteral *DeletedMessage) {
18329 switch (BodyKind) {
18330 case FnBodyKind::Delete:
18331 SetDeclDeleted(D, Loc, DeletedMessage);
18332 break;
18334 SetDeclDefaulted(D, Loc);
18335 break;
18336 case FnBodyKind::Other:
18337 llvm_unreachable(
18338 "Parsed function body should be '= delete;' or '= default;'");
18339 }
18340}
18341
18343 const CXXMethodDecl *Old) {
18344 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18345 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18346
18347 if (OldFT->hasExtParameterInfos()) {
18348 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18349 // A parameter of the overriding method should be annotated with noescape
18350 // if the corresponding parameter of the overridden method is annotated.
18351 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18352 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18353 Diag(New->getParamDecl(I)->getLocation(),
18354 diag::warn_overriding_method_missing_noescape);
18355 Diag(Old->getParamDecl(I)->getLocation(),
18356 diag::note_overridden_marked_noescape);
18357 }
18358 }
18359
18360 // SME attributes must match when overriding a function declaration.
18361 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18362 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18363 << New << New->getType() << Old->getType();
18364 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18365 return true;
18366 }
18367
18368 // Virtual overrides must have the same code_seg.
18369 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18370 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18371 if ((NewCSA || OldCSA) &&
18372 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18373 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18374 Diag(Old->getLocation(), diag::note_previous_declaration);
18375 return true;
18376 }
18377
18378 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18379
18380 // If the calling conventions match, everything is fine
18381 if (NewCC == OldCC)
18382 return false;
18383
18384 // If the calling conventions mismatch because the new function is static,
18385 // suppress the calling convention mismatch error; the error about static
18386 // function override (err_static_overrides_virtual from
18387 // Sema::CheckFunctionDeclaration) is more clear.
18388 if (New->getStorageClass() == SC_Static)
18389 return false;
18390
18391 Diag(New->getLocation(),
18392 diag::err_conflicting_overriding_cc_attributes)
18393 << New->getDeclName() << New->getType() << Old->getType();
18394 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18395 return true;
18396}
18397
18399 const CXXMethodDecl *Old) {
18400 // CWG2553
18401 // A virtual function shall not be an explicit object member function.
18403 return true;
18404 Diag(New->getParamDecl(0)->getBeginLoc(),
18405 diag::err_explicit_object_parameter_nonmember)
18406 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18407 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18408 New->setInvalidDecl();
18409 return false;
18410}
18411
18413 const CXXMethodDecl *Old) {
18414 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18415 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18416
18417 if (Context.hasSameType(NewTy, OldTy) ||
18418 NewTy->isDependentType() || OldTy->isDependentType())
18419 return false;
18420
18421 // Check if the return types are covariant
18422 QualType NewClassTy, OldClassTy;
18423
18424 /// Both types must be pointers or references to classes.
18425 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18426 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18427 NewClassTy = NewPT->getPointeeType();
18428 OldClassTy = OldPT->getPointeeType();
18429 }
18430 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18431 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18432 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18433 NewClassTy = NewRT->getPointeeType();
18434 OldClassTy = OldRT->getPointeeType();
18435 }
18436 }
18437 }
18438
18439 // The return types aren't either both pointers or references to a class type.
18440 if (NewClassTy.isNull()) {
18441 Diag(New->getLocation(),
18442 diag::err_different_return_type_for_overriding_virtual_function)
18443 << New->getDeclName() << NewTy << OldTy
18444 << New->getReturnTypeSourceRange();
18445 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18446 << Old->getReturnTypeSourceRange();
18447
18448 return true;
18449 }
18450
18451 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18452 // C++14 [class.virtual]p8:
18453 // If the class type in the covariant return type of D::f differs from
18454 // that of B::f, the class type in the return type of D::f shall be
18455 // complete at the point of declaration of D::f or shall be the class
18456 // type D.
18457 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18458 if (!RT->isBeingDefined() &&
18459 RequireCompleteType(New->getLocation(), NewClassTy,
18460 diag::err_covariant_return_incomplete,
18461 New->getDeclName()))
18462 return true;
18463 }
18464
18465 // Check if the new class derives from the old class.
18466 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18467 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18468 << New->getDeclName() << NewTy << OldTy
18469 << New->getReturnTypeSourceRange();
18470 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18471 << Old->getReturnTypeSourceRange();
18472 return true;
18473 }
18474
18475 // Check if we the conversion from derived to base is valid.
18477 NewClassTy, OldClassTy,
18478 diag::err_covariant_return_inaccessible_base,
18479 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18481 New->getDeclName(), nullptr)) {
18482 // FIXME: this note won't trigger for delayed access control
18483 // diagnostics, and it's impossible to get an undelayed error
18484 // here from access control during the original parse because
18485 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18486 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18487 << Old->getReturnTypeSourceRange();
18488 return true;
18489 }
18490 }
18491
18492 // The qualifiers of the return types must be the same.
18493 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18494 Diag(New->getLocation(),
18495 diag::err_covariant_return_type_different_qualifications)
18496 << New->getDeclName() << NewTy << OldTy
18497 << New->getReturnTypeSourceRange();
18498 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18499 << Old->getReturnTypeSourceRange();
18500 return true;
18501 }
18502
18503
18504 // The new class type must have the same or less qualifiers as the old type.
18505 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18506 Diag(New->getLocation(),
18507 diag::err_covariant_return_type_class_type_more_qualified)
18508 << New->getDeclName() << NewTy << OldTy
18509 << New->getReturnTypeSourceRange();
18510 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18511 << Old->getReturnTypeSourceRange();
18512 return true;
18513 }
18514
18515 return false;
18516}
18517
18518/// Mark the given method pure.
18519///
18520/// \param Method the method to be marked pure.
18521///
18522/// \param InitRange the source range that covers the "0" initializer.
18524 SourceLocation EndLoc = InitRange.getEnd();
18525 if (EndLoc.isValid())
18526 Method->setRangeEnd(EndLoc);
18527
18528 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18529 Method->setIsPureVirtual();
18530 return false;
18531 }
18532
18533 if (!Method->isInvalidDecl())
18534 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18535 << Method->getDeclName() << InitRange;
18536 return true;
18537}
18538
18540 if (D->getFriendObjectKind())
18541 Diag(D->getLocation(), diag::err_pure_friend);
18542 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18543 CheckPureMethod(M, ZeroLoc);
18544 else
18545 Diag(D->getLocation(), diag::err_illegal_initializer);
18546}
18547
18548/// Determine whether the given declaration is a global variable or
18549/// static data member.
18550static bool isNonlocalVariable(const Decl *D) {
18551 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
18552 return Var->hasGlobalStorage();
18553
18554 return false;
18555}
18556
18557/// Invoked when we are about to parse an initializer for the declaration
18558/// 'Dcl'.
18559///
18560/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18561/// static data member of class X, names should be looked up in the scope of
18562/// class X. If the declaration had a scope specifier, a scope will have
18563/// been created and passed in for this purpose. Otherwise, S will be null.
18565 // If there is no declaration, there was an error parsing it.
18566 if (!D || D->isInvalidDecl())
18567 return;
18568
18569 // We will always have a nested name specifier here, but this declaration
18570 // might not be out of line if the specifier names the current namespace:
18571 // extern int n;
18572 // int ::n = 0;
18573 if (S && D->isOutOfLine())
18575
18576 // If we are parsing the initializer for a static data member, push a
18577 // new expression evaluation context that is associated with this static
18578 // data member.
18579 if (isNonlocalVariable(D))
18582}
18583
18584/// Invoked after we are finished parsing an initializer for the declaration D.
18586 // If there is no declaration, there was an error parsing it.
18587 if (!D || D->isInvalidDecl())
18588 return;
18589
18590 if (isNonlocalVariable(D))
18592
18593 if (S && D->isOutOfLine())
18595}
18596
18597/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18598/// C++ if/switch/while/for statement.
18599/// e.g: "if (int x = f()) {...}"
18601 // C++ 6.4p2:
18602 // The declarator shall not specify a function or an array.
18603 // The type-specifier-seq shall not contain typedef and shall not declare a
18604 // new class or enumeration.
18606 "Parser allowed 'typedef' as storage class of condition decl.");
18607
18608 Decl *Dcl = ActOnDeclarator(S, D);
18609 if (!Dcl)
18610 return true;
18611
18612 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18613 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18614 << D.getSourceRange();
18615 return true;
18616 }
18617
18618 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18619 VD->setCXXCondDecl();
18620
18621 return Dcl;
18622}
18623
18625 if (!ExternalSource)
18626 return;
18627
18629 ExternalSource->ReadUsedVTables(VTables);
18631 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18632 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18633 = VTablesUsed.find(VTables[I].Record);
18634 // Even if a definition wasn't required before, it may be required now.
18635 if (Pos != VTablesUsed.end()) {
18636 if (!Pos->second && VTables[I].DefinitionRequired)
18637 Pos->second = true;
18638 continue;
18639 }
18640
18641 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18642 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18643 }
18644
18645 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18646}
18647
18649 bool DefinitionRequired) {
18650 // Ignore any vtable uses in unevaluated operands or for classes that do
18651 // not have a vtable.
18652 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18654 return;
18655 // Do not mark as used if compiling for the device outside of the target
18656 // region.
18657 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18658 !OpenMP().isInOpenMPDeclareTargetContext() &&
18659 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18660 if (!DefinitionRequired)
18662 return;
18663 }
18664
18665 // Try to insert this class into the map.
18667 Class = Class->getCanonicalDecl();
18668 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18669 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18670 if (!Pos.second) {
18671 // If we already had an entry, check to see if we are promoting this vtable
18672 // to require a definition. If so, we need to reappend to the VTableUses
18673 // list, since we may have already processed the first entry.
18674 if (DefinitionRequired && !Pos.first->second) {
18675 Pos.first->second = true;
18676 } else {
18677 // Otherwise, we can early exit.
18678 return;
18679 }
18680 } else {
18681 // The Microsoft ABI requires that we perform the destructor body
18682 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18683 // the deleting destructor is emitted with the vtable, not with the
18684 // destructor definition as in the Itanium ABI.
18686 CXXDestructorDecl *DD = Class->getDestructor();
18687 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18688 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18689 // If this is an out-of-line declaration, marking it referenced will
18690 // not do anything. Manually call CheckDestructor to look up operator
18691 // delete().
18692 ContextRAII SavedContext(*this, DD);
18693 CheckDestructor(DD);
18694 } else {
18695 MarkFunctionReferenced(Loc, Class->getDestructor());
18696 }
18697 }
18698 }
18699 }
18700
18701 // Local classes need to have their virtual members marked
18702 // immediately. For all other classes, we mark their virtual members
18703 // at the end of the translation unit.
18704 if (Class->isLocalClass())
18705 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18706 else
18707 VTableUses.push_back(std::make_pair(Class, Loc));
18708}
18709
18712 if (VTableUses.empty())
18713 return false;
18714
18715 // Note: The VTableUses vector could grow as a result of marking
18716 // the members of a class as "used", so we check the size each
18717 // time through the loop and prefer indices (which are stable) to
18718 // iterators (which are not).
18719 bool DefinedAnything = false;
18720 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18721 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18722 if (!Class)
18723 continue;
18725 Class->getTemplateSpecializationKind();
18726
18727 SourceLocation Loc = VTableUses[I].second;
18728
18729 bool DefineVTable = true;
18730
18731 // If this class has a key function, but that key function is
18732 // defined in another translation unit, we don't need to emit the
18733 // vtable even though we're using it.
18734 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18735 if (KeyFunction && !KeyFunction->hasBody()) {
18736 // The key function is in another translation unit.
18737 DefineVTable = false;
18739 KeyFunction->getTemplateSpecializationKind();
18742 "Instantiations don't have key functions");
18743 (void)TSK;
18744 } else if (!KeyFunction) {
18745 // If we have a class with no key function that is the subject
18746 // of an explicit instantiation declaration, suppress the
18747 // vtable; it will live with the explicit instantiation
18748 // definition.
18749 bool IsExplicitInstantiationDeclaration =
18751 for (auto *R : Class->redecls()) {
18753 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18755 IsExplicitInstantiationDeclaration = true;
18756 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18757 IsExplicitInstantiationDeclaration = false;
18758 break;
18759 }
18760 }
18761
18762 if (IsExplicitInstantiationDeclaration)
18763 DefineVTable = false;
18764 }
18765
18766 // The exception specifications for all virtual members may be needed even
18767 // if we are not providing an authoritative form of the vtable in this TU.
18768 // We may choose to emit it available_externally anyway.
18769 if (!DefineVTable) {
18771 continue;
18772 }
18773
18774 // Mark all of the virtual members of this class as referenced, so
18775 // that we can build a vtable. Then, tell the AST consumer that a
18776 // vtable for this class is required.
18777 DefinedAnything = true;
18779 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18780 if (VTablesUsed[Canonical])
18782
18783 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18784 // no key function or the key function is inlined. Don't warn in C++ ABIs
18785 // that lack key functions, since the user won't be able to make one.
18787 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18789 const FunctionDecl *KeyFunctionDef = nullptr;
18790 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18791 KeyFunctionDef->isInlined()))
18792 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18793 }
18794 }
18795 VTableUses.clear();
18796
18797 return DefinedAnything;
18798}
18799
18801 const CXXRecordDecl *RD) {
18802 for (const auto *I : RD->methods())
18803 if (I->isVirtual() && !I->isPureVirtual())
18804 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18805}
18806
18808 const CXXRecordDecl *RD,
18809 bool ConstexprOnly) {
18810 // Mark all functions which will appear in RD's vtable as used.
18811 CXXFinalOverriderMap FinalOverriders;
18812 RD->getFinalOverriders(FinalOverriders);
18813 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18814 E = FinalOverriders.end();
18815 I != E; ++I) {
18816 for (OverridingMethods::const_iterator OI = I->second.begin(),
18817 OE = I->second.end();
18818 OI != OE; ++OI) {
18819 assert(OI->second.size() > 0 && "no final overrider");
18820 CXXMethodDecl *Overrider = OI->second.front().Method;
18821
18822 // C++ [basic.def.odr]p2:
18823 // [...] A virtual member function is used if it is not pure. [...]
18824 if (!Overrider->isPureVirtual() &&
18825 (!ConstexprOnly || Overrider->isConstexpr()))
18826 MarkFunctionReferenced(Loc, Overrider);
18827 }
18828 }
18829
18830 // Only classes that have virtual bases need a VTT.
18831 if (RD->getNumVBases() == 0)
18832 return;
18833
18834 for (const auto &I : RD->bases()) {
18835 const auto *Base =
18836 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18837 if (Base->getNumVBases() == 0)
18838 continue;
18840 }
18841}
18842
18843/// SetIvarInitializers - This routine builds initialization ASTs for the
18844/// Objective-C implementation whose ivars need be initialized.
18846 if (!getLangOpts().CPlusPlus)
18847 return;
18848 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18851 if (ivars.empty())
18852 return;
18854 for (unsigned i = 0; i < ivars.size(); i++) {
18855 FieldDecl *Field = ivars[i];
18856 if (Field->isInvalidDecl())
18857 continue;
18858
18861 InitializationKind InitKind =
18862 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18863
18864 InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18865 ExprResult MemberInit =
18866 InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18867 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18868 // Note, MemberInit could actually come back empty if no initialization
18869 // is required (e.g., because it would call a trivial default constructor)
18870 if (!MemberInit.get() || MemberInit.isInvalid())
18871 continue;
18872
18873 Member =
18876 MemberInit.getAs<Expr>(),
18877 SourceLocation());
18878 AllToInit.push_back(Member);
18879
18880 // Be sure that the destructor is accessible and is marked as referenced.
18881 if (const RecordType *RecordTy =
18882 Context.getBaseElementType(Field->getType())
18883 ->getAs<RecordType>()) {
18884 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18886 MarkFunctionReferenced(Field->getLocation(), Destructor);
18887 CheckDestructorAccess(Field->getLocation(), Destructor,
18888 PDiag(diag::err_access_dtor_ivar)
18889 << Context.getBaseElementType(Field->getType()));
18890 }
18891 }
18892 }
18893 ObjCImplementation->setIvarInitializers(Context,
18894 AllToInit.data(), AllToInit.size());
18895 }
18896}
18897
18898static
18903 Sema &S) {
18904 if (Ctor->isInvalidDecl())
18905 return;
18906
18908
18909 // Target may not be determinable yet, for instance if this is a dependent
18910 // call in an uninstantiated template.
18911 if (Target) {
18912 const FunctionDecl *FNTarget = nullptr;
18913 (void)Target->hasBody(FNTarget);
18914 Target = const_cast<CXXConstructorDecl*>(
18915 cast_or_null<CXXConstructorDecl>(FNTarget));
18916 }
18917
18918 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18919 // Avoid dereferencing a null pointer here.
18920 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18921
18922 if (!Current.insert(Canonical).second)
18923 return;
18924
18925 // We know that beyond here, we aren't chaining into a cycle.
18926 if (!Target || !Target->isDelegatingConstructor() ||
18927 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18928 Valid.insert(Current.begin(), Current.end());
18929 Current.clear();
18930 // We've hit a cycle.
18931 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18932 Current.count(TCanonical)) {
18933 // If we haven't diagnosed this cycle yet, do so now.
18934 if (!Invalid.count(TCanonical)) {
18935 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18936 diag::warn_delegating_ctor_cycle)
18937 << Ctor;
18938
18939 // Don't add a note for a function delegating directly to itself.
18940 if (TCanonical != Canonical)
18941 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18942
18944 while (C->getCanonicalDecl() != Canonical) {
18945 const FunctionDecl *FNTarget = nullptr;
18946 (void)C->getTargetConstructor()->hasBody(FNTarget);
18947 assert(FNTarget && "Ctor cycle through bodiless function");
18948
18949 C = const_cast<CXXConstructorDecl*>(
18950 cast<CXXConstructorDecl>(FNTarget));
18951 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18952 }
18953 }
18954
18955 Invalid.insert(Current.begin(), Current.end());
18956 Current.clear();
18957 } else {
18958 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18959 }
18960}
18961
18962
18965
18966 for (DelegatingCtorDeclsType::iterator
18969 I != E; ++I)
18970 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18971
18972 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18973 (*CI)->setInvalidDecl();
18974}
18975
18976namespace {
18977 /// AST visitor that finds references to the 'this' expression.
18978 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18979 Sema &S;
18980
18981 public:
18982 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18983
18984 bool VisitCXXThisExpr(CXXThisExpr *E) {
18985 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18986 << E->isImplicit();
18987 return false;
18988 }
18989 };
18990}
18991
18993 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18994 if (!TSInfo)
18995 return false;
18996
18997 TypeLoc TL = TSInfo->getTypeLoc();
18999 if (!ProtoTL)
19000 return false;
19001
19002 // C++11 [expr.prim.general]p3:
19003 // [The expression this] shall not appear before the optional
19004 // cv-qualifier-seq and it shall not appear within the declaration of a
19005 // static member function (although its type and value category are defined
19006 // within a static member function as they are within a non-static member
19007 // function). [ Note: this is because declaration matching does not occur
19008 // until the complete declarator is known. - end note ]
19009 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19010 FindCXXThisExpr Finder(*this);
19011
19012 // If the return type came after the cv-qualifier-seq, check it now.
19013 if (Proto->hasTrailingReturn() &&
19014 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19015 return true;
19016
19017 // Check the exception specification.
19019 return true;
19020
19021 // Check the trailing requires clause
19022 if (Expr *E = Method->getTrailingRequiresClause())
19023 if (!Finder.TraverseStmt(E))
19024 return true;
19025
19027}
19028
19030 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19031 if (!TSInfo)
19032 return false;
19033
19034 TypeLoc TL = TSInfo->getTypeLoc();
19036 if (!ProtoTL)
19037 return false;
19038
19039 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19040 FindCXXThisExpr Finder(*this);
19041
19042 switch (Proto->getExceptionSpecType()) {
19043 case EST_Unparsed:
19044 case EST_Uninstantiated:
19045 case EST_Unevaluated:
19046 case EST_BasicNoexcept:
19047 case EST_NoThrow:
19048 case EST_DynamicNone:
19049 case EST_MSAny:
19050 case EST_None:
19051 break;
19052
19054 case EST_NoexceptFalse:
19055 case EST_NoexceptTrue:
19056 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19057 return true;
19058 [[fallthrough]];
19059
19060 case EST_Dynamic:
19061 for (const auto &E : Proto->exceptions()) {
19062 if (!Finder.TraverseType(E))
19063 return true;
19064 }
19065 break;
19066 }
19067
19068 return false;
19069}
19070
19072 FindCXXThisExpr Finder(*this);
19073
19074 // Check attributes.
19075 for (const auto *A : Method->attrs()) {
19076 // FIXME: This should be emitted by tblgen.
19077 Expr *Arg = nullptr;
19078 ArrayRef<Expr *> Args;
19079 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19080 Arg = G->getArg();
19081 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19082 Arg = G->getArg();
19083 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19084 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19085 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19086 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19087 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
19088 Arg = ETLF->getSuccessValue();
19089 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
19090 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
19091 Arg = STLF->getSuccessValue();
19092 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
19093 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19094 Arg = LR->getArg();
19095 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19096 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19097 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19098 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19099 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19100 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19101 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
19102 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19103 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19104 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19105
19106 if (Arg && !Finder.TraverseStmt(Arg))
19107 return true;
19108
19109 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19110 if (!Finder.TraverseStmt(Args[I]))
19111 return true;
19112 }
19113 }
19114
19115 return false;
19116}
19117
19119 bool IsTopLevel, ExceptionSpecificationType EST,
19120 ArrayRef<ParsedType> DynamicExceptions,
19121 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19122 SmallVectorImpl<QualType> &Exceptions,
19124 Exceptions.clear();
19125 ESI.Type = EST;
19126 if (EST == EST_Dynamic) {
19127 Exceptions.reserve(DynamicExceptions.size());
19128 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19129 // FIXME: Preserve type source info.
19130 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19131
19132 if (IsTopLevel) {
19134 collectUnexpandedParameterPacks(ET, Unexpanded);
19135 if (!Unexpanded.empty()) {
19137 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19138 Unexpanded);
19139 continue;
19140 }
19141 }
19142
19143 // Check that the type is valid for an exception spec, and
19144 // drop it if not.
19145 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19146 Exceptions.push_back(ET);
19147 }
19148 ESI.Exceptions = Exceptions;
19149 return;
19150 }
19151
19152 if (isComputedNoexcept(EST)) {
19153 assert((NoexceptExpr->isTypeDependent() ||
19154 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19155 Context.BoolTy) &&
19156 "Parser should have made sure that the expression is boolean");
19157 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19158 ESI.Type = EST_BasicNoexcept;
19159 return;
19160 }
19161
19162 ESI.NoexceptExpr = NoexceptExpr;
19163 return;
19164 }
19165}
19166
19169 SourceRange SpecificationRange,
19170 ArrayRef<ParsedType> DynamicExceptions,
19171 ArrayRef<SourceRange> DynamicExceptionRanges,
19172 Expr *NoexceptExpr) {
19173 if (!MethodD)
19174 return;
19175
19176 // Dig out the method we're referring to.
19177 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
19178 MethodD = FunTmpl->getTemplatedDecl();
19179
19180 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
19181 if (!Method)
19182 return;
19183
19184 // Check the exception specification.
19187 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
19188 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19189 ESI);
19190
19191 // Update the exception specification on the function type.
19192 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
19193
19194 if (Method->isStatic())
19196
19197 if (Method->isVirtual()) {
19198 // Check overrides, which we previously had to delay.
19199 for (const CXXMethodDecl *O : Method->overridden_methods())
19201 }
19202}
19203
19204/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19205///
19207 SourceLocation DeclStart, Declarator &D,
19208 Expr *BitWidth,
19209 InClassInitStyle InitStyle,
19210 AccessSpecifier AS,
19211 const ParsedAttr &MSPropertyAttr) {
19212 const IdentifierInfo *II = D.getIdentifier();
19213 if (!II) {
19214 Diag(DeclStart, diag::err_anonymous_property);
19215 return nullptr;
19216 }
19218
19220 QualType T = TInfo->getType();
19221 if (getLangOpts().CPlusPlus) {
19223
19226 D.setInvalidType();
19227 T = Context.IntTy;
19228 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19229 }
19230 }
19231
19233
19235 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19236 << getLangOpts().CPlusPlus17;
19239 diag::err_invalid_thread)
19241
19242 // Check to see if this name was declared as a member previously
19243 NamedDecl *PrevDecl = nullptr;
19244 LookupResult Previous(*this, II, Loc, LookupMemberName,
19245 RedeclarationKind::ForVisibleRedeclaration);
19246 LookupName(Previous, S);
19247 switch (Previous.getResultKind()) {
19250 PrevDecl = Previous.getAsSingle<NamedDecl>();
19251 break;
19252
19254 PrevDecl = Previous.getRepresentativeDecl();
19255 break;
19256
19260 break;
19261 }
19262
19263 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19264 // Maybe we will complain about the shadowed template parameter.
19266 // Just pretend that we didn't see the previous declaration.
19267 PrevDecl = nullptr;
19268 }
19269
19270 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19271 PrevDecl = nullptr;
19272
19273 SourceLocation TSSL = D.getBeginLoc();
19274 MSPropertyDecl *NewPD =
19275 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19276 MSPropertyAttr.getPropertyDataGetter(),
19277 MSPropertyAttr.getPropertyDataSetter());
19278 ProcessDeclAttributes(TUScope, NewPD, D);
19279 NewPD->setAccess(AS);
19280
19281 if (NewPD->isInvalidDecl())
19282 Record->setInvalidDecl();
19283
19285 NewPD->setModulePrivate();
19286
19287 if (NewPD->isInvalidDecl() && PrevDecl) {
19288 // Don't introduce NewFD into scope; there's already something
19289 // with the same name in the same scope.
19290 } else if (II) {
19291 PushOnScopeChains(NewPD, S);
19292 } else
19293 Record->addDecl(NewPD);
19294
19295 return NewPD;
19296}
19297
19299 Declarator &Declarator, unsigned TemplateParameterDepth) {
19300 auto &Info = InventedParameterInfos.emplace_back();
19301 TemplateParameterList *ExplicitParams = nullptr;
19302 ArrayRef<TemplateParameterList *> ExplicitLists =
19304 if (!ExplicitLists.empty()) {
19305 bool IsMemberSpecialization, IsInvalid;
19308 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19309 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19310 /*SuppressDiagnostic=*/true);
19311 }
19312 // C++23 [dcl.fct]p23:
19313 // An abbreviated function template can have a template-head. The invented
19314 // template-parameters are appended to the template-parameter-list after
19315 // the explicitly declared template-parameters.
19316 //
19317 // A template-head must have one or more template-parameters (read:
19318 // 'template<>' is *not* a template-head). Only append the invented
19319 // template parameters if we matched the nested-name-specifier to a non-empty
19320 // TemplateParameterList.
19321 if (ExplicitParams && !ExplicitParams->empty()) {
19322 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19323 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19324 Info.NumExplicitTemplateParams = ExplicitParams->size();
19325 } else {
19326 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19327 Info.NumExplicitTemplateParams = 0;
19328 }
19329}
19330
19332 auto &FSI = InventedParameterInfos.back();
19333 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19334 if (FSI.NumExplicitTemplateParams != 0) {
19335 TemplateParameterList *ExplicitParams =
19339 Context, ExplicitParams->getTemplateLoc(),
19340 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19341 ExplicitParams->getRAngleLoc(),
19342 ExplicitParams->getRequiresClause()));
19343 } else {
19346 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19347 SourceLocation(), /*RequiresClause=*/nullptr));
19348 }
19349 }
19350 InventedParameterInfos.pop_back();
19351}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3284
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
DynTypedNode Node
StringRef P
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
int Category
Definition: Format.cpp:2974
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:48
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 bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current)
Determine whether the given class is a base class of the given class, including looking at dependent ...
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool isNonlocalVariable(const Decl *D)
Determine whether the given declaration is a global variable or static data member.
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.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
const NestedNameSpecifier * Specifier
StateNode * Previous
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:123
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2767
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3234
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3248
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
void Deallocate(void *Ptr) const
Definition: ASTContext.h:724
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1590
CanQualType WideCharTy
Definition: ASTContext.h:1095
IdentifierTable & Idents
Definition: ASTContext.h:644
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1298
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:2271
QualType AutoDeductTy
Definition: ASTContext.h:1148
CanQualType BoolTy
Definition: ASTContext.h:1092
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3213
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1093
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3227
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3220
CanQualType IntTy
Definition: ASTContext.h:1100
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3244
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
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:2340
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3209
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:3241
CanQualType VoidTy
Definition: ASTContext.h:1091
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3223
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1568
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:3025
CanQualType Char32Ty
Definition: ASTContext.h:1099
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3216
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:1188
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3230
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CanQualType Char8Ty
Definition: ASTContext.h:1097
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3237
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:3514
QualType getElementType() const
Definition: Type.h:3526
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:5977
AutoTypeKeyword getKeyword() const
Definition: Type.h:6008
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3417
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3495
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3142
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3487
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3151
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
Expr * getLHS() const
Definition: Expr.h:3889
Expr * getRHS() const
Definition: Expr.h:3891
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4781
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3980
Opcode getOpcode() const
Definition: Expr.h:3884
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2143
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3336
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
This class is used for builtin types like 'int'.
Definition: Type.h:2977
Kind getKind() const
Definition: Type.h:3019
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
std::list< CXXBasePath >::iterator paths_iterator
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition: ExprCXX.cpp:1110
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1683
bool isImmediateEscalating() const
Definition: ExprCXX.h:1698
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1603
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2777
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition: DeclCXX.cpp:2767
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2606
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2631
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2744
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2762
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2753
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2772
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2723
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2472
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2672
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2659
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2446
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2857
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1731
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:673
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2455
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2462
bool isVirtual() const
Definition: DeclCXX.h:2115
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2214
bool isVolatile() const
Definition: DeclCXX.h:2113
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2163
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2534
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2528
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2518
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isInstance() const
Definition: DeclCXX.h:2087
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2274
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isStatic() const
Definition: DeclCXX.cpp:2186
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2466
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition: DeclCXX.h:1271
friend_range friends() const
Definition: DeclFriend.h:246
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1342
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:576
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1564
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1005
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:831
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition: DeclCXX.h:725
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition: DeclCXX.h:1421
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1392
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1371
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:717
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.cpp:1390
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:965
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1357
base_class_range bases()
Definition: DeclCXX.h:619
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:569
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1302
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:777
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:896
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:914
method_range methods() const
Definition: DeclCXX.h:661
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:935
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1723
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1264
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1279
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:977
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:564
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1215
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:708
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1283
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition: DeclCXX.cpp:692
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1329
base_class_range vbases()
Definition: DeclCXX.h:636
base_class_iterator vbases_begin()
Definition: DeclCXX.h:643
ctor_range ctors() const
Definition: DeclCXX.h:681
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:878
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1222
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1237
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:869
bool isDynamicClass() const
Definition: DeclCXX.h:585
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1152
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:810
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1403
bool hasNonTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1294
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1208
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:804
bool hasDefinition() const
Definition: DeclCXX.h:571
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:920
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1011
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1897
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition: DeclCXX.h:906
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:998
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
bool hasNonTrivialDestructorForCall() const
Definition: DeclCXX.h:1381
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1017
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1415
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1606
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:816
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:857
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:987
bool isInterfaceLike() const
Definition: DeclCXX.cpp:2004
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:929
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1307
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition: DeclCXX.h:950
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
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:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
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:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
Represents the this expression in C++.
Definition: ExprCXX.h:1148
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1168
bool isImplicit() const
Definition: ExprCXX.h:1171
SourceLocation getLocation() const
Definition: ExprCXX.h:1165
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:108
unsigned getNumHandlers() const
Definition: StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
bool isCallToStdMove() const
Definition: Expr.cpp:3510
Expr * getCallee()
Definition: Expr.h:2970
arg_range arguments()
Definition: Expr.h:3059
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastKind getCastKind() const
Definition: Expr.h:3527
Expr * getSubExpr()
Definition: Expr.h:3533
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3082
QualType getElementType() const
Definition: Type.h:3092
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
body_range body()
Definition: Stmt.h:1664
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3552
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3608
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3598
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3662
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:3124
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1975
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1617
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
decl_iterator decls_end() const
Definition: DeclBase.h:2324
bool isStdNamespace() const
Definition: DeclBase.cpp:1248
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1319
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1334
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1672
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2059
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1345
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1554
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
ValueDecl * getDecl()
Definition: Expr.h:1328
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1452
bool isImmediateEscalating() const
Definition: Expr.h:1462
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:825
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:687
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:641
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:556
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
TST getTypeSpecType() const
Definition: DeclSpec.h:533
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:612
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:823
ParsedType getRepAsType() const
Definition: DeclSpec.h:543
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:821
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:619
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:613
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:651
Expr * getRepAsExpr() const
Definition: DeclSpec.h:551
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:614
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1013
void ClearConstexprSpec()
Definition: DeclSpec.h:837
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:616
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:578
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition: DeclSpec.cpp:453
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:615
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:817
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
static const TST TST_auto
Definition: DeclSpec.h:317
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_range decls()
Definition: Stmt.h:1545
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1523
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1204
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1209
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2739
bool isInvalidDecl() const
Definition: DeclBase.h:594
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:879
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1159
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:820
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setReferenced(bool R=true)
Definition: DeclBase.h:629
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
DeclContext * getDeclContext()
Definition: DeclBase.h:454
attr_range attrs() const
Definition: DeclBase.h:541
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
void dropAttr()
Definition: DeclBase.h:562
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:871
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:858
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2454
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition: DeclSpec.cpp:325
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2396
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2045
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2508
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2334
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2337
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2409
bool hasGroupingParens() const
Definition: DeclSpec.h:2717
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2711
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2392
bool isRedeclaration() const
Definition: DeclSpec.h:2763
DeclaratorContext getContext() const
Definition: DeclSpec.h:2070
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2066
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2081
bool isFunctionDefinition() const
Definition: DeclSpec.h:2735
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2064
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2060
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2647
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2654
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition: DeclSpec.h:2209
bool isInvalidType() const
Definition: DeclSpec.h:2712
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2080
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2324
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2052
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2485
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2328
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:1788
ArrayRef< Binding > bindings() const
Definition: DeclSpec.h:1826
SourceRange getSourceRange() const
Definition: DeclSpec.h:1834
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1832
Represents a C++17 deduced template specialization type.
Definition: Type.h:6025
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:5631
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:3298
Represents an enum.
Definition: Decl.h:3868
enumerator_range enumerators() const
Definition: Decl.h:4001
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
const Expr * getExpr() const
Definition: DeclCXX.h:1906
void setExpr(Expr *E)
Definition: DeclCXX.h:1931
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1930
This represents one expression.
Definition: Expr.h:110
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3193
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3058
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4572
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3219
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4646
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4562
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3213
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:3242
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4582
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3282
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition: Diagnostic.h:110
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:176
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3096
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3236
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2779
bool isTrivialForCall() const
Definition: Decl.h:2343
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2439
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3255
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2284
bool isImmediateFunction() const
Definition: Decl.cpp:3288
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3117
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3873
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3474
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2831
SourceLocation getDefaultLoc() const
Definition: Decl.h:2361
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2352
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2340
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2692
void setWillHaveBody(bool V=true)
Definition: Decl.h:2597
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3617
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3867
param_iterator param_begin()
Definition: Decl.h:2696
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2733
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2296
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2503
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2449
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4106
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2798
bool isStatic() const
Definition: Decl.h:2839
void setTrivial(bool IT)
Definition: Decl.h:2341
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2433
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2323
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3492
bool isImmediateEscalating() const
Definition: Decl.cpp:3268
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3306
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2826
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3180
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2190
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2348
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4397
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2843
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2436
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4268
void setDefaulted(bool D=true)
Definition: Decl.h:2349
bool isConsteval() const
Definition: Decl.h:2445
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2373
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:2772
void setBody(Stmt *B)
Definition: Decl.cpp:3248
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2314
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3745
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3126
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
size_t param_size() const
Definition: Decl.h:2700
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2183
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3156
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3203
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2809
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3151
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2715
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2596
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5097
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4911
unsigned getNumParams() const
Definition: Type.h:4885
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5024
QualType getParamType(unsigned i) const
Definition: Type.h:4887
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4969
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4892
ArrayRef< QualType > exceptions() const
Definition: Type.h:5054
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5069
Declaration of a template function.
Definition: DeclTemplate.h:958
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:4478
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
CallingConv getCallConv() const
Definition: Type.h:4580
QualType getReturnType() const
Definition: Type.h:4569
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2138
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5600
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3342
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3364
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2518
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4847
unsigned getNumInits() const
Definition: Expr.h:4877
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4893
child_range children()
Definition: Expr.h:5039
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8591
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:3470
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.
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:1948
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1290
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1303
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
void push_back(const T &LocalValue)
iterator begin(Source *source, bool LocalOnly=false)
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
Represents a linkage specification.
Definition: DeclCXX.h:2934
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2920
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2976
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:673
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:719
bool hasNext() const
Definition: Lookup.h:704
NamedDecl * next()
Definition: Lookup.h:708
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:603
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:469
DeclClass * getAsSingle() const
Definition: Lookup.h:556
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:662
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:747
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
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:573
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
iterator end() const
Definition: Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4235
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3401
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
Expr * getBase() const
Definition: Expr.h:3249
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3367
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:675
bool isExplicitGlobalModule() const
Definition: Module.h:203
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:686
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3038
Represent a C++ namespace.
Definition: Decl.h:547
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:610
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2982
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:665
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:688
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
Definition: DeclObjC.cpp:2305
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
PtrTy get() const
Definition: Ownership.h:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
MapType::iterator iterator
MapType::const_iterator const_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4723
Represents a parameter to a function.
Definition: Decl.h:1761
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2980
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1857
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1902
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1890
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2985
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3005
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1894
bool hasInheritedDefaultArg() const
Definition: Decl.h:1906
bool isExplicitObjectParameter() const
Definition: Decl.h:1849
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
Expr * getDefaultArg()
Definition: Decl.cpp:2968
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3010
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1910
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2938
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:477
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:471
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:826
const ParsedAttr * getMSPropertyAttr() const
Definition: ParsedAttr.h:912
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:906
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
QualType getPointeeType() const
Definition: Type.h:3145
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6305
ArrayRef< Expr * > semantics()
Definition: Expr.h:6384
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7439
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7444
QualType withConst() const
Definition: Type.h:1154
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2828
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1092
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7527
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7428
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7401
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1436
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2561
The collection of all-type qualifiers we support.
Definition: Type.h:318
void addAddressSpace(LangAS space)
Definition: Type.h:583
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
void removeConst()
Definition: Type.h:445
void removeAddressSpace()
Definition: Type.h:582
void addConst()
Definition: Type.h:446
void removeVolatile()
Definition: Type.h:455
LangAS getAddressSpace() const
Definition: Type.h:557
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3438
Represents a struct/union/class.
Definition: Decl.h:4169
bool hasFlexibleArrayMember() const
Definition: Decl.h:4202
field_iterator field_end() const
Definition: Decl.h:4378
field_range fields() const
Definition: Decl.h:4375
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5037
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4360
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4221
bool field_empty() const
Definition: Decl.h:4383
field_iterator field_begin() const
Definition: Decl.cpp:5071
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
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:4995
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:3376
QualType getPointeeType() const
Definition: Type.h:3394
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
void setEntity(DeclContext *E)
Definition: Scope.h:389
void AddDecl(Decl *D)
Definition: Scope.h:342
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:267
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema & SemaRef
Definition: SemaBase.h:40
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:372
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
A RAII object to enter scope of a compound statement.
Definition: Sema.h:865
bool isInvalid() const
Definition: Sema.h:5878
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2544
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4681
DefaultedComparisonKind asComparison() const
Definition: Sema.h:4713
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4710
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:4020
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:7328
CXXMethodDecl * getMethod() const
Definition: Sema.h:7340
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:10185
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5776
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
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:11101
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl< ObjCIvarDecl * > &Ivars)
CollectIvarsToConstructOrDestruct - Collect those ivars which require initialization.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6827
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:9787
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9871
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition: Sema.h:4834
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:1583
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3848
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15753
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:4638
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:7403
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7411
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:7399
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7384
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:423
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6763
VariadicCallType
Definition: Sema.h:2013
@ VariadicDoesNotApply
Definition: Sema.h:2018
@ VariadicConstructor
Definition: Sema.h:2017
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:6232
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:10325
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:4629
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:6199
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:825
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:4811
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:4792
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:1109
SemaCUDA & CUDA()
Definition: Sema.h:998
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:17673
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:1075
@ AR_accessible
Definition: Sema.h:1073
@ AR_inaccessible
Definition: Sema.h:1074
@ AR_delayed
Definition: Sema.h:1076
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:2245
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2107
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6360
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:17458
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:4906
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:51
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:18586
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1420
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:858
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:5898
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation IdentLoc, IdentifierInfo &II, CXXScopeSpec *SS=nullptr)
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:5016
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:5790
@ AllowFold
Definition: Sema.h:5792
@ NoFold
Definition: Sema.h:5791
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1521
ASTContext & getASTContext() const
Definition: Sema.h:527
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:4818
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:20154
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:4896
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:18099
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:645
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:4483
@ 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:9662
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:4829
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
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:775
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2206
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:9267
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1518
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6476
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1970
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2126
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:522
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20670
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
@ UPPC_RequiresClause
Definition: Sema.h:10860
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:10815
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:10833
@ UPPC_Initializer
An initializer.
Definition: Sema.h:10824
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:10794
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:10818
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:10827
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:10797
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:10800
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:10806
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:520
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:4373
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:1411
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,...
Preprocessor & PP
Definition: Sema.h:857
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:6651
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:8340
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:11246
const LangOptions & LangOpts
Definition: Sema.h:856
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
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:17795
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8554
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:4796
SemaHLSL & HLSL()
Definition: Sema.h:1003
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:12046
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:4379
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:3873
@ 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:4789
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20311
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:3855
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:4888
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:4822
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:9761
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:1398
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
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:2273
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:9799
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:4369
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:651
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:3432
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11732
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:7739
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:15600
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:5211
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:4803
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15527
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
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:15070
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5904
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:4668
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:4670
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:4673
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6287
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:20258
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:10484
SourceManager & getSourceManager() const
Definition: Sema.h:525
@ AA_Passing
Definition: Sema.h:5198
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:1363
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:7356
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9908
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.
void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member function (or member function template).
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:1380
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:227
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:8374
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:4018
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11707
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:7605
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14430
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:4814
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:8033
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:8031
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:8035
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3194
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:290
ASTConsumer & Consumer
Definition: Sema.h:859
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:3424
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:7934
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:7926
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:7930
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:5356
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.
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6981
@ 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:9876
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6122
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:17321
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:9276
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:830
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19320
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:1389
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:8136
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:18177
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1328
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:861
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:860
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:5848
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
@ TUK_Friend
Definition: Sema.h:3185
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7398
@ TPC_TypeAliasTemplate
Definition: Sema.h:9011
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:6867
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5788
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1335
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:3342
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4826
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:1605
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9270
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:1588
@ OOK_Outside
Definition: Sema.h:3190
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13502
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:4628
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:18360
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:6138
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:21454
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6166
AbstractDiagSelID
Definition: Sema.h:4583
@ AbstractVariableType
Definition: Sema.h:4587
@ AbstractReturnType
Definition: Sema.h:4585
@ AbstractNone
Definition: Sema.h:4584
@ AbstractFieldType
Definition: Sema.h:4588
@ AbstractArrayType
Definition: Sema.h:4591
@ AbstractParamType
Definition: Sema.h:4586
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)
Definition: SemaDecl.cpp:1728
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6480
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:15065
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:4734
@ 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:3222
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:414
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:2537
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:6153
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:7566
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:5584
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:550
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6733
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3309
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
bool isUnevaluated() const
Definition: Expr.h:1902
StringRef getString() const
Definition: Expr.h:1850
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3708
StringRef getKindName() const
Definition: Decl.h:3776
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3688
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4728
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4722
bool isUnion() const
Definition: Decl.h:3791
TagKind getTagKind() const
Definition: Decl.h:3780
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3739
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:1235
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:583
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1273
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
Represents a template argument.
Definition: TemplateBase.h:61
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:247
@ Template
A single template declaration.
Definition: TemplateName.h:219
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6085
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:5775
unsigned getDepth() const
Definition: Type.h:5774
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3556
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5556
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3575
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:3391
const Type * getTypeForDecl() const
Definition: Decl.h:3415
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:7326
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:7337
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:3139
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6348
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3121
The base class of the type hierarchy.
Definition: Type.h:1813
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2454
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isVoidType() const
Definition: Type.h:7901
bool isBooleanType() const
Definition: Type.h:8029
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2880
bool isIncompleteArrayType() const
Definition: Type.h:7682
bool isUndeducedAutoType() const
Definition: Type.h:7757
bool isRValueReferenceType() const
Definition: Type.h:7628
bool isArrayType() const
Definition: Type.h:7674
bool isPointerType() const
Definition: Type.h:7608
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7941
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
bool isEnumeralType() const
Definition: Type.h:7706
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3246
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isLValueReferenceType() const
Definition: Type.h:7624
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7870
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
QualType getCanonicalTypeInternal() const
Definition: Type.h:2932
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2643
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8069
bool isFunctionProtoType() const
Definition: Type.h:2490
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8042
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2667
bool isObjCObjectType() const
Definition: Type.h:7744
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8035
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
bool isRecordType() const
Definition: Type.h:7702
bool isUnionType() const
Definition: Type.cpp:660
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:1878
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1874
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
QualType getUnderlyingType() const
Definition: Decl.h:3488
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2283
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4838
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:1060
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1236
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1233
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:1068
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition: DeclSpec.h:1071
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4040
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3288
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3959
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3267
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3239
Represents a C++ using-declaration.
Definition: DeclCXX.h:3512
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3561
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3553
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3173
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3549
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3539
Represents C++ using-directive.
Definition: DeclCXX.h:3015
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2937
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3713
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3194
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3217
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3356
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3113
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2787
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1549
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2257
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2813
void setCXXCondDecl()
Definition: Decl.h:1599
bool isInlineSpecified() const
Definition: Decl.h:1534
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2551
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1213
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1195
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2820
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1164
const Expr * getInit() const
Definition: Decl.h:1355
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:944
void setInit(Expr *I)
Definition: Decl.cpp:2454
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2505
void setExceptionVariable(bool EV)
Definition: Decl.h:1477
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:3965
unsigned getNumElements() const
Definition: Type.h:3980
QualType getElementType() const
Definition: Type.h:3979
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2778
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2798
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2810
bool isOverrideSpecified() const
Definition: DeclSpec.h:2797
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2802
bool isFinalSpecified() const
Definition: DeclSpec.h:2800
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2801
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:60
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:589
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1867
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:708
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_decltype
Definition: Specifiers.h:89
@ TST_typename_pack_indexing
Definition: Specifiers.h:97
@ TST_decltype_auto
Definition: Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isa(CodeGen::Address addr)
Definition: Address.h:294
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2926
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:268
@ ICIS_ListInit
Direct list-initialization.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1762
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
CXXConstructionKind
Definition: ExprCXX.h:1532
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
StmtResult StmtError()
Definition: Ownership.h:265
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:805
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6295
@ 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:1042
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:431
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6270
@ 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:21
#define false
Definition: stdbool.h:22
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:1364
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1424
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1373
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1427
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1525
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1399
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1554
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1557
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1463
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1550
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1339
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1247
enum clang::DeclaratorChunk::@221 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1638
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:4703
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:4715
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4705
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4708
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:4711
Extra information about a function prototype.
Definition: Type.h:4731
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4738
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4732
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1006
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9804
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:9921
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:9898
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:9895
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:9848
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:9862
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:9866
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9924
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition: Sema.h:9950
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6379
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition: Ownership.h:104