clang 21.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
17#include "clang/AST/CharUnits.h"
19#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
27#include "clang/AST/TypeLoc.h"
36#include "clang/Sema/DeclSpec.h"
39#include "clang/Sema/Lookup.h"
42#include "clang/Sema/Scope.h"
44#include "clang/Sema/SemaCUDA.h"
46#include "clang/Sema/SemaObjC.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/StringExtras.h"
53#include "llvm/Support/ConvertUTF.h"
54#include "llvm/Support/SaveAndRestore.h"
55#include <map>
56#include <optional>
57#include <set>
58
59using namespace clang;
60
61//===----------------------------------------------------------------------===//
62// CheckDefaultArgumentVisitor
63//===----------------------------------------------------------------------===//
64
65namespace {
66/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
67/// the default argument of a parameter to determine whether it
68/// contains any ill-formed subexpressions. For example, this will
69/// diagnose the use of local variables or parameters within the
70/// default argument expression.
71class CheckDefaultArgumentVisitor
72 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
73 Sema &S;
74 const Expr *DefaultArg;
75
76public:
77 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
78 : S(S), DefaultArg(DefaultArg) {}
79
80 bool VisitExpr(const Expr *Node);
81 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
82 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
83 bool VisitLambdaExpr(const LambdaExpr *Lambda);
84 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
85};
86
87/// VisitExpr - Visit all of the children of this expression.
88bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
89 bool IsInvalid = false;
90 for (const Stmt *SubStmt : Node->children())
91 if (SubStmt)
92 IsInvalid |= Visit(SubStmt);
93 return IsInvalid;
94}
95
96/// VisitDeclRefExpr - Visit a reference to a declaration, to
97/// determine whether this declaration can be used in the default
98/// argument expression.
99bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
100 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
101
102 if (!isa<VarDecl, BindingDecl>(Decl))
103 return false;
104
105 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
106 // C++ [dcl.fct.default]p9:
107 // [...] parameters of a function shall not be used in default
108 // argument expressions, even if they are not evaluated. [...]
109 //
110 // C++17 [dcl.fct.default]p9 (by CWG 2082):
111 // [...] A parameter shall not appear as a potentially-evaluated
112 // expression in a default argument. [...]
113 //
114 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_param)
117 << Param->getDeclName() << DefaultArg->getSourceRange();
118 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
119 // C++ [dcl.fct.default]p7:
120 // Local variables shall not be used in default argument
121 // expressions.
122 //
123 // C++17 [dcl.fct.default]p7 (by CWG 2082):
124 // A local variable shall not appear as a potentially-evaluated
125 // expression in a default argument.
126 //
127 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
128 // Note: A local variable cannot be odr-used (6.3) in a default
129 // argument.
130 //
131 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
132 return S.Diag(DRE->getBeginLoc(),
133 diag::err_param_default_argument_references_local)
134 << Decl << DefaultArg->getSourceRange();
135 }
136 return false;
137}
138
139/// VisitCXXThisExpr - Visit a C++ "this" expression.
140bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
141 // C++ [dcl.fct.default]p8:
142 // The keyword this shall not be used in a default argument of a
143 // member function.
144 return S.Diag(ThisE->getBeginLoc(),
145 diag::err_param_default_argument_references_this)
146 << ThisE->getSourceRange();
147}
148
149bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
150 const PseudoObjectExpr *POE) {
151 bool Invalid = false;
152 for (const Expr *E : POE->semantics()) {
153 // Look through bindings.
154 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
155 E = OVE->getSourceExpr();
156 assert(E && "pseudo-object binding without source expression?");
157 }
158
159 Invalid |= Visit(E);
160 }
161 return Invalid;
162}
163
164bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
165 // [expr.prim.lambda.capture]p9
166 // a lambda-expression appearing in a default argument cannot implicitly or
167 // explicitly capture any local entity. Such a lambda-expression can still
168 // have an init-capture if any full-expression in its initializer satisfies
169 // the constraints of an expression appearing in a default argument.
170 bool Invalid = false;
171 for (const LambdaCapture &LC : Lambda->captures()) {
172 if (!Lambda->isInitCapture(&LC))
173 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
174 // Init captures are always VarDecl.
175 auto *D = cast<VarDecl>(LC.getCapturedVar());
176 Invalid |= Visit(D->getInit());
177 }
178 return Invalid;
179}
180} // namespace
181
182void
184 const CXXMethodDecl *Method) {
185 // If we have an MSAny spec already, don't bother.
186 if (!Method || ComputedEST == EST_MSAny)
187 return;
188
189 const FunctionProtoType *Proto
190 = Method->getType()->getAs<FunctionProtoType>();
191 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
192 if (!Proto)
193 return;
194
196
197 // If we have a throw-all spec at this point, ignore the function.
198 if (ComputedEST == EST_None)
199 return;
200
201 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
202 EST = EST_BasicNoexcept;
203
204 switch (EST) {
205 case EST_Unparsed:
207 case EST_Unevaluated:
208 llvm_unreachable("should not see unresolved exception specs here");
209
210 // If this function can throw any exceptions, make a note of that.
211 case EST_MSAny:
212 case EST_None:
213 // FIXME: Whichever we see last of MSAny and None determines our result.
214 // We should make a consistent, order-independent choice here.
215 ClearExceptions();
216 ComputedEST = EST;
217 return;
219 ClearExceptions();
220 ComputedEST = EST_None;
221 return;
222 // FIXME: If the call to this decl is using any of its default arguments, we
223 // need to search them for potentially-throwing calls.
224 // If this function has a basic noexcept, it doesn't affect the outcome.
226 case EST_NoexceptTrue:
227 case EST_NoThrow:
228 return;
229 // If we're still at noexcept(true) and there's a throw() callee,
230 // change to that specification.
231 case EST_DynamicNone:
232 if (ComputedEST == EST_BasicNoexcept)
233 ComputedEST = EST_DynamicNone;
234 return;
236 llvm_unreachable(
237 "should not generate implicit declarations for dependent cases");
238 case EST_Dynamic:
239 break;
240 }
241 assert(EST == EST_Dynamic && "EST case not considered earlier.");
242 assert(ComputedEST != EST_None &&
243 "Shouldn't collect exceptions when throw-all is guaranteed.");
244 ComputedEST = EST_Dynamic;
245 // Record the exceptions in this function's exception specification.
246 for (const auto &E : Proto->exceptions())
247 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
248 Exceptions.push_back(E);
249}
250
252 if (!S || ComputedEST == EST_MSAny)
253 return;
254
255 // FIXME:
256 //
257 // C++0x [except.spec]p14:
258 // [An] implicit exception-specification specifies the type-id T if and
259 // only if T is allowed by the exception-specification of a function directly
260 // invoked by f's implicit definition; f shall allow all exceptions if any
261 // function it directly invokes allows all exceptions, and f shall allow no
262 // exceptions if every function it directly invokes allows no exceptions.
263 //
264 // Note in particular that if an implicit exception-specification is generated
265 // for a function containing a throw-expression, that specification can still
266 // be noexcept(true).
267 //
268 // Note also that 'directly invoked' is not defined in the standard, and there
269 // is no indication that we should only consider potentially-evaluated calls.
270 //
271 // Ultimately we should implement the intent of the standard: the exception
272 // specification should be the set of exceptions which can be thrown by the
273 // implicit definition. For now, we assume that any non-nothrow expression can
274 // throw any exception.
275
276 if (Self->canThrow(S))
277 ComputedEST = EST_None;
278}
279
281 SourceLocation EqualLoc) {
282 if (RequireCompleteType(Param->getLocation(), Param->getType(),
283 diag::err_typecheck_decl_incomplete_type))
284 return true;
285
286 // C++ [dcl.fct.default]p5
287 // A default argument expression is implicitly converted (clause
288 // 4) to the parameter type. The default argument expression has
289 // the same semantic constraints as the initializer expression in
290 // a declaration of a variable of the parameter type, using the
291 // copy-initialization semantics (8.5).
293 Param);
295 EqualLoc);
296 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
297 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
298 if (Result.isInvalid())
299 return true;
300 Arg = Result.getAs<Expr>();
301
302 CheckCompletedExpr(Arg, EqualLoc);
304
305 return Arg;
306}
307
309 SourceLocation EqualLoc) {
310 // Add the default argument to the parameter
311 Param->setDefaultArg(Arg);
312
313 // We have already instantiated this parameter; provide each of the
314 // instantiations with the uninstantiated default argument.
315 UnparsedDefaultArgInstantiationsMap::iterator InstPos
317 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
318 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
319 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
320
321 // We're done tracking this parameter's instantiations.
323 }
324}
325
326void
328 Expr *DefaultArg) {
329 if (!param || !DefaultArg)
330 return;
331
332 ParmVarDecl *Param = cast<ParmVarDecl>(param);
333 UnparsedDefaultArgLocs.erase(Param);
334
335 // Default arguments are only permitted in C++
336 if (!getLangOpts().CPlusPlus) {
337 Diag(EqualLoc, diag::err_param_default_argument)
338 << DefaultArg->getSourceRange();
339 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
340 }
341
342 // Check for unexpanded parameter packs.
344 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
345
346 // C++11 [dcl.fct.default]p3
347 // A default argument expression [...] shall not be specified for a
348 // parameter pack.
349 if (Param->isParameterPack()) {
350 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
351 << DefaultArg->getSourceRange();
352 // Recover by discarding the default argument.
353 Param->setDefaultArg(nullptr);
354 return;
355 }
356
357 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
358 if (Result.isInvalid())
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360
361 DefaultArg = Result.getAs<Expr>();
362
363 // Check that the default argument is well-formed
364 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
365 if (DefaultArgChecker.Visit(DefaultArg))
366 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
367
368 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
369}
370
372 SourceLocation EqualLoc,
373 SourceLocation ArgLoc) {
374 if (!param)
375 return;
376
377 ParmVarDecl *Param = cast<ParmVarDecl>(param);
378 Param->setUnparsedDefaultArg();
379 UnparsedDefaultArgLocs[Param] = ArgLoc;
380}
381
383 Expr *DefaultArg) {
384 if (!param)
385 return;
386
387 ParmVarDecl *Param = cast<ParmVarDecl>(param);
388 Param->setInvalidDecl();
389 UnparsedDefaultArgLocs.erase(Param);
390 ExprResult RE;
391 if (DefaultArg) {
392 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
393 Param->getType().getNonReferenceType());
394 } else {
395 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
396 Param->getType().getNonReferenceType());
397 }
398 Param->setDefaultArg(RE.get());
399}
400
402 // C++ [dcl.fct.default]p3
403 // A default argument expression shall be specified only in the
404 // parameter-declaration-clause of a function declaration or in a
405 // template-parameter (14.1). It shall not be specified for a
406 // parameter pack. If it is specified in a
407 // parameter-declaration-clause, it shall not occur within a
408 // declarator or abstract-declarator of a parameter-declaration.
409 bool MightBeFunction = D.isFunctionDeclarationContext();
410 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
411 DeclaratorChunk &chunk = D.getTypeObject(i);
412 if (chunk.Kind == DeclaratorChunk::Function) {
413 if (MightBeFunction) {
414 // This is a function declaration. It can have default arguments, but
415 // keep looking in case its return type is a function type with default
416 // arguments.
417 MightBeFunction = false;
418 continue;
419 }
420 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
421 ++argIdx) {
422 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
423 if (Param->hasUnparsedDefaultArg()) {
424 std::unique_ptr<CachedTokens> Toks =
425 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
426 SourceRange SR;
427 if (Toks->size() > 1)
428 SR = SourceRange((*Toks)[1].getLocation(),
429 Toks->back().getLocation());
430 else
431 SR = UnparsedDefaultArgLocs[Param];
432 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
433 << SR;
434 } else if (Param->getDefaultArg()) {
435 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
436 << Param->getDefaultArg()->getSourceRange();
437 Param->setDefaultArg(nullptr);
438 }
439 }
440 } else if (chunk.Kind != DeclaratorChunk::Paren) {
441 MightBeFunction = false;
442 }
443 }
444}
445
447 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
448 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
449 });
450}
451
453 Scope *S) {
454 bool Invalid = false;
455
456 // The declaration context corresponding to the scope is the semantic
457 // parent, unless this is a local function declaration, in which case
458 // it is that surrounding function.
459 DeclContext *ScopeDC = New->isLocalExternDecl()
460 ? New->getLexicalDeclContext()
461 : New->getDeclContext();
462
463 // Find the previous declaration for the purpose of default arguments.
464 FunctionDecl *PrevForDefaultArgs = Old;
465 for (/**/; PrevForDefaultArgs;
466 // Don't bother looking back past the latest decl if this is a local
467 // extern declaration; nothing else could work.
468 PrevForDefaultArgs = New->isLocalExternDecl()
469 ? nullptr
470 : PrevForDefaultArgs->getPreviousDecl()) {
471 // Ignore hidden declarations.
472 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
473 continue;
474
475 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
476 !New->isCXXClassMember()) {
477 // Ignore default arguments of old decl if they are not in
478 // the same scope and this is not an out-of-line definition of
479 // a member function.
480 continue;
481 }
482
483 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
484 // If only one of these is a local function declaration, then they are
485 // declared in different scopes, even though isDeclInScope may think
486 // they're in the same scope. (If both are local, the scope check is
487 // sufficient, and if neither is local, then they are in the same scope.)
488 continue;
489 }
490
491 // We found the right previous declaration.
492 break;
493 }
494
495 // C++ [dcl.fct.default]p4:
496 // For non-template functions, default arguments can be added in
497 // later declarations of a function in the same
498 // scope. Declarations in different scopes have completely
499 // distinct sets of default arguments. That is, declarations in
500 // inner scopes do not acquire default arguments from
501 // declarations in outer scopes, and vice versa. In a given
502 // function declaration, all parameters subsequent to a
503 // parameter with a default argument shall have default
504 // arguments supplied in this or previous declarations. A
505 // default argument shall not be redefined by a later
506 // declaration (not even to the same value).
507 //
508 // C++ [dcl.fct.default]p6:
509 // Except for member functions of class templates, the default arguments
510 // in a member function definition that appears outside of the class
511 // definition are added to the set of default arguments provided by the
512 // member function declaration in the class definition.
513 for (unsigned p = 0, NumParams = PrevForDefaultArgs
514 ? PrevForDefaultArgs->getNumParams()
515 : 0;
516 p < NumParams; ++p) {
517 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
518 ParmVarDecl *NewParam = New->getParamDecl(p);
519
520 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
521 bool NewParamHasDfl = NewParam->hasDefaultArg();
522
523 if (OldParamHasDfl && NewParamHasDfl) {
524 unsigned DiagDefaultParamID =
525 diag::err_param_default_argument_redefinition;
526
527 // MSVC accepts that default parameters be redefined for member functions
528 // of template class. The new default parameter's value is ignored.
529 Invalid = true;
530 if (getLangOpts().MicrosoftExt) {
531 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
532 if (MD && MD->getParent()->getDescribedClassTemplate()) {
533 // Merge the old default argument into the new parameter.
534 NewParam->setHasInheritedDefaultArg();
535 if (OldParam->hasUninstantiatedDefaultArg())
537 OldParam->getUninstantiatedDefaultArg());
538 else
539 NewParam->setDefaultArg(OldParam->getInit());
540 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
541 Invalid = false;
542 }
543 }
544
545 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
546 // hint here. Alternatively, we could walk the type-source information
547 // for NewParam to find the last source location in the type... but it
548 // isn't worth the effort right now. This is the kind of test case that
549 // is hard to get right:
550 // int f(int);
551 // void g(int (*fp)(int) = f);
552 // void g(int (*fp)(int) = &f);
553 Diag(NewParam->getLocation(), DiagDefaultParamID)
554 << NewParam->getDefaultArgRange();
555
556 // Look for the function declaration where the default argument was
557 // actually written, which may be a declaration prior to Old.
558 for (auto Older = PrevForDefaultArgs;
559 OldParam->hasInheritedDefaultArg(); /**/) {
560 Older = Older->getPreviousDecl();
561 OldParam = Older->getParamDecl(p);
562 }
563
564 Diag(OldParam->getLocation(), diag::note_previous_definition)
565 << OldParam->getDefaultArgRange();
566 } else if (OldParamHasDfl) {
567 // Merge the old default argument into the new parameter unless the new
568 // function is a friend declaration in a template class. In the latter
569 // case the default arguments will be inherited when the friend
570 // declaration will be instantiated.
571 if (New->getFriendObjectKind() == Decl::FOK_None ||
573 // It's important to use getInit() here; getDefaultArg()
574 // strips off any top-level ExprWithCleanups.
575 NewParam->setHasInheritedDefaultArg();
576 if (OldParam->hasUnparsedDefaultArg())
577 NewParam->setUnparsedDefaultArg();
578 else if (OldParam->hasUninstantiatedDefaultArg())
580 OldParam->getUninstantiatedDefaultArg());
581 else
582 NewParam->setDefaultArg(OldParam->getInit());
583 }
584 } else if (NewParamHasDfl) {
585 if (New->getDescribedFunctionTemplate()) {
586 // Paragraph 4, quoted above, only applies to non-template functions.
587 Diag(NewParam->getLocation(),
588 diag::err_param_default_argument_template_redecl)
589 << NewParam->getDefaultArgRange();
590 Diag(PrevForDefaultArgs->getLocation(),
591 diag::note_template_prev_declaration)
592 << false;
593 } else if (New->getTemplateSpecializationKind()
596 // C++ [temp.expr.spec]p21:
597 // Default function arguments shall not be specified in a declaration
598 // or a definition for one of the following explicit specializations:
599 // - the explicit specialization of a function template;
600 // - the explicit specialization of a member function template;
601 // - the explicit specialization of a member function of a class
602 // template where the class template specialization to which the
603 // member function specialization belongs is implicitly
604 // instantiated.
605 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
607 << New->getDeclName()
608 << NewParam->getDefaultArgRange();
609 } else if (New->getDeclContext()->isDependentContext()) {
610 // C++ [dcl.fct.default]p6 (DR217):
611 // Default arguments for a member function of a class template shall
612 // be specified on the initial declaration of the member function
613 // within the class template.
614 //
615 // Reading the tea leaves a bit in DR217 and its reference to DR205
616 // leads me to the conclusion that one cannot add default function
617 // arguments for an out-of-line definition of a member function of a
618 // dependent type.
619 int WhichKind = 2;
621 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
622 if (Record->getDescribedClassTemplate())
623 WhichKind = 0;
624 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
625 WhichKind = 1;
626 else
627 WhichKind = 2;
628 }
629
630 Diag(NewParam->getLocation(),
631 diag::err_param_default_argument_member_template_redecl)
632 << WhichKind
633 << NewParam->getDefaultArgRange();
634 }
635 }
636 }
637
638 // DR1344: If a default argument is added outside a class definition and that
639 // default argument makes the function a special member function, the program
640 // is ill-formed. This can only happen for constructors.
641 if (isa<CXXConstructorDecl>(New) &&
643 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
644 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
645 if (NewSM != OldSM) {
646 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
647 assert(NewParam->hasDefaultArg());
648 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
649 << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
650 Diag(Old->getLocation(), diag::note_previous_declaration);
651 }
652 }
653
654 const FunctionDecl *Def;
655 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
656 // template has a constexpr specifier then all its declarations shall
657 // contain the constexpr specifier.
658 if (New->getConstexprKind() != Old->getConstexprKind()) {
659 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
660 << New << static_cast<int>(New->getConstexprKind())
661 << static_cast<int>(Old->getConstexprKind());
662 Diag(Old->getLocation(), diag::note_previous_declaration);
663 Invalid = true;
664 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
665 Old->isDefined(Def) &&
666 // If a friend function is inlined but does not have 'inline'
667 // specifier, it is a definition. Do not report attribute conflict
668 // in this case, redefinition will be diagnosed later.
669 (New->isInlineSpecified() ||
671 // C++11 [dcl.fcn.spec]p4:
672 // If the definition of a function appears in a translation unit before its
673 // first declaration as inline, the program is ill-formed.
674 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
675 Diag(Def->getLocation(), diag::note_previous_definition);
676 Invalid = true;
677 }
678
679 // C++17 [temp.deduct.guide]p3:
680 // Two deduction guide declarations in the same translation unit
681 // for the same class template shall not have equivalent
682 // parameter-declaration-clauses.
683 if (isa<CXXDeductionGuideDecl>(New) &&
685 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
686 Diag(Old->getLocation(), diag::note_previous_declaration);
687 }
688
689 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
690 // argument expression, that declaration shall be a definition and shall be
691 // the only declaration of the function or function template in the
692 // translation unit.
695 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
696 Diag(Old->getLocation(), diag::note_previous_declaration);
697 Invalid = true;
698 }
699
700 // C++11 [temp.friend]p4 (DR329):
701 // When a function is defined in a friend function declaration in a class
702 // template, the function is instantiated when the function is odr-used.
703 // The same restrictions on multiple declarations and definitions that
704 // apply to non-template function declarations and definitions also apply
705 // to these implicit definitions.
706 const FunctionDecl *OldDefinition = nullptr;
708 Old->isDefined(OldDefinition, true))
709 CheckForFunctionRedefinition(New, OldDefinition);
710
711 return Invalid;
712}
713
716 ? diag::warn_cxx23_placeholder_var_definition
717 : diag::ext_placeholder_var_definition);
718}
719
720NamedDecl *
722 MultiTemplateParamsArg TemplateParamLists) {
723 assert(D.isDecompositionDeclarator());
724 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
725
726 // The syntax only allows a decomposition declarator as a simple-declaration,
727 // a for-range-declaration, or a condition in Clang, but we parse it in more
728 // cases than that.
729 if (!D.mayHaveDecompositionDeclarator()) {
730 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
731 << Decomp.getSourceRange();
732 return nullptr;
733 }
734
735 if (!TemplateParamLists.empty()) {
736 // FIXME: There's no rule against this, but there are also no rules that
737 // would actually make it usable, so we reject it for now.
738 Diag(TemplateParamLists.front()->getTemplateLoc(),
739 diag::err_decomp_decl_template);
740 return nullptr;
741 }
742
743 Diag(Decomp.getLSquareLoc(),
745 ? diag::ext_decomp_decl
746 : D.getContext() == DeclaratorContext::Condition
747 ? diag::ext_decomp_decl_cond
748 : diag::warn_cxx14_compat_decomp_decl)
749 << Decomp.getSourceRange();
750
751 // The semantic context is always just the current context.
752 DeclContext *const DC = CurContext;
753
754 // C++17 [dcl.dcl]/8:
755 // The decl-specifier-seq shall contain only the type-specifier auto
756 // and cv-qualifiers.
757 // C++20 [dcl.dcl]/8:
758 // If decl-specifier-seq contains any decl-specifier other than static,
759 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
760 // C++23 [dcl.pre]/6:
761 // Each decl-specifier in the decl-specifier-seq shall be static,
762 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
763 auto &DS = D.getDeclSpec();
764 {
765 // Note: While constrained-auto needs to be checked, we do so separately so
766 // we can emit a better diagnostic.
767 SmallVector<StringRef, 8> BadSpecifiers;
768 SmallVector<SourceLocation, 8> BadSpecifierLocs;
769 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
770 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
771 if (auto SCS = DS.getStorageClassSpec()) {
772 if (SCS == DeclSpec::SCS_static) {
773 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
774 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
775 } else {
776 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
777 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
778 }
779 }
780 if (auto TSCS = DS.getThreadStorageClassSpec()) {
781 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
782 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
783 }
784 if (DS.hasConstexprSpecifier()) {
785 BadSpecifiers.push_back(
786 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
787 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
788 }
789 if (DS.isInlineSpecified()) {
790 BadSpecifiers.push_back("inline");
791 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
792 }
793
794 if (!BadSpecifiers.empty()) {
795 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
796 Err << (int)BadSpecifiers.size()
797 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
798 // Don't add FixItHints to remove the specifiers; we do still respect
799 // them when building the underlying variable.
800 for (auto Loc : BadSpecifierLocs)
801 Err << SourceRange(Loc, Loc);
802 } else if (!CPlusPlus20Specifiers.empty()) {
803 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
805 ? diag::warn_cxx17_compat_decomp_decl_spec
806 : diag::ext_decomp_decl_spec);
807 Warn << (int)CPlusPlus20Specifiers.size()
808 << llvm::join(CPlusPlus20Specifiers.begin(),
809 CPlusPlus20Specifiers.end(), " ");
810 for (auto Loc : CPlusPlus20SpecifierLocs)
811 Warn << SourceRange(Loc, Loc);
812 }
813 // We can't recover from it being declared as a typedef.
814 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
815 return nullptr;
816 }
817
818 // C++2a [dcl.struct.bind]p1:
819 // A cv that includes volatile is deprecated
820 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
822 Diag(DS.getVolatileSpecLoc(),
823 diag::warn_deprecated_volatile_structured_binding);
824
826 QualType R = TInfo->getType();
827
828 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
830 D.setInvalidType();
831
832 // The syntax only allows a single ref-qualifier prior to the decomposition
833 // declarator. No other declarator chunks are permitted. Also check the type
834 // specifier here.
835 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
836 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
837 (D.getNumTypeObjects() == 1 &&
838 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
839 Diag(Decomp.getLSquareLoc(),
840 (D.hasGroupingParens() ||
841 (D.getNumTypeObjects() &&
842 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
843 ? diag::err_decomp_decl_parens
844 : diag::err_decomp_decl_type)
845 << R;
846
847 // In most cases, there's no actual problem with an explicitly-specified
848 // type, but a function type won't work here, and ActOnVariableDeclarator
849 // shouldn't be called for such a type.
850 if (R->isFunctionType())
851 D.setInvalidType();
852 }
853
854 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
855 if (DS.isConstrainedAuto()) {
856 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
857 assert(TemplRep->Kind == TNK_Concept_template &&
858 "No other template kind should be possible for a constrained auto");
859
860 SourceRange TemplRange{TemplRep->TemplateNameLoc,
861 TemplRep->RAngleLoc.isValid()
862 ? TemplRep->RAngleLoc
863 : TemplRep->TemplateNameLoc};
864 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
865 << TemplRange << FixItHint::CreateRemoval(TemplRange);
866 }
867
868 // Build the BindingDecls.
870
871 // Build the BindingDecls.
872 for (auto &B : D.getDecompositionDeclarator().bindings()) {
873 // Check for name conflicts.
874 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
875 IdentifierInfo *VarName = B.Name;
876 assert(VarName && "Cannot have an unnamed binding declaration");
877
879 RedeclarationKind::ForVisibleRedeclaration);
881 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
882
883 // It's not permitted to shadow a template parameter name.
884 if (Previous.isSingleResult() &&
885 Previous.getFoundDecl()->isTemplateParameter()) {
886 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
887 Previous.getFoundDecl());
888 Previous.clear();
889 }
890
891 QualType QT;
892 if (B.EllipsisLoc.isValid()) {
893 if (!cast<Decl>(DC)->isTemplated())
894 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
896 /*ExpectsPackInType=*/false);
897 }
898
899 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
900
901 ProcessDeclAttributeList(S, BD, *B.Attrs);
902
903 // Find the shadowed declaration before filtering for scope.
904 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
906 : nullptr;
907
908 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
909 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
910 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
911 /*AllowInlineNamespace*/false);
912
913 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
914 DC->isFunctionOrMethod() && VarName->isPlaceholder();
915 if (!Previous.empty()) {
916 if (IsPlaceholder) {
917 bool sameDC = (Previous.end() - 1)
918 ->getDeclContext()
919 ->getRedeclContext()
920 ->Equals(DC->getRedeclContext());
921 if (sameDC &&
922 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
923 Previous.clear();
925 }
926 } else {
927 auto *Old = Previous.getRepresentativeDecl();
928 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
929 Diag(Old->getLocation(), diag::note_previous_definition);
930 }
931 } else if (ShadowedDecl && !D.isRedeclaration()) {
932 CheckShadow(BD, ShadowedDecl, Previous);
933 }
934 PushOnScopeChains(BD, S, true);
935 Bindings.push_back(BD);
936 ParsingInitForAutoVars.insert(BD);
937 }
938
939 // There are no prior lookup results for the variable itself, because it
940 // is unnamed.
941 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
942 Decomp.getLSquareLoc());
944 RedeclarationKind::ForVisibleRedeclaration);
945
946 // Build the variable that holds the non-decomposed object.
947 bool AddToScope = true;
948 NamedDecl *New =
949 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
950 MultiTemplateParamsArg(), AddToScope, Bindings);
951 if (AddToScope) {
952 S->AddDecl(New);
954 }
955
956 if (OpenMP().isInOpenMPDeclareTargetContext())
958
959 return New;
960}
961
962// Check the arity of the structured bindings.
963// Create the resolved pack expr if needed.
965 QualType DecompType,
967 unsigned MemberCount) {
968 auto BindingWithPackItr =
969 std::find_if(Bindings.begin(), Bindings.end(),
970 [](BindingDecl *D) -> bool { return D->isParameterPack(); });
971 bool HasPack = BindingWithPackItr != Bindings.end();
972 bool IsValid;
973 if (!HasPack) {
974 IsValid = Bindings.size() == MemberCount;
975 } else {
976 // There may not be more members than non-pack bindings.
977 IsValid = MemberCount >= Bindings.size() - 1;
978 }
979
980 if (IsValid && HasPack) {
981 // Create the pack expr and assign it to the binding.
982 unsigned PackSize = MemberCount - Bindings.size() + 1;
984 S.Context.DependentTy, std::nullopt, /*ExpectsPackInType=*/false);
985 BindingDecl *BD = (*BindingWithPackItr);
987 DecompType, PackSize);
988 BD->setDecomposedDecl(DD);
989 BD->setBinding(PackType, RP);
990
991 BindingDecl *BPack = *BindingWithPackItr;
992 // Create the nested BindingDecls.
993 for (Expr *&E : RP->getExprs()) {
994 auto *NestedBD = BindingDecl::Create(S.Context, BPack->getDeclContext(),
995 BPack->getLocation(),
996 BPack->getIdentifier(), QualType());
997 NestedBD->setDecomposedDecl(DD);
999 BPack->getLocation());
1000 }
1001 }
1002
1003 if (IsValid)
1004 return false;
1005
1006 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1007 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1008 << (MemberCount < Bindings.size());
1009 return true;
1010}
1011
1014 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1015 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1016 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1017 auto *DD = cast<DecompositionDecl>(Src);
1018
1019 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1020 return true;
1021
1022 unsigned I = 0;
1023 for (auto *B : DD->flat_bindings()) {
1024 SourceLocation Loc = B->getLocation();
1025 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1026 if (E.isInvalid())
1027 return true;
1028 E = GetInit(Loc, E.get(), I++);
1029 if (E.isInvalid())
1030 return true;
1031 B->setBinding(ElemType, E.get());
1032 }
1033
1034 return false;
1035}
1036
1039 ValueDecl *Src, QualType DecompType,
1040 const llvm::APSInt &NumElems,
1041 QualType ElemType) {
1043 S, Bindings, Src, DecompType, NumElems, ElemType,
1044 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1046 if (E.isInvalid())
1047 return ExprError();
1048 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1049 });
1050}
1051
1053 ValueDecl *Src, QualType DecompType,
1054 const ConstantArrayType *CAT) {
1055 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1056 llvm::APSInt(CAT->getSize()),
1057 CAT->getElementType());
1058}
1059
1061 ValueDecl *Src, QualType DecompType,
1062 const VectorType *VT) {
1064 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1066 DecompType.getQualifiers()));
1067}
1068
1071 ValueDecl *Src, QualType DecompType,
1072 const ComplexType *CT) {
1074 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1076 DecompType.getQualifiers()),
1077 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1078 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1079 });
1080}
1081
1084 const TemplateParameterList *Params) {
1086 llvm::raw_svector_ostream OS(SS);
1087 bool First = true;
1088 unsigned I = 0;
1089 for (auto &Arg : Args.arguments()) {
1090 if (!First)
1091 OS << ", ";
1092 Arg.getArgument().print(PrintingPolicy, OS,
1094 PrintingPolicy, Params, I));
1095 First = false;
1096 I++;
1097 }
1098 return std::string(OS.str());
1099}
1100
1101static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1102 SourceLocation Loc, StringRef Trait,
1104 unsigned DiagID) {
1105 auto DiagnoseMissing = [&] {
1106 if (DiagID)
1108 Args, /*Params*/ nullptr);
1109 return true;
1110 };
1111
1112 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1114 if (!Std)
1115 return DiagnoseMissing();
1116
1117 // Look up the trait itself, within namespace std. We can diagnose various
1118 // problems with this lookup even if we've been asked to not diagnose a
1119 // missing specialization, because this can only fail if the user has been
1120 // declaring their own names in namespace std or we don't support the
1121 // standard library implementation in use.
1125 return DiagnoseMissing();
1126 if (Result.isAmbiguous())
1127 return true;
1128
1129 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1130 if (!TraitTD) {
1131 Result.suppressDiagnostics();
1132 NamedDecl *Found = *Result.begin();
1133 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1134 S.Diag(Found->getLocation(), diag::note_declared_at);
1135 return true;
1136 }
1137
1138 // Build the template-id.
1139 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1140 if (TraitTy.isNull())
1141 return true;
1142 if (!S.isCompleteType(Loc, TraitTy)) {
1143 if (DiagID)
1145 Loc, TraitTy, DiagID,
1147 TraitTD->getTemplateParameters()));
1148 return true;
1149 }
1150
1151 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1152 assert(RD && "specialization of class template is not a class?");
1153
1154 // Look up the member of the trait type.
1155 S.LookupQualifiedName(TraitMemberLookup, RD);
1156 return TraitMemberLookup.isAmbiguous();
1157}
1158
1161 uint64_t I) {
1163 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1164}
1165
1169}
1170
1171namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1172
1174 llvm::APSInt &Size) {
1177
1180
1181 // Form template argument list for tuple_size<T>.
1184
1185 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1186 // it's not tuple-like.
1187 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1188 R.empty())
1189 return IsTupleLike::NotTupleLike;
1190
1191 // If we get this far, we've committed to the tuple interpretation, but
1192 // we can still fail if there actually isn't a usable ::value.
1193
1194 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1195 LookupResult &R;
1197 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1198 : R(R), Args(Args) {}
1199 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1200 SourceLocation Loc) override {
1201 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1203 /*Params*/ nullptr);
1204 }
1205 } Diagnoser(R, Args);
1206
1207 ExprResult E =
1208 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1209 if (E.isInvalid())
1210 return IsTupleLike::Error;
1211
1212 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1213 if (E.isInvalid())
1214 return IsTupleLike::Error;
1215
1216 return IsTupleLike::TupleLike;
1217}
1218
1219/// \return std::tuple_element<I, T>::type.
1221 unsigned I, QualType T) {
1222 // Form template argument list for tuple_element<I, T>.
1224 Args.addArgument(
1227
1228 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1231 S, R, Loc, "tuple_element", Args,
1232 diag::err_decomp_decl_std_tuple_element_not_specialized))
1233 return QualType();
1234
1235 auto *TD = R.getAsSingle<TypeDecl>();
1236 if (!TD) {
1238 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1240 /*Params*/ nullptr);
1241 if (!R.empty())
1242 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1243 return QualType();
1244 }
1245
1246 return S.Context.getTypeDeclType(TD);
1247}
1248
1249namespace {
1250struct InitializingBinding {
1251 Sema &S;
1252 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1255 Ctx.PointOfInstantiation = BD->getLocation();
1256 Ctx.Entity = BD;
1258 }
1259 ~InitializingBinding() {
1261 }
1262};
1263}
1264
1267 VarDecl *Src, QualType DecompType,
1268 const llvm::APSInt &TupleSize) {
1269 auto *DD = cast<DecompositionDecl>(Src);
1270 unsigned NumElems = (unsigned)TupleSize.getLimitedValue(UINT_MAX);
1271 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1272 return true;
1273
1274 if (Bindings.empty())
1275 return false;
1276
1277 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1278
1279 // [dcl.decomp]p3:
1280 // The unqualified-id get is looked up in the scope of E by class member
1281 // access lookup ...
1282 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1283 bool UseMemberGet = false;
1284 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1285 if (auto *RD = DecompType->getAsCXXRecordDecl())
1286 S.LookupQualifiedName(MemberGet, RD);
1287 if (MemberGet.isAmbiguous())
1288 return true;
1289 // ... and if that finds at least one declaration that is a function
1290 // template whose first template parameter is a non-type parameter ...
1291 for (NamedDecl *D : MemberGet) {
1292 if (FunctionTemplateDecl *FTD =
1293 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1294 TemplateParameterList *TPL = FTD->getTemplateParameters();
1295 if (TPL->size() != 0 &&
1296 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1297 // ... the initializer is e.get<i>().
1298 UseMemberGet = true;
1299 break;
1300 }
1301 }
1302 }
1303 }
1304
1305 unsigned I = 0;
1306 for (auto *B : DD->flat_bindings()) {
1307 InitializingBinding InitContext(S, B);
1308 SourceLocation Loc = B->getLocation();
1309
1310 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1311 if (E.isInvalid())
1312 return true;
1313
1314 // e is an lvalue if the type of the entity is an lvalue reference and
1315 // an xvalue otherwise
1316 if (!Src->getType()->isLValueReferenceType())
1317 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1318 E.get(), nullptr, VK_XValue,
1320
1322 Args.addArgument(
1324
1325 if (UseMemberGet) {
1326 // if [lookup of member get] finds at least one declaration, the
1327 // initializer is e.get<i-1>().
1328 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1329 CXXScopeSpec(), SourceLocation(), nullptr,
1330 MemberGet, &Args, nullptr);
1331 if (E.isInvalid())
1332 return true;
1333
1334 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1335 } else {
1336 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1337 // in the associated namespaces.
1340 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1342 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1343
1344 Expr *Arg = E.get();
1345 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1346 }
1347 if (E.isInvalid())
1348 return true;
1349 Expr *Init = E.get();
1350
1351 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1352 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1353 if (T.isNull())
1354 return true;
1355
1356 // each vi is a variable of type "reference to T" initialized with the
1357 // initializer, where the reference is an lvalue reference if the
1358 // initializer is an lvalue and an rvalue reference otherwise
1359 QualType RefType =
1360 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1361 if (RefType.isNull())
1362 return true;
1363 auto *RefVD = VarDecl::Create(
1364 S.Context, Src->getDeclContext(), Loc, Loc,
1365 B->getDeclName().getAsIdentifierInfo(), RefType,
1367 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1368 RefVD->setTSCSpec(Src->getTSCSpec());
1369 RefVD->setImplicit();
1370 if (Src->isInlineSpecified())
1371 RefVD->setInlineSpecified();
1372 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1373
1376 InitializationSequence Seq(S, Entity, Kind, Init);
1377 E = Seq.Perform(S, Entity, Kind, Init);
1378 if (E.isInvalid())
1379 return true;
1380 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1381 if (E.isInvalid())
1382 return true;
1383 RefVD->setInit(E.get());
1385
1387 DeclarationNameInfo(B->getDeclName(), Loc),
1388 RefVD);
1389 if (E.isInvalid())
1390 return true;
1391
1392 B->setBinding(T, E.get());
1393 I++;
1394 }
1395
1396 return false;
1397}
1398
1399/// Find the base class to decompose in a built-in decomposition of a class type.
1400/// This base class search is, unfortunately, not quite like any other that we
1401/// perform anywhere else in C++.
1403 const CXXRecordDecl *RD,
1404 CXXCastPath &BasePath) {
1405 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1406 CXXBasePath &Path) {
1407 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1408 };
1409
1410 const CXXRecordDecl *ClassWithFields = nullptr;
1412 if (RD->hasDirectFields())
1413 // [dcl.decomp]p4:
1414 // Otherwise, all of E's non-static data members shall be public direct
1415 // members of E ...
1416 ClassWithFields = RD;
1417 else {
1418 // ... or of ...
1419 CXXBasePaths Paths;
1420 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1421 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1422 // If no classes have fields, just decompose RD itself. (This will work
1423 // if and only if zero bindings were provided.)
1424 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1425 }
1426
1427 CXXBasePath *BestPath = nullptr;
1428 for (auto &P : Paths) {
1429 if (!BestPath)
1430 BestPath = &P;
1431 else if (!S.Context.hasSameType(P.back().Base->getType(),
1432 BestPath->back().Base->getType())) {
1433 // ... the same ...
1434 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1435 << false << RD << BestPath->back().Base->getType()
1436 << P.back().Base->getType();
1437 return DeclAccessPair();
1438 } else if (P.Access < BestPath->Access) {
1439 BestPath = &P;
1440 }
1441 }
1442
1443 // ... unambiguous ...
1444 QualType BaseType = BestPath->back().Base->getType();
1445 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1446 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1447 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1448 return DeclAccessPair();
1449 }
1450
1451 // ... [accessible, implied by other rules] base class of E.
1452 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1453 *BestPath, diag::err_decomp_decl_inaccessible_base);
1454 AS = BestPath->Access;
1455
1456 ClassWithFields = BaseType->getAsCXXRecordDecl();
1457 S.BuildBasePathArray(Paths, BasePath);
1458 }
1459
1460 // The above search did not check whether the selected class itself has base
1461 // classes with fields, so check that now.
1462 CXXBasePaths Paths;
1463 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1464 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1465 << (ClassWithFields == RD) << RD << ClassWithFields
1466 << Paths.front().back().Base->getType();
1467 return DeclAccessPair();
1468 }
1469
1470 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1471}
1472
1474 ValueDecl *Src, QualType DecompType,
1475 const CXXRecordDecl *OrigRD) {
1476 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1477 diag::err_incomplete_type))
1478 return true;
1479
1480 CXXCastPath BasePath;
1481 DeclAccessPair BasePair =
1482 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1483 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1484 if (!RD)
1485 return true;
1487 DecompType.getQualifiers());
1488
1489 auto *DD = cast<DecompositionDecl>(Src);
1490 unsigned NumFields = llvm::count_if(
1491 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1492 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1493 return true;
1494
1495 // all of E's non-static data members shall be [...] well-formed
1496 // when named as e.name in the context of the structured binding,
1497 // E shall not have an anonymous union member, ...
1498 auto FlatBindings = DD->flat_bindings();
1499 assert(llvm::range_size(FlatBindings) == NumFields);
1500 auto FlatBindingsItr = FlatBindings.begin();
1501 for (auto *FD : RD->fields()) {
1502 if (FD->isUnnamedBitField())
1503 continue;
1504
1505 // All the non-static data members are required to be nameable, so they
1506 // must all have names.
1507 if (!FD->getDeclName()) {
1508 if (RD->isLambda()) {
1509 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1510 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1511 return true;
1512 }
1513
1514 if (FD->isAnonymousStructOrUnion()) {
1515 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1516 << DecompType << FD->getType()->isUnionType();
1517 S.Diag(FD->getLocation(), diag::note_declared_at);
1518 return true;
1519 }
1520
1521 // FIXME: Are there any other ways we could have an anonymous member?
1522 }
1523
1524 // We have a real field to bind.
1525 assert(FlatBindingsItr != FlatBindings.end());
1526 BindingDecl *B = *(FlatBindingsItr++);
1528
1529 // The field must be accessible in the context of the structured binding.
1530 // We already checked that the base class is accessible.
1531 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1532 // const_cast here.
1534 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1536 BasePair.getAccess(), FD->getAccess())));
1537
1538 // Initialize the binding to Src.FD.
1539 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1540 if (E.isInvalid())
1541 return true;
1542 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1543 VK_LValue, &BasePath);
1544 if (E.isInvalid())
1545 return true;
1546 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1547 CXXScopeSpec(), FD,
1548 DeclAccessPair::make(FD, FD->getAccess()),
1549 DeclarationNameInfo(FD->getDeclName(), Loc));
1550 if (E.isInvalid())
1551 return true;
1552
1553 // If the type of the member is T, the referenced type is cv T, where cv is
1554 // the cv-qualification of the decomposition expression.
1555 //
1556 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1557 // 'const' to the type of the field.
1558 Qualifiers Q = DecompType.getQualifiers();
1559 if (FD->isMutable())
1560 Q.removeConst();
1561 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1562 }
1563
1564 return false;
1565}
1566
1568 QualType DecompType = DD->getType();
1569
1570 // If the type of the decomposition is dependent, then so is the type of
1571 // each binding.
1572 if (DecompType->isDependentType()) {
1573 // Note that all of the types are still Null or PackExpansionType.
1574 for (auto *B : DD->bindings()) {
1575 // Do not overwrite any pack type.
1576 if (B->getType().isNull())
1577 B->setType(Context.DependentTy);
1578 }
1579 return;
1580 }
1581
1582 DecompType = DecompType.getNonReferenceType();
1584
1585 // C++1z [dcl.decomp]/2:
1586 // If E is an array type [...]
1587 // As an extension, we also support decomposition of built-in complex and
1588 // vector types.
1589 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1590 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1591 DD->setInvalidDecl();
1592 return;
1593 }
1594 if (auto *VT = DecompType->getAs<VectorType>()) {
1595 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1596 DD->setInvalidDecl();
1597 return;
1598 }
1599 if (auto *CT = DecompType->getAs<ComplexType>()) {
1600 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1601 DD->setInvalidDecl();
1602 return;
1603 }
1604
1605 // C++1z [dcl.decomp]/3:
1606 // if the expression std::tuple_size<E>::value is a well-formed integral
1607 // constant expression, [...]
1608 llvm::APSInt TupleSize(32);
1609 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1610 case IsTupleLike::Error:
1611 DD->setInvalidDecl();
1612 return;
1613
1614 case IsTupleLike::TupleLike:
1615 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1616 DD->setInvalidDecl();
1617 return;
1618
1619 case IsTupleLike::NotTupleLike:
1620 break;
1621 }
1622
1623 // C++1z [dcl.dcl]/8:
1624 // [E shall be of array or non-union class type]
1625 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1626 if (!RD || RD->isUnion()) {
1627 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1628 << DD << !RD << DecompType;
1629 DD->setInvalidDecl();
1630 return;
1631 }
1632
1633 // C++1z [dcl.decomp]/4:
1634 // all of E's non-static data members shall be [...] direct members of
1635 // E or of the same unambiguous public base class of E, ...
1636 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1637 DD->setInvalidDecl();
1638}
1639
1641 // Shortcut if exceptions are disabled.
1642 if (!getLangOpts().CXXExceptions)
1643 return;
1644
1645 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1646 "Should only be called if types are otherwise the same.");
1647
1648 QualType NewType = New->getType();
1649 QualType OldType = Old->getType();
1650
1651 // We're only interested in pointers and references to functions, as well
1652 // as pointers to member functions.
1653 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1654 NewType = R->getPointeeType();
1655 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1656 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1657 NewType = P->getPointeeType();
1658 OldType = OldType->castAs<PointerType>()->getPointeeType();
1659 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1660 NewType = M->getPointeeType();
1661 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1662 }
1663
1664 if (!NewType->isFunctionProtoType())
1665 return;
1666
1667 // There's lots of special cases for functions. For function pointers, system
1668 // libraries are hopefully not as broken so that we don't need these
1669 // workarounds.
1671 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1672 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1673 New->setInvalidDecl();
1674 }
1675}
1676
1677/// CheckCXXDefaultArguments - Verify that the default arguments for a
1678/// function declaration are well-formed according to C++
1679/// [dcl.fct.default].
1681 // This checking doesn't make sense for explicit specializations; their
1682 // default arguments are determined by the declaration we're specializing,
1683 // not by FD.
1685 return;
1686 if (auto *FTD = FD->getDescribedFunctionTemplate())
1687 if (FTD->isMemberSpecialization())
1688 return;
1689
1690 unsigned NumParams = FD->getNumParams();
1691 unsigned ParamIdx = 0;
1692
1693 // Find first parameter with a default argument
1694 for (; ParamIdx < NumParams; ++ParamIdx) {
1695 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1696 if (Param->hasDefaultArg())
1697 break;
1698 }
1699
1700 // C++20 [dcl.fct.default]p4:
1701 // In a given function declaration, each parameter subsequent to a parameter
1702 // with a default argument shall have a default argument supplied in this or
1703 // a previous declaration, unless the parameter was expanded from a
1704 // parameter pack, or shall be a function parameter pack.
1705 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1706 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1707 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1710 continue;
1711 if (Param->isInvalidDecl())
1712 /* We already complained about this parameter. */;
1713 else if (Param->getIdentifier())
1714 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1715 << Param->getIdentifier();
1716 else
1717 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1718 }
1719}
1720
1721/// Check that the given type is a literal type. Issue a diagnostic if not,
1722/// if Kind is Diagnose.
1723/// \return \c true if a problem has been found (and optionally diagnosed).
1724template <typename... Ts>
1726 SourceLocation Loc, QualType T, unsigned DiagID,
1727 Ts &&...DiagArgs) {
1728 if (T->isDependentType())
1729 return false;
1730
1731 switch (Kind) {
1733 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1734 std::forward<Ts>(DiagArgs)...);
1735
1737 return !T->isLiteralType(SemaRef.Context);
1738 }
1739
1740 llvm_unreachable("unknown CheckConstexprKind");
1741}
1742
1743/// Determine whether a destructor cannot be constexpr due to
1745 const CXXDestructorDecl *DD,
1747 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1748 "this check is obsolete for C++23");
1749 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1750 const CXXRecordDecl *RD =
1752 if (!RD || RD->hasConstexprDestructor())
1753 return true;
1754
1756 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1757 << static_cast<int>(DD->getConstexprKind()) << !FD
1758 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1759 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1760 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1761 }
1762 return false;
1763 };
1764
1765 const CXXRecordDecl *RD = DD->getParent();
1766 for (const CXXBaseSpecifier &B : RD->bases())
1767 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1768 return false;
1769 for (const FieldDecl *FD : RD->fields())
1770 if (!Check(FD->getLocation(), FD->getType(), FD))
1771 return false;
1772 return true;
1773}
1774
1775/// Check whether a function's parameter types are all literal types. If so,
1776/// return true. If not, produce a suitable diagnostic and return false.
1778 const FunctionDecl *FD,
1780 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1781 "this check is obsolete for C++23");
1782 unsigned ArgIndex = 0;
1783 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1784 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1785 e = FT->param_type_end();
1786 i != e; ++i, ++ArgIndex) {
1787 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1788 assert(PD && "null in a parameter list");
1789 SourceLocation ParamLoc = PD->getLocation();
1790 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1791 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1792 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1793 FD->isConsteval()))
1794 return false;
1795 }
1796 return true;
1797}
1798
1799/// Check whether a function's return type is a literal type. If so, return
1800/// true. If not, produce a suitable diagnostic and return false.
1803 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1804 "this check is obsolete for C++23");
1805 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1806 diag::err_constexpr_non_literal_return,
1807 FD->isConsteval()))
1808 return false;
1809 return true;
1810}
1811
1812/// Get diagnostic %select index for tag kind for
1813/// record diagnostic message.
1814/// WARNING: Indexes apply to particular diagnostics only!
1815///
1816/// \returns diagnostic %select index.
1818 switch (Tag) {
1820 return 0;
1822 return 1;
1823 case TagTypeKind::Class:
1824 return 2;
1825 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1826 }
1827}
1828
1829static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1830 Stmt *Body,
1832static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1833
1835 CheckConstexprKind Kind) {
1836 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1837 if (MD && MD->isInstance()) {
1838 // C++11 [dcl.constexpr]p4:
1839 // The definition of a constexpr constructor shall satisfy the following
1840 // constraints:
1841 // - the class shall not have any virtual base classes;
1842 //
1843 // FIXME: This only applies to constructors and destructors, not arbitrary
1844 // member functions.
1845 const CXXRecordDecl *RD = MD->getParent();
1846 if (RD->getNumVBases()) {
1848 return false;
1849
1850 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1851 << isa<CXXConstructorDecl>(NewFD)
1853 for (const auto &I : RD->vbases())
1854 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1855 << I.getSourceRange();
1856 return false;
1857 }
1858 }
1859
1860 if (!isa<CXXConstructorDecl>(NewFD)) {
1861 // C++11 [dcl.constexpr]p3:
1862 // The definition of a constexpr function shall satisfy the following
1863 // constraints:
1864 // - it shall not be virtual; (removed in C++20)
1865 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1866 if (Method && Method->isVirtual()) {
1867 if (getLangOpts().CPlusPlus20) {
1868 if (Kind == CheckConstexprKind::Diagnose)
1869 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1870 } else {
1872 return false;
1873
1874 Method = Method->getCanonicalDecl();
1875 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1876
1877 // If it's not obvious why this function is virtual, find an overridden
1878 // function which uses the 'virtual' keyword.
1879 const CXXMethodDecl *WrittenVirtual = Method;
1880 while (!WrittenVirtual->isVirtualAsWritten())
1881 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1882 if (WrittenVirtual != Method)
1883 Diag(WrittenVirtual->getLocation(),
1884 diag::note_overridden_virtual_function);
1885 return false;
1886 }
1887 }
1888
1889 // - its return type shall be a literal type; (removed in C++23)
1890 if (!getLangOpts().CPlusPlus23 &&
1891 !CheckConstexprReturnType(*this, NewFD, Kind))
1892 return false;
1893 }
1894
1895 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1896 // A destructor can be constexpr only if the defaulted destructor could be;
1897 // we don't need to check the members and bases if we already know they all
1898 // have constexpr destructors. (removed in C++23)
1899 if (!getLangOpts().CPlusPlus23 &&
1900 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1902 return false;
1903 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1904 return false;
1905 }
1906 }
1907
1908 // - each of its parameter types shall be a literal type; (removed in C++23)
1909 if (!getLangOpts().CPlusPlus23 &&
1910 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1911 return false;
1912
1913 Stmt *Body = NewFD->getBody();
1914 assert(Body &&
1915 "CheckConstexprFunctionDefinition called on function with no body");
1916 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1917}
1918
1919/// Check the given declaration statement is legal within a constexpr function
1920/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1921///
1922/// \return true if the body is OK (maybe only as an extension), false if we
1923/// have diagnosed a problem.
1925 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1927 // C++11 [dcl.constexpr]p3 and p4:
1928 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1929 // contain only
1930 for (const auto *DclIt : DS->decls()) {
1931 switch (DclIt->getKind()) {
1932 case Decl::StaticAssert:
1933 case Decl::Using:
1934 case Decl::UsingShadow:
1935 case Decl::UsingDirective:
1936 case Decl::UnresolvedUsingTypename:
1937 case Decl::UnresolvedUsingValue:
1938 case Decl::UsingEnum:
1939 // - static_assert-declarations
1940 // - using-declarations,
1941 // - using-directives,
1942 // - using-enum-declaration
1943 continue;
1944
1945 case Decl::Typedef:
1946 case Decl::TypeAlias: {
1947 // - typedef declarations and alias-declarations that do not define
1948 // classes or enumerations,
1949 const auto *TN = cast<TypedefNameDecl>(DclIt);
1950 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1951 // Don't allow variably-modified types in constexpr functions.
1953 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1954 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1955 << TL.getSourceRange() << TL.getType()
1956 << isa<CXXConstructorDecl>(Dcl);
1957 }
1958 return false;
1959 }
1960 continue;
1961 }
1962
1963 case Decl::Enum:
1964 case Decl::CXXRecord:
1965 // C++1y allows types to be defined, not just declared.
1966 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1968 SemaRef.Diag(DS->getBeginLoc(),
1969 SemaRef.getLangOpts().CPlusPlus14
1970 ? diag::warn_cxx11_compat_constexpr_type_definition
1971 : diag::ext_constexpr_type_definition)
1972 << isa<CXXConstructorDecl>(Dcl);
1973 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1974 return false;
1975 }
1976 }
1977 continue;
1978
1979 case Decl::EnumConstant:
1980 case Decl::IndirectField:
1981 case Decl::ParmVar:
1982 // These can only appear with other declarations which are banned in
1983 // C++11 and permitted in C++1y, so ignore them.
1984 continue;
1985
1986 case Decl::Var:
1987 case Decl::Decomposition: {
1988 // C++1y [dcl.constexpr]p3 allows anything except:
1989 // a definition of a variable of non-literal type or of static or
1990 // thread storage duration or [before C++2a] for which no
1991 // initialization is performed.
1992 const auto *VD = cast<VarDecl>(DclIt);
1993 if (VD->isThisDeclarationADefinition()) {
1994 if (VD->isStaticLocal()) {
1996 SemaRef.Diag(VD->getLocation(),
1997 SemaRef.getLangOpts().CPlusPlus23
1998 ? diag::warn_cxx20_compat_constexpr_var
1999 : diag::ext_constexpr_static_var)
2000 << isa<CXXConstructorDecl>(Dcl)
2001 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2002 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2003 return false;
2004 }
2005 }
2006 if (SemaRef.LangOpts.CPlusPlus23) {
2007 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2008 diag::warn_cxx20_compat_constexpr_var,
2009 isa<CXXConstructorDecl>(Dcl),
2010 /*variable of non-literal type*/ 2);
2011 } else if (CheckLiteralType(
2012 SemaRef, Kind, VD->getLocation(), VD->getType(),
2013 diag::err_constexpr_local_var_non_literal_type,
2014 isa<CXXConstructorDecl>(Dcl))) {
2015 return false;
2016 }
2017 if (!VD->getType()->isDependentType() &&
2018 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2020 SemaRef.Diag(
2021 VD->getLocation(),
2022 SemaRef.getLangOpts().CPlusPlus20
2023 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
2024 : diag::ext_constexpr_local_var_no_init)
2025 << isa<CXXConstructorDecl>(Dcl);
2026 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2027 return false;
2028 }
2029 continue;
2030 }
2031 }
2033 SemaRef.Diag(VD->getLocation(),
2034 SemaRef.getLangOpts().CPlusPlus14
2035 ? diag::warn_cxx11_compat_constexpr_local_var
2036 : diag::ext_constexpr_local_var)
2037 << isa<CXXConstructorDecl>(Dcl);
2038 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2039 return false;
2040 }
2041 continue;
2042 }
2043
2044 case Decl::NamespaceAlias:
2045 case Decl::Function:
2046 // These are disallowed in C++11 and permitted in C++1y. Allow them
2047 // everywhere as an extension.
2048 if (!Cxx1yLoc.isValid())
2049 Cxx1yLoc = DS->getBeginLoc();
2050 continue;
2051
2052 default:
2054 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2055 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2056 }
2057 return false;
2058 }
2059 }
2060
2061 return true;
2062}
2063
2064/// Check that the given field is initialized within a constexpr constructor.
2065///
2066/// \param Dcl The constexpr constructor being checked.
2067/// \param Field The field being checked. This may be a member of an anonymous
2068/// struct or union nested within the class being checked.
2069/// \param Inits All declarations, including anonymous struct/union members and
2070/// indirect members, for which any initialization was provided.
2071/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2072/// multiple notes for different members to the same error.
2073/// \param Kind Whether we're diagnosing a constructor as written or determining
2074/// whether the formal requirements are satisfied.
2075/// \return \c false if we're checking for validity and the constructor does
2076/// not satisfy the requirements on a constexpr constructor.
2078 const FunctionDecl *Dcl,
2079 FieldDecl *Field,
2080 llvm::SmallSet<Decl*, 16> &Inits,
2081 bool &Diagnosed,
2083 // In C++20 onwards, there's nothing to check for validity.
2085 SemaRef.getLangOpts().CPlusPlus20)
2086 return true;
2087
2088 if (Field->isInvalidDecl())
2089 return true;
2090
2091 if (Field->isUnnamedBitField())
2092 return true;
2093
2094 // Anonymous unions with no variant members and empty anonymous structs do not
2095 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2096 // indirect fields don't need initializing.
2097 if (Field->isAnonymousStructOrUnion() &&
2098 (Field->getType()->isUnionType()
2099 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2100 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2101 return true;
2102
2103 if (!Inits.count(Field)) {
2105 if (!Diagnosed) {
2106 SemaRef.Diag(Dcl->getLocation(),
2107 SemaRef.getLangOpts().CPlusPlus20
2108 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2109 : diag::ext_constexpr_ctor_missing_init);
2110 Diagnosed = true;
2111 }
2112 SemaRef.Diag(Field->getLocation(),
2113 diag::note_constexpr_ctor_missing_init);
2114 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2115 return false;
2116 }
2117 } else if (Field->isAnonymousStructOrUnion()) {
2118 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2119 for (auto *I : RD->fields())
2120 // If an anonymous union contains an anonymous struct of which any member
2121 // is initialized, all members must be initialized.
2122 if (!RD->isUnion() || Inits.count(I))
2123 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2124 Kind))
2125 return false;
2126 }
2127 return true;
2128}
2129
2130/// Check the provided statement is allowed in a constexpr function
2131/// definition.
2132static bool
2135 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2136 SourceLocation &Cxx2bLoc,
2138 // - its function-body shall be [...] a compound-statement that contains only
2139 switch (S->getStmtClass()) {
2140 case Stmt::NullStmtClass:
2141 // - null statements,
2142 return true;
2143
2144 case Stmt::DeclStmtClass:
2145 // - static_assert-declarations
2146 // - using-declarations,
2147 // - using-directives,
2148 // - typedef declarations and alias-declarations that do not define
2149 // classes or enumerations,
2150 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2151 return false;
2152 return true;
2153
2154 case Stmt::ReturnStmtClass:
2155 // - and exactly one return statement;
2156 if (isa<CXXConstructorDecl>(Dcl)) {
2157 // C++1y allows return statements in constexpr constructors.
2158 if (!Cxx1yLoc.isValid())
2159 Cxx1yLoc = S->getBeginLoc();
2160 return true;
2161 }
2162
2163 ReturnStmts.push_back(S->getBeginLoc());
2164 return true;
2165
2166 case Stmt::AttributedStmtClass:
2167 // Attributes on a statement don't affect its formal kind and hence don't
2168 // affect its validity in a constexpr function.
2170 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2171 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2172
2173 case Stmt::CompoundStmtClass: {
2174 // C++1y allows compound-statements.
2175 if (!Cxx1yLoc.isValid())
2176 Cxx1yLoc = S->getBeginLoc();
2177
2178 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2179 for (auto *BodyIt : CompStmt->body()) {
2180 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2181 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2182 return false;
2183 }
2184 return true;
2185 }
2186
2187 case Stmt::IfStmtClass: {
2188 // C++1y allows if-statements.
2189 if (!Cxx1yLoc.isValid())
2190 Cxx1yLoc = S->getBeginLoc();
2191
2192 IfStmt *If = cast<IfStmt>(S);
2193 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2194 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2195 return false;
2196 if (If->getElse() &&
2197 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2198 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2199 return false;
2200 return true;
2201 }
2202
2203 case Stmt::WhileStmtClass:
2204 case Stmt::DoStmtClass:
2205 case Stmt::ForStmtClass:
2206 case Stmt::CXXForRangeStmtClass:
2207 case Stmt::ContinueStmtClass:
2208 // C++1y allows all of these. We don't allow them as extensions in C++11,
2209 // because they don't make sense without variable mutation.
2210 if (!SemaRef.getLangOpts().CPlusPlus14)
2211 break;
2212 if (!Cxx1yLoc.isValid())
2213 Cxx1yLoc = S->getBeginLoc();
2214 for (Stmt *SubStmt : S->children()) {
2215 if (SubStmt &&
2216 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2217 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2218 return false;
2219 }
2220 return true;
2221
2222 case Stmt::SwitchStmtClass:
2223 case Stmt::CaseStmtClass:
2224 case Stmt::DefaultStmtClass:
2225 case Stmt::BreakStmtClass:
2226 // C++1y allows switch-statements, and since they don't need variable
2227 // mutation, we can reasonably allow them in C++11 as an extension.
2228 if (!Cxx1yLoc.isValid())
2229 Cxx1yLoc = S->getBeginLoc();
2230 for (Stmt *SubStmt : S->children()) {
2231 if (SubStmt &&
2232 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2233 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2234 return false;
2235 }
2236 return true;
2237
2238 case Stmt::LabelStmtClass:
2239 case Stmt::GotoStmtClass:
2240 if (Cxx2bLoc.isInvalid())
2241 Cxx2bLoc = S->getBeginLoc();
2242 for (Stmt *SubStmt : S->children()) {
2243 if (SubStmt &&
2244 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2245 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2246 return false;
2247 }
2248 return true;
2249
2250 case Stmt::GCCAsmStmtClass:
2251 case Stmt::MSAsmStmtClass:
2252 // C++2a allows inline assembly statements.
2253 case Stmt::CXXTryStmtClass:
2254 if (Cxx2aLoc.isInvalid())
2255 Cxx2aLoc = S->getBeginLoc();
2256 for (Stmt *SubStmt : S->children()) {
2257 if (SubStmt &&
2258 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2259 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2260 return false;
2261 }
2262 return true;
2263
2264 case Stmt::CXXCatchStmtClass:
2265 // Do not bother checking the language mode (already covered by the
2266 // try block check).
2268 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2269 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2270 return false;
2271 return true;
2272
2273 default:
2274 if (!isa<Expr>(S))
2275 break;
2276
2277 // C++1y allows expression-statements.
2278 if (!Cxx1yLoc.isValid())
2279 Cxx1yLoc = S->getBeginLoc();
2280 return true;
2281 }
2282
2284 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2285 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2286 }
2287 return false;
2288}
2289
2290/// Check the body for the given constexpr function declaration only contains
2291/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2292///
2293/// \return true if the body is OK, false if we have found or diagnosed a
2294/// problem.
2296 Stmt *Body,
2299
2300 if (isa<CXXTryStmt>(Body)) {
2301 // C++11 [dcl.constexpr]p3:
2302 // The definition of a constexpr function shall satisfy the following
2303 // constraints: [...]
2304 // - its function-body shall be = delete, = default, or a
2305 // compound-statement
2306 //
2307 // C++11 [dcl.constexpr]p4:
2308 // In the definition of a constexpr constructor, [...]
2309 // - its function-body shall not be a function-try-block;
2310 //
2311 // This restriction is lifted in C++2a, as long as inner statements also
2312 // apply the general constexpr rules.
2313 switch (Kind) {
2315 if (!SemaRef.getLangOpts().CPlusPlus20)
2316 return false;
2317 break;
2318
2320 SemaRef.Diag(Body->getBeginLoc(),
2321 !SemaRef.getLangOpts().CPlusPlus20
2322 ? diag::ext_constexpr_function_try_block_cxx20
2323 : diag::warn_cxx17_compat_constexpr_function_try_block)
2324 << isa<CXXConstructorDecl>(Dcl);
2325 break;
2326 }
2327 }
2328
2329 // - its function-body shall be [...] a compound-statement that contains only
2330 // [... list of cases ...]
2331 //
2332 // Note that walking the children here is enough to properly check for
2333 // CompoundStmt and CXXTryStmt body.
2334 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2335 for (Stmt *SubStmt : Body->children()) {
2336 if (SubStmt &&
2337 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2338 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2339 return false;
2340 }
2341
2343 // If this is only valid as an extension, report that we don't satisfy the
2344 // constraints of the current language.
2345 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2346 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2347 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2348 return false;
2349 } else if (Cxx2bLoc.isValid()) {
2350 SemaRef.Diag(Cxx2bLoc,
2351 SemaRef.getLangOpts().CPlusPlus23
2352 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2353 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2354 << isa<CXXConstructorDecl>(Dcl);
2355 } else if (Cxx2aLoc.isValid()) {
2356 SemaRef.Diag(Cxx2aLoc,
2357 SemaRef.getLangOpts().CPlusPlus20
2358 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2359 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2360 << isa<CXXConstructorDecl>(Dcl);
2361 } else if (Cxx1yLoc.isValid()) {
2362 SemaRef.Diag(Cxx1yLoc,
2363 SemaRef.getLangOpts().CPlusPlus14
2364 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2365 : diag::ext_constexpr_body_invalid_stmt)
2366 << isa<CXXConstructorDecl>(Dcl);
2367 }
2368
2369 if (const CXXConstructorDecl *Constructor
2370 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2371 const CXXRecordDecl *RD = Constructor->getParent();
2372 // DR1359:
2373 // - every non-variant non-static data member and base class sub-object
2374 // shall be initialized;
2375 // DR1460:
2376 // - if the class is a union having variant members, exactly one of them
2377 // shall be initialized;
2378 if (RD->isUnion()) {
2379 if (Constructor->getNumCtorInitializers() == 0 &&
2380 RD->hasVariantMembers()) {
2382 SemaRef.Diag(
2383 Dcl->getLocation(),
2384 SemaRef.getLangOpts().CPlusPlus20
2385 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2386 : diag::ext_constexpr_union_ctor_no_init);
2387 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2388 return false;
2389 }
2390 }
2391 } else if (!Constructor->isDependentContext() &&
2392 !Constructor->isDelegatingConstructor()) {
2393 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2394
2395 // Skip detailed checking if we have enough initializers, and we would
2396 // allow at most one initializer per member.
2397 bool AnyAnonStructUnionMembers = false;
2398 unsigned Fields = 0;
2400 E = RD->field_end(); I != E; ++I, ++Fields) {
2401 if (I->isAnonymousStructOrUnion()) {
2402 AnyAnonStructUnionMembers = true;
2403 break;
2404 }
2405 }
2406 // DR1460:
2407 // - if the class is a union-like class, but is not a union, for each of
2408 // its anonymous union members having variant members, exactly one of
2409 // them shall be initialized;
2410 if (AnyAnonStructUnionMembers ||
2411 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2412 // Check initialization of non-static data members. Base classes are
2413 // always initialized so do not need to be checked. Dependent bases
2414 // might not have initializers in the member initializer list.
2415 llvm::SmallSet<Decl*, 16> Inits;
2416 for (const auto *I: Constructor->inits()) {
2417 if (FieldDecl *FD = I->getMember())
2418 Inits.insert(FD);
2419 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2420 Inits.insert(ID->chain_begin(), ID->chain_end());
2421 }
2422
2423 bool Diagnosed = false;
2424 for (auto *I : RD->fields())
2425 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2426 Kind))
2427 return false;
2428 }
2429 }
2430 } else {
2431 if (ReturnStmts.empty()) {
2432 switch (Kind) {
2435 return false;
2436 break;
2437
2439 // The formal requirements don't include this rule in C++14, even
2440 // though the "must be able to produce a constant expression" rules
2441 // still imply it in some cases.
2442 if (!SemaRef.getLangOpts().CPlusPlus14)
2443 return false;
2444 break;
2445 }
2446 } else if (ReturnStmts.size() > 1) {
2447 switch (Kind) {
2449 SemaRef.Diag(
2450 ReturnStmts.back(),
2451 SemaRef.getLangOpts().CPlusPlus14
2452 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2453 : diag::ext_constexpr_body_multiple_return);
2454 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2455 SemaRef.Diag(ReturnStmts[I],
2456 diag::note_constexpr_body_previous_return);
2457 break;
2458
2460 if (!SemaRef.getLangOpts().CPlusPlus14)
2461 return false;
2462 break;
2463 }
2464 }
2465 }
2466
2467 // C++11 [dcl.constexpr]p5:
2468 // if no function argument values exist such that the function invocation
2469 // substitution would produce a constant expression, the program is
2470 // ill-formed; no diagnostic required.
2471 // C++11 [dcl.constexpr]p3:
2472 // - every constructor call and implicit conversion used in initializing the
2473 // return value shall be one of those allowed in a constant expression.
2474 // C++11 [dcl.constexpr]p4:
2475 // - every constructor involved in initializing non-static data members and
2476 // base class sub-objects shall be a constexpr constructor.
2477 //
2478 // Note that this rule is distinct from the "requirements for a constexpr
2479 // function", so is not checked in CheckValid mode. Because the check for
2480 // constexpr potential is expensive, skip the check if the diagnostic is
2481 // disabled, the function is declared in a system header, or we're in C++23
2482 // or later mode (see https://wg21.link/P2448).
2483 bool SkipCheck =
2484 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2487 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2489 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2491 SemaRef.Diag(Dcl->getLocation(),
2492 diag::ext_constexpr_function_never_constant_expr)
2493 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2494 << Dcl->getNameInfo().getSourceRange();
2495 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2496 SemaRef.Diag(Diags[I].first, Diags[I].second);
2497 // Don't return false here: we allow this for compatibility in
2498 // system headers.
2499 }
2500
2501 return true;
2502}
2503
2505 const FunctionDecl *Dcl) {
2506 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2508 // Skip emitting a missing return error diagnostic for non-void functions
2509 // since C++23 no longer mandates constexpr functions to yield constant
2510 // expressions.
2511 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2512 return true;
2513
2514 // C++14 doesn't require constexpr functions to contain a 'return'
2515 // statement. We still do, unless the return type might be void, because
2516 // otherwise if there's no return statement, the function cannot
2517 // be used in a core constant expression.
2518 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2519 SemaRef.Diag(Dcl->getLocation(),
2520 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2521 : diag::err_constexpr_body_no_return)
2522 << Dcl->isConsteval();
2523 return OK;
2524}
2525
2527 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2529 return true;
2533 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2534 if (it != UndefinedButUsed.end()) {
2535 Diag(it->second, diag::err_immediate_function_used_before_definition)
2536 << it->first;
2537 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2538 if (FD->isImmediateFunction() && !FD->isConsteval())
2540 return false;
2541 }
2542 }
2543 return true;
2544}
2545
2547 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2548 "expected an immediate function");
2549 assert(FD->hasBody() && "expected the function to have a body");
2550 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2551 Sema &SemaRef;
2552
2553 const FunctionDecl *ImmediateFn;
2554 bool ImmediateFnIsConstructor;
2555 CXXConstructorDecl *CurrentConstructor = nullptr;
2556 CXXCtorInitializer *CurrentInit = nullptr;
2557
2558 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2559 : SemaRef(SemaRef), ImmediateFn(FD),
2560 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2561 ShouldVisitImplicitCode = true;
2562 ShouldVisitLambdaBody = false;
2563 }
2564
2565 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2568 if (CurrentConstructor && CurrentInit) {
2569 Loc = CurrentConstructor->getLocation();
2570 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2571 : SourceRange();
2572 }
2573
2574 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2575
2576 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2577 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2578 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2579 << (InitializedField != nullptr)
2580 << (CurrentInit && !CurrentInit->isWritten())
2581 << InitializedField << Range;
2582 }
2583 bool TraverseCallExpr(CallExpr *E) override {
2584 if (const auto *DR =
2585 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2586 DR && DR->isImmediateEscalating()) {
2587 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2588 return false;
2589 }
2590
2591 for (Expr *A : E->arguments())
2592 if (!TraverseStmt(A))
2593 return false;
2594
2595 return true;
2596 }
2597
2598 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2599 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2600 ReferencedFn && E->isImmediateEscalating()) {
2601 Diag(E, ReferencedFn, /*IsCall=*/false);
2602 return false;
2603 }
2604
2605 return true;
2606 }
2607
2608 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2609 CXXConstructorDecl *D = E->getConstructor();
2610 if (E->isImmediateEscalating()) {
2611 Diag(E, D, /*IsCall=*/true);
2612 return false;
2613 }
2614 return true;
2615 }
2616
2617 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2618 llvm::SaveAndRestore RAII(CurrentInit, Init);
2620 }
2621
2622 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2623 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2624 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2625 }
2626
2627 bool TraverseType(QualType T) override { return true; }
2628 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2629
2630 } Visitor(*this, FD);
2631 Visitor.TraverseDecl(FD);
2632}
2633
2635 assert(getLangOpts().CPlusPlus && "No class names in C!");
2636
2637 if (SS && SS->isInvalid())
2638 return nullptr;
2639
2640 if (SS && SS->isNotEmpty()) {
2641 DeclContext *DC = computeDeclContext(*SS, true);
2642 return dyn_cast_or_null<CXXRecordDecl>(DC);
2643 }
2644
2645 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2646}
2647
2649 const CXXScopeSpec *SS) {
2650 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2651 return CurDecl && &II == CurDecl->getIdentifier();
2652}
2653
2655 assert(getLangOpts().CPlusPlus && "No class names in C!");
2656
2657 if (!getLangOpts().SpellChecking)
2658 return false;
2659
2660 CXXRecordDecl *CurDecl;
2661 if (SS && SS->isSet() && !SS->isInvalid()) {
2662 DeclContext *DC = computeDeclContext(*SS, true);
2663 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2664 } else
2665 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2666
2667 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2668 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2669 < II->getLength()) {
2670 II = CurDecl->getIdentifier();
2671 return true;
2672 }
2673
2674 return false;
2675}
2676
2678 SourceRange SpecifierRange,
2679 bool Virtual, AccessSpecifier Access,
2680 TypeSourceInfo *TInfo,
2681 SourceLocation EllipsisLoc) {
2682 QualType BaseType = TInfo->getType();
2683 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2684 if (BaseType->containsErrors()) {
2685 // Already emitted a diagnostic when parsing the error type.
2686 return nullptr;
2687 }
2688
2689 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2690 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2691 << TInfo->getTypeLoc().getSourceRange();
2692 EllipsisLoc = SourceLocation();
2693 }
2694
2695 auto *BaseDecl =
2696 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2697 // C++ [class.derived.general]p2:
2698 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2699 // that is not an incompletely defined class; any cv-qualifiers are
2700 // ignored.
2701 if (BaseDecl) {
2702 // C++ [class.union.general]p4:
2703 // [...] A union shall not be used as a base class.
2704 if (BaseDecl->isUnion()) {
2705 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2706 return nullptr;
2707 }
2708
2709 if (BaseType.hasQualifiers()) {
2710 std::string Quals =
2712 Diag(BaseLoc, diag::warn_qual_base_type)
2713 << Quals << std::count(Quals.begin(), Quals.end(), ' ') + 1
2714 << BaseType;
2715 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2716 }
2717
2718 // For the MS ABI, propagate DLL attributes to base class templates.
2720 Context.getTargetInfo().getTriple().isPS()) {
2721 if (Attr *ClassAttr = getDLLAttr(Class)) {
2722 if (auto *BaseSpec =
2723 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2724 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2725 BaseLoc);
2726 }
2727 }
2728 }
2729
2730 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2731 SpecifierRange)) {
2732 Class->setInvalidDecl();
2733 return nullptr;
2734 }
2735
2736 BaseDecl = BaseDecl->getDefinition();
2737 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2738
2739 // Microsoft docs say:
2740 // "If a base-class has a code_seg attribute, derived classes must have the
2741 // same attribute."
2742 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2743 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2744 if ((DerivedCSA || BaseCSA) &&
2745 (!BaseCSA || !DerivedCSA ||
2746 BaseCSA->getName() != DerivedCSA->getName())) {
2747 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2748 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2749 << BaseDecl;
2750 return nullptr;
2751 }
2752
2753 // A class which contains a flexible array member is not suitable for use as
2754 // a base class:
2755 // - If the layout determines that a base comes before another base,
2756 // the flexible array member would index into the subsequent base.
2757 // - If the layout determines that base comes before the derived class,
2758 // the flexible array member would index into the derived class.
2759 if (BaseDecl->hasFlexibleArrayMember()) {
2760 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2761 << BaseDecl->getDeclName();
2762 return nullptr;
2763 }
2764
2765 // C++ [class]p3:
2766 // If a class is marked final and it appears as a base-type-specifier in
2767 // base-clause, the program is ill-formed.
2768 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2769 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2770 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2771 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2772 << BaseDecl->getDeclName() << FA->getRange();
2773 return nullptr;
2774 }
2775
2776 // If the base class is invalid the derived class is as well.
2777 if (BaseDecl->isInvalidDecl())
2778 Class->setInvalidDecl();
2779 } else if (BaseType->isDependentType()) {
2780 // Make sure that we don't make an ill-formed AST where the type of the
2781 // Class is non-dependent and its attached base class specifier is an
2782 // dependent type, which violates invariants in many clang code paths (e.g.
2783 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2784 // explicitly mark the Class decl invalid. The diagnostic was already
2785 // emitted.
2786 if (!Class->isDependentContext())
2787 Class->setInvalidDecl();
2788 } else {
2789 // The base class is some non-dependent non-class type.
2790 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2791 return nullptr;
2792 }
2793
2794 // In HLSL, unspecified class access is public rather than private.
2795 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2796 Access == AS_none)
2797 Access = AS_public;
2798
2799 // Create the base specifier.
2800 return new (Context) CXXBaseSpecifier(
2801 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2802 Access, TInfo, EllipsisLoc);
2803}
2804
2806 const ParsedAttributesView &Attributes,
2807 bool Virtual, AccessSpecifier Access,
2808 ParsedType basetype, SourceLocation BaseLoc,
2809 SourceLocation EllipsisLoc) {
2810 if (!classdecl)
2811 return true;
2812
2813 AdjustDeclIfTemplate(classdecl);
2814 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2815 if (!Class)
2816 return true;
2817
2818 // We haven't yet attached the base specifiers.
2819 Class->setIsParsingBaseSpecifiers();
2820
2821 // We do not support any C++11 attributes on base-specifiers yet.
2822 // Diagnose any attributes we see.
2823 for (const ParsedAttr &AL : Attributes) {
2824 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2825 continue;
2826 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2827 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2828 << AL << AL.getRange();
2829 else
2830 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2831 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2832 }
2833
2834 TypeSourceInfo *TInfo = nullptr;
2835 GetTypeFromParser(basetype, &TInfo);
2836
2837 if (EllipsisLoc.isInvalid() &&
2838 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2840 return true;
2841
2842 // C++ [class.union.general]p4:
2843 // [...] A union shall not have base classes.
2844 if (Class->isUnion()) {
2845 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2846 << SpecifierRange;
2847 return true;
2848 }
2849
2850 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2851 Virtual, Access, TInfo,
2852 EllipsisLoc))
2853 return BaseSpec;
2854
2855 Class->setInvalidDecl();
2856 return true;
2857}
2858
2859/// Use small set to collect indirect bases. As this is only used
2860/// locally, there's no need to abstract the small size parameter.
2862
2863/// Recursively add the bases of Type. Don't add Type itself.
2864static void
2866 const QualType &Type)
2867{
2868 // Even though the incoming type is a base, it might not be
2869 // a class -- it could be a template parm, for instance.
2870 if (auto Rec = Type->getAs<RecordType>()) {
2871 auto Decl = Rec->getAsCXXRecordDecl();
2872
2873 // Iterate over its bases.
2874 for (const auto &BaseSpec : Decl->bases()) {
2875 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2877 if (Set.insert(Base).second)
2878 // If we've not already seen it, recurse.
2880 }
2881 }
2882}
2883
2886 if (Bases.empty())
2887 return false;
2888
2889 // Used to keep track of which base types we have already seen, so
2890 // that we can properly diagnose redundant direct base types. Note
2891 // that the key is always the unqualified canonical type of the base
2892 // class.
2893 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2894
2895 // Used to track indirect bases so we can see if a direct base is
2896 // ambiguous.
2897 IndirectBaseSet IndirectBaseTypes;
2898
2899 // Copy non-redundant base specifiers into permanent storage.
2900 unsigned NumGoodBases = 0;
2901 bool Invalid = false;
2902 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2903 QualType NewBaseType
2904 = Context.getCanonicalType(Bases[idx]->getType());
2905 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2906
2907 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2908 if (KnownBase) {
2909 // C++ [class.mi]p3:
2910 // A class shall not be specified as a direct base class of a
2911 // derived class more than once.
2912 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2913 << KnownBase->getType() << Bases[idx]->getSourceRange();
2914
2915 // Delete the duplicate base class specifier; we're going to
2916 // overwrite its pointer later.
2917 Context.Deallocate(Bases[idx]);
2918
2919 Invalid = true;
2920 } else {
2921 // Okay, add this new base class.
2922 KnownBase = Bases[idx];
2923 Bases[NumGoodBases++] = Bases[idx];
2924
2925 if (NewBaseType->isDependentType())
2926 continue;
2927 // Note this base's direct & indirect bases, if there could be ambiguity.
2928 if (Bases.size() > 1)
2929 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2930
2931 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2932 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2933 if (Class->isInterface() &&
2934 (!RD->isInterfaceLike() ||
2935 KnownBase->getAccessSpecifier() != AS_public)) {
2936 // The Microsoft extension __interface does not permit bases that
2937 // are not themselves public interfaces.
2938 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2939 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2940 << RD->getSourceRange();
2941 Invalid = true;
2942 }
2943 if (RD->hasAttr<WeakAttr>())
2944 Class->addAttr(WeakAttr::CreateImplicit(Context));
2945 }
2946 }
2947 }
2948
2949 // Attach the remaining base class specifiers to the derived class.
2950 Class->setBases(Bases.data(), NumGoodBases);
2951
2952 // Check that the only base classes that are duplicate are virtual.
2953 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2954 // Check whether this direct base is inaccessible due to ambiguity.
2955 QualType BaseType = Bases[idx]->getType();
2956
2957 // Skip all dependent types in templates being used as base specifiers.
2958 // Checks below assume that the base specifier is a CXXRecord.
2959 if (BaseType->isDependentType())
2960 continue;
2961
2962 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2964
2965 if (IndirectBaseTypes.count(CanonicalBase)) {
2966 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2967 /*DetectVirtual=*/true);
2968 bool found
2969 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2970 assert(found);
2971 (void)found;
2972
2973 if (Paths.isAmbiguous(CanonicalBase))
2974 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2975 << BaseType << getAmbiguousPathsDisplayString(Paths)
2976 << Bases[idx]->getSourceRange();
2977 else
2978 assert(Bases[idx]->isVirtual());
2979 }
2980
2981 // Delete the base class specifier, since its data has been copied
2982 // into the CXXRecordDecl.
2983 Context.Deallocate(Bases[idx]);
2984 }
2985
2986 return Invalid;
2987}
2988
2991 if (!ClassDecl || Bases.empty())
2992 return;
2993
2994 AdjustDeclIfTemplate(ClassDecl);
2995 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2996}
2997
2999 if (!getLangOpts().CPlusPlus)
3000 return false;
3001
3002 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3003 if (!DerivedRD)
3004 return false;
3005
3006 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3007 if (!BaseRD)
3008 return false;
3009
3010 // If either the base or the derived type is invalid, don't try to
3011 // check whether one is derived from the other.
3012 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3013 return false;
3014
3015 // FIXME: In a modules build, do we need the entire path to be visible for us
3016 // to be able to use the inheritance relationship?
3017 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3018 return false;
3019
3020 return DerivedRD->isDerivedFrom(BaseRD);
3021}
3022
3024 CXXBasePaths &Paths) {
3025 if (!getLangOpts().CPlusPlus)
3026 return false;
3027
3028 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3029 if (!DerivedRD)
3030 return false;
3031
3032 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3033 if (!BaseRD)
3034 return false;
3035
3036 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3037 return false;
3038
3039 return DerivedRD->isDerivedFrom(BaseRD, Paths);
3040}
3041
3043 CXXCastPath &BasePathArray) {
3044 // We first go backward and check if we have a virtual base.
3045 // FIXME: It would be better if CXXBasePath had the base specifier for
3046 // the nearest virtual base.
3047 unsigned Start = 0;
3048 for (unsigned I = Path.size(); I != 0; --I) {
3049 if (Path[I - 1].Base->isVirtual()) {
3050 Start = I - 1;
3051 break;
3052 }
3053 }
3054
3055 // Now add all bases.
3056 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3057 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3058}
3059
3060
3062 CXXCastPath &BasePathArray) {
3063 assert(BasePathArray.empty() && "Base path array must be empty!");
3064 assert(Paths.isRecordingPaths() && "Must record paths!");
3065 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3066}
3067
3068bool
3070 unsigned InaccessibleBaseID,
3071 unsigned AmbiguousBaseConvID,
3073 DeclarationName Name,
3074 CXXCastPath *BasePath,
3075 bool IgnoreAccess) {
3076 // First, determine whether the path from Derived to Base is
3077 // ambiguous. This is slightly more expensive than checking whether
3078 // the Derived to Base conversion exists, because here we need to
3079 // explore multiple paths to determine if there is an ambiguity.
3080 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3081 /*DetectVirtual=*/false);
3082 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3083 if (!DerivationOkay)
3084 return true;
3085
3086 const CXXBasePath *Path = nullptr;
3087 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3088 Path = &Paths.front();
3089
3090 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3091 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3092 // user to access such bases.
3093 if (!Path && getLangOpts().MSVCCompat) {
3094 for (const CXXBasePath &PossiblePath : Paths) {
3095 if (PossiblePath.size() == 1) {
3096 Path = &PossiblePath;
3097 if (AmbiguousBaseConvID)
3098 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3099 << Base << Derived << Range;
3100 break;
3101 }
3102 }
3103 }
3104
3105 if (Path) {
3106 if (!IgnoreAccess) {
3107 // Check that the base class can be accessed.
3108 switch (
3109 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3110 case AR_inaccessible:
3111 return true;
3112 case AR_accessible:
3113 case AR_dependent:
3114 case AR_delayed:
3115 break;
3116 }
3117 }
3118
3119 // Build a base path if necessary.
3120 if (BasePath)
3121 ::BuildBasePathArray(*Path, *BasePath);
3122 return false;
3123 }
3124
3125 if (AmbiguousBaseConvID) {
3126 // We know that the derived-to-base conversion is ambiguous, and
3127 // we're going to produce a diagnostic. Perform the derived-to-base
3128 // search just one more time to compute all of the possible paths so
3129 // that we can print them out. This is more expensive than any of
3130 // the previous derived-to-base checks we've done, but at this point
3131 // performance isn't as much of an issue.
3132 Paths.clear();
3133 Paths.setRecordingPaths(true);
3134 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3135 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3136 (void)StillOkay;
3137
3138 // Build up a textual representation of the ambiguous paths, e.g.,
3139 // D -> B -> A, that will be used to illustrate the ambiguous
3140 // conversions in the diagnostic. We only print one of the paths
3141 // to each base class subobject.
3142 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3143
3144 Diag(Loc, AmbiguousBaseConvID)
3145 << Derived << Base << PathDisplayStr << Range << Name;
3146 }
3147 return true;
3148}
3149
3150bool
3153 CXXCastPath *BasePath,
3154 bool IgnoreAccess) {
3156 Derived, Base, diag::err_upcast_to_inaccessible_base,
3157 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3158 BasePath, IgnoreAccess);
3159}
3160
3162 std::string PathDisplayStr;
3163 std::set<unsigned> DisplayedPaths;
3164 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3165 Path != Paths.end(); ++Path) {
3166 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3167 // We haven't displayed a path to this particular base
3168 // class subobject yet.
3169 PathDisplayStr += "\n ";
3170 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3171 for (CXXBasePath::const_iterator Element = Path->begin();
3172 Element != Path->end(); ++Element)
3173 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3174 }
3175 }
3176
3177 return PathDisplayStr;
3178}
3179
3180//===----------------------------------------------------------------------===//
3181// C++ class member Handling
3182//===----------------------------------------------------------------------===//
3183
3185 SourceLocation ColonLoc,
3186 const ParsedAttributesView &Attrs) {
3187 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3189 ASLoc, ColonLoc);
3190 CurContext->addHiddenDecl(ASDecl);
3191 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3192}
3193
3195 if (D->isInvalidDecl())
3196 return;
3197
3198 // We only care about "override" and "final" declarations.
3199 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3200 return;
3201
3202 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3203
3204 // We can't check dependent instance methods.
3205 if (MD && MD->isInstance() &&
3206 (MD->getParent()->hasAnyDependentBases() ||
3207 MD->getType()->isDependentType()))
3208 return;
3209
3210 if (MD && !MD->isVirtual()) {
3211 // If we have a non-virtual method, check if it hides a virtual method.
3212 // (In that case, it's most likely the method has the wrong type.)
3213 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3214 FindHiddenVirtualMethods(MD, OverloadedMethods);
3215
3216 if (!OverloadedMethods.empty()) {
3217 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3218 Diag(OA->getLocation(),
3219 diag::override_keyword_hides_virtual_member_function)
3220 << "override" << (OverloadedMethods.size() > 1);
3221 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3222 Diag(FA->getLocation(),
3223 diag::override_keyword_hides_virtual_member_function)
3224 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3225 << (OverloadedMethods.size() > 1);
3226 }
3227 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3228 MD->setInvalidDecl();
3229 return;
3230 }
3231 // Fall through into the general case diagnostic.
3232 // FIXME: We might want to attempt typo correction here.
3233 }
3234
3235 if (!MD || !MD->isVirtual()) {
3236 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3237 Diag(OA->getLocation(),
3238 diag::override_keyword_only_allowed_on_virtual_member_functions)
3239 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3240 D->dropAttr<OverrideAttr>();
3241 }
3242 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3243 Diag(FA->getLocation(),
3244 diag::override_keyword_only_allowed_on_virtual_member_functions)
3245 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3246 << FixItHint::CreateRemoval(FA->getLocation());
3247 D->dropAttr<FinalAttr>();
3248 }
3249 return;
3250 }
3251
3252 // C++11 [class.virtual]p5:
3253 // If a function is marked with the virt-specifier override and
3254 // does not override a member function of a base class, the program is
3255 // ill-formed.
3256 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3257 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3258 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3259 << MD->getDeclName();
3260}
3261
3263 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3264 return;
3265 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3266 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3267 return;
3268
3270 SourceLocation SpellingLoc = Loc;
3271 if (getSourceManager().isMacroArgExpansion(Loc))
3273 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3274 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3275 return;
3276
3277 if (MD->size_overridden_methods() > 0) {
3278 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3279 unsigned DiagID =
3280 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3281 ? DiagInconsistent
3282 : DiagSuggest;
3283 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3284 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3285 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3286 };
3287 if (isa<CXXDestructorDecl>(MD))
3288 EmitDiag(
3289 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3290 diag::warn_suggest_destructor_marked_not_override_overriding);
3291 else
3292 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3293 diag::warn_suggest_function_marked_not_override_overriding);
3294 }
3295}
3296
3298 const CXXMethodDecl *Old) {
3299 FinalAttr *FA = Old->getAttr<FinalAttr>();
3300 if (!FA)
3301 return false;
3302
3303 Diag(New->getLocation(), diag::err_final_function_overridden)
3304 << New->getDeclName()
3305 << FA->isSpelledAsSealed();
3306 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3307 return true;
3308}
3309
3311 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3312 // FIXME: Destruction of ObjC lifetime types has side-effects.
3313 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3314 return !RD->isCompleteDefinition() ||
3315 !RD->hasTrivialDefaultConstructor() ||
3316 !RD->hasTrivialDestructor();
3317 return false;
3318}
3319
3320void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3321 DeclarationName FieldName,
3322 const CXXRecordDecl *RD,
3323 bool DeclIsField) {
3324 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3325 return;
3326
3327 // To record a shadowed field in a base
3328 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3329 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3330 CXXBasePath &Path) {
3331 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3332 // Record an ambiguous path directly
3333 if (Bases.find(Base) != Bases.end())
3334 return true;
3335 for (const auto Field : Base->lookup(FieldName)) {
3336 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3337 Field->getAccess() != AS_private) {
3338 assert(Field->getAccess() != AS_none);
3339 assert(Bases.find(Base) == Bases.end());
3340 Bases[Base] = Field;
3341 return true;
3342 }
3343 }
3344 return false;
3345 };
3346
3347 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3348 /*DetectVirtual=*/true);
3349 if (!RD->lookupInBases(FieldShadowed, Paths))
3350 return;
3351
3352 for (const auto &P : Paths) {
3353 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3354 auto It = Bases.find(Base);
3355 // Skip duplicated bases
3356 if (It == Bases.end())
3357 continue;
3358 auto BaseField = It->second;
3359 assert(BaseField->getAccess() != AS_private);
3360 if (AS_none !=
3361 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3362 Diag(Loc, diag::warn_shadow_field)
3363 << FieldName << RD << Base << DeclIsField;
3364 Diag(BaseField->getLocation(), diag::note_shadow_field);
3365 Bases.erase(It);
3366 }
3367 }
3368}
3369
3370template <typename AttrType>
3371inline static bool HasAttribute(const QualType &T) {
3372 if (const TagDecl *TD = T->getAsTagDecl())
3373 return TD->hasAttr<AttrType>();
3374 if (const TypedefType *TDT = T->getAs<TypedefType>())
3375 return TDT->getDecl()->hasAttr<AttrType>();
3376 return false;
3377}
3378
3379static bool IsUnusedPrivateField(const FieldDecl *FD) {
3380 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3381 QualType FieldType = FD->getType();
3382 if (HasAttribute<WarnUnusedAttr>(FieldType))
3383 return true;
3384
3385 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3386 !FD->getParent()->isDependentContext() &&
3387 !HasAttribute<UnusedAttr>(FieldType) &&
3389 }
3390 return false;
3391}
3392
3393NamedDecl *
3395 MultiTemplateParamsArg TemplateParameterLists,
3396 Expr *BW, const VirtSpecifiers &VS,
3397 InClassInitStyle InitStyle) {
3398 const DeclSpec &DS = D.getDeclSpec();
3400 DeclarationName Name = NameInfo.getName();
3401 SourceLocation Loc = NameInfo.getLoc();
3402
3403 // For anonymous bitfields, the location should point to the type.
3404 if (Loc.isInvalid())
3405 Loc = D.getBeginLoc();
3406
3407 Expr *BitWidth = static_cast<Expr*>(BW);
3408
3409 assert(isa<CXXRecordDecl>(CurContext));
3410 assert(!DS.isFriendSpecified());
3411
3412 bool isFunc = D.isDeclarationOfFunction();
3413 const ParsedAttr *MSPropertyAttr =
3414 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3415
3416 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3417 // The Microsoft extension __interface only permits public member functions
3418 // and prohibits constructors, destructors, operators, non-public member
3419 // functions, static methods and data members.
3420 unsigned InvalidDecl;
3421 bool ShowDeclName = true;
3422 if (!isFunc &&
3423 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3424 InvalidDecl = 0;
3425 else if (!isFunc)
3426 InvalidDecl = 1;
3427 else if (AS != AS_public)
3428 InvalidDecl = 2;
3430 InvalidDecl = 3;
3431 else switch (Name.getNameKind()) {
3433 InvalidDecl = 4;
3434 ShowDeclName = false;
3435 break;
3436
3438 InvalidDecl = 5;
3439 ShowDeclName = false;
3440 break;
3441
3444 InvalidDecl = 6;
3445 break;
3446
3447 default:
3448 InvalidDecl = 0;
3449 break;
3450 }
3451
3452 if (InvalidDecl) {
3453 if (ShowDeclName)
3454 Diag(Loc, diag::err_invalid_member_in_interface)
3455 << (InvalidDecl-1) << Name;
3456 else
3457 Diag(Loc, diag::err_invalid_member_in_interface)
3458 << (InvalidDecl-1) << "";
3459 return nullptr;
3460 }
3461 }
3462
3463 // C++ 9.2p6: A member shall not be declared to have automatic storage
3464 // duration (auto, register) or with the extern storage-class-specifier.
3465 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3466 // data members and cannot be applied to names declared const or static,
3467 // and cannot be applied to reference members.
3468 switch (DS.getStorageClassSpec()) {
3472 break;
3474 if (isFunc) {
3475 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3476
3477 // FIXME: It would be nicer if the keyword was ignored only for this
3478 // declarator. Otherwise we could get follow-up errors.
3479 D.getMutableDeclSpec().ClearStorageClassSpecs();
3480 }
3481 break;
3482 default:
3484 diag::err_storageclass_invalid_for_member);
3485 D.getMutableDeclSpec().ClearStorageClassSpecs();
3486 break;
3487 }
3488
3489 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3491 !isFunc && TemplateParameterLists.empty();
3492
3493 if (DS.hasConstexprSpecifier() && isInstField) {
3495 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3496 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3497 if (InitStyle == ICIS_NoInit) {
3498 B << 0 << 0;
3499 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3500 B << FixItHint::CreateRemoval(ConstexprLoc);
3501 else {
3502 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3503 D.getMutableDeclSpec().ClearConstexprSpec();
3504 const char *PrevSpec;
3505 unsigned DiagID;
3506 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3507 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3508 (void)Failed;
3509 assert(!Failed && "Making a constexpr member const shouldn't fail");
3510 }
3511 } else {
3512 B << 1;
3513 const char *PrevSpec;
3514 unsigned DiagID;
3515 if (D.getMutableDeclSpec().SetStorageClassSpec(
3516 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3519 "This is the only DeclSpec that should fail to be applied");
3520 B << 1;
3521 } else {
3522 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3523 isInstField = false;
3524 }
3525 }
3526 }
3527
3529 if (isInstField) {
3530 CXXScopeSpec &SS = D.getCXXScopeSpec();
3531
3532 // Data members must have identifiers for names.
3533 if (!Name.isIdentifier()) {
3534 Diag(Loc, diag::err_bad_variable_name)
3535 << Name;
3536 return nullptr;
3537 }
3538
3539 IdentifierInfo *II = Name.getAsIdentifierInfo();
3540 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3541 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3542 << II
3543 << SourceRange(D.getName().TemplateId->LAngleLoc,
3544 D.getName().TemplateId->RAngleLoc)
3545 << D.getName().TemplateId->LAngleLoc;
3546 D.SetIdentifier(II, Loc);
3547 }
3548
3549 if (SS.isSet() && !SS.isInvalid()) {
3550 // The user provided a superfluous scope specifier inside a class
3551 // definition:
3552 //
3553 // class X {
3554 // int X::member;
3555 // };
3556 if (DeclContext *DC = computeDeclContext(SS, false)) {
3557 TemplateIdAnnotation *TemplateId =
3559 ? D.getName().TemplateId
3560 : nullptr;
3561 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3562 TemplateId,
3563 /*IsMemberSpecialization=*/false);
3564 } else {
3565 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3566 << Name << SS.getRange();
3567 }
3568 SS.clear();
3569 }
3570
3571 if (MSPropertyAttr) {
3572 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3573 BitWidth, InitStyle, AS, *MSPropertyAttr);
3574 if (!Member)
3575 return nullptr;
3576 isInstField = false;
3577 } else {
3578 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3579 BitWidth, InitStyle, AS);
3580 if (!Member)
3581 return nullptr;
3582 }
3583
3584 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3585 } else {
3586 Member = HandleDeclarator(S, D, TemplateParameterLists);
3587 if (!Member)
3588 return nullptr;
3589
3590 // Non-instance-fields can't have a bitfield.
3591 if (BitWidth) {
3592 if (Member->isInvalidDecl()) {
3593 // don't emit another diagnostic.
3594 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3595 // C++ 9.6p3: A bit-field shall not be a static member.
3596 // "static member 'A' cannot be a bit-field"
3597 Diag(Loc, diag::err_static_not_bitfield)
3598 << Name << BitWidth->getSourceRange();
3599 } else if (isa<TypedefDecl>(Member)) {
3600 // "typedef member 'x' cannot be a bit-field"
3601 Diag(Loc, diag::err_typedef_not_bitfield)
3602 << Name << BitWidth->getSourceRange();
3603 } else {
3604 // A function typedef ("typedef int f(); f a;").
3605 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3606 Diag(Loc, diag::err_not_integral_type_bitfield)
3607 << Name << cast<ValueDecl>(Member)->getType()
3608 << BitWidth->getSourceRange();
3609 }
3610
3611 BitWidth = nullptr;
3612 Member->setInvalidDecl();
3613 }
3614
3615 NamedDecl *NonTemplateMember = Member;
3616 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3617 NonTemplateMember = FunTmpl->getTemplatedDecl();
3618 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3619 NonTemplateMember = VarTmpl->getTemplatedDecl();
3620
3621 Member->setAccess(AS);
3622
3623 // If we have declared a member function template or static data member
3624 // template, set the access of the templated declaration as well.
3625 if (NonTemplateMember != Member)
3626 NonTemplateMember->setAccess(AS);
3627
3628 // C++ [temp.deduct.guide]p3:
3629 // A deduction guide [...] for a member class template [shall be
3630 // declared] with the same access [as the template].
3631 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3632 auto *TD = DG->getDeducedTemplate();
3633 // Access specifiers are only meaningful if both the template and the
3634 // deduction guide are from the same scope.
3635 if (AS != TD->getAccess() &&
3636 TD->getDeclContext()->getRedeclContext()->Equals(
3637 DG->getDeclContext()->getRedeclContext())) {
3638 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3639 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3640 << TD->getAccess();
3641 const AccessSpecDecl *LastAccessSpec = nullptr;
3642 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3643 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3644 LastAccessSpec = AccessSpec;
3645 }
3646 assert(LastAccessSpec && "differing access with no access specifier");
3647 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3648 << AS;
3649 }
3650 }
3651 }
3652
3653 if (VS.isOverrideSpecified())
3654 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3655 if (VS.isFinalSpecified())
3656 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3658 ? FinalAttr::Keyword_sealed
3659 : FinalAttr::Keyword_final));
3660
3661 if (VS.getLastLocation().isValid()) {
3662 // Update the end location of a method that has a virt-specifiers.
3663 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3664 MD->setRangeEnd(VS.getLastLocation());
3665 }
3666
3668
3669 assert((Name || isInstField) && "No identifier for non-field ?");
3670
3671 if (isInstField) {
3672 FieldDecl *FD = cast<FieldDecl>(Member);
3673 FieldCollector->Add(FD);
3674
3675 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3677 // Remember all explicit private FieldDecls that have a name, no side
3678 // effects and are not part of a dependent type declaration.
3679 UnusedPrivateFields.insert(FD);
3680 }
3681 }
3682
3683 return Member;
3684}
3685
3686namespace {
3687 class UninitializedFieldVisitor
3688 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3689 Sema &S;
3690 // List of Decls to generate a warning on. Also remove Decls that become
3691 // initialized.
3692 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3693 // List of base classes of the record. Classes are removed after their
3694 // initializers.
3695 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3696 // Vector of decls to be removed from the Decl set prior to visiting the
3697 // nodes. These Decls may have been initialized in the prior initializer.
3699 // If non-null, add a note to the warning pointing back to the constructor.
3700 const CXXConstructorDecl *Constructor;
3701 // Variables to hold state when processing an initializer list. When
3702 // InitList is true, special case initialization of FieldDecls matching
3703 // InitListFieldDecl.
3704 bool InitList;
3705 FieldDecl *InitListFieldDecl;
3706 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3707
3708 public:
3710 UninitializedFieldVisitor(Sema &S,
3711 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3712 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3713 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3714 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3715
3716 // Returns true if the use of ME is not an uninitialized use.
3717 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3718 bool CheckReferenceOnly) {
3720 bool ReferenceField = false;
3721 while (ME) {
3722 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3723 if (!FD)
3724 return false;
3725 Fields.push_back(FD);
3726 if (FD->getType()->isReferenceType())
3727 ReferenceField = true;
3728 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3729 }
3730
3731 // Binding a reference to an uninitialized field is not an
3732 // uninitialized use.
3733 if (CheckReferenceOnly && !ReferenceField)
3734 return true;
3735
3736 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3737 // Discard the first field since it is the field decl that is being
3738 // initialized.
3739 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3740 UsedFieldIndex.push_back(FD->getFieldIndex());
3741
3742 for (auto UsedIter = UsedFieldIndex.begin(),
3743 UsedEnd = UsedFieldIndex.end(),
3744 OrigIter = InitFieldIndex.begin(),
3745 OrigEnd = InitFieldIndex.end();
3746 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3747 if (*UsedIter < *OrigIter)
3748 return true;
3749 if (*UsedIter > *OrigIter)
3750 break;
3751 }
3752
3753 return false;
3754 }
3755
3756 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3757 bool AddressOf) {
3758 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3759 return;
3760
3761 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3762 // or union.
3763 MemberExpr *FieldME = ME;
3764
3765 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3766
3767 Expr *Base = ME;
3768 while (MemberExpr *SubME =
3769 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3770
3771 if (isa<VarDecl>(SubME->getMemberDecl()))
3772 return;
3773
3774 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3775 if (!FD->isAnonymousStructOrUnion())
3776 FieldME = SubME;
3777
3778 if (!FieldME->getType().isPODType(S.Context))
3779 AllPODFields = false;
3780
3781 Base = SubME->getBase();
3782 }
3783
3784 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3785 Visit(Base);
3786 return;
3787 }
3788
3789 if (AddressOf && AllPODFields)
3790 return;
3791
3792 ValueDecl* FoundVD = FieldME->getMemberDecl();
3793
3794 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3795 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3796 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3797 }
3798
3799 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3800 QualType T = BaseCast->getType();
3801 if (T->isPointerType() &&
3802 BaseClasses.count(T->getPointeeType())) {
3803 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3804 << T->getPointeeType() << FoundVD;
3805 }
3806 }
3807 }
3808
3809 if (!Decls.count(FoundVD))
3810 return;
3811
3812 const bool IsReference = FoundVD->getType()->isReferenceType();
3813
3814 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3815 // Special checking for initializer lists.
3816 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3817 return;
3818 }
3819 } else {
3820 // Prevent double warnings on use of unbounded references.
3821 if (CheckReferenceOnly && !IsReference)
3822 return;
3823 }
3824
3825 unsigned diag = IsReference
3826 ? diag::warn_reference_field_is_uninit
3827 : diag::warn_field_is_uninit;
3828 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3829 if (Constructor)
3830 S.Diag(Constructor->getLocation(),
3831 diag::note_uninit_in_this_constructor)
3832 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3833
3834 }
3835
3836 void HandleValue(Expr *E, bool AddressOf) {
3837 E = E->IgnoreParens();
3838
3839 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3840 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3841 AddressOf /*AddressOf*/);
3842 return;
3843 }
3844
3845 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3846 Visit(CO->getCond());
3847 HandleValue(CO->getTrueExpr(), AddressOf);
3848 HandleValue(CO->getFalseExpr(), AddressOf);
3849 return;
3850 }
3851
3852 if (BinaryConditionalOperator *BCO =
3853 dyn_cast<BinaryConditionalOperator>(E)) {
3854 Visit(BCO->getCond());
3855 HandleValue(BCO->getFalseExpr(), AddressOf);
3856 return;
3857 }
3858
3859 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3860 HandleValue(OVE->getSourceExpr(), AddressOf);
3861 return;
3862 }
3863
3864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3865 switch (BO->getOpcode()) {
3866 default:
3867 break;
3868 case(BO_PtrMemD):
3869 case(BO_PtrMemI):
3870 HandleValue(BO->getLHS(), AddressOf);
3871 Visit(BO->getRHS());
3872 return;
3873 case(BO_Comma):
3874 Visit(BO->getLHS());
3875 HandleValue(BO->getRHS(), AddressOf);
3876 return;
3877 }
3878 }
3879
3880 Visit(E);
3881 }
3882
3883 void CheckInitListExpr(InitListExpr *ILE) {
3884 InitFieldIndex.push_back(0);
3885 for (auto *Child : ILE->children()) {
3886 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3887 CheckInitListExpr(SubList);
3888 } else {
3889 Visit(Child);
3890 }
3891 ++InitFieldIndex.back();
3892 }
3893 InitFieldIndex.pop_back();
3894 }
3895
3896 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3897 FieldDecl *Field, const Type *BaseClass) {
3898 // Remove Decls that may have been initialized in the previous
3899 // initializer.
3900 for (ValueDecl* VD : DeclsToRemove)
3901 Decls.erase(VD);
3902 DeclsToRemove.clear();
3903
3904 Constructor = FieldConstructor;
3905 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3906
3907 if (ILE && Field) {
3908 InitList = true;
3909 InitListFieldDecl = Field;
3910 InitFieldIndex.clear();
3911 CheckInitListExpr(ILE);
3912 } else {
3913 InitList = false;
3914 Visit(E);
3915 }
3916
3917 if (Field)
3918 Decls.erase(Field);
3919 if (BaseClass)
3920 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3921 }
3922
3923 void VisitMemberExpr(MemberExpr *ME) {
3924 // All uses of unbounded reference fields will warn.
3925 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3926 }
3927
3928 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3929 if (E->getCastKind() == CK_LValueToRValue) {
3930 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3931 return;
3932 }
3933
3934 Inherited::VisitImplicitCastExpr(E);
3935 }
3936
3937 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3938 if (E->getConstructor()->isCopyConstructor()) {
3939 Expr *ArgExpr = E->getArg(0);
3940 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3941 if (ILE->getNumInits() == 1)
3942 ArgExpr = ILE->getInit(0);
3943 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3944 if (ICE->getCastKind() == CK_NoOp)
3945 ArgExpr = ICE->getSubExpr();
3946 HandleValue(ArgExpr, false /*AddressOf*/);
3947 return;
3948 }
3949 Inherited::VisitCXXConstructExpr(E);
3950 }
3951
3952 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3953 Expr *Callee = E->getCallee();
3954 if (isa<MemberExpr>(Callee)) {
3955 HandleValue(Callee, false /*AddressOf*/);
3956 for (auto *Arg : E->arguments())
3957 Visit(Arg);
3958 return;
3959 }
3960
3961 Inherited::VisitCXXMemberCallExpr(E);
3962 }
3963
3964 void VisitCallExpr(CallExpr *E) {
3965 // Treat std::move as a use.
3966 if (E->isCallToStdMove()) {
3967 HandleValue(E->getArg(0), /*AddressOf=*/false);
3968 return;
3969 }
3970
3971 Inherited::VisitCallExpr(E);
3972 }
3973
3974 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3975 Expr *Callee = E->getCallee();
3976
3977 if (isa<UnresolvedLookupExpr>(Callee))
3978 return Inherited::VisitCXXOperatorCallExpr(E);
3979
3980 Visit(Callee);
3981 for (auto *Arg : E->arguments())
3982 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3983 }
3984
3985 void VisitBinaryOperator(BinaryOperator *E) {
3986 // If a field assignment is detected, remove the field from the
3987 // uninitiailized field set.
3988 if (E->getOpcode() == BO_Assign)
3989 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3990 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3991 if (!FD->getType()->isReferenceType())
3992 DeclsToRemove.push_back(FD);
3993
3994 if (E->isCompoundAssignmentOp()) {
3995 HandleValue(E->getLHS(), false /*AddressOf*/);
3996 Visit(E->getRHS());
3997 return;
3998 }
3999
4000 Inherited::VisitBinaryOperator(E);
4001 }
4002
4003 void VisitUnaryOperator(UnaryOperator *E) {
4004 if (E->isIncrementDecrementOp()) {
4005 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4006 return;
4007 }
4008 if (E->getOpcode() == UO_AddrOf) {
4009 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4010 HandleValue(ME->getBase(), true /*AddressOf*/);
4011 return;
4012 }
4013 }
4014
4015 Inherited::VisitUnaryOperator(E);
4016 }
4017 };
4018
4019 // Diagnose value-uses of fields to initialize themselves, e.g.
4020 // foo(foo)
4021 // where foo is not also a parameter to the constructor.
4022 // Also diagnose across field uninitialized use such as
4023 // x(y), y(x)
4024 // TODO: implement -Wuninitialized and fold this into that framework.
4025 static void DiagnoseUninitializedFields(
4026 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4027
4028 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4029 Constructor->getLocation())) {
4030 return;
4031 }
4032
4033 if (Constructor->isInvalidDecl())
4034 return;
4035
4036 const CXXRecordDecl *RD = Constructor->getParent();
4037
4038 if (RD->isDependentContext())
4039 return;
4040
4041 // Holds fields that are uninitialized.
4042 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4043
4044 // At the beginning, all fields are uninitialized.
4045 for (auto *I : RD->decls()) {
4046 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4047 UninitializedFields.insert(FD);
4048 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4049 UninitializedFields.insert(IFD->getAnonField());
4050 }
4051 }
4052
4053 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4054 for (const auto &I : RD->bases())
4055 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4056
4057 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4058 return;
4059
4060 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4061 UninitializedFields,
4062 UninitializedBaseClasses);
4063
4064 for (const auto *FieldInit : Constructor->inits()) {
4065 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4066 break;
4067
4068 Expr *InitExpr = FieldInit->getInit();
4069 if (!InitExpr)
4070 continue;
4071
4073 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4074 InitExpr = Default->getExpr();
4075 if (!InitExpr)
4076 continue;
4077 // In class initializers will point to the constructor.
4078 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4079 FieldInit->getAnyMember(),
4080 FieldInit->getBaseClass());
4081 } else {
4082 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4083 FieldInit->getAnyMember(),
4084 FieldInit->getBaseClass());
4085 }
4086 }
4087 }
4088} // namespace
4089
4091 // Create a synthetic function scope to represent the call to the constructor
4092 // that notionally surrounds a use of this initializer.
4094}
4095
4097 if (!D.isFunctionDeclarator())
4098 return;
4099 auto &FTI = D.getFunctionTypeInfo();
4100 if (!FTI.Params)
4101 return;
4102 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4103 FTI.NumParams)) {
4104 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4105 if (ParamDecl->getDeclName())
4106 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4107 }
4108}
4109
4111 return ActOnRequiresClause(ConstraintExpr);
4112}
4113
4115 if (ConstraintExpr.isInvalid())
4116 return ExprError();
4117
4118 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4119 if (ConstraintExpr.isInvalid())
4120 return ExprError();
4121
4122 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4124 return ExprError();
4125
4126 return ConstraintExpr;
4127}
4128
4130 Expr *InitExpr,
4131 SourceLocation InitLoc) {
4132 InitializedEntity Entity =
4134 InitializationKind Kind =
4137 InitExpr->getBeginLoc(),
4138 InitExpr->getEndLoc())
4139 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4140 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4141 return Seq.Perform(*this, Entity, Kind, InitExpr);
4142}
4143
4145 SourceLocation InitLoc,
4146 ExprResult InitExpr) {
4147 // Pop the notional constructor scope we created earlier.
4148 PopFunctionScopeInfo(nullptr, D);
4149
4150 // Microsoft C++'s property declaration cannot have a default member
4151 // initializer.
4152 if (isa<MSPropertyDecl>(D)) {
4153 D->setInvalidDecl();
4154 return;
4155 }
4156
4157 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4158 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4159 "must set init style when field is created");
4160
4161 if (!InitExpr.isUsable() ||
4163 FD->setInvalidDecl();
4164 ExprResult RecoveryInit =
4165 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4166 if (RecoveryInit.isUsable())
4167 FD->setInClassInitializer(RecoveryInit.get());
4168 return;
4169 }
4170
4171 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4172 /*RecoverUncorrectedTypos=*/true);
4173 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4174 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4175 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4176 // C++11 [class.base.init]p7:
4177 // The initialization of each base and member constitutes a
4178 // full-expression.
4179 if (!Init.isInvalid())
4180 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4181 if (Init.isInvalid()) {
4182 FD->setInvalidDecl();
4183 return;
4184 }
4185 }
4186
4187 FD->setInClassInitializer(Init.get());
4188}
4189
4190/// Find the direct and/or virtual base specifiers that
4191/// correspond to the given base type, for use in base initialization
4192/// within a constructor.
4194 CXXRecordDecl *ClassDecl,
4195 QualType BaseType,
4196 const CXXBaseSpecifier *&DirectBaseSpec,
4197 const CXXBaseSpecifier *&VirtualBaseSpec) {
4198 // First, check for a direct base class.
4199 DirectBaseSpec = nullptr;
4200 for (const auto &Base : ClassDecl->bases()) {
4201 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4202 // We found a direct base of this type. That's what we're
4203 // initializing.
4204 DirectBaseSpec = &Base;
4205 break;
4206 }
4207 }
4208
4209 // Check for a virtual base class.
4210 // FIXME: We might be able to short-circuit this if we know in advance that
4211 // there are no virtual bases.
4212 VirtualBaseSpec = nullptr;
4213 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4214 // We haven't found a base yet; search the class hierarchy for a
4215 // virtual base class.
4216 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4217 /*DetectVirtual=*/false);
4218 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4219 SemaRef.Context.getTypeDeclType(ClassDecl),
4220 BaseType, Paths)) {
4221 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4222 Path != Paths.end(); ++Path) {
4223 if (Path->back().Base->isVirtual()) {
4224 VirtualBaseSpec = Path->back().Base;
4225 break;
4226 }
4227 }
4228 }
4229 }
4230
4231 return DirectBaseSpec || VirtualBaseSpec;
4232}
4233
4236 Scope *S,
4237 CXXScopeSpec &SS,
4238 IdentifierInfo *MemberOrBase,
4239 ParsedType TemplateTypeTy,
4240 const DeclSpec &DS,
4241 SourceLocation IdLoc,
4242 Expr *InitList,
4243 SourceLocation EllipsisLoc) {
4244 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4245 DS, IdLoc, InitList,
4246 EllipsisLoc);
4247}
4248
4251 Scope *S,
4252 CXXScopeSpec &SS,
4253 IdentifierInfo *MemberOrBase,
4254 ParsedType TemplateTypeTy,
4255 const DeclSpec &DS,
4256 SourceLocation IdLoc,
4257 SourceLocation LParenLoc,
4258 ArrayRef<Expr *> Args,
4259 SourceLocation RParenLoc,
4260 SourceLocation EllipsisLoc) {
4261 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4263 DS, IdLoc, List, EllipsisLoc);
4264}
4265
4266namespace {
4267
4268// Callback to only accept typo corrections that can be a valid C++ member
4269// initializer: either a non-static field member or a base class.
4270class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4271public:
4272 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4273 : ClassDecl(ClassDecl) {}
4274
4275 bool ValidateCandidate(const TypoCorrection &candidate) override {
4276 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4277 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4278 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4279 return isa<TypeDecl>(ND);
4280 }
4281 return false;
4282 }
4283
4284 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4285 return std::make_unique<MemInitializerValidatorCCC>(*this);
4286 }
4287
4288private:
4289 CXXRecordDecl *ClassDecl;
4290};
4291
4292}
4293
4295 RecordDecl *ClassDecl,
4296 const IdentifierInfo *Name) {
4297 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4299 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4300 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4302 });
4303 // We did not find a placeholder variable
4304 if (Found == Result.end())
4305 return false;
4306 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4307 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4308 const NamedDecl *ND = *It;
4309 if (ND->getDeclContext() != ND->getDeclContext())
4310 break;
4311 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4313 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4314 }
4315 return true;
4316}
4317
4318ValueDecl *
4320 const IdentifierInfo *MemberOrBase) {
4321 ValueDecl *ND = nullptr;
4322 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4323 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4324 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4325 if (ND) {
4326 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4327 return nullptr;
4328 break;
4329 }
4330 if (!IsPlaceholder)
4331 return cast<ValueDecl>(D);
4332 ND = cast<ValueDecl>(D);
4333 }
4334 }
4335 return ND;
4336}
4337
4339 CXXScopeSpec &SS,
4340 ParsedType TemplateTypeTy,
4341 IdentifierInfo *MemberOrBase) {
4342 if (SS.getScopeRep() || TemplateTypeTy)
4343 return nullptr;
4344 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4345}
4346
4349 Scope *S,
4350 CXXScopeSpec &SS,
4351 IdentifierInfo *MemberOrBase,
4352 ParsedType TemplateTypeTy,
4353 const DeclSpec &DS,
4354 SourceLocation IdLoc,
4355 Expr *Init,
4356 SourceLocation EllipsisLoc) {
4357 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4358 /*RecoverUncorrectedTypos=*/true);
4359 if (!Res.isUsable())
4360 return true;
4361 Init = Res.get();
4362
4363 if (!ConstructorD)
4364 return true;
4365
4366 AdjustDeclIfTemplate(ConstructorD);
4367
4368 CXXConstructorDecl *Constructor
4369 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4370 if (!Constructor) {
4371 // The user wrote a constructor initializer on a function that is
4372 // not a C++ constructor. Ignore the error for now, because we may
4373 // have more member initializers coming; we'll diagnose it just
4374 // once in ActOnMemInitializers.
4375 return true;
4376 }
4377
4378 CXXRecordDecl *ClassDecl = Constructor->getParent();
4379
4380 // C++ [class.base.init]p2:
4381 // Names in a mem-initializer-id are looked up in the scope of the
4382 // constructor's class and, if not found in that scope, are looked
4383 // up in the scope containing the constructor's definition.
4384 // [Note: if the constructor's class contains a member with the
4385 // same name as a direct or virtual base class of the class, a
4386 // mem-initializer-id naming the member or base class and composed
4387 // of a single identifier refers to the class member. A
4388 // mem-initializer-id for the hidden base class may be specified
4389 // using a qualified name. ]
4390
4391 // Look for a member, first.
4393 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4394 if (EllipsisLoc.isValid())
4395 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4396 << MemberOrBase
4397 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4398
4399 return BuildMemberInitializer(Member, Init, IdLoc);
4400 }
4401 // It didn't name a member, so see if it names a class.
4402 QualType BaseType;
4403 TypeSourceInfo *TInfo = nullptr;
4404
4405 if (TemplateTypeTy) {
4406 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4407 if (BaseType.isNull())
4408 return true;
4409 } else if (DS.getTypeSpecType() == TST_decltype) {
4410 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4411 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4412 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4413 return true;
4414 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4415 BaseType =
4417 DS.getBeginLoc(), DS.getEllipsisLoc());
4418 } else {
4419 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4420 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4421
4422 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4423 if (!TyD) {
4424 if (R.isAmbiguous()) return true;
4425
4426 // We don't want access-control diagnostics here.
4428
4429 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4430 bool NotUnknownSpecialization = false;
4431 DeclContext *DC = computeDeclContext(SS, false);
4432 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4433 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4434
4435 if (!NotUnknownSpecialization) {
4436 // When the scope specifier can refer to a member of an unknown
4437 // specialization, we take it as a type name.
4438 BaseType = CheckTypenameType(
4440 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4441 if (BaseType.isNull())
4442 return true;
4443
4444 TInfo = Context.CreateTypeSourceInfo(BaseType);
4447 if (!TL.isNull()) {
4448 TL.setNameLoc(IdLoc);
4451 }
4452
4453 R.clear();
4454 R.setLookupName(MemberOrBase);
4455 }
4456 }
4457
4458 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4459 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4460 auto *TempSpec = cast<TemplateSpecializationType>(
4461 UnqualifiedBase->getInjectedClassNameSpecialization());
4462 TemplateName TN = TempSpec->getTemplateName();
4463 for (auto const &Base : ClassDecl->bases()) {
4464 auto BaseTemplate =
4465 Base.getType()->getAs<TemplateSpecializationType>();
4466 if (BaseTemplate &&
4467 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4468 /*IgnoreDeduced=*/true)) {
4469 Diag(IdLoc, diag::ext_unqualified_base_class)
4470 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4471 BaseType = Base.getType();
4472 break;
4473 }
4474 }
4475 }
4476 }
4477
4478 // If no results were found, try to correct typos.
4479 TypoCorrection Corr;
4480 MemInitializerValidatorCCC CCC(ClassDecl);
4481 if (R.empty() && BaseType.isNull() &&
4482 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4483 CCC, CTK_ErrorRecovery, ClassDecl))) {
4485 // We have found a non-static data member with a similar
4486 // name to what was typed; complain and initialize that
4487 // member.
4488 diagnoseTypo(Corr,
4489 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4490 << MemberOrBase << true);
4491 return BuildMemberInitializer(Member, Init, IdLoc);
4492 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4493 const CXXBaseSpecifier *DirectBaseSpec;
4494 const CXXBaseSpecifier *VirtualBaseSpec;
4495 if (FindBaseInitializer(*this, ClassDecl,
4497 DirectBaseSpec, VirtualBaseSpec)) {
4498 // We have found a direct or virtual base class with a
4499 // similar name to what was typed; complain and initialize
4500 // that base class.
4501 diagnoseTypo(Corr,
4502 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4503 << MemberOrBase << false,
4504 PDiag() /*Suppress note, we provide our own.*/);
4505
4506 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4507 : VirtualBaseSpec;
4508 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4509 << BaseSpec->getType() << BaseSpec->getSourceRange();
4510
4511 TyD = Type;
4512 }
4513 }
4514 }
4515
4516 if (!TyD && BaseType.isNull()) {
4517 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4518 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4519 return true;
4520 }
4521 }
4522
4523 if (BaseType.isNull()) {
4526 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4527 TInfo = Context.CreateTypeSourceInfo(BaseType);
4529 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4532 }
4533 }
4534
4535 if (!TInfo)
4536 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4537
4538 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4539}
4540
4543 SourceLocation IdLoc) {
4544 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4545 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4546 assert((DirectMember || IndirectMember) &&
4547 "Member must be a FieldDecl or IndirectFieldDecl");
4548
4550 return true;
4551
4552 if (Member->isInvalidDecl())
4553 return true;
4554
4555 MultiExprArg Args;
4556 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4557 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4558 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4559 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4560 } else {
4561 // Template instantiation doesn't reconstruct ParenListExprs for us.
4562 Args = Init;
4563 }
4564
4565 SourceRange InitRange = Init->getSourceRange();
4566
4567 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4568 // Can't check initialization for a member of dependent type or when
4569 // any of the arguments are type-dependent expressions.
4571 } else {
4572 bool InitList = false;
4573 if (isa<InitListExpr>(Init)) {
4574 InitList = true;
4575 Args = Init;
4576 }
4577
4578 // Initialize the member.
4579 InitializedEntity MemberEntity =
4580 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4581 : InitializedEntity::InitializeMember(IndirectMember,
4582 nullptr);
4583 InitializationKind Kind =
4585 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4586 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4587 InitRange.getEnd());
4588
4589 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4590 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4591 nullptr);
4592 if (!MemberInit.isInvalid()) {
4593 // C++11 [class.base.init]p7:
4594 // The initialization of each base and member constitutes a
4595 // full-expression.
4596 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4597 /*DiscardedValue*/ false);
4598 }
4599
4600 if (MemberInit.isInvalid()) {
4601 // Args were sensible expressions but we couldn't initialize the member
4602 // from them. Preserve them in a RecoveryExpr instead.
4603 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4604 Member->getType())
4605 .get();
4606 if (!Init)
4607 return true;
4608 } else {
4609 Init = MemberInit.get();
4610 }
4611 }
4612
4613 if (DirectMember) {
4614 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4615 InitRange.getBegin(), Init,
4616 InitRange.getEnd());
4617 } else {
4618 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4619 InitRange.getBegin(), Init,
4620 InitRange.getEnd());
4621 }
4622}
4623
4626 CXXRecordDecl *ClassDecl) {
4627 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4628 if (!LangOpts.CPlusPlus11)
4629 return Diag(NameLoc, diag::err_delegating_ctor)
4630 << TInfo->getTypeLoc().getSourceRange();
4631 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4632
4633 bool InitList = true;
4634 MultiExprArg Args = Init;
4635 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4636 InitList = false;
4637 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4638 }
4639
4640 SourceRange InitRange = Init->getSourceRange();
4641 // Initialize the object.
4643 QualType(ClassDecl->getTypeForDecl(), 0));
4644 InitializationKind Kind =
4646 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4647 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4648 InitRange.getEnd());
4649 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4650 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4651 Args, nullptr);
4652 if (!DelegationInit.isInvalid()) {
4653 assert((DelegationInit.get()->containsErrors() ||
4654 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4655 "Delegating constructor with no target?");
4656
4657 // C++11 [class.base.init]p7:
4658 // The initialization of each base and member constitutes a
4659 // full-expression.
4660 DelegationInit = ActOnFinishFullExpr(
4661 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4662 }
4663
4664 if (DelegationInit.isInvalid()) {
4665 DelegationInit =
4666 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4667 QualType(ClassDecl->getTypeForDecl(), 0));
4668 if (DelegationInit.isInvalid())
4669 return true;
4670 } else {
4671 // If we are in a dependent context, template instantiation will
4672 // perform this type-checking again. Just save the arguments that we
4673 // received in a ParenListExpr.
4674 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4675 // of the information that we have about the base
4676 // initializer. However, deconstructing the ASTs is a dicey process,
4677 // and this approach is far more likely to get the corner cases right.
4679 DelegationInit = Init;
4680 }
4681
4682 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4683 DelegationInit.getAs<Expr>(),
4684 InitRange.getEnd());
4685}
4686
4689 Expr *Init, CXXRecordDecl *ClassDecl,
4690 SourceLocation EllipsisLoc) {
4691 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4692
4693 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4694 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4695 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4696
4697 // C++ [class.base.init]p2:
4698 // [...] Unless the mem-initializer-id names a nonstatic data
4699 // member of the constructor's class or a direct or virtual base
4700 // of that class, the mem-initializer is ill-formed. A
4701 // mem-initializer-list can initialize a base class using any
4702 // name that denotes that base class type.
4703
4704 // We can store the initializers in "as-written" form and delay analysis until
4705 // instantiation if the constructor is dependent. But not for dependent
4706 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4708 (BaseType->isDependentType() || Init->isTypeDependent());
4709
4710 SourceRange InitRange = Init->getSourceRange();
4711 if (EllipsisLoc.isValid()) {
4712 // This is a pack expansion.
4713 if (!BaseType->containsUnexpandedParameterPack()) {
4714 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4715 << SourceRange(BaseLoc, InitRange.getEnd());
4716
4717 EllipsisLoc = SourceLocation();
4718 }
4719 } else {
4720 // Check for any unexpanded parameter packs.
4721 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4722 return true;
4723
4725 return true;
4726 }
4727
4728 // Check for direct and virtual base classes.
4729 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4730 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4731 if (!Dependent) {
4733 BaseType))
4734 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4735
4736 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4737 VirtualBaseSpec);
4738
4739 // C++ [base.class.init]p2:
4740 // Unless the mem-initializer-id names a nonstatic data member of the
4741 // constructor's class or a direct or virtual base of that class, the
4742 // mem-initializer is ill-formed.
4743 if (!DirectBaseSpec && !VirtualBaseSpec) {
4744 // If the class has any dependent bases, then it's possible that
4745 // one of those types will resolve to the same type as
4746 // BaseType. Therefore, just treat this as a dependent base
4747 // class initialization. FIXME: Should we try to check the
4748 // initialization anyway? It seems odd.
4749 if (ClassDecl->hasAnyDependentBases())
4750 Dependent = true;
4751 else
4752 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4753 << BaseType << Context.getTypeDeclType(ClassDecl)
4754 << BaseTInfo->getTypeLoc().getSourceRange();
4755 }
4756 }
4757
4758 if (Dependent) {
4760
4761 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4762 /*IsVirtual=*/false,
4763 InitRange.getBegin(), Init,
4764 InitRange.getEnd(), EllipsisLoc);
4765 }
4766
4767 // C++ [base.class.init]p2:
4768 // If a mem-initializer-id is ambiguous because it designates both
4769 // a direct non-virtual base class and an inherited virtual base
4770 // class, the mem-initializer is ill-formed.
4771 if (DirectBaseSpec && VirtualBaseSpec)
4772 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4773 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4774
4775 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4776 if (!BaseSpec)
4777 BaseSpec = VirtualBaseSpec;
4778
4779 // Initialize the base.
4780 bool InitList = true;
4781 MultiExprArg Args = Init;
4782 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4783 InitList = false;
4784 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4785 }
4786
4787 InitializedEntity BaseEntity =
4788 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4789 InitializationKind Kind =
4790 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4791 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4792 InitRange.getEnd());
4793 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4794 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4795 if (!BaseInit.isInvalid()) {
4796 // C++11 [class.base.init]p7:
4797 // The initialization of each base and member constitutes a
4798 // full-expression.
4799 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4800 /*DiscardedValue*/ false);
4801 }
4802
4803 if (BaseInit.isInvalid()) {
4804 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4805 Args, BaseType);
4806 if (BaseInit.isInvalid())
4807 return true;
4808 } else {
4809 // If we are in a dependent context, template instantiation will
4810 // perform this type-checking again. Just save the arguments that we
4811 // received in a ParenListExpr.
4812 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4813 // of the information that we have about the base
4814 // initializer. However, deconstructing the ASTs is a dicey process,
4815 // and this approach is far more likely to get the corner cases right.
4817 BaseInit = Init;
4818 }
4819
4820 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4821 BaseSpec->isVirtual(),
4822 InitRange.getBegin(),
4823 BaseInit.getAs<Expr>(),
4824 InitRange.getEnd(), EllipsisLoc);
4825}
4826
4827// Create a static_cast<T&&>(expr).
4829 QualType TargetType =
4830 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4832 SourceLocation ExprLoc = E->getBeginLoc();
4834 TargetType, ExprLoc);
4835
4836 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4837 SourceRange(ExprLoc, ExprLoc),
4838 E->getSourceRange()).get();
4839}
4840
4841/// ImplicitInitializerKind - How an implicit base or member initializer should
4842/// initialize its base or member.
4849
4850static bool
4852 ImplicitInitializerKind ImplicitInitKind,
4853 CXXBaseSpecifier *BaseSpec,
4854 bool IsInheritedVirtualBase,
4855 CXXCtorInitializer *&CXXBaseInit) {
4856 InitializedEntity InitEntity
4858 IsInheritedVirtualBase);
4859
4860 ExprResult BaseInit;
4861
4862 switch (ImplicitInitKind) {
4863 case IIK_Inherit:
4864 case IIK_Default: {
4865 InitializationKind InitKind
4866 = InitializationKind::CreateDefault(Constructor->getLocation());
4867 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4868 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4869 break;
4870 }
4871
4872 case IIK_Move:
4873 case IIK_Copy: {
4874 bool Moving = ImplicitInitKind == IIK_Move;
4875 ParmVarDecl *Param = Constructor->getParamDecl(0);
4876 QualType ParamType = Param->getType().getNonReferenceType();
4877
4878 Expr *CopyCtorArg =
4880 SourceLocation(), Param, false,
4881 Constructor->getLocation(), ParamType,
4882 VK_LValue, nullptr);
4883
4884 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4885
4886 // Cast to the base class to avoid ambiguities.
4887 QualType ArgTy =
4889 ParamType.getQualifiers());
4890
4891 if (Moving) {
4892 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4893 }
4894
4895 CXXCastPath BasePath;
4896 BasePath.push_back(BaseSpec);
4897 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4898 CK_UncheckedDerivedToBase,
4899 Moving ? VK_XValue : VK_LValue,
4900 &BasePath).get();
4901
4902 InitializationKind InitKind
4903 = InitializationKind::CreateDirect(Constructor->getLocation(),
4905 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4906 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4907 break;
4908 }
4909 }
4910
4911 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4912 if (BaseInit.isInvalid())
4913 return true;
4914
4915 CXXBaseInit =
4918 SourceLocation()),
4919 BaseSpec->isVirtual(),
4921 BaseInit.getAs<Expr>(),
4923 SourceLocation());
4924
4925 return false;
4926}
4927
4928static bool RefersToRValueRef(Expr *MemRef) {
4929 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4930 return Referenced->getType()->isRValueReferenceType();
4931}
4932
4933static bool
4935 ImplicitInitializerKind ImplicitInitKind,
4937 CXXCtorInitializer *&CXXMemberInit) {
4938 if (Field->isInvalidDecl())
4939 return true;
4940
4941 SourceLocation Loc = Constructor->getLocation();
4942
4943 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4944 bool Moving = ImplicitInitKind == IIK_Move;
4945 ParmVarDecl *Param = Constructor->getParamDecl(0);
4946 QualType ParamType = Param->getType().getNonReferenceType();
4947
4948 // Suppress copying zero-width bitfields.
4949 if (Field->isZeroLengthBitField())
4950 return false;
4951
4952 Expr *MemberExprBase =
4954 SourceLocation(), Param, false,
4955 Loc, ParamType, VK_LValue, nullptr);
4956
4957 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4958
4959 if (Moving) {
4960 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4961 }
4962
4963 // Build a reference to this field within the parameter.
4964 CXXScopeSpec SS;
4965 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4967 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4968 : cast<ValueDecl>(Field), AS_public);
4969 MemberLookup.resolveKind();
4970 ExprResult CtorArg
4971 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4972 ParamType, Loc,
4973 /*IsArrow=*/false,
4974 SS,
4975 /*TemplateKWLoc=*/SourceLocation(),
4976 /*FirstQualifierInScope=*/nullptr,
4977 MemberLookup,
4978 /*TemplateArgs=*/nullptr,
4979 /*S*/nullptr);
4980 if (CtorArg.isInvalid())
4981 return true;
4982
4983 // C++11 [class.copy]p15:
4984 // - if a member m has rvalue reference type T&&, it is direct-initialized
4985 // with static_cast<T&&>(x.m);
4986 if (RefersToRValueRef(CtorArg.get())) {
4987 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4988 }
4989
4990 InitializedEntity Entity =
4992 /*Implicit*/ true)
4993 : InitializedEntity::InitializeMember(Field, nullptr,
4994 /*Implicit*/ true);
4995
4996 // Direct-initialize to use the copy constructor.
4997 InitializationKind InitKind =
4999
5000 Expr *CtorArgE = CtorArg.getAs<Expr>();
5001 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5002 ExprResult MemberInit =
5003 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5004 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5005 if (MemberInit.isInvalid())
5006 return true;
5007
5008 if (Indirect)
5009 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5010 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5011 else
5012 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5013 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5014 return false;
5015 }
5016
5017 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5018 "Unhandled implicit init kind!");
5019
5020 QualType FieldBaseElementType =
5021 SemaRef.Context.getBaseElementType(Field->getType());
5022
5023 if (FieldBaseElementType->isRecordType()) {
5024 InitializedEntity InitEntity =
5026 /*Implicit*/ true)
5027 : InitializedEntity::InitializeMember(Field, nullptr,
5028 /*Implicit*/ true);
5029 InitializationKind InitKind =
5031
5032 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5033 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5034
5035 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5036 if (MemberInit.isInvalid())
5037 return true;
5038
5039 if (Indirect)
5040 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5041 Indirect, Loc,
5042 Loc,
5043 MemberInit.get(),
5044 Loc);
5045 else
5046 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5047 Field, Loc, Loc,
5048 MemberInit.get(),
5049 Loc);
5050 return false;
5051 }
5052
5053 if (!Field->getParent()->isUnion()) {
5054 if (FieldBaseElementType->isReferenceType()) {
5055 SemaRef.Diag(Constructor->getLocation(),
5056 diag::err_uninitialized_member_in_ctor)
5057 << (int)Constructor->isImplicit()
5058 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5059 << 0 << Field->getDeclName();
5060 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5061 return true;
5062 }
5063
5064 if (FieldBaseElementType.isConstQualified()) {
5065 SemaRef.Diag(Constructor->getLocation(),
5066 diag::err_uninitialized_member_in_ctor)
5067 << (int)Constructor->isImplicit()
5068 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5069 << 1 << Field->getDeclName();
5070 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5071 return true;
5072 }
5073 }
5074
5075 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5076 // ARC and Weak:
5077 // Default-initialize Objective-C pointers to NULL.
5078 CXXMemberInit
5080 Loc, Loc,
5081 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5082 Loc);
5083 return false;
5084 }
5085
5086 // Nothing to initialize.
5087 CXXMemberInit = nullptr;
5088 return false;
5089}
5090
5091namespace {
5092struct BaseAndFieldInfo {
5093 Sema &S;
5094 CXXConstructorDecl *Ctor;
5095 bool AnyErrorsInInits;
5097 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5099 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5100
5101 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5102 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5103 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5104 if (Ctor->getInheritedConstructor())
5105 IIK = IIK_Inherit;
5106 else if (Generated && Ctor->isCopyConstructor())
5107 IIK = IIK_Copy;
5108 else if (Generated && Ctor->isMoveConstructor())
5109 IIK = IIK_Move;
5110 else
5111 IIK = IIK_Default;
5112 }
5113
5114 bool isImplicitCopyOrMove() const {
5115 switch (IIK) {
5116 case IIK_Copy:
5117 case IIK_Move:
5118 return true;
5119
5120 case IIK_Default:
5121 case IIK_Inherit:
5122 return false;
5123 }
5124
5125 llvm_unreachable("Invalid ImplicitInitializerKind!");
5126 }
5127
5128 bool addFieldInitializer(CXXCtorInitializer *Init) {
5129 AllToInit.push_back(Init);
5130
5131 // Check whether this initializer makes the field "used".
5132 if (Init->getInit()->HasSideEffects(S.Context))
5133 S.UnusedPrivateFields.remove(Init->getAnyMember());
5134
5135 return false;
5136 }
5137
5138 bool isInactiveUnionMember(FieldDecl *Field) {
5139 RecordDecl *Record = Field->getParent();
5140 if (!Record->isUnion())
5141 return false;
5142
5143 if (FieldDecl *Active =
5144 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5145 return Active != Field->getCanonicalDecl();
5146
5147 // In an implicit copy or move constructor, ignore any in-class initializer.
5148 if (isImplicitCopyOrMove())
5149 return true;
5150
5151 // If there's no explicit initialization, the field is active only if it
5152 // has an in-class initializer...
5153 if (Field->hasInClassInitializer())
5154 return false;
5155 // ... or it's an anonymous struct or union whose class has an in-class
5156 // initializer.
5157 if (!Field->isAnonymousStructOrUnion())
5158 return true;
5159 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5160 return !FieldRD->hasInClassInitializer();
5161 }
5162
5163 /// Determine whether the given field is, or is within, a union member
5164 /// that is inactive (because there was an initializer given for a different
5165 /// member of the union, or because the union was not initialized at all).
5166 bool isWithinInactiveUnionMember(FieldDecl *Field,
5168 if (!Indirect)
5169 return isInactiveUnionMember(Field);
5170
5171 for (auto *C : Indirect->chain()) {
5172 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5173 if (Field && isInactiveUnionMember(Field))
5174 return true;
5175 }
5176 return false;
5177 }
5178};
5179}
5180
5181/// Determine whether the given type is an incomplete or zero-lenfgth
5182/// array type.
5184 if (T->isIncompleteArrayType())
5185 return true;
5186
5187 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5188 if (ArrayT->isZeroSize())
5189 return true;
5190
5191 T = ArrayT->getElementType();
5192 }
5193
5194 return false;
5195}
5196
5197static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5198 FieldDecl *Field,
5199 IndirectFieldDecl *Indirect = nullptr) {
5200 if (Field->isInvalidDecl())
5201 return false;
5202
5203 // Overwhelmingly common case: we have a direct initializer for this field.
5205 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5206 return Info.addFieldInitializer(Init);
5207
5208 // C++11 [class.base.init]p8:
5209 // if the entity is a non-static data member that has a
5210 // brace-or-equal-initializer and either
5211 // -- the constructor's class is a union and no other variant member of that
5212 // union is designated by a mem-initializer-id or
5213 // -- the constructor's class is not a union, and, if the entity is a member
5214 // of an anonymous union, no other member of that union is designated by
5215 // a mem-initializer-id,
5216 // the entity is initialized as specified in [dcl.init].
5217 //
5218 // We also apply the same rules to handle anonymous structs within anonymous
5219 // unions.
5220 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5221 return false;
5222
5223 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5224 ExprResult DIE =
5225 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5226 if (DIE.isInvalid())
5227 return true;
5228
5229 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5230 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5231
5233 if (Indirect)
5234 Init = new (SemaRef.Context)
5236 SourceLocation(), DIE.get(), SourceLocation());
5237 else
5238 Init = new (SemaRef.Context)
5240 SourceLocation(), DIE.get(), SourceLocation());
5241 return Info.addFieldInitializer(Init);
5242 }
5243
5244 // Don't initialize incomplete or zero-length arrays.
5245 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5246 return false;
5247
5248 // Don't try to build an implicit initializer if there were semantic
5249 // errors in any of the initializers (and therefore we might be
5250 // missing some that the user actually wrote).
5251 if (Info.AnyErrorsInInits)
5252 return false;
5253
5254 CXXCtorInitializer *Init = nullptr;
5255 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5256 Indirect, Init))
5257 return true;
5258
5259 if (!Init)
5260 return false;
5261
5262 return Info.addFieldInitializer(Init);
5263}
5264
5265bool
5268 assert(Initializer->isDelegatingInitializer());
5269 Constructor->setNumCtorInitializers(1);
5270 CXXCtorInitializer **initializer =
5271 new (Context) CXXCtorInitializer*[1];
5272 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5273 Constructor->setCtorInitializers(initializer);
5274
5275 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5276 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5277 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5278 }
5279
5280 DelegatingCtorDecls.push_back(Constructor);
5281
5282 DiagnoseUninitializedFields(*this, Constructor);
5283
5284 return false;
5285}
5286
5287bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5288 ArrayRef<CXXCtorInitializer *> Initializers) {
5289 if (Constructor->isDependentContext()) {
5290 // Just store the initializers as written, they will be checked during
5291 // instantiation.
5292 if (!Initializers.empty()) {
5293 Constructor->setNumCtorInitializers(Initializers.size());
5294 CXXCtorInitializer **baseOrMemberInitializers =
5295 new (Context) CXXCtorInitializer*[Initializers.size()];
5296 memcpy(baseOrMemberInitializers, Initializers.data(),
5297 Initializers.size() * sizeof(CXXCtorInitializer*));
5298 Constructor->setCtorInitializers(baseOrMemberInitializers);
5299 }
5300
5301 // Let template instantiation know whether we had errors.
5302 if (AnyErrors)
5303 Constructor->setInvalidDecl();
5304
5305 return false;
5306 }
5307
5308 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5309
5310 // We need to build the initializer AST according to order of construction
5311 // and not what user specified in the Initializers list.
5312 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5313 if (!ClassDecl)
5314 return true;
5315
5316 bool HadError = false;
5317
5318 for (unsigned i = 0; i < Initializers.size(); i++) {
5319 CXXCtorInitializer *Member = Initializers[i];
5320
5321 if (Member->isBaseInitializer())
5322 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5323 else {
5324 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5325
5326 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5327 for (auto *C : F->chain()) {
5328 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5329 if (FD && FD->getParent()->isUnion())
5330 Info.ActiveUnionMember.insert(std::make_pair(
5332 }
5333 } else if (FieldDecl *FD = Member->getMember()) {
5334 if (FD->getParent()->isUnion())
5335 Info.ActiveUnionMember.insert(std::make_pair(
5337 }
5338 }
5339 }
5340
5341 // Keep track of the direct virtual bases.
5343 for (auto &I : ClassDecl->bases()) {
5344 if (I.isVirtual())
5345 DirectVBases.insert(&I);
5346 }
5347
5348 // Push virtual bases before others.
5349 for (auto &VBase : ClassDecl->vbases()) {
5351 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5352 // [class.base.init]p7, per DR257:
5353 // A mem-initializer where the mem-initializer-id names a virtual base
5354 // class is ignored during execution of a constructor of any class that
5355 // is not the most derived class.
5356 if (ClassDecl->isAbstract()) {
5357 // FIXME: Provide a fixit to remove the base specifier. This requires
5358 // tracking the location of the associated comma for a base specifier.
5359 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5360 << VBase.getType() << ClassDecl;
5361 DiagnoseAbstractType(ClassDecl);
5362 }
5363
5364 Info.AllToInit.push_back(Value);
5365 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5366 // [class.base.init]p8, per DR257:
5367 // If a given [...] base class is not named by a mem-initializer-id
5368 // [...] and the entity is not a virtual base class of an abstract
5369 // class, then [...] the entity is default-initialized.
5370 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5371 CXXCtorInitializer *CXXBaseInit;
5372 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5373 &VBase, IsInheritedVirtualBase,
5374 CXXBaseInit)) {
5375 HadError = true;
5376 continue;
5377 }
5378
5379 Info.AllToInit.push_back(CXXBaseInit);
5380 }
5381 }
5382
5383 // Non-virtual bases.
5384 for (auto &Base : ClassDecl->bases()) {
5385 // Virtuals are in the virtual base list and already constructed.
5386 if (Base.isVirtual())
5387 continue;
5388
5390 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5391 Info.AllToInit.push_back(Value);
5392 } else if (!AnyErrors) {
5393 CXXCtorInitializer *CXXBaseInit;
5394 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5395 &Base, /*IsInheritedVirtualBase=*/false,
5396 CXXBaseInit)) {
5397 HadError = true;
5398 continue;
5399 }
5400
5401 Info.AllToInit.push_back(CXXBaseInit);
5402 }
5403 }
5404
5405 // Fields.
5406 for (auto *Mem : ClassDecl->decls()) {
5407 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5408 // C++ [class.bit]p2:
5409 // A declaration for a bit-field that omits the identifier declares an
5410 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5411 // initialized.
5412 if (F->isUnnamedBitField())
5413 continue;
5414
5415 // If we're not generating the implicit copy/move constructor, then we'll
5416 // handle anonymous struct/union fields based on their individual
5417 // indirect fields.
5418 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5419 continue;
5420
5421 if (CollectFieldInitializer(*this, Info, F))
5422 HadError = true;
5423 continue;
5424 }
5425
5426 // Beyond this point, we only consider default initialization.
5427 if (Info.isImplicitCopyOrMove())
5428 continue;
5429
5430 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5431 if (F->getType()->isIncompleteArrayType()) {
5432 assert(ClassDecl->hasFlexibleArrayMember() &&
5433 "Incomplete array type is not valid");
5434 continue;
5435 }
5436
5437 // Initialize each field of an anonymous struct individually.
5438 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5439 HadError = true;
5440
5441 continue;
5442 }
5443 }
5444
5445 unsigned NumInitializers = Info.AllToInit.size();
5446 if (NumInitializers > 0) {
5447 Constructor->setNumCtorInitializers(NumInitializers);
5448 CXXCtorInitializer **baseOrMemberInitializers =
5449 new (Context) CXXCtorInitializer*[NumInitializers];
5450 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5451 NumInitializers * sizeof(CXXCtorInitializer*));
5452 Constructor->setCtorInitializers(baseOrMemberInitializers);
5453
5454 // Constructors implicitly reference the base and member
5455 // destructors.
5456 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5457 Constructor->getParent());
5458 }
5459
5460 return HadError;
5461}
5462
5464 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5465 const RecordDecl *RD = RT->getDecl();
5466 if (RD->isAnonymousStructOrUnion()) {
5467 for (auto *Field : RD->fields())
5468 PopulateKeysForFields(Field, IdealInits);
5469 return;
5470 }
5471 }
5472 IdealInits.push_back(Field->getCanonicalDecl());
5473}
5474
5475static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5476 return Context.getCanonicalType(BaseType).getTypePtr();
5477}
5478
5481 if (!Member->isAnyMemberInitializer())
5482 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5483
5484 return Member->getAnyMember()->getCanonicalDecl();
5485}
5486
5489 const CXXCtorInitializer *Current) {
5490 if (Previous->isAnyMemberInitializer())
5491 Diag << 0 << Previous->getAnyMember();
5492 else
5493 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5494
5495 if (Current->isAnyMemberInitializer())
5496 Diag << 0 << Current->getAnyMember();
5497 else
5498 Diag << 1 << Current->getTypeSourceInfo()->getType();
5499}
5500
5502 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5504 if (Constructor->getDeclContext()->isDependentContext())
5505 return;
5506
5507 // Don't check initializers order unless the warning is enabled at the
5508 // location of at least one initializer.
5509 bool ShouldCheckOrder = false;
5510 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5511 CXXCtorInitializer *Init = Inits[InitIndex];
5512 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5513 Init->getSourceLocation())) {
5514 ShouldCheckOrder = true;
5515 break;
5516 }
5517 }
5518 if (!ShouldCheckOrder)
5519 return;
5520
5521 // Build the list of bases and members in the order that they'll
5522 // actually be initialized. The explicit initializers should be in
5523 // this same order but may be missing things.
5524 SmallVector<const void*, 32> IdealInitKeys;
5525
5526 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5527
5528 // 1. Virtual bases.
5529 for (const auto &VBase : ClassDecl->vbases())
5530 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5531
5532 // 2. Non-virtual bases.
5533 for (const auto &Base : ClassDecl->bases()) {
5534 if (Base.isVirtual())
5535 continue;
5536 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5537 }
5538
5539 // 3. Direct fields.
5540 for (auto *Field : ClassDecl->fields()) {
5541 if (Field->isUnnamedBitField())
5542 continue;
5543
5544 PopulateKeysForFields(Field, IdealInitKeys);
5545 }
5546
5547 unsigned NumIdealInits = IdealInitKeys.size();
5548 unsigned IdealIndex = 0;
5549
5550 // Track initializers that are in an incorrect order for either a warning or
5551 // note if multiple ones occur.
5552 SmallVector<unsigned> WarnIndexes;
5553 // Correlates the index of an initializer in the init-list to the index of
5554 // the field/base in the class.
5555 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5556
5557 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5558 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5559
5560 // Scan forward to try to find this initializer in the idealized
5561 // initializers list.
5562 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5563 if (InitKey == IdealInitKeys[IdealIndex])
5564 break;
5565
5566 // If we didn't find this initializer, it must be because we
5567 // scanned past it on a previous iteration. That can only
5568 // happen if we're out of order; emit a warning.
5569 if (IdealIndex == NumIdealInits && InitIndex) {
5570 WarnIndexes.push_back(InitIndex);
5571
5572 // Move back to the initializer's location in the ideal list.
5573 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5574 if (InitKey == IdealInitKeys[IdealIndex])
5575 break;
5576
5577 assert(IdealIndex < NumIdealInits &&
5578 "initializer not found in initializer list");
5579 }
5580 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5581 }
5582
5583 if (WarnIndexes.empty())
5584 return;
5585
5586 // Sort based on the ideal order, first in the pair.
5587 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5588
5589 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5590 // emit the diagnostic before we can try adding notes.
5591 {
5593 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5594 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5595 : diag::warn_some_initializers_out_of_order);
5596
5597 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5598 if (CorrelatedInitOrder[I].second == I)
5599 continue;
5600 // Ideally we would be using InsertFromRange here, but clang doesn't
5601 // appear to handle InsertFromRange correctly when the source range is
5602 // modified by another fix-it.
5604 Inits[I]->getSourceRange(),
5607 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5609 }
5610
5611 // If there is only 1 item out of order, the warning expects the name and
5612 // type of each being added to it.
5613 if (WarnIndexes.size() == 1) {
5614 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5615 Inits[WarnIndexes.front()]);
5616 return;
5617 }
5618 }
5619 // More than 1 item to warn, create notes letting the user know which ones
5620 // are bad.
5621 for (unsigned WarnIndex : WarnIndexes) {
5622 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5623 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5624 diag::note_initializer_out_of_order);
5625 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5626 D << PrevInit->getSourceRange();
5627 }
5628}
5629
5630namespace {
5631bool CheckRedundantInit(Sema &S,
5633 CXXCtorInitializer *&PrevInit) {
5634 if (!PrevInit) {
5635 PrevInit = Init;
5636 return false;
5637 }
5638
5639 if (FieldDecl *Field = Init->getAnyMember())
5640 S.Diag(Init->getSourceLocation(),
5641 diag::err_multiple_mem_initialization)
5642 << Field->getDeclName()
5643 << Init->getSourceRange();
5644 else {
5645 const Type *BaseClass = Init->getBaseClass();
5646 assert(BaseClass && "neither field nor base");
5647 S.Diag(Init->getSourceLocation(),
5648 diag::err_multiple_base_initialization)
5649 << QualType(BaseClass, 0)
5650 << Init->getSourceRange();
5651 }
5652 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5653 << 0 << PrevInit->getSourceRange();
5654
5655 return true;
5656}
5657
5658typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5659typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5660
5661bool CheckRedundantUnionInit(Sema &S,
5663 RedundantUnionMap &Unions) {
5664 FieldDecl *Field = Init->getAnyMember();
5665 RecordDecl *Parent = Field->getParent();
5666 NamedDecl *Child = Field;
5667
5668 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5669 if (Parent->isUnion()) {
5670 UnionEntry &En = Unions[Parent];
5671 if (En.first && En.first != Child) {
5672 S.Diag(Init->getSourceLocation(),
5673 diag::err_multiple_mem_union_initialization)
5674 << Field->getDeclName()
5675 << Init->getSourceRange();
5676 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5677 << 0 << En.second->getSourceRange();
5678 return true;
5679 }
5680 if (!En.first) {
5681 En.first = Child;
5682 En.second = Init;
5683 }
5684 if (!Parent->isAnonymousStructOrUnion())
5685 return false;
5686 }
5687
5688 Child = Parent;
5689 Parent = cast<RecordDecl>(Parent->getDeclContext());
5690 }
5691
5692 return false;
5693}
5694} // namespace
5695
5696void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5697 SourceLocation ColonLoc,
5699 bool AnyErrors) {
5700 if (!ConstructorDecl)
5701 return;
5702
5703 AdjustDeclIfTemplate(ConstructorDecl);
5704
5705 CXXConstructorDecl *Constructor
5706 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5707
5708 if (!Constructor) {
5709 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5710 return;
5711 }
5712
5713 // Mapping for the duplicate initializers check.
5714 // For member initializers, this is keyed with a FieldDecl*.
5715 // For base initializers, this is keyed with a Type*.
5716 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5717
5718 // Mapping for the inconsistent anonymous-union initializers check.
5719 RedundantUnionMap MemberUnions;
5720
5721 bool HadError = false;
5722 for (unsigned i = 0; i < MemInits.size(); i++) {
5723 CXXCtorInitializer *Init = MemInits[i];
5724
5725 // Set the source order index.
5726 Init->setSourceOrder(i);
5727
5728 if (Init->isAnyMemberInitializer()) {
5729 const void *Key = GetKeyForMember(Context, Init);
5730 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5731 CheckRedundantUnionInit(*this, Init, MemberUnions))
5732 HadError = true;
5733 } else if (Init->isBaseInitializer()) {
5734 const void *Key = GetKeyForMember(Context, Init);
5735 if (CheckRedundantInit(*this, Init, Members[Key]))
5736 HadError = true;
5737 } else {
5738 assert(Init->isDelegatingInitializer());
5739 // This must be the only initializer
5740 if (MemInits.size() != 1) {
5741 Diag(Init->getSourceLocation(),
5742 diag::err_delegating_initializer_alone)
5743 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5744 // We will treat this as being the only initializer.
5745 }
5746 SetDelegatingInitializer(Constructor, MemInits[i]);
5747 // Return immediately as the initializer is set.
5748 return;
5749 }
5750 }
5751
5752 if (HadError)
5753 return;
5754
5755 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5756
5757 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5758
5759 DiagnoseUninitializedFields(*this, Constructor);
5760}
5761
5762void
5764 CXXRecordDecl *ClassDecl) {
5765 // Ignore dependent contexts. Also ignore unions, since their members never
5766 // have destructors implicitly called.
5767 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5768 return;
5769
5770 // FIXME: all the access-control diagnostics are positioned on the
5771 // field/base declaration. That's probably good; that said, the
5772 // user might reasonably want to know why the destructor is being
5773 // emitted, and we currently don't say.
5774
5775 // Non-static data members.
5776 for (auto *Field : ClassDecl->fields()) {
5777 if (Field->isInvalidDecl())
5778 continue;
5779
5780 // Don't destroy incomplete or zero-length arrays.
5781 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5782 continue;
5783
5784 QualType FieldType = Context.getBaseElementType(Field->getType());
5785
5786 const RecordType* RT = FieldType->getAs<RecordType>();
5787 if (!RT)
5788 continue;
5789
5790 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5791 if (FieldClassDecl->isInvalidDecl())
5792 continue;
5793 if (FieldClassDecl->hasIrrelevantDestructor())
5794 continue;
5795 // The destructor for an implicit anonymous union member is never invoked.
5796 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5797 continue;
5798
5799 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5800 // Dtor might still be missing, e.g because it's invalid.
5801 if (!Dtor)
5802 continue;
5803 CheckDestructorAccess(Field->getLocation(), Dtor,
5804 PDiag(diag::err_access_dtor_field)
5805 << Field->getDeclName()
5806 << FieldType);
5807
5808 MarkFunctionReferenced(Location, Dtor);
5809 DiagnoseUseOfDecl(Dtor, Location);
5810 }
5811
5812 // We only potentially invoke the destructors of potentially constructed
5813 // subobjects.
5814 bool VisitVirtualBases = !ClassDecl->isAbstract();
5815
5816 // If the destructor exists and has already been marked used in the MS ABI,
5817 // then virtual base destructors have already been checked and marked used.
5818 // Skip checking them again to avoid duplicate diagnostics.
5820 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5821 if (Dtor && Dtor->isUsed())
5822 VisitVirtualBases = false;
5823 }
5824
5826
5827 // Bases.
5828 for (const auto &Base : ClassDecl->bases()) {
5829 const RecordType *RT = Base.getType()->getAs<RecordType>();
5830 if (!RT)
5831 continue;
5832
5833 // Remember direct virtual bases.
5834 if (Base.isVirtual()) {
5835 if (!VisitVirtualBases)
5836 continue;
5837 DirectVirtualBases.insert(RT);
5838 }
5839
5840 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5841 // If our base class is invalid, we probably can't get its dtor anyway.
5842 if (BaseClassDecl->isInvalidDecl())
5843 continue;
5844 if (BaseClassDecl->hasIrrelevantDestructor())
5845 continue;
5846
5847 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5848 // Dtor might still be missing, e.g because it's invalid.
5849 if (!Dtor)
5850 continue;
5851
5852 // FIXME: caret should be on the start of the class name
5853 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5854 PDiag(diag::err_access_dtor_base)
5855 << Base.getType() << Base.getSourceRange(),
5856 Context.getTypeDeclType(ClassDecl));
5857
5858 MarkFunctionReferenced(Location, Dtor);
5859 DiagnoseUseOfDecl(Dtor, Location);
5860 }
5861
5862 if (VisitVirtualBases)
5863 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5864 &DirectVirtualBases);
5865}
5866
5868 SourceLocation Location, CXXRecordDecl *ClassDecl,
5869 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5870 // Virtual bases.
5871 for (const auto &VBase : ClassDecl->vbases()) {
5872 // Bases are always records in a well-formed non-dependent class.
5873 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5874
5875 // Ignore already visited direct virtual bases.
5876 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5877 continue;
5878
5879 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5880 // If our base class is invalid, we probably can't get its dtor anyway.
5881 if (BaseClassDecl->isInvalidDecl())
5882 continue;
5883 if (BaseClassDecl->hasIrrelevantDestructor())
5884 continue;
5885
5886 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5887 // Dtor might still be missing, e.g because it's invalid.
5888 if (!Dtor)
5889 continue;
5891 ClassDecl->getLocation(), Dtor,
5892 PDiag(diag::err_access_dtor_vbase)
5893 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5894 Context.getTypeDeclType(ClassDecl)) ==
5895 AR_accessible) {
5897 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5898 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5899 SourceRange(), DeclarationName(), nullptr);
5900 }
5901
5902 MarkFunctionReferenced(Location, Dtor);
5903 DiagnoseUseOfDecl(Dtor, Location);
5904 }
5905}
5906
5908 if (!CDtorDecl)
5909 return;
5910
5911 if (CXXConstructorDecl *Constructor
5912 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5913 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5914 !ClassDecl || ClassDecl->isInvalidDecl()) {
5915 return;
5916 }
5917 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5918 DiagnoseUninitializedFields(*this, Constructor);
5919 }
5920}
5921
5923 if (!getLangOpts().CPlusPlus)
5924 return false;
5925
5926 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5927 if (!RD)
5928 return false;
5929
5930 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5931 // class template specialization here, but doing so breaks a lot of code.
5932
5933 // We can't answer whether something is abstract until it has a
5934 // definition. If it's currently being defined, we'll walk back
5935 // over all the declarations when we have a full definition.
5936 const CXXRecordDecl *Def = RD->getDefinition();
5937 if (!Def || Def->isBeingDefined())
5938 return false;
5939
5940 return RD->isAbstract();
5941}
5942
5944 TypeDiagnoser &Diagnoser) {
5945 if (!isAbstractType(Loc, T))
5946 return false;
5947
5949 Diagnoser.diagnose(*this, Loc, T);
5951 return true;
5952}
5953
5955 // Check if we've already emitted the list of pure virtual functions
5956 // for this class.
5958 return;
5959
5960 // If the diagnostic is suppressed, don't emit the notes. We're only
5961 // going to emit them once, so try to attach them to a diagnostic we're
5962 // actually going to show.
5964 return;
5965
5966 CXXFinalOverriderMap FinalOverriders;
5967 RD->getFinalOverriders(FinalOverriders);
5968
5969 // Keep a set of seen pure methods so we won't diagnose the same method
5970 // more than once.
5972
5973 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5974 MEnd = FinalOverriders.end();
5975 M != MEnd;
5976 ++M) {
5977 for (OverridingMethods::iterator SO = M->second.begin(),
5978 SOEnd = M->second.end();
5979 SO != SOEnd; ++SO) {
5980 // C++ [class.abstract]p4:
5981 // A class is abstract if it contains or inherits at least one
5982 // pure virtual function for which the final overrider is pure
5983 // virtual.
5984
5985 //
5986 if (SO->second.size() != 1)
5987 continue;
5988
5989 if (!SO->second.front().Method->isPureVirtual())
5990 continue;
5991
5992 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5993 continue;
5994
5995 Diag(SO->second.front().Method->getLocation(),
5996 diag::note_pure_virtual_function)
5997 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5998 }
5999 }
6000
6003 PureVirtualClassDiagSet->insert(RD);
6004}
6005
6006namespace {
6007struct AbstractUsageInfo {
6008 Sema &S;
6010 CanQualType AbstractType;
6011 bool Invalid;
6012
6013 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6014 : S(S), Record(Record),
6015 AbstractType(S.Context.getCanonicalType(
6016 S.Context.getTypeDeclType(Record))),
6017 Invalid(false) {}
6018
6019 void DiagnoseAbstractType() {
6020 if (Invalid) return;
6022 Invalid = true;
6023 }
6024
6025 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6026};
6027
6028struct CheckAbstractUsage {
6029 AbstractUsageInfo &Info;
6030 const NamedDecl *Ctx;
6031
6032 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6033 : Info(Info), Ctx(Ctx) {}
6034
6035 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6036 switch (TL.getTypeLocClass()) {
6037#define ABSTRACT_TYPELOC(CLASS, PARENT)
6038#define TYPELOC(CLASS, PARENT) \
6039 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6040#include "clang/AST/TypeLocNodes.def"
6041 }
6042 }
6043
6044 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6046 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6047 if (!TL.getParam(I))
6048 continue;
6049
6051 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6052 }
6053 }
6054
6055 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6057 }
6058
6060 // Visit the type parameters from a permissive context.
6061 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6062 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6064 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6065 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6066 // TODO: other template argument types?
6067 }
6068 }
6069
6070 // Visit pointee types from a permissive context.
6071#define CheckPolymorphic(Type) \
6072 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6073 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6074 }
6080
6081 /// Handle all the types we haven't given a more specific
6082 /// implementation for above.
6083 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6084 // Every other kind of type that we haven't called out already
6085 // that has an inner type is either (1) sugar or (2) contains that
6086 // inner type in some way as a subobject.
6087 if (TypeLoc Next = TL.getNextTypeLoc())
6088 return Visit(Next, Sel);
6089
6090 // If there's no inner type and we're in a permissive context,
6091 // don't diagnose.
6092 if (Sel == Sema::AbstractNone) return;
6093
6094 // Check whether the type matches the abstract type.
6095 QualType T = TL.getType();
6096 if (T->isArrayType()) {
6098 T = Info.S.Context.getBaseElementType(T);
6099 }
6101 if (CT != Info.AbstractType) return;
6102
6103 // It matched; do some magic.
6104 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6105 if (Sel == Sema::AbstractArrayType) {
6106 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6107 << T << TL.getSourceRange();
6108 } else {
6109 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6110 << Sel << T << TL.getSourceRange();
6111 }
6112 Info.DiagnoseAbstractType();
6113 }
6114};
6115
6116void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6118 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6119}
6120
6121}
6122
6123/// Check for invalid uses of an abstract type in a function declaration.
6124static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6125 FunctionDecl *FD) {
6126 // Only definitions are required to refer to complete and
6127 // non-abstract types.
6129 return;
6130
6131 // For safety's sake, just ignore it if we don't have type source
6132 // information. This should never happen for non-implicit methods,
6133 // but...
6134 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6135 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6136}
6137
6138/// Check for invalid uses of an abstract type in a variable0 declaration.
6139static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6140 VarDecl *VD) {
6141 // No need to do the check on definitions, which require that
6142 // the type is complete.
6144 return;
6145
6146 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6148}
6149
6150/// Check for invalid uses of an abstract type within a class definition.
6151static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6152 CXXRecordDecl *RD) {
6153 for (auto *D : RD->decls()) {
6154 if (D->isImplicit()) continue;
6155
6156 // Step through friends to the befriended declaration.
6157 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6158 D = FD->getFriendDecl();
6159 if (!D) continue;
6160 }
6161
6162 // Functions and function templates.
6163 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6164 CheckAbstractClassUsage(Info, FD);
6165 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6166 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6167
6168 // Fields and static variables.
6169 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6170 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6171 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6172 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6173 CheckAbstractClassUsage(Info, VD);
6174 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6175 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6176
6177 // Nested classes and class templates.
6178 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6179 CheckAbstractClassUsage(Info, RD);
6180 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6181 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6182 }
6183 }
6184}
6185
6187 Attr *ClassAttr = getDLLAttr(Class);
6188 if (!ClassAttr)
6189 return;
6190
6191 assert(ClassAttr->getKind() == attr::DLLExport);
6192
6193 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6194
6196 // Don't go any further if this is just an explicit instantiation
6197 // declaration.
6198 return;
6199
6200 // Add a context note to explain how we got to any diagnostics produced below.
6201 struct MarkingClassDllexported {
6202 Sema &S;
6203 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6204 SourceLocation AttrLoc)
6205 : S(S) {
6208 Ctx.PointOfInstantiation = AttrLoc;
6209 Ctx.Entity = Class;
6211 }
6212 ~MarkingClassDllexported() {
6214 }
6215 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6216
6217 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6218 S.MarkVTableUsed(Class->getLocation(), Class, true);
6219
6220 for (Decl *Member : Class->decls()) {
6221 // Skip members that were not marked exported.
6222 if (!Member->hasAttr<DLLExportAttr>())
6223 continue;
6224
6225 // Defined static variables that are members of an exported base
6226 // class must be marked export too.
6227 auto *VD = dyn_cast<VarDecl>(Member);
6228 if (VD && VD->getStorageClass() == SC_Static &&
6230 S.MarkVariableReferenced(VD->getLocation(), VD);
6231
6232 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6233 if (!MD)
6234 continue;
6235
6236 if (MD->isUserProvided()) {
6237 // Instantiate non-default class member functions ...
6238
6239 // .. except for certain kinds of template specializations.
6240 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6241 continue;
6242
6243 // If this is an MS ABI dllexport default constructor, instantiate any
6244 // default arguments.
6246 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6247 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6249 }
6250 }
6251
6252 S.MarkFunctionReferenced(Class->getLocation(), MD);
6253
6254 // The function will be passed to the consumer when its definition is
6255 // encountered.
6256 } else if (MD->isExplicitlyDefaulted()) {
6257 // Synthesize and instantiate explicitly defaulted methods.
6258 S.MarkFunctionReferenced(Class->getLocation(), MD);
6259
6261 // Except for explicit instantiation defs, we will not see the
6262 // definition again later, so pass it to the consumer now.
6264 }
6265 } else if (!MD->isTrivial() ||
6266 MD->isCopyAssignmentOperator() ||
6267 MD->isMoveAssignmentOperator()) {
6268 // Synthesize and instantiate non-trivial implicit methods, and the copy
6269 // and move assignment operators. The latter are exported even if they
6270 // are trivial, because the address of an operator can be taken and
6271 // should compare equal across libraries.
6272 S.MarkFunctionReferenced(Class->getLocation(), MD);
6273
6274 // There is no later point when we will see the definition of this
6275 // function, so pass it to the consumer now.
6277 }
6278 }
6279}
6280
6283 // Only the MS ABI has default constructor closures, so we don't need to do
6284 // this semantic checking anywhere else.
6286 return;
6287
6288 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6289 for (Decl *Member : Class->decls()) {
6290 // Look for exported default constructors.
6291 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6292 if (!CD || !CD->isDefaultConstructor())
6293 continue;
6294 auto *Attr = CD->getAttr<DLLExportAttr>();
6295 if (!Attr)
6296 continue;
6297
6298 // If the class is non-dependent, mark the default arguments as ODR-used so
6299 // that we can properly codegen the constructor closure.
6300 if (!Class->isDependentContext()) {
6301 for (ParmVarDecl *PD : CD->parameters()) {
6302 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6304 }
6305 }
6306
6307 if (LastExportedDefaultCtor) {
6308 S.Diag(LastExportedDefaultCtor->getLocation(),
6309 diag::err_attribute_dll_ambiguous_default_ctor)
6310 << Class;
6311 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6312 << CD->getDeclName();
6313 return;
6314 }
6315 LastExportedDefaultCtor = CD;
6316 }
6317}
6318
6321 bool ErrorReported = false;
6322 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6323 ClassTemplateDecl *TD) {
6324 if (ErrorReported)
6325 return;
6326 S.Diag(TD->getLocation(),
6327 diag::err_cuda_device_builtin_surftex_cls_template)
6328 << /*surface*/ 0 << TD;
6329 ErrorReported = true;
6330 };
6331
6332 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6333 if (!TD) {
6334 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6335 if (!SD) {
6336 S.Diag(Class->getLocation(),
6337 diag::err_cuda_device_builtin_surftex_ref_decl)
6338 << /*surface*/ 0 << Class;
6339 S.Diag(Class->getLocation(),
6340 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6341 << Class;
6342 return;
6343 }
6344 TD = SD->getSpecializedTemplate();
6345 }
6346
6348 unsigned N = Params->size();
6349
6350 if (N != 2) {
6351 reportIllegalClassTemplate(S, TD);
6352 S.Diag(TD->getLocation(),
6353 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6354 << TD << 2;
6355 }
6356 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6357 reportIllegalClassTemplate(S, TD);
6358 S.Diag(TD->getLocation(),
6359 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6360 << TD << /*1st*/ 0 << /*type*/ 0;
6361 }
6362 if (N > 1) {
6363 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6364 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6365 reportIllegalClassTemplate(S, TD);
6366 S.Diag(TD->getLocation(),
6367 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6368 << TD << /*2nd*/ 1 << /*integer*/ 1;
6369 }
6370 }
6371}
6372
6375 bool ErrorReported = false;
6376 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6377 ClassTemplateDecl *TD) {
6378 if (ErrorReported)
6379 return;
6380 S.Diag(TD->getLocation(),
6381 diag::err_cuda_device_builtin_surftex_cls_template)
6382 << /*texture*/ 1 << TD;
6383 ErrorReported = true;
6384 };
6385
6386 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6387 if (!TD) {
6388 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6389 if (!SD) {
6390 S.Diag(Class->getLocation(),
6391 diag::err_cuda_device_builtin_surftex_ref_decl)
6392 << /*texture*/ 1 << Class;
6393 S.Diag(Class->getLocation(),
6394 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6395 << Class;
6396 return;
6397 }
6398 TD = SD->getSpecializedTemplate();
6399 }
6400
6402 unsigned N = Params->size();
6403
6404 if (N != 3) {
6405 reportIllegalClassTemplate(S, TD);
6406 S.Diag(TD->getLocation(),
6407 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6408 << TD << 3;
6409 }
6410 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6411 reportIllegalClassTemplate(S, TD);
6412 S.Diag(TD->getLocation(),
6413 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6414 << TD << /*1st*/ 0 << /*type*/ 0;
6415 }
6416 if (N > 1) {
6417 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6418 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6419 reportIllegalClassTemplate(S, TD);
6420 S.Diag(TD->getLocation(),
6421 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6422 << TD << /*2nd*/ 1 << /*integer*/ 1;
6423 }
6424 }
6425 if (N > 2) {
6426 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6427 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6428 reportIllegalClassTemplate(S, TD);
6429 S.Diag(TD->getLocation(),
6430 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6431 << TD << /*3rd*/ 2 << /*integer*/ 1;
6432 }
6433 }
6434}
6435
6437 // Mark any compiler-generated routines with the implicit code_seg attribute.
6438 for (auto *Method : Class->methods()) {
6439 if (Method->isUserProvided())
6440 continue;
6441 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6442 Method->addAttr(A);
6443 }
6444}
6445
6447 Attr *ClassAttr = getDLLAttr(Class);
6448
6449 // MSVC inherits DLL attributes to partial class template specializations.
6450 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6451 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6452 if (Attr *TemplateAttr =
6453 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6454 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6455 A->setInherited(true);
6456 ClassAttr = A;
6457 }
6458 }
6459 }
6460
6461 if (!ClassAttr)
6462 return;
6463
6464 // MSVC allows imported or exported template classes that have UniqueExternal
6465 // linkage. This occurs when the template class has been instantiated with
6466 // a template parameter which itself has internal linkage.
6467 // We drop the attribute to avoid exporting or importing any members.
6469 Context.getTargetInfo().getTriple().isPS()) &&
6470 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6471 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6472 return;
6473 }
6474
6475 if (!Class->isExternallyVisible()) {
6476 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6477 << Class << ClassAttr;
6478 return;
6479 }
6480
6482 !ClassAttr->isInherited()) {
6483 // Diagnose dll attributes on members of class with dll attribute.
6484 for (Decl *Member : Class->decls()) {
6485 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6486 continue;
6487 InheritableAttr *MemberAttr = getDLLAttr(Member);
6488 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6489 continue;
6490
6491 Diag(MemberAttr->getLocation(),
6492 diag::err_attribute_dll_member_of_dll_class)
6493 << MemberAttr << ClassAttr;
6494 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6495 Member->setInvalidDecl();
6496 }
6497 }
6498
6499 if (Class->getDescribedClassTemplate())
6500 // Don't inherit dll attribute until the template is instantiated.
6501 return;
6502
6503 // The class is either imported or exported.
6504 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6505
6506 // Check if this was a dllimport attribute propagated from a derived class to
6507 // a base class template specialization. We don't apply these attributes to
6508 // static data members.
6509 const bool PropagatedImport =
6510 !ClassExported &&
6511 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6512
6513 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6514
6515 // Ignore explicit dllexport on explicit class template instantiation
6516 // declarations, except in MinGW mode.
6517 if (ClassExported && !ClassAttr->isInherited() &&
6519 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6520 Class->dropAttr<DLLExportAttr>();
6521 return;
6522 }
6523
6524 // Force declaration of implicit members so they can inherit the attribute.
6526
6527 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6528 // seem to be true in practice?
6529
6530 for (Decl *Member : Class->decls()) {
6531 VarDecl *VD = dyn_cast<VarDecl>(Member);
6532 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6533
6534 // Only methods and static fields inherit the attributes.
6535 if (!VD && !MD)
6536 continue;
6537
6538 if (MD) {
6539 // Don't process deleted methods.
6540 if (MD->isDeleted())
6541 continue;
6542
6543 if (MD->isInlined()) {
6544 // MinGW does not import or export inline methods. But do it for
6545 // template instantiations.
6549 continue;
6550
6551 // MSVC versions before 2015 don't export the move assignment operators
6552 // and move constructor, so don't attempt to import/export them if
6553 // we have a definition.
6554 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6555 if ((MD->isMoveAssignmentOperator() ||
6556 (Ctor && Ctor->isMoveConstructor())) &&
6557 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6558 continue;
6559
6560 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6561 // operator is exported anyway.
6562 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6563 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6564 continue;
6565 }
6566 }
6567
6568 // Don't apply dllimport attributes to static data members of class template
6569 // instantiations when the attribute is propagated from a derived class.
6570 if (VD && PropagatedImport)
6571 continue;
6572
6573 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6574 continue;
6575
6576 if (!getDLLAttr(Member)) {
6577 InheritableAttr *NewAttr = nullptr;
6578
6579 // Do not export/import inline function when -fno-dllexport-inlines is
6580 // passed. But add attribute for later local static var check.
6581 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6584 if (ClassExported) {
6585 NewAttr = ::new (getASTContext())
6586 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6587 } else {
6588 NewAttr = ::new (getASTContext())
6589 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6590 }
6591 } else {
6592 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6593 }
6594
6595 NewAttr->setInherited(true);
6596 Member->addAttr(NewAttr);
6597
6598 if (MD) {
6599 // Propagate DLLAttr to friend re-declarations of MD that have already
6600 // been constructed.
6601 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6602 FD = FD->getPreviousDecl()) {
6604 continue;
6605 assert(!getDLLAttr(FD) &&
6606 "friend re-decl should not already have a DLLAttr");
6607 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6608 NewAttr->setInherited(true);
6609 FD->addAttr(NewAttr);
6610 }
6611 }
6612 }
6613 }
6614
6615 if (ClassExported)
6616 DelayedDllExportClasses.push_back(Class);
6617}
6618
6620 CXXRecordDecl *Class, Attr *ClassAttr,
6621 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6622 if (getDLLAttr(
6623 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6624 // If the base class template has a DLL attribute, don't try to change it.
6625 return;
6626 }
6627
6628 auto TSK = BaseTemplateSpec->getSpecializationKind();
6629 if (!getDLLAttr(BaseTemplateSpec) &&
6631 TSK == TSK_ImplicitInstantiation)) {
6632 // The template hasn't been instantiated yet (or it has, but only as an
6633 // explicit instantiation declaration or implicit instantiation, which means
6634 // we haven't codegenned any members yet), so propagate the attribute.
6635 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6636 NewAttr->setInherited(true);
6637 BaseTemplateSpec->addAttr(NewAttr);
6638
6639 // If this was an import, mark that we propagated it from a derived class to
6640 // a base class template specialization.
6641 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6642 ImportAttr->setPropagatedToBaseTemplate();
6643
6644 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6645 // needs to be run again to work see the new attribute. Otherwise this will
6646 // get run whenever the template is instantiated.
6647 if (TSK != TSK_Undeclared)
6648 checkClassLevelDLLAttribute(BaseTemplateSpec);
6649
6650 return;
6651 }
6652
6653 if (getDLLAttr(BaseTemplateSpec)) {
6654 // The template has already been specialized or instantiated with an
6655 // attribute, explicitly or through propagation. We should not try to change
6656 // it.
6657 return;
6658 }
6659
6660 // The template was previously instantiated or explicitly specialized without
6661 // a dll attribute, It's too late for us to add an attribute, so warn that
6662 // this is unsupported.
6663 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6664 << BaseTemplateSpec->isExplicitSpecialization();
6665 Diag(ClassAttr->getLocation(), diag::note_attribute);
6666 if (BaseTemplateSpec->isExplicitSpecialization()) {
6667 Diag(BaseTemplateSpec->getLocation(),
6668 diag::note_template_class_explicit_specialization_was_here)
6669 << BaseTemplateSpec;
6670 } else {
6671 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6672 diag::note_template_class_instantiation_was_here)
6673 << BaseTemplateSpec;
6674 }
6675}
6676
6679 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6680 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6681 if (Ctor->isDefaultConstructor())
6683
6684 if (Ctor->isCopyConstructor())
6686
6687 if (Ctor->isMoveConstructor())
6689 }
6690
6691 if (MD->isCopyAssignmentOperator())
6693
6694 if (MD->isMoveAssignmentOperator())
6696
6697 if (isa<CXXDestructorDecl>(FD))
6699 }
6700
6701 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6702 case OO_EqualEqual:
6704
6705 case OO_ExclaimEqual:
6707
6708 case OO_Spaceship:
6709 // No point allowing this if <=> doesn't exist in the current language mode.
6710 if (!getLangOpts().CPlusPlus20)
6711 break;
6713
6714 case OO_Less:
6715 case OO_LessEqual:
6716 case OO_Greater:
6717 case OO_GreaterEqual:
6718 // No point allowing this if <=> doesn't exist in the current language mode.
6719 if (!getLangOpts().CPlusPlus20)
6720 break;
6722
6723 default:
6724 break;
6725 }
6726
6727 // Not defaultable.
6728 return DefaultedFunctionKind();
6729}
6730
6732 SourceLocation DefaultLoc) {
6734 if (DFK.isComparison())
6735 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6736
6737 switch (DFK.asSpecialMember()) {
6740 cast<CXXConstructorDecl>(FD));
6741 break;
6743 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6744 break;
6746 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6747 break;
6749 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6750 break;
6752 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6753 break;
6755 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6756 break;
6758 llvm_unreachable("Invalid special member.");
6759 }
6760}
6761
6762/// Determine whether a type is permitted to be passed or returned in
6763/// registers, per C++ [class.temporary]p3.
6766 if (D->isDependentType() || D->isInvalidDecl())
6767 return false;
6768
6769 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6770 // The PS4 platform ABI follows the behavior of Clang 3.2.
6772 return !D->hasNonTrivialDestructorForCall() &&
6773 !D->hasNonTrivialCopyConstructorForCall();
6774
6775 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6776 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6777 bool DtorIsTrivialForCall = false;
6778
6779 // If a class has at least one eligible, trivial copy constructor, it
6780 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6781 //
6782 // Note: This permits classes with non-trivial copy or move ctors to be
6783 // passed in registers, so long as they *also* have a trivial copy ctor,
6784 // which is non-conforming.
6785 if (D->needsImplicitCopyConstructor()) {
6786 if (!D->defaultedCopyConstructorIsDeleted()) {
6787 if (D->hasTrivialCopyConstructor())
6788 CopyCtorIsTrivial = true;
6789 if (D->hasTrivialCopyConstructorForCall())
6790 CopyCtorIsTrivialForCall = true;
6791 }
6792 } else {
6793 for (const CXXConstructorDecl *CD : D->ctors()) {
6794 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6795 !CD->isIneligibleOrNotSelected()) {
6796 if (CD->isTrivial())
6797 CopyCtorIsTrivial = true;
6798 if (CD->isTrivialForCall())
6799 CopyCtorIsTrivialForCall = true;
6800 }
6801 }
6802 }
6803
6804 if (D->needsImplicitDestructor()) {
6805 if (!D->defaultedDestructorIsDeleted() &&
6806 D->hasTrivialDestructorForCall())
6807 DtorIsTrivialForCall = true;
6808 } else if (const auto *DD = D->getDestructor()) {
6809 if (!DD->isDeleted() && DD->isTrivialForCall())
6810 DtorIsTrivialForCall = true;
6811 }
6812
6813 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6814 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6815 return true;
6816
6817 // If a class has a destructor, we'd really like to pass it indirectly
6818 // because it allows us to elide copies. Unfortunately, MSVC makes that
6819 // impossible for small types, which it will pass in a single register or
6820 // stack slot. Most objects with dtors are large-ish, so handle that early.
6821 // We can't call out all large objects as being indirect because there are
6822 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6823 // how we pass large POD types.
6824
6825 // Note: This permits small classes with nontrivial destructors to be
6826 // passed in registers, which is non-conforming.
6827 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6828 uint64_t TypeSize = isAArch64 ? 128 : 64;
6829
6830 if (CopyCtorIsTrivial &&
6831 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6832 return true;
6833 return false;
6834 }
6835
6836 // Per C++ [class.temporary]p3, the relevant condition is:
6837 // each copy constructor, move constructor, and destructor of X is
6838 // either trivial or deleted, and X has at least one non-deleted copy
6839 // or move constructor
6840 bool HasNonDeletedCopyOrMove = false;
6841
6842 if (D->needsImplicitCopyConstructor() &&
6843 !D->defaultedCopyConstructorIsDeleted()) {
6844 if (!D->hasTrivialCopyConstructorForCall())
6845 return false;
6846 HasNonDeletedCopyOrMove = true;
6847 }
6848
6849 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6850 !D->defaultedMoveConstructorIsDeleted()) {
6851 if (!D->hasTrivialMoveConstructorForCall())
6852 return false;
6853 HasNonDeletedCopyOrMove = true;
6854 }
6855
6856 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6857 !D->hasTrivialDestructorForCall())
6858 return false;
6859
6860 for (const CXXMethodDecl *MD : D->methods()) {
6861 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6862 continue;
6863
6864 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6865 if (CD && CD->isCopyOrMoveConstructor())
6866 HasNonDeletedCopyOrMove = true;
6867 else if (!isa<CXXDestructorDecl>(MD))
6868 continue;
6869
6870 if (!MD->isTrivialForCall())
6871 return false;
6872 }
6873
6874 return HasNonDeletedCopyOrMove;
6875}
6876
6877/// Report an error regarding overriding, along with any relevant
6878/// overridden methods.
6879///
6880/// \param DiagID the primary error to report.
6881/// \param MD the overriding method.
6882static bool
6883ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6884 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6885 bool IssuedDiagnostic = false;
6886 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6887 if (Report(O)) {
6888 if (!IssuedDiagnostic) {
6889 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6890 IssuedDiagnostic = true;
6891 }
6892 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6893 }
6894 }
6895 return IssuedDiagnostic;
6896}
6897
6899 if (!Record)
6900 return;
6901
6902 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6903 AbstractUsageInfo Info(*this, Record);
6905 }
6906
6907 // If this is not an aggregate type and has no user-declared constructor,
6908 // complain about any non-static data members of reference or const scalar
6909 // type, since they will never get initializers.
6910 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6911 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6912 !Record->isLambda()) {
6913 bool Complained = false;
6914 for (const auto *F : Record->fields()) {
6915 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6916 continue;
6917
6918 if (F->getType()->isReferenceType() ||
6919 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6920 if (!Complained) {
6921 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6922 << llvm::to_underlying(Record->getTagKind()) << Record;
6923 Complained = true;
6924 }
6925
6926 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6927 << F->getType()->isReferenceType()
6928 << F->getDeclName();
6929 }
6930 }
6931 }
6932
6933 if (Record->getIdentifier()) {
6934 // C++ [class.mem]p13:
6935 // If T is the name of a class, then each of the following shall have a
6936 // name different from T:
6937 // - every member of every anonymous union that is a member of class T.
6938 //
6939 // C++ [class.mem]p14:
6940 // In addition, if class T has a user-declared constructor (12.1), every
6941 // non-static data member of class T shall have a name different from T.
6942 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6943 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6944 ++I) {
6945 NamedDecl *D = (*I)->getUnderlyingDecl();
6946 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6947 Record->hasUserDeclaredConstructor()) ||
6948 isa<IndirectFieldDecl>(D)) {
6949 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6950 << D->getDeclName();
6951 break;
6952 }
6953 }
6954 }
6955
6956 // Warn if the class has virtual methods but non-virtual public destructor.
6957 if (Record->isPolymorphic() && !Record->isDependentType()) {
6958 CXXDestructorDecl *dtor = Record->getDestructor();
6959 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6960 !Record->hasAttr<FinalAttr>())
6961 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6962 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6963 }
6964
6965 if (Record->isAbstract()) {
6966 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6967 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6968 << FA->isSpelledAsSealed();
6970 }
6971 }
6972
6973 // Warn if the class has a final destructor but is not itself marked final.
6974 if (!Record->hasAttr<FinalAttr>()) {
6975 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6976 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6977 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6978 << FA->isSpelledAsSealed()
6980 getLocForEndOfToken(Record->getLocation()),
6981 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6982 Diag(Record->getLocation(),
6983 diag::note_final_dtor_non_final_class_silence)
6984 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6985 }
6986 }
6987 }
6988
6989 // See if trivial_abi has to be dropped.
6990 if (Record->hasAttr<TrivialABIAttr>())
6992
6993 // Set HasTrivialSpecialMemberForCall if the record has attribute
6994 // "trivial_abi".
6995 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6996
6997 if (HasTrivialABI)
6998 Record->setHasTrivialSpecialMemberForCall();
6999
7000 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7001 // We check these last because they can depend on the properties of the
7002 // primary comparison functions (==, <=>).
7003 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7004
7005 // Perform checks that can't be done until we know all the properties of a
7006 // member function (whether it's defaulted, deleted, virtual, overriding,
7007 // ...).
7008 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7009 // A static function cannot override anything.
7010 if (MD->getStorageClass() == SC_Static) {
7011 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7012 [](const CXXMethodDecl *) { return true; }))
7013 return;
7014 }
7015
7016 // A deleted function cannot override a non-deleted function and vice
7017 // versa.
7018 if (ReportOverrides(*this,
7019 MD->isDeleted() ? diag::err_deleted_override
7020 : diag::err_non_deleted_override,
7021 MD, [&](const CXXMethodDecl *V) {
7022 return MD->isDeleted() != V->isDeleted();
7023 })) {
7024 if (MD->isDefaulted() && MD->isDeleted())
7025 // Explain why this defaulted function was deleted.
7027 return;
7028 }
7029
7030 // A consteval function cannot override a non-consteval function and vice
7031 // versa.
7032 if (ReportOverrides(*this,
7033 MD->isConsteval() ? diag::err_consteval_override
7034 : diag::err_non_consteval_override,
7035 MD, [&](const CXXMethodDecl *V) {
7036 return MD->isConsteval() != V->isConsteval();
7037 })) {
7038 if (MD->isDefaulted() && MD->isDeleted())
7039 // Explain why this defaulted function was deleted.
7041 return;
7042 }
7043 };
7044
7045 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7046 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7047 return false;
7048
7052 DefaultedSecondaryComparisons.push_back(FD);
7053 return true;
7054 }
7055
7057 return false;
7058 };
7059
7060 if (!Record->isInvalidDecl() &&
7061 Record->hasAttr<VTablePointerAuthenticationAttr>())
7063
7064 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7065 // Check whether the explicitly-defaulted members are valid.
7066 bool Incomplete = CheckForDefaultedFunction(M);
7067
7068 // Skip the rest of the checks for a member of a dependent class.
7069 if (Record->isDependentType())
7070 return;
7071
7072 // For an explicitly defaulted or deleted special member, we defer
7073 // determining triviality until the class is complete. That time is now!
7075 if (!M->isImplicit() && !M->isUserProvided()) {
7076 if (CSM != CXXSpecialMemberKind::Invalid) {
7077 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7078 // Inform the class that we've finished declaring this member.
7079 Record->finishedDefaultedOrDeletedMember(M);
7080 M->setTrivialForCall(
7081 HasTrivialABI ||
7083 Record->setTrivialForCallFlags(M);
7084 }
7085 }
7086
7087 // Set triviality for the purpose of calls if this is a user-provided
7088 // copy/move constructor or destructor.
7092 M->isUserProvided()) {
7093 M->setTrivialForCall(HasTrivialABI);
7094 Record->setTrivialForCallFlags(M);
7095 }
7096
7097 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7098 M->hasAttr<DLLExportAttr>()) {
7099 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7100 M->isTrivial() &&
7104 M->dropAttr<DLLExportAttr>();
7105
7106 if (M->hasAttr<DLLExportAttr>()) {
7107 // Define after any fields with in-class initializers have been parsed.
7109 }
7110 }
7111
7112 bool EffectivelyConstexprDestructor = true;
7113 // Avoid triggering vtable instantiation due to a dtor that is not
7114 // "effectively constexpr" for better compatibility.
7115 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7116 if (isa<CXXDestructorDecl>(M)) {
7117 auto Check = [](QualType T, auto &&Check) -> bool {
7118 const CXXRecordDecl *RD =
7120 if (!RD || !RD->isCompleteDefinition())
7121 return true;
7122
7123 if (!RD->hasConstexprDestructor())
7124 return false;
7125
7126 QualType CanUnqualT = T.getCanonicalType().getUnqualifiedType();
7127 for (const CXXBaseSpecifier &B : RD->bases())
7128 if (B.getType().getCanonicalType().getUnqualifiedType() !=
7129 CanUnqualT &&
7130 !Check(B.getType(), Check))
7131 return false;
7132 for (const FieldDecl *FD : RD->fields())
7134 CanUnqualT &&
7135 !Check(FD->getType(), Check))
7136 return false;
7137 return true;
7138 };
7139 EffectivelyConstexprDestructor =
7140 Check(QualType(Record->getTypeForDecl(), 0), Check);
7141 }
7142
7143 // Define defaulted constexpr virtual functions that override a base class
7144 // function right away.
7145 // FIXME: We can defer doing this until the vtable is marked as used.
7146 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7147 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7148 EffectivelyConstexprDestructor)
7149 DefineDefaultedFunction(*this, M, M->getLocation());
7150
7151 if (!Incomplete)
7152 CheckCompletedMemberFunction(M);
7153 };
7154
7155 // Check the destructor before any other member function. We need to
7156 // determine whether it's trivial in order to determine whether the claas
7157 // type is a literal type, which is a prerequisite for determining whether
7158 // other special member functions are valid and whether they're implicitly
7159 // 'constexpr'.
7160 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7161 CompleteMemberFunction(Dtor);
7162
7163 bool HasMethodWithOverrideControl = false,
7164 HasOverridingMethodWithoutOverrideControl = false;
7165 for (auto *D : Record->decls()) {
7166 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7167 // FIXME: We could do this check for dependent types with non-dependent
7168 // bases.
7169 if (!Record->isDependentType()) {
7170 // See if a method overloads virtual methods in a base
7171 // class without overriding any.
7172 if (!M->isStatic())
7174 if (M->hasAttr<OverrideAttr>())
7175 HasMethodWithOverrideControl = true;
7176 else if (M->size_overridden_methods() > 0)
7177 HasOverridingMethodWithoutOverrideControl = true;
7178 }
7179
7180 if (!isa<CXXDestructorDecl>(M))
7181 CompleteMemberFunction(M);
7182 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7183 CheckForDefaultedFunction(
7184 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7185 }
7186 }
7187
7188 if (HasOverridingMethodWithoutOverrideControl) {
7189 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7190 for (auto *M : Record->methods())
7191 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7192 }
7193
7194 // Check the defaulted secondary comparisons after any other member functions.
7195 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7197
7198 // If this is a member function, we deferred checking it until now.
7199 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7200 CheckCompletedMemberFunction(MD);
7201 }
7202
7203 // ms_struct is a request to use the same ABI rules as MSVC. Check
7204 // whether this class uses any C++ features that are implemented
7205 // completely differently in MSVC, and if so, emit a diagnostic.
7206 // That diagnostic defaults to an error, but we allow projects to
7207 // map it down to a warning (or ignore it). It's a fairly common
7208 // practice among users of the ms_struct pragma to mass-annotate
7209 // headers, sweeping up a bunch of types that the project doesn't
7210 // really rely on MSVC-compatible layout for. We must therefore
7211 // support "ms_struct except for C++ stuff" as a secondary ABI.
7212 // Don't emit this diagnostic if the feature was enabled as a
7213 // language option (as opposed to via a pragma or attribute), as
7214 // the option -mms-bitfields otherwise essentially makes it impossible
7215 // to build C++ code, unless this diagnostic is turned off.
7216 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7217 (Record->isPolymorphic() || Record->getNumBases())) {
7218 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7219 }
7220
7223
7224 bool ClangABICompat4 =
7225 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7227 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7228 bool CanPass = canPassInRegisters(*this, Record, CCK);
7229
7230 // Do not change ArgPassingRestrictions if it has already been set to
7231 // RecordArgPassingKind::CanNeverPassInRegs.
7232 if (Record->getArgPassingRestrictions() !=
7234 Record->setArgPassingRestrictions(
7237
7238 // If canPassInRegisters returns true despite the record having a non-trivial
7239 // destructor, the record is destructed in the callee. This happens only when
7240 // the record or one of its subobjects has a field annotated with trivial_abi
7241 // or a field qualified with ObjC __strong/__weak.
7243 Record->setParamDestroyedInCallee(true);
7244 else if (Record->hasNonTrivialDestructor())
7245 Record->setParamDestroyedInCallee(CanPass);
7246
7247 if (getLangOpts().ForceEmitVTables) {
7248 // If we want to emit all the vtables, we need to mark it as used. This
7249 // is especially required for cases like vtable assumption loads.
7250 MarkVTableUsed(Record->getInnerLocStart(), Record);
7251 }
7252
7253 if (getLangOpts().CUDA) {
7254 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7256 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7258 }
7259}
7260
7261/// Look up the special member function that would be called by a special
7262/// member function for a subobject of class type.
7263///
7264/// \param Class The class type of the subobject.
7265/// \param CSM The kind of special member function.
7266/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7267/// \param ConstRHS True if this is a copy operation with a const object
7268/// on its RHS, that is, if the argument to the outer special member
7269/// function is 'const' and this is not a field marked 'mutable'.
7272 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7273 bool ConstRHS) {
7274 unsigned LHSQuals = 0;
7277 LHSQuals = FieldQuals;
7278
7279 unsigned RHSQuals = FieldQuals;
7282 RHSQuals = 0;
7283 else if (ConstRHS)
7284 RHSQuals |= Qualifiers::Const;
7285
7286 return S.LookupSpecialMember(Class, CSM,
7287 RHSQuals & Qualifiers::Const,
7288 RHSQuals & Qualifiers::Volatile,
7289 false,
7290 LHSQuals & Qualifiers::Const,
7291 LHSQuals & Qualifiers::Volatile);
7292}
7293
7295 Sema &S;
7296 SourceLocation UseLoc;
7297
7298 /// A mapping from the base classes through which the constructor was
7299 /// inherited to the using shadow declaration in that base class (or a null
7300 /// pointer if the constructor was declared in that base class).
7301 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7302 InheritedFromBases;
7303
7304public:
7307 : S(S), UseLoc(UseLoc) {
7308 bool DiagnosedMultipleConstructedBases = false;
7309 CXXRecordDecl *ConstructedBase = nullptr;
7310 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7311
7312 // Find the set of such base class subobjects and check that there's a
7313 // unique constructed subobject.
7314 for (auto *D : Shadow->redecls()) {
7315 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7316 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7317 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7318
7319 InheritedFromBases.insert(
7320 std::make_pair(DNominatedBase->getCanonicalDecl(),
7321 DShadow->getNominatedBaseClassShadowDecl()));
7322 if (DShadow->constructsVirtualBase())
7323 InheritedFromBases.insert(
7324 std::make_pair(DConstructedBase->getCanonicalDecl(),
7325 DShadow->getConstructedBaseClassShadowDecl()));
7326 else
7327 assert(DNominatedBase == DConstructedBase);
7328
7329 // [class.inhctor.init]p2:
7330 // If the constructor was inherited from multiple base class subobjects
7331 // of type B, the program is ill-formed.
7332 if (!ConstructedBase) {
7333 ConstructedBase = DConstructedBase;
7334 ConstructedBaseIntroducer = D->getIntroducer();
7335 } else if (ConstructedBase != DConstructedBase &&
7336 !Shadow->isInvalidDecl()) {
7337 if (!DiagnosedMultipleConstructedBases) {
7338 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7339 << Shadow->getTargetDecl();
7340 S.Diag(ConstructedBaseIntroducer->getLocation(),
7341 diag::note_ambiguous_inherited_constructor_using)
7342 << ConstructedBase;
7343 DiagnosedMultipleConstructedBases = true;
7344 }
7345 S.Diag(D->getIntroducer()->getLocation(),
7346 diag::note_ambiguous_inherited_constructor_using)
7347 << DConstructedBase;
7348 }
7349 }
7350
7351 if (DiagnosedMultipleConstructedBases)
7352 Shadow->setInvalidDecl();
7353 }
7354
7355 /// Find the constructor to use for inherited construction of a base class,
7356 /// and whether that base class constructor inherits the constructor from a
7357 /// virtual base class (in which case it won't actually invoke it).
7358 std::pair<CXXConstructorDecl *, bool>
7360 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7361 if (It == InheritedFromBases.end())
7362 return std::make_pair(nullptr, false);
7363
7364 // This is an intermediary class.
7365 if (It->second)
7366 return std::make_pair(
7367 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7368 It->second->constructsVirtualBase());
7369
7370 // This is the base class from which the constructor was inherited.
7371 return std::make_pair(Ctor, false);
7372 }
7373};
7374
7375/// Is the special member function which would be selected to perform the
7376/// specified operation on the specified class type a constexpr constructor?
7378 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7379 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7380 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7381 // Suppress duplicate constraint checking here, in case a constraint check
7382 // caused us to decide to do this. Any truely recursive checks will get
7383 // caught during these checks anyway.
7385
7386 // If we're inheriting a constructor, see if we need to call it for this base
7387 // class.
7388 if (InheritedCtor) {
7390 auto BaseCtor =
7391 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7392 if (BaseCtor)
7393 return BaseCtor->isConstexpr();
7394 }
7395
7397 return ClassDecl->hasConstexprDefaultConstructor();
7399 return ClassDecl->hasConstexprDestructor();
7400
7402 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7403 if (!SMOR.getMethod())
7404 // A constructor we wouldn't select can't be "involved in initializing"
7405 // anything.
7406 return true;
7407 return SMOR.getMethod()->isConstexpr();
7408}
7409
7410/// Determine whether the specified special member function would be constexpr
7411/// if it were implicitly defined.
7413 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7414 CXXConstructorDecl *InheritedCtor = nullptr,
7415 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7416 if (!S.getLangOpts().CPlusPlus11)
7417 return false;
7418
7419 // C++11 [dcl.constexpr]p4:
7420 // In the definition of a constexpr constructor [...]
7421 bool Ctor = true;
7422 switch (CSM) {
7424 if (Inherited)
7425 break;
7426 // Since default constructor lookup is essentially trivial (and cannot
7427 // involve, for instance, template instantiation), we compute whether a
7428 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7429 //
7430 // This is important for performance; we need to know whether the default
7431 // constructor is constexpr to determine whether the type is a literal type.
7432 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7433
7436 // For copy or move constructors, we need to perform overload resolution.
7437 break;
7438
7441 if (!S.getLangOpts().CPlusPlus14)
7442 return false;
7443 // In C++1y, we need to perform overload resolution.
7444 Ctor = false;
7445 break;
7446
7448 return ClassDecl->defaultedDestructorIsConstexpr();
7449
7451 return false;
7452 }
7453
7454 // -- if the class is a non-empty union, or for each non-empty anonymous
7455 // union member of a non-union class, exactly one non-static data member
7456 // shall be initialized; [DR1359]
7457 //
7458 // If we squint, this is guaranteed, since exactly one non-static data member
7459 // will be initialized (if the constructor isn't deleted), we just don't know
7460 // which one.
7461 if (Ctor && ClassDecl->isUnion())
7463 ? ClassDecl->hasInClassInitializer() ||
7464 !ClassDecl->hasVariantMembers()
7465 : true;
7466
7467 // -- the class shall not have any virtual base classes;
7468 if (Ctor && ClassDecl->getNumVBases())
7469 return false;
7470
7471 // C++1y [class.copy]p26:
7472 // -- [the class] is a literal type, and
7473 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7474 return false;
7475
7476 // -- every constructor involved in initializing [...] base class
7477 // sub-objects shall be a constexpr constructor;
7478 // -- the assignment operator selected to copy/move each direct base
7479 // class is a constexpr function, and
7480 if (!S.getLangOpts().CPlusPlus23) {
7481 for (const auto &B : ClassDecl->bases()) {
7482 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7483 if (!BaseType)
7484 continue;
7485 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7486 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7487 InheritedCtor, Inherited))
7488 return false;
7489 }
7490 }
7491
7492 // -- every constructor involved in initializing non-static data members
7493 // [...] shall be a constexpr constructor;
7494 // -- every non-static data member and base class sub-object shall be
7495 // initialized
7496 // -- for each non-static data member of X that is of class type (or array
7497 // thereof), the assignment operator selected to copy/move that member is
7498 // a constexpr function
7499 if (!S.getLangOpts().CPlusPlus23) {
7500 for (const auto *F : ClassDecl->fields()) {
7501 if (F->isInvalidDecl())
7502 continue;
7504 F->hasInClassInitializer())
7505 continue;
7506 QualType BaseType = S.Context.getBaseElementType(F->getType());
7507 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7508 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7509 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7510 BaseType.getCVRQualifiers(),
7511 ConstArg && !F->isMutable()))
7512 return false;
7513 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7514 return false;
7515 }
7516 }
7517 }
7518
7519 // All OK, it's constexpr!
7520 return true;
7521}
7522
7523namespace {
7524/// RAII object to register a defaulted function as having its exception
7525/// specification computed.
7526struct ComputingExceptionSpec {
7527 Sema &S;
7528
7529 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7530 : S(S) {
7533 Ctx.PointOfInstantiation = Loc;
7534 Ctx.Entity = FD;
7536 }
7537 ~ComputingExceptionSpec() {
7539 }
7540};
7541}
7542
7545 CXXMethodDecl *MD,
7548
7551 FunctionDecl *FD,
7553
7556 auto DFK = S.getDefaultedFunctionKind(FD);
7557 if (DFK.isSpecialMember())
7559 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7560 if (DFK.isComparison())
7562 DFK.asComparison());
7563
7564 auto *CD = cast<CXXConstructorDecl>(FD);
7565 assert(CD->getInheritedConstructor() &&
7566 "only defaulted functions and inherited constructors have implicit "
7567 "exception specs");
7569 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7572}
7573
7575 CXXMethodDecl *MD) {
7577
7578 // Build an exception specification pointing back at this member.
7580 EPI.ExceptionSpec.SourceDecl = MD;
7581
7582 // Set the calling convention to the default for C++ instance methods.
7584 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7585 /*IsCXXMethod=*/true));
7586 return EPI;
7587}
7588
7590 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7592 return;
7593
7594 // Evaluate the exception specification.
7595 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7596 auto ESI = IES.getExceptionSpec();
7597
7598 // Update the type of the special member to use it.
7599 UpdateExceptionSpec(FD, ESI);
7600}
7601
7603 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7604
7606 if (!DefKind) {
7607 assert(FD->getDeclContext()->isDependentContext());
7608 return;
7609 }
7610
7611 if (DefKind.isComparison()) {
7612 auto PT = FD->getParamDecl(0)->getType();
7613 if (const CXXRecordDecl *RD =
7614 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7615 for (FieldDecl *Field : RD->fields()) {
7616 UnusedPrivateFields.remove(Field);
7617 }
7618 }
7619 }
7620
7621 if (DefKind.isSpecialMember()
7622 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7623 DefKind.asSpecialMember(),
7624 FD->getDefaultLoc())
7626 FD->setInvalidDecl();
7627}
7628
7631 SourceLocation DefaultLoc) {
7632 CXXRecordDecl *RD = MD->getParent();
7633
7635 "not an explicitly-defaulted special member");
7636
7637 // Defer all checking for special members of a dependent type.
7638 if (RD->isDependentType())
7639 return false;
7640
7641 // Whether this was the first-declared instance of the constructor.
7642 // This affects whether we implicitly add an exception spec and constexpr.
7643 bool First = MD == MD->getCanonicalDecl();
7644
7645 bool HadError = false;
7646
7647 // C++11 [dcl.fct.def.default]p1:
7648 // A function that is explicitly defaulted shall
7649 // -- be a special member function [...] (checked elsewhere),
7650 // -- have the same type (except for ref-qualifiers, and except that a
7651 // copy operation can take a non-const reference) as an implicit
7652 // declaration, and
7653 // -- not have default arguments.
7654 // C++2a changes the second bullet to instead delete the function if it's
7655 // defaulted on its first declaration, unless it's "an assignment operator,
7656 // and its return type differs or its parameter type is not a reference".
7657 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7658 bool ShouldDeleteForTypeMismatch = false;
7659 unsigned ExpectedParams = 1;
7662 ExpectedParams = 0;
7663 if (MD->getNumExplicitParams() != ExpectedParams) {
7664 // This checks for default arguments: a copy or move constructor with a
7665 // default argument is classified as a default constructor, and assignment
7666 // operations and destructors can't have default arguments.
7667 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7668 << llvm::to_underlying(CSM) << MD->getSourceRange();
7669 HadError = true;
7670 } else if (MD->isVariadic()) {
7671 if (DeleteOnTypeMismatch)
7672 ShouldDeleteForTypeMismatch = true;
7673 else {
7674 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7675 << llvm::to_underlying(CSM) << MD->getSourceRange();
7676 HadError = true;
7677 }
7678 }
7679
7681
7682 bool CanHaveConstParam = false;
7684 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7686 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7687
7688 QualType ReturnType = Context.VoidTy;
7691 // Check for return type matching.
7692 ReturnType = Type->getReturnType();
7694
7695 QualType DeclType = Context.getTypeDeclType(RD);
7697 DeclType, nullptr);
7698 DeclType = Context.getAddrSpaceQualType(
7699 DeclType, ThisType.getQualifiers().getAddressSpace());
7700 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7701
7702 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7703 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7705 << ExpectedReturnType;
7706 HadError = true;
7707 }
7708
7709 // A defaulted special member cannot have cv-qualifiers.
7710 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7711 if (DeleteOnTypeMismatch)
7712 ShouldDeleteForTypeMismatch = true;
7713 else {
7714 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7716 << getLangOpts().CPlusPlus14;
7717 HadError = true;
7718 }
7719 }
7720 // [C++23][dcl.fct.def.default]/p2.2
7721 // if F2 has an implicit object parameter of type “reference to C”,
7722 // F1 may be an explicit object member function whose explicit object
7723 // parameter is of (possibly different) type “reference to C”,
7724 // in which case the type of F1 would differ from the type of F2
7725 // in that the type of F1 has an additional parameter;
7726 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7727 ? MD->getParamDecl(0)->getType()
7728 : QualType();
7729 if (!ExplicitObjectParameter.isNull() &&
7730 (!ExplicitObjectParameter->isReferenceType() ||
7731 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7732 Context.getRecordType(RD)))) {
7733 if (DeleteOnTypeMismatch)
7734 ShouldDeleteForTypeMismatch = true;
7735 else {
7736 Diag(MD->getLocation(),
7737 diag::err_defaulted_special_member_explicit_object_mismatch)
7738 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7739 << MD->getSourceRange();
7740 HadError = true;
7741 }
7742 }
7743 }
7744
7745 // Check for parameter type matching.
7746 QualType ArgType =
7747 ExpectedParams
7748 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7749 : QualType();
7750 bool HasConstParam = false;
7751 if (ExpectedParams && ArgType->isReferenceType()) {
7752 // Argument must be reference to possibly-const T.
7753 QualType ReferentType = ArgType->getPointeeType();
7754 HasConstParam = ReferentType.isConstQualified();
7755
7756 if (ReferentType.isVolatileQualified()) {
7757 if (DeleteOnTypeMismatch)
7758 ShouldDeleteForTypeMismatch = true;
7759 else {
7760 Diag(MD->getLocation(),
7761 diag::err_defaulted_special_member_volatile_param)
7762 << llvm::to_underlying(CSM);
7763 HadError = true;
7764 }
7765 }
7766
7767 if (HasConstParam && !CanHaveConstParam) {
7768 if (DeleteOnTypeMismatch)
7769 ShouldDeleteForTypeMismatch = true;
7770 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7772 Diag(MD->getLocation(),
7773 diag::err_defaulted_special_member_copy_const_param)
7775 // FIXME: Explain why this special member can't be const.
7776 HadError = true;
7777 } else {
7778 Diag(MD->getLocation(),
7779 diag::err_defaulted_special_member_move_const_param)
7781 HadError = true;
7782 }
7783 }
7784 } else if (ExpectedParams) {
7785 // A copy assignment operator can take its argument by value, but a
7786 // defaulted one cannot.
7788 "unexpected non-ref argument");
7789 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7790 HadError = true;
7791 }
7792
7793 // C++11 [dcl.fct.def.default]p2:
7794 // An explicitly-defaulted function may be declared constexpr only if it
7795 // would have been implicitly declared as constexpr,
7796 // Do not apply this rule to members of class templates, since core issue 1358
7797 // makes such functions always instantiate to constexpr functions. For
7798 // functions which cannot be constexpr (for non-constructors in C++11 and for
7799 // destructors in C++14 and C++17), this is checked elsewhere.
7800 //
7801 // FIXME: This should not apply if the member is deleted.
7802 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7803 HasConstParam);
7804
7805 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7806 // If the instantiated template specialization of a constexpr function
7807 // template or member function of a class template would fail to satisfy
7808 // the requirements for a constexpr function or constexpr constructor, that
7809 // specialization is still a constexpr function or constexpr constructor,
7810 // even though a call to such a function cannot appear in a constant
7811 // expression.
7812 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7813 Constexpr = true;
7814
7815 if ((getLangOpts().CPlusPlus20 ||
7816 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7817 : isa<CXXConstructorDecl>(MD))) &&
7818 MD->isConstexpr() && !Constexpr &&
7820 if (!MD->isConsteval() && RD->getNumVBases()) {
7821 Diag(MD->getBeginLoc(),
7822 diag::err_incorrect_defaulted_constexpr_with_vb)
7823 << llvm::to_underlying(CSM);
7824 for (const auto &I : RD->vbases())
7825 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7826 } else {
7827 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7828 << llvm::to_underlying(CSM) << MD->isConsteval();
7829 }
7830 HadError = true;
7831 // FIXME: Explain why the special member can't be constexpr.
7832 }
7833
7834 if (First) {
7835 // C++2a [dcl.fct.def.default]p3:
7836 // If a function is explicitly defaulted on its first declaration, it is
7837 // implicitly considered to be constexpr if the implicit declaration
7838 // would be.
7843
7844 if (!Type->hasExceptionSpec()) {
7845 // C++2a [except.spec]p3:
7846 // If a declaration of a function does not have a noexcept-specifier
7847 // [and] is defaulted on its first declaration, [...] the exception
7848 // specification is as specified below
7849 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7851 EPI.ExceptionSpec.SourceDecl = MD;
7852 MD->setType(
7853 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7854 }
7855 }
7856
7857 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7858 if (First) {
7859 SetDeclDeleted(MD, MD->getLocation());
7860 if (!inTemplateInstantiation() && !HadError) {
7861 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7862 << llvm::to_underlying(CSM);
7863 if (ShouldDeleteForTypeMismatch) {
7864 Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7865 << llvm::to_underlying(CSM);
7866 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7867 /*Diagnose*/ true) &&
7868 DefaultLoc.isValid()) {
7869 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7870 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7871 }
7872 }
7873 if (ShouldDeleteForTypeMismatch && !HadError) {
7874 Diag(MD->getLocation(),
7875 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7876 << llvm::to_underlying(CSM);
7877 }
7878 } else {
7879 // C++11 [dcl.fct.def.default]p4:
7880 // [For a] user-provided explicitly-defaulted function [...] if such a
7881 // function is implicitly defined as deleted, the program is ill-formed.
7882 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7883 << llvm::to_underlying(CSM);
7884 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7885 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7886 HadError = true;
7887 }
7888 }
7889
7890 return HadError;
7891}
7892
7893namespace {
7894/// Helper class for building and checking a defaulted comparison.
7895///
7896/// Defaulted functions are built in two phases:
7897///
7898/// * First, the set of operations that the function will perform are
7899/// identified, and some of them are checked. If any of the checked
7900/// operations is invalid in certain ways, the comparison function is
7901/// defined as deleted and no body is built.
7902/// * Then, if the function is not defined as deleted, the body is built.
7903///
7904/// This is accomplished by performing two visitation steps over the eventual
7905/// body of the function.
7906template<typename Derived, typename ResultList, typename Result,
7907 typename Subobject>
7908class DefaultedComparisonVisitor {
7909public:
7910 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7911
7912 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7913 DefaultedComparisonKind DCK)
7914 : S(S), RD(RD), FD(FD), DCK(DCK) {
7915 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7916 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7917 // UnresolvedSet to avoid this copy.
7918 Fns.assign(Info->getUnqualifiedLookups().begin(),
7919 Info->getUnqualifiedLookups().end());
7920 }
7921 }
7922
7923 ResultList visit() {
7924 // The type of an lvalue naming a parameter of this function.
7925 QualType ParamLvalType =
7927
7928 ResultList Results;
7929
7930 switch (DCK) {
7931 case DefaultedComparisonKind::None:
7932 llvm_unreachable("not a defaulted comparison");
7933
7934 case DefaultedComparisonKind::Equal:
7935 case DefaultedComparisonKind::ThreeWay:
7936 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7937 return Results;
7938
7939 case DefaultedComparisonKind::NotEqual:
7940 case DefaultedComparisonKind::Relational:
7941 Results.add(getDerived().visitExpandedSubobject(
7942 ParamLvalType, getDerived().getCompleteObject()));
7943 return Results;
7944 }
7945 llvm_unreachable("");
7946 }
7947
7948protected:
7949 Derived &getDerived() { return static_cast<Derived&>(*this); }
7950
7951 /// Visit the expanded list of subobjects of the given type, as specified in
7952 /// C++2a [class.compare.default].
7953 ///
7954 /// \return \c true if the ResultList object said we're done, \c false if not.
7955 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7956 Qualifiers Quals) {
7957 // C++2a [class.compare.default]p4:
7958 // The direct base class subobjects of C
7959 for (CXXBaseSpecifier &Base : Record->bases())
7960 if (Results.add(getDerived().visitSubobject(
7961 S.Context.getQualifiedType(Base.getType(), Quals),
7962 getDerived().getBase(&Base))))
7963 return true;
7964
7965 // followed by the non-static data members of C
7966 for (FieldDecl *Field : Record->fields()) {
7967 // C++23 [class.bit]p2:
7968 // Unnamed bit-fields are not members ...
7969 if (Field->isUnnamedBitField())
7970 continue;
7971 // Recursively expand anonymous structs.
7972 if (Field->isAnonymousStructOrUnion()) {
7973 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7974 Quals))
7975 return true;
7976 continue;
7977 }
7978
7979 // Figure out the type of an lvalue denoting this field.
7980 Qualifiers FieldQuals = Quals;
7981 if (Field->isMutable())
7982 FieldQuals.removeConst();
7983 QualType FieldType =
7984 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7985
7986 if (Results.add(getDerived().visitSubobject(
7987 FieldType, getDerived().getField(Field))))
7988 return true;
7989 }
7990
7991 // form a list of subobjects.
7992 return false;
7993 }
7994
7995 Result visitSubobject(QualType Type, Subobject Subobj) {
7996 // In that list, any subobject of array type is recursively expanded
7997 const ArrayType *AT = S.Context.getAsArrayType(Type);
7998 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7999 return getDerived().visitSubobjectArray(CAT->getElementType(),
8000 CAT->getSize(), Subobj);
8001 return getDerived().visitExpandedSubobject(Type, Subobj);
8002 }
8003
8004 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8005 Subobject Subobj) {
8006 return getDerived().visitSubobject(Type, Subobj);
8007 }
8008
8009protected:
8010 Sema &S;
8011 CXXRecordDecl *RD;
8012 FunctionDecl *FD;
8013 DefaultedComparisonKind DCK;
8015};
8016
8017/// Information about a defaulted comparison, as determined by
8018/// DefaultedComparisonAnalyzer.
8019struct DefaultedComparisonInfo {
8020 bool Deleted = false;
8021 bool Constexpr = true;
8022 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8023
8024 static DefaultedComparisonInfo deleted() {
8025 DefaultedComparisonInfo Deleted;
8026 Deleted.Deleted = true;
8027 return Deleted;
8028 }
8029
8030 bool add(const DefaultedComparisonInfo &R) {
8031 Deleted |= R.Deleted;
8032 Constexpr &= R.Constexpr;
8033 Category = commonComparisonType(Category, R.Category);
8034 return Deleted;
8035 }
8036};
8037
8038/// An element in the expanded list of subobjects of a defaulted comparison, as
8039/// specified in C++2a [class.compare.default]p4.
8040struct DefaultedComparisonSubobject {
8041 enum { CompleteObject, Member, Base } Kind;
8042 NamedDecl *Decl;
8044};
8045
8046/// A visitor over the notional body of a defaulted comparison that determines
8047/// whether that body would be deleted or constexpr.
8048class DefaultedComparisonAnalyzer
8049 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8050 DefaultedComparisonInfo,
8051 DefaultedComparisonInfo,
8052 DefaultedComparisonSubobject> {
8053public:
8054 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8055
8056private:
8057 DiagnosticKind Diagnose;
8058
8059public:
8060 using Base = DefaultedComparisonVisitor;
8061 using Result = DefaultedComparisonInfo;
8062 using Subobject = DefaultedComparisonSubobject;
8063
8064 friend Base;
8065
8066 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8067 DefaultedComparisonKind DCK,
8068 DiagnosticKind Diagnose = NoDiagnostics)
8069 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8070
8071 Result visit() {
8072 if ((DCK == DefaultedComparisonKind::Equal ||
8073 DCK == DefaultedComparisonKind::ThreeWay) &&
8074 RD->hasVariantMembers()) {
8075 // C++2a [class.compare.default]p2 [P2002R0]:
8076 // A defaulted comparison operator function for class C is defined as
8077 // deleted if [...] C has variant members.
8078 if (Diagnose == ExplainDeleted) {
8079 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8080 << FD << RD->isUnion() << RD;
8081 }
8082 return Result::deleted();
8083 }
8084
8085 return Base::visit();
8086 }
8087
8088private:
8089 Subobject getCompleteObject() {
8090 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8091 }
8092
8093 Subobject getBase(CXXBaseSpecifier *Base) {
8094 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8095 Base->getBaseTypeLoc()};
8096 }
8097
8098 Subobject getField(FieldDecl *Field) {
8099 return Subobject{Subobject::Member, Field, Field->getLocation()};
8100 }
8101
8102 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8103 // C++2a [class.compare.default]p2 [P2002R0]:
8104 // A defaulted <=> or == operator function for class C is defined as
8105 // deleted if any non-static data member of C is of reference type
8106 if (Type->isReferenceType()) {
8107 if (Diagnose == ExplainDeleted) {
8108 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8109 << FD << RD;
8110 }
8111 return Result::deleted();
8112 }
8113
8114 // [...] Let xi be an lvalue denoting the ith element [...]
8116 Expr *Args[] = {&Xi, &Xi};
8117
8118 // All operators start by trying to apply that same operator recursively.
8120 assert(OO != OO_None && "not an overloaded operator!");
8121 return visitBinaryOperator(OO, Args, Subobj);
8122 }
8123
8124 Result
8125 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8126 Subobject Subobj,
8127 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8128 // Note that there is no need to consider rewritten candidates here if
8129 // we've already found there is no viable 'operator<=>' candidate (and are
8130 // considering synthesizing a '<=>' from '==' and '<').
8131 OverloadCandidateSet CandidateSet(
8134 OO, FD->getLocation(),
8135 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8136
8137 /// C++2a [class.compare.default]p1 [P2002R0]:
8138 /// [...] the defaulted function itself is never a candidate for overload
8139 /// resolution [...]
8140 CandidateSet.exclude(FD);
8141
8142 if (Args[0]->getType()->isOverloadableType())
8143 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8144 else
8145 // FIXME: We determine whether this is a valid expression by checking to
8146 // see if there's a viable builtin operator candidate for it. That isn't
8147 // really what the rules ask us to do, but should give the right results.
8148 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8149
8150 Result R;
8151
8153 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8154 case OR_Success: {
8155 // C++2a [class.compare.secondary]p2 [P2002R0]:
8156 // The operator function [...] is defined as deleted if [...] the
8157 // candidate selected by overload resolution is not a rewritten
8158 // candidate.
8159 if ((DCK == DefaultedComparisonKind::NotEqual ||
8160 DCK == DefaultedComparisonKind::Relational) &&
8161 !Best->RewriteKind) {
8162 if (Diagnose == ExplainDeleted) {
8163 if (Best->Function) {
8164 S.Diag(Best->Function->getLocation(),
8165 diag::note_defaulted_comparison_not_rewritten_callee)
8166 << FD;
8167 } else {
8168 assert(Best->Conversions.size() == 2 &&
8169 Best->Conversions[0].isUserDefined() &&
8170 "non-user-defined conversion from class to built-in "
8171 "comparison");
8172 S.Diag(Best->Conversions[0]
8173 .UserDefined.FoundConversionFunction.getDecl()
8174 ->getLocation(),
8175 diag::note_defaulted_comparison_not_rewritten_conversion)
8176 << FD;
8177 }
8178 }
8179 return Result::deleted();
8180 }
8181
8182 // Throughout C++2a [class.compare]: if overload resolution does not
8183 // result in a usable function, the candidate function is defined as
8184 // deleted. This requires that we selected an accessible function.
8185 //
8186 // Note that this only considers the access of the function when named
8187 // within the type of the subobject, and not the access path for any
8188 // derived-to-base conversion.
8189 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8190 if (ArgClass && Best->FoundDecl.getDecl() &&
8191 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8192 QualType ObjectType = Subobj.Kind == Subobject::Member
8193 ? Args[0]->getType()
8194 : S.Context.getRecordType(RD);
8196 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8197 Diagnose == ExplainDeleted
8198 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8199 << FD << Subobj.Kind << Subobj.Decl
8200 : S.PDiag()))
8201 return Result::deleted();
8202 }
8203
8204 bool NeedsDeducing =
8205 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8206
8207 if (FunctionDecl *BestFD = Best->Function) {
8208 // C++2a [class.compare.default]p3 [P2002R0]:
8209 // A defaulted comparison function is constexpr-compatible if
8210 // [...] no overlod resolution performed [...] results in a
8211 // non-constexpr function.
8212 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8213 // If it's not constexpr, explain why not.
8214 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8215 if (Subobj.Kind != Subobject::CompleteObject)
8216 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8217 << Subobj.Kind << Subobj.Decl;
8218 S.Diag(BestFD->getLocation(),
8219 diag::note_defaulted_comparison_not_constexpr_here);
8220 // Bail out after explaining; we don't want any more notes.
8221 return Result::deleted();
8222 }
8223 R.Constexpr &= BestFD->isConstexpr();
8224
8225 if (NeedsDeducing) {
8226 // If any callee has an undeduced return type, deduce it now.
8227 // FIXME: It's not clear how a failure here should be handled. For
8228 // now, we produce an eager diagnostic, because that is forward
8229 // compatible with most (all?) other reasonable options.
8230 if (BestFD->getReturnType()->isUndeducedType() &&
8231 S.DeduceReturnType(BestFD, FD->getLocation(),
8232 /*Diagnose=*/false)) {
8233 // Don't produce a duplicate error when asked to explain why the
8234 // comparison is deleted: we diagnosed that when initially checking
8235 // the defaulted operator.
8236 if (Diagnose == NoDiagnostics) {
8237 S.Diag(
8238 FD->getLocation(),
8239 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8240 << Subobj.Kind << Subobj.Decl;
8241 S.Diag(
8242 Subobj.Loc,
8243 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8244 << Subobj.Kind << Subobj.Decl;
8245 S.Diag(BestFD->getLocation(),
8246 diag::note_defaulted_comparison_cannot_deduce_callee)
8247 << Subobj.Kind << Subobj.Decl;
8248 }
8249 return Result::deleted();
8250 }
8252 BestFD->getCallResultType());
8253 if (!Info) {
8254 if (Diagnose == ExplainDeleted) {
8255 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8256 << Subobj.Kind << Subobj.Decl
8257 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8258 S.Diag(BestFD->getLocation(),
8259 diag::note_defaulted_comparison_cannot_deduce_callee)
8260 << Subobj.Kind << Subobj.Decl;
8261 }
8262 return Result::deleted();
8263 }
8264 R.Category = Info->Kind;
8265 }
8266 } else {
8267 QualType T = Best->BuiltinParamTypes[0];
8268 assert(T == Best->BuiltinParamTypes[1] &&
8269 "builtin comparison for different types?");
8270 assert(Best->BuiltinParamTypes[2].isNull() &&
8271 "invalid builtin comparison");
8272
8273 if (NeedsDeducing) {
8274 std::optional<ComparisonCategoryType> Cat =
8276 assert(Cat && "no category for builtin comparison?");
8277 R.Category = *Cat;
8278 }
8279 }
8280
8281 // Note that we might be rewriting to a different operator. That call is
8282 // not considered until we come to actually build the comparison function.
8283 break;
8284 }
8285
8286 case OR_Ambiguous:
8287 if (Diagnose == ExplainDeleted) {
8288 unsigned Kind = 0;
8289 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8290 Kind = OO == OO_EqualEqual ? 1 : 2;
8291 CandidateSet.NoteCandidates(
8293 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8294 << FD << Kind << Subobj.Kind << Subobj.Decl),
8295 S, OCD_AmbiguousCandidates, Args);
8296 }
8297 R = Result::deleted();
8298 break;
8299
8300 case OR_Deleted:
8301 if (Diagnose == ExplainDeleted) {
8302 if ((DCK == DefaultedComparisonKind::NotEqual ||
8303 DCK == DefaultedComparisonKind::Relational) &&
8304 !Best->RewriteKind) {
8305 S.Diag(Best->Function->getLocation(),
8306 diag::note_defaulted_comparison_not_rewritten_callee)
8307 << FD;
8308 } else {
8309 S.Diag(Subobj.Loc,
8310 diag::note_defaulted_comparison_calls_deleted)
8311 << FD << Subobj.Kind << Subobj.Decl;
8312 S.NoteDeletedFunction(Best->Function);
8313 }
8314 }
8315 R = Result::deleted();
8316 break;
8317
8319 // If there's no usable candidate, we're done unless we can rewrite a
8320 // '<=>' in terms of '==' and '<'.
8321 if (OO == OO_Spaceship &&
8323 // For any kind of comparison category return type, we need a usable
8324 // '==' and a usable '<'.
8325 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8326 &CandidateSet)))
8327 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8328 break;
8329 }
8330
8331 if (Diagnose == ExplainDeleted) {
8332 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8333 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8334 << Subobj.Kind << Subobj.Decl;
8335
8336 // For a three-way comparison, list both the candidates for the
8337 // original operator and the candidates for the synthesized operator.
8338 if (SpaceshipCandidates) {
8339 SpaceshipCandidates->NoteCandidates(
8340 S, Args,
8341 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8342 Args, FD->getLocation()));
8343 S.Diag(Subobj.Loc,
8344 diag::note_defaulted_comparison_no_viable_function_synthesized)
8345 << (OO == OO_EqualEqual ? 0 : 1);
8346 }
8347
8348 CandidateSet.NoteCandidates(
8349 S, Args,
8350 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8351 FD->getLocation()));
8352 }
8353 R = Result::deleted();
8354 break;
8355 }
8356
8357 return R;
8358 }
8359};
8360
8361/// A list of statements.
8362struct StmtListResult {
8363 bool IsInvalid = false;
8365
8366 bool add(const StmtResult &S) {
8367 IsInvalid |= S.isInvalid();
8368 if (IsInvalid)
8369 return true;
8370 Stmts.push_back(S.get());
8371 return false;
8372 }
8373};
8374
8375/// A visitor over the notional body of a defaulted comparison that synthesizes
8376/// the actual body.
8377class DefaultedComparisonSynthesizer
8378 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8379 StmtListResult, StmtResult,
8380 std::pair<ExprResult, ExprResult>> {
8382 unsigned ArrayDepth = 0;
8383
8384public:
8385 using Base = DefaultedComparisonVisitor;
8386 using ExprPair = std::pair<ExprResult, ExprResult>;
8387
8388 friend Base;
8389
8390 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8391 DefaultedComparisonKind DCK,
8392 SourceLocation BodyLoc)
8393 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8394
8395 /// Build a suitable function body for this defaulted comparison operator.
8396 StmtResult build() {
8397 Sema::CompoundScopeRAII CompoundScope(S);
8398
8399 StmtListResult Stmts = visit();
8400 if (Stmts.IsInvalid)
8401 return StmtError();
8402
8403 ExprResult RetVal;
8404 switch (DCK) {
8405 case DefaultedComparisonKind::None:
8406 llvm_unreachable("not a defaulted comparison");
8407
8408 case DefaultedComparisonKind::Equal: {
8409 // C++2a [class.eq]p3:
8410 // [...] compar[e] the corresponding elements [...] until the first
8411 // index i where xi == yi yields [...] false. If no such index exists,
8412 // V is true. Otherwise, V is false.
8413 //
8414 // Join the comparisons with '&&'s and return the result. Use a right
8415 // fold (traversing the conditions right-to-left), because that
8416 // short-circuits more naturally.
8417 auto OldStmts = std::move(Stmts.Stmts);
8418 Stmts.Stmts.clear();
8419 ExprResult CmpSoFar;
8420 // Finish a particular comparison chain.
8421 auto FinishCmp = [&] {
8422 if (Expr *Prior = CmpSoFar.get()) {
8423 // Convert the last expression to 'return ...;'
8424 if (RetVal.isUnset() && Stmts.Stmts.empty())
8425 RetVal = CmpSoFar;
8426 // Convert any prior comparison to 'if (!(...)) return false;'
8427 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8428 return true;
8429 CmpSoFar = ExprResult();
8430 }
8431 return false;
8432 };
8433 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8434 Expr *E = dyn_cast<Expr>(EAsStmt);
8435 if (!E) {
8436 // Found an array comparison.
8437 if (FinishCmp() || Stmts.add(EAsStmt))
8438 return StmtError();
8439 continue;
8440 }
8441
8442 if (CmpSoFar.isUnset()) {
8443 CmpSoFar = E;
8444 continue;
8445 }
8446 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8447 if (CmpSoFar.isInvalid())
8448 return StmtError();
8449 }
8450 if (FinishCmp())
8451 return StmtError();
8452 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8453 // If no such index exists, V is true.
8454 if (RetVal.isUnset())
8455 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8456 break;
8457 }
8458
8459 case DefaultedComparisonKind::ThreeWay: {
8460 // Per C++2a [class.spaceship]p3, as a fallback add:
8461 // return static_cast<R>(std::strong_ordering::equal);
8463 ComparisonCategoryType::StrongOrdering, Loc,
8464 Sema::ComparisonCategoryUsage::DefaultedOperator);
8465 if (StrongOrdering.isNull())
8466 return StmtError();
8468 .getValueInfo(ComparisonCategoryResult::Equal)
8469 ->VD;
8470 RetVal = getDecl(EqualVD);
8471 if (RetVal.isInvalid())
8472 return StmtError();
8473 RetVal = buildStaticCastToR(RetVal.get());
8474 break;
8475 }
8476
8477 case DefaultedComparisonKind::NotEqual:
8478 case DefaultedComparisonKind::Relational:
8479 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8480 break;
8481 }
8482
8483 // Build the final return statement.
8484 if (RetVal.isInvalid())
8485 return StmtError();
8487 if (ReturnStmt.isInvalid())
8488 return StmtError();
8489 Stmts.Stmts.push_back(ReturnStmt.get());
8490
8491 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8492 }
8493
8494private:
8495 ExprResult getDecl(ValueDecl *VD) {
8496 return S.BuildDeclarationNameExpr(
8498 }
8499
8500 ExprResult getParam(unsigned I) {
8501 ParmVarDecl *PD = FD->getParamDecl(I);
8502 return getDecl(PD);
8503 }
8504
8505 ExprPair getCompleteObject() {
8506 unsigned Param = 0;
8507 ExprResult LHS;
8508 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8509 MD && MD->isImplicitObjectMemberFunction()) {
8510 // LHS is '*this'.
8511 LHS = S.ActOnCXXThis(Loc);
8512 if (!LHS.isInvalid())
8513 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8514 } else {
8515 LHS = getParam(Param++);
8516 }
8517 ExprResult RHS = getParam(Param++);
8518 assert(Param == FD->getNumParams());
8519 return {LHS, RHS};
8520 }
8521
8522 ExprPair getBase(CXXBaseSpecifier *Base) {
8523 ExprPair Obj = getCompleteObject();
8524 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8525 return {ExprError(), ExprError()};
8526 CXXCastPath Path = {Base};
8527 const auto CastToBase = [&](Expr *E) {
8529 Base->getType(), E->getType().getQualifiers());
8530 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8531 };
8532 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8533 }
8534
8535 ExprPair getField(FieldDecl *Field) {
8536 ExprPair Obj = getCompleteObject();
8537 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8538 return {ExprError(), ExprError()};
8539
8540 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8541 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8542 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8543 CXXScopeSpec(), Field, Found, NameInfo),
8544 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8545 CXXScopeSpec(), Field, Found, NameInfo)};
8546 }
8547
8548 // FIXME: When expanding a subobject, register a note in the code synthesis
8549 // stack to say which subobject we're comparing.
8550
8551 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8552 if (Cond.isInvalid())
8553 return StmtError();
8554
8555 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8556 if (NotCond.isInvalid())
8557 return StmtError();
8558
8559 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8560 assert(!False.isInvalid() && "should never fail");
8561 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8562 if (ReturnFalse.isInvalid())
8563 return StmtError();
8564
8565 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8566 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8567 Sema::ConditionKind::Boolean),
8568 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8569 }
8570
8571 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8572 ExprPair Subobj) {
8573 QualType SizeType = S.Context.getSizeType();
8574 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8575
8576 // Build 'size_t i$n = 0'.
8577 IdentifierInfo *IterationVarName = nullptr;
8578 {
8579 SmallString<8> Str;
8580 llvm::raw_svector_ostream OS(Str);
8581 OS << "i" << ArrayDepth;
8582 IterationVarName = &S.Context.Idents.get(OS.str());
8583 }
8584 VarDecl *IterationVar = VarDecl::Create(
8585 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8587 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8588 IterationVar->setInit(
8589 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8590 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8591
8592 auto IterRef = [&] {
8594 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8595 IterationVar);
8596 assert(!Ref.isInvalid() && "can't reference our own variable?");
8597 return Ref.get();
8598 };
8599
8600 // Build 'i$n != Size'.
8602 Loc, BO_NE, IterRef(),
8603 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8604 assert(!Cond.isInvalid() && "should never fail");
8605
8606 // Build '++i$n'.
8607 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8608 assert(!Inc.isInvalid() && "should never fail");
8609
8610 // Build 'a[i$n]' and 'b[i$n]'.
8611 auto Index = [&](ExprResult E) {
8612 if (E.isInvalid())
8613 return ExprError();
8614 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8615 };
8616 Subobj.first = Index(Subobj.first);
8617 Subobj.second = Index(Subobj.second);
8618
8619 // Compare the array elements.
8620 ++ArrayDepth;
8621 StmtResult Substmt = visitSubobject(Type, Subobj);
8622 --ArrayDepth;
8623
8624 if (Substmt.isInvalid())
8625 return StmtError();
8626
8627 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8628 // For outer levels or for an 'operator<=>' we already have a suitable
8629 // statement that returns as necessary.
8630 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8631 assert(DCK == DefaultedComparisonKind::Equal &&
8632 "should have non-expression statement");
8633 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8634 if (Substmt.isInvalid())
8635 return StmtError();
8636 }
8637
8638 // Build 'for (...) ...'
8639 return S.ActOnForStmt(Loc, Loc, Init,
8640 S.ActOnCondition(nullptr, Loc, Cond.get(),
8641 Sema::ConditionKind::Boolean),
8643 Substmt.get());
8644 }
8645
8646 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8647 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8648 return StmtError();
8649
8652 ExprResult Op;
8653 if (Type->isOverloadableType())
8654 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8655 Obj.second.get(), /*PerformADL=*/true,
8656 /*AllowRewrittenCandidates=*/true, FD);
8657 else
8658 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8659 if (Op.isInvalid())
8660 return StmtError();
8661
8662 switch (DCK) {
8663 case DefaultedComparisonKind::None:
8664 llvm_unreachable("not a defaulted comparison");
8665
8666 case DefaultedComparisonKind::Equal:
8667 // Per C++2a [class.eq]p2, each comparison is individually contextually
8668 // converted to bool.
8670 if (Op.isInvalid())
8671 return StmtError();
8672 return Op.get();
8673
8674 case DefaultedComparisonKind::ThreeWay: {
8675 // Per C++2a [class.spaceship]p3, form:
8676 // if (R cmp = static_cast<R>(op); cmp != 0)
8677 // return cmp;
8678 QualType R = FD->getReturnType();
8679 Op = buildStaticCastToR(Op.get());
8680 if (Op.isInvalid())
8681 return StmtError();
8682
8683 // R cmp = ...;
8684 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8685 VarDecl *VD =
8686 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8688 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8689 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8690
8691 // cmp != 0
8692 ExprResult VDRef = getDecl(VD);
8693 if (VDRef.isInvalid())
8694 return StmtError();
8695 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8696 Expr *Zero =
8699 if (VDRef.get()->getType()->isOverloadableType())
8700 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8701 true, FD);
8702 else
8703 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8704 if (Comp.isInvalid())
8705 return StmtError();
8707 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8708 if (Cond.isInvalid())
8709 return StmtError();
8710
8711 // return cmp;
8712 VDRef = getDecl(VD);
8713 if (VDRef.isInvalid())
8714 return StmtError();
8716 if (ReturnStmt.isInvalid())
8717 return StmtError();
8718
8719 // if (...)
8720 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8721 Loc, ReturnStmt.get(),
8722 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8723 }
8724
8725 case DefaultedComparisonKind::NotEqual:
8726 case DefaultedComparisonKind::Relational:
8727 // C++2a [class.compare.secondary]p2:
8728 // Otherwise, the operator function yields x @ y.
8729 return Op.get();
8730 }
8731 llvm_unreachable("");
8732 }
8733
8734 /// Build "static_cast<R>(E)".
8735 ExprResult buildStaticCastToR(Expr *E) {
8736 QualType R = FD->getReturnType();
8737 assert(!R->isUndeducedType() && "type should have been deduced already");
8738
8739 // Don't bother forming a no-op cast in the common case.
8740 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8741 return E;
8742 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8745 }
8746};
8747}
8748
8749/// Perform the unqualified lookups that might be needed to form a defaulted
8750/// comparison function for the given operator.
8752 UnresolvedSetImpl &Operators,
8754 auto Lookup = [&](OverloadedOperatorKind OO) {
8755 Self.LookupOverloadedOperatorName(OO, S, Operators);
8756 };
8757
8758 // Every defaulted operator looks up itself.
8759 Lookup(Op);
8760 // ... and the rewritten form of itself, if any.
8762 Lookup(ExtraOp);
8763
8764 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8765 // synthesize a three-way comparison from '<' and '=='. In a dependent
8766 // context, we also need to look up '==' in case we implicitly declare a
8767 // defaulted 'operator=='.
8768 if (Op == OO_Spaceship) {
8769 Lookup(OO_ExclaimEqual);
8770 Lookup(OO_Less);
8771 Lookup(OO_EqualEqual);
8772 }
8773}
8774
8777 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8778
8779 // Perform any unqualified lookups we're going to need to default this
8780 // function.
8781 if (S) {
8782 UnresolvedSet<32> Operators;
8783 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8784 FD->getOverloadedOperator());
8787 Context, Operators.pairs()));
8788 }
8789
8790 // C++2a [class.compare.default]p1:
8791 // A defaulted comparison operator function for some class C shall be a
8792 // non-template function declared in the member-specification of C that is
8793 // -- a non-static const non-volatile member of C having one parameter of
8794 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8795 // -- a friend of C having two parameters of type const C& or two
8796 // parameters of type C.
8797
8798 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8799 bool IsMethod = isa<CXXMethodDecl>(FD);
8800 if (IsMethod) {
8801 auto *MD = cast<CXXMethodDecl>(FD);
8802 assert(!MD->isStatic() && "comparison function cannot be a static member");
8803
8804 if (MD->getRefQualifier() == RQ_RValue) {
8805 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8806
8807 // Remove the ref qualifier to recover.
8808 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8809 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8810 EPI.RefQualifier = RQ_None;
8811 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8812 FPT->getParamTypes(), EPI));
8813 }
8814
8815 // If we're out-of-class, this is the class we're comparing.
8816 if (!RD)
8817 RD = MD->getParent();
8819 if (!T.getNonReferenceType().isConstQualified() &&
8821 SourceLocation Loc, InsertLoc;
8823 Loc = MD->getParamDecl(0)->getBeginLoc();
8824 InsertLoc = getLocForEndOfToken(
8826 } else {
8827 Loc = MD->getLocation();
8829 InsertLoc = Loc.getRParenLoc();
8830 }
8831 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8832 // corresponding defaulted 'operator<=>' already.
8833 if (!MD->isImplicit()) {
8834 Diag(Loc, diag::err_defaulted_comparison_non_const)
8835 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8836 }
8837
8838 // Add the 'const' to the type to recover.
8840 assert(T->isLValueReferenceType());
8842 T.getNonReferenceType().withConst()));
8843 } else {
8844 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8845 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8846 EPI.TypeQuals.addConst();
8847 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8848 FPT->getParamTypes(), EPI));
8849 }
8850 }
8851
8852 if (MD->isVolatile()) {
8853 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8854
8855 // Remove the 'volatile' from the type to recover.
8856 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8857 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8859 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8860 FPT->getParamTypes(), EPI));
8861 }
8862 }
8863
8864 if ((FD->getNumParams() -
8865 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8866 (IsMethod ? 1 : 2)) {
8867 // Let's not worry about using a variadic template pack here -- who would do
8868 // such a thing?
8869 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8870 << int(IsMethod) << int(DCK);
8871 return true;
8872 }
8873
8874 const ParmVarDecl *KnownParm = nullptr;
8875 for (const ParmVarDecl *Param : FD->parameters()) {
8876 QualType ParmTy = Param->getType();
8877 if (!KnownParm) {
8878 auto CTy = ParmTy;
8879 // Is it `T const &`?
8880 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
8881 QualType ExpectedTy;
8882 if (RD)
8883 ExpectedTy = Context.getRecordType(RD);
8884 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
8885 CTy = Ref->getPointeeType();
8886 if (RD)
8887 ExpectedTy.addConst();
8888 Ok = true;
8889 }
8890
8891 // Is T a class?
8892 if (RD) {
8893 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
8894 } else {
8895 RD = CTy->getAsCXXRecordDecl();
8896 Ok &= RD != nullptr;
8897 }
8898
8899 if (Ok) {
8900 KnownParm = Param;
8901 } else {
8902 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8903 // corresponding defaulted 'operator<=>' already.
8904 if (!FD->isImplicit()) {
8905 if (RD) {
8906 QualType PlainTy = Context.getRecordType(RD);
8907 QualType RefTy =
8909 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8910 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8911 << Param->getSourceRange();
8912 } else {
8913 assert(!IsMethod && "should know expected type for method");
8914 Diag(FD->getLocation(),
8915 diag::err_defaulted_comparison_param_unknown)
8916 << int(DCK) << ParmTy << Param->getSourceRange();
8917 }
8918 }
8919 return true;
8920 }
8921 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8922 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8923 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8924 << ParmTy << Param->getSourceRange();
8925 return true;
8926 }
8927 }
8928
8929 assert(RD && "must have determined class");
8930 if (IsMethod) {
8931 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8932 // In-class, must be a friend decl.
8933 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8934 } else {
8935 // Out of class, require the defaulted comparison to be a friend (of a
8936 // complete type, per CWG2547).
8938 diag::err_defaulted_comparison_not_friend, int(DCK),
8939 int(1)))
8940 return true;
8941
8942 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8943 return FD->getCanonicalDecl() ==
8944 F->getFriendDecl()->getCanonicalDecl();
8945 })) {
8946 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8947 << int(DCK) << int(0) << RD;
8948 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8949 return true;
8950 }
8951 }
8952
8953 // C++2a [class.eq]p1, [class.rel]p1:
8954 // A [defaulted comparison other than <=>] shall have a declared return
8955 // type bool.
8959 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8960 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8961 << FD->getReturnTypeSourceRange();
8962 return true;
8963 }
8964 // C++2a [class.spaceship]p2 [P2002R0]:
8965 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8966 // R shall not contain a placeholder type.
8967 if (QualType RT = FD->getDeclaredReturnType();
8969 RT->getContainedDeducedType() &&
8971 RT->getContainedAutoType()->isConstrained())) {
8972 Diag(FD->getLocation(),
8973 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8974 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8975 << FD->getReturnTypeSourceRange();
8976 return true;
8977 }
8978
8979 // For a defaulted function in a dependent class, defer all remaining checks
8980 // until instantiation.
8981 if (RD->isDependentType())
8982 return false;
8983
8984 // Determine whether the function should be defined as deleted.
8985 DefaultedComparisonInfo Info =
8986 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8987
8988 bool First = FD == FD->getCanonicalDecl();
8989
8990 if (!First) {
8991 if (Info.Deleted) {
8992 // C++11 [dcl.fct.def.default]p4:
8993 // [For a] user-provided explicitly-defaulted function [...] if such a
8994 // function is implicitly defined as deleted, the program is ill-formed.
8995 //
8996 // This is really just a consequence of the general rule that you can
8997 // only delete a function on its first declaration.
8998 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8999 << FD->isImplicit() << (int)DCK;
9000 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9001 DefaultedComparisonAnalyzer::ExplainDeleted)
9002 .visit();
9003 return true;
9004 }
9005 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9006 // C++20 [class.compare.default]p1:
9007 // [...] A definition of a comparison operator as defaulted that appears
9008 // in a class shall be the first declaration of that function.
9009 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9010 << (int)DCK;
9012 diag::note_previous_declaration);
9013 return true;
9014 }
9015 }
9016
9017 // If we want to delete the function, then do so; there's nothing else to
9018 // check in that case.
9019 if (Info.Deleted) {
9020 SetDeclDeleted(FD, FD->getLocation());
9021 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9022 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9023 << (int)DCK;
9024 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9025 DefaultedComparisonAnalyzer::ExplainDeleted)
9026 .visit();
9027 if (FD->getDefaultLoc().isValid())
9028 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9029 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9030 }
9031 return false;
9032 }
9033
9034 // C++2a [class.spaceship]p2:
9035 // The return type is deduced as the common comparison type of R0, R1, ...
9039 if (RetLoc.isInvalid())
9040 RetLoc = FD->getBeginLoc();
9041 // FIXME: Should we really care whether we have the complete type and the
9042 // 'enumerator' constants here? A forward declaration seems sufficient.
9044 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9045 if (Cat.isNull())
9046 return true;
9048 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9049 }
9050
9051 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9052 // An explicitly-defaulted function that is not defined as deleted may be
9053 // declared constexpr or consteval only if it is constexpr-compatible.
9054 // C++2a [class.compare.default]p3 [P2002R0]:
9055 // A defaulted comparison function is constexpr-compatible if it satisfies
9056 // the requirements for a constexpr function [...]
9057 // The only relevant requirements are that the parameter and return types are
9058 // literal types. The remaining conditions are checked by the analyzer.
9059 //
9060 // We support P2448R2 in language modes earlier than C++23 as an extension.
9061 // The concept of constexpr-compatible was removed.
9062 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9063 // A function explicitly defaulted on its first declaration is implicitly
9064 // inline, and is implicitly constexpr if it is constexpr-suitable.
9065 // C++23 [dcl.constexpr]p3
9066 // A function is constexpr-suitable if
9067 // - it is not a coroutine, and
9068 // - if the function is a constructor or destructor, its class does not
9069 // have any virtual base classes.
9070 if (FD->isConstexpr()) {
9071 if (!getLangOpts().CPlusPlus23 &&
9074 !Info.Constexpr) {
9075 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9076 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9077 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9078 DefaultedComparisonAnalyzer::ExplainConstexpr)
9079 .visit();
9080 }
9081 }
9082
9083 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9084 // If a constexpr-compatible function is explicitly defaulted on its first
9085 // declaration, it is implicitly considered to be constexpr.
9086 // FIXME: Only applying this to the first declaration seems problematic, as
9087 // simple reorderings can affect the meaning of the program.
9088 if (First && !FD->isConstexpr() && Info.Constexpr)
9090
9091 // C++2a [except.spec]p3:
9092 // If a declaration of a function does not have a noexcept-specifier
9093 // [and] is defaulted on its first declaration, [...] the exception
9094 // specification is as specified below
9095 if (FD->getExceptionSpecType() == EST_None) {
9096 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9097 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9099 EPI.ExceptionSpec.SourceDecl = FD;
9100 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9101 FPT->getParamTypes(), EPI));
9102 }
9103
9104 return false;
9105}
9106
9108 FunctionDecl *Spaceship) {
9111 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9112 Ctx.Entity = Spaceship;
9114
9115 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9116 EqualEqual->setImplicit();
9117
9119}
9120
9123 assert(FD->isDefaulted() && !FD->isDeleted() &&
9125 if (FD->willHaveBody() || FD->isInvalidDecl())
9126 return;
9127
9129
9130 // Add a context note for diagnostics produced after this point.
9131 Scope.addContextNote(UseLoc);
9132
9133 {
9134 // Build and set up the function body.
9135 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9136 // the type of the class being compared.
9137 auto PT = FD->getParamDecl(0)->getType();
9138 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9139 SourceLocation BodyLoc =
9140 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9141 StmtResult Body =
9142 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9143 if (Body.isInvalid()) {
9144 FD->setInvalidDecl();
9145 return;
9146 }
9147 FD->setBody(Body.get());
9148 FD->markUsed(Context);
9149 }
9150
9151 // The exception specification is needed because we are defining the
9152 // function. Note that this will reuse the body we just built.
9154
9156 L->CompletedImplicitDefinition(FD);
9157}
9158
9161 FunctionDecl *FD,
9163 ComputingExceptionSpec CES(S, FD, Loc);
9165
9166 if (FD->isInvalidDecl())
9167 return ExceptSpec;
9168
9169 // The common case is that we just defined the comparison function. In that
9170 // case, just look at whether the body can throw.
9171 if (FD->hasBody()) {
9172 ExceptSpec.CalledStmt(FD->getBody());
9173 } else {
9174 // Otherwise, build a body so we can check it. This should ideally only
9175 // happen when we're not actually marking the function referenced. (This is
9176 // only really important for efficiency: we don't want to build and throw
9177 // away bodies for comparison functions more than we strictly need to.)
9178
9179 // Pretend to synthesize the function body in an unevaluated context.
9180 // Note that we can't actually just go ahead and define the function here:
9181 // we are not permitted to mark its callees as referenced.
9185
9186 CXXRecordDecl *RD =
9187 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9188 ? FD->getDeclContext()
9189 : FD->getLexicalDeclContext());
9190 SourceLocation BodyLoc =
9191 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9192 StmtResult Body =
9193 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9194 if (!Body.isInvalid())
9195 ExceptSpec.CalledStmt(Body.get());
9196
9197 // FIXME: Can we hold onto this body and just transform it to potentially
9198 // evaluated when we're asked to define the function rather than rebuilding
9199 // it? Either that, or we should only build the bits of the body that we
9200 // need (the expressions, not the statements).
9201 }
9202
9203 return ExceptSpec;
9204}
9205
9207 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9209
9210 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9212
9213 // Perform any deferred checking of exception specifications for virtual
9214 // destructors.
9215 for (auto &Check : Overriding)
9216 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9217
9218 // Perform any deferred checking of exception specifications for befriended
9219 // special members.
9220 for (auto &Check : Equivalent)
9221 CheckEquivalentExceptionSpec(Check.second, Check.first);
9222}
9223
9224namespace {
9225/// CRTP base class for visiting operations performed by a special member
9226/// function (or inherited constructor).
9227template<typename Derived>
9228struct SpecialMemberVisitor {
9229 Sema &S;
9230 CXXMethodDecl *MD;
9233
9234 // Properties of the special member, computed for convenience.
9235 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9236
9237 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9239 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9240 switch (CSM) {
9241 case CXXSpecialMemberKind::DefaultConstructor:
9242 case CXXSpecialMemberKind::CopyConstructor:
9243 case CXXSpecialMemberKind::MoveConstructor:
9244 IsConstructor = true;
9245 break;
9246 case CXXSpecialMemberKind::CopyAssignment:
9247 case CXXSpecialMemberKind::MoveAssignment:
9248 IsAssignment = true;
9249 break;
9250 case CXXSpecialMemberKind::Destructor:
9251 break;
9252 case CXXSpecialMemberKind::Invalid:
9253 llvm_unreachable("invalid special member kind");
9254 }
9255
9256 if (MD->getNumExplicitParams()) {
9257 if (const ReferenceType *RT =
9259 ConstArg = RT->getPointeeType().isConstQualified();
9260 }
9261 }
9262
9263 Derived &getDerived() { return static_cast<Derived&>(*this); }
9264
9265 /// Is this a "move" special member?
9266 bool isMove() const {
9267 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9268 CSM == CXXSpecialMemberKind::MoveAssignment;
9269 }
9270
9271 /// Look up the corresponding special member in the given class.
9273 unsigned Quals, bool IsMutable) {
9274 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9275 ConstArg && !IsMutable);
9276 }
9277
9278 /// Look up the constructor for the specified base class to see if it's
9279 /// overridden due to this being an inherited constructor.
9280 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9281 if (!ICI)
9282 return {};
9283 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9284 auto *BaseCtor =
9285 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9286 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9287 return MD;
9288 return {};
9289 }
9290
9291 /// A base or member subobject.
9292 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9293
9294 /// Get the location to use for a subobject in diagnostics.
9295 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9296 // FIXME: For an indirect virtual base, the direct base leading to
9297 // the indirect virtual base would be a more useful choice.
9298 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9299 return B->getBaseTypeLoc();
9300 else
9301 return cast<FieldDecl *>(Subobj)->getLocation();
9302 }
9303
9304 enum BasesToVisit {
9305 /// Visit all non-virtual (direct) bases.
9306 VisitNonVirtualBases,
9307 /// Visit all direct bases, virtual or not.
9308 VisitDirectBases,
9309 /// Visit all non-virtual bases, and all virtual bases if the class
9310 /// is not abstract.
9311 VisitPotentiallyConstructedBases,
9312 /// Visit all direct or virtual bases.
9313 VisitAllBases
9314 };
9315
9316 // Visit the bases and members of the class.
9317 bool visit(BasesToVisit Bases) {
9318 CXXRecordDecl *RD = MD->getParent();
9319
9320 if (Bases == VisitPotentiallyConstructedBases)
9321 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9322
9323 for (auto &B : RD->bases())
9324 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9325 getDerived().visitBase(&B))
9326 return true;
9327
9328 if (Bases == VisitAllBases)
9329 for (auto &B : RD->vbases())
9330 if (getDerived().visitBase(&B))
9331 return true;
9332
9333 for (auto *F : RD->fields())
9334 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9335 getDerived().visitField(F))
9336 return true;
9337
9338 return false;
9339 }
9340};
9341}
9342
9343namespace {
9344struct SpecialMemberDeletionInfo
9345 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9346 bool Diagnose;
9347
9349
9350 bool AllFieldsAreConst;
9351
9352 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9354 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9355 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9356 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9357
9358 bool inUnion() const { return MD->getParent()->isUnion(); }
9359
9360 CXXSpecialMemberKind getEffectiveCSM() {
9361 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9362 }
9363
9364 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9365
9366 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9367 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9368
9369 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9370 bool shouldDeleteForField(FieldDecl *FD);
9371 bool shouldDeleteForAllConstMembers();
9372
9373 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9374 unsigned Quals);
9375 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9377 bool IsDtorCallInCtor);
9378
9379 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9380};
9381}
9382
9383/// Is the given special member inaccessible when used on the given
9384/// sub-object.
9385bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9386 CXXMethodDecl *target) {
9387 /// If we're operating on a base class, the object type is the
9388 /// type of this special member.
9389 QualType objectTy;
9390 AccessSpecifier access = target->getAccess();
9391 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9392 objectTy = S.Context.getTypeDeclType(MD->getParent());
9393 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9394
9395 // If we're operating on a field, the object type is the type of the field.
9396 } else {
9397 objectTy = S.Context.getTypeDeclType(target->getParent());
9398 }
9399
9401 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9402}
9403
9404/// Check whether we should delete a special member due to the implicit
9405/// definition containing a call to a special member of a subobject.
9406bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9407 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9408 bool IsDtorCallInCtor) {
9409 CXXMethodDecl *Decl = SMOR.getMethod();
9410 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9411
9412 int DiagKind = -1;
9413
9415 DiagKind = !Decl ? 0 : 1;
9417 DiagKind = 2;
9418 else if (!isAccessible(Subobj, Decl))
9419 DiagKind = 3;
9420 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9421 !Decl->isTrivial()) {
9422 // A member of a union must have a trivial corresponding special member.
9423 // As a weird special case, a destructor call from a union's constructor
9424 // must be accessible and non-deleted, but need not be trivial. Such a
9425 // destructor is never actually called, but is semantically checked as
9426 // if it were.
9428 // [class.default.ctor]p2:
9429 // A defaulted default constructor for class X is defined as deleted if
9430 // - X is a union that has a variant member with a non-trivial default
9431 // constructor and no variant member of X has a default member
9432 // initializer
9433 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9434 if (!RD->hasInClassInitializer())
9435 DiagKind = 4;
9436 } else {
9437 DiagKind = 4;
9438 }
9439 }
9440
9441 if (DiagKind == -1)
9442 return false;
9443
9444 if (Diagnose) {
9445 if (Field) {
9446 S.Diag(Field->getLocation(),
9447 diag::note_deleted_special_member_class_subobject)
9448 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9449 << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9450 << /*IsObjCPtr*/ false;
9451 } else {
9452 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9453 S.Diag(Base->getBeginLoc(),
9454 diag::note_deleted_special_member_class_subobject)
9455 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9456 << /*IsField*/ false << Base->getType() << DiagKind
9457 << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9458 }
9459
9460 if (DiagKind == 1)
9462 // FIXME: Explain inaccessibility if DiagKind == 3.
9463 }
9464
9465 return true;
9466}
9467
9468/// Check whether we should delete a special member function due to having a
9469/// direct or virtual base class or non-static data member of class type M.
9470bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9471 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9472 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9473 bool IsMutable = Field && Field->isMutable();
9474
9475 // C++11 [class.ctor]p5:
9476 // -- any direct or virtual base class, or non-static data member with no
9477 // brace-or-equal-initializer, has class type M (or array thereof) and
9478 // either M has no default constructor or overload resolution as applied
9479 // to M's default constructor results in an ambiguity or in a function
9480 // that is deleted or inaccessible
9481 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9482 // -- a direct or virtual base class B that cannot be copied/moved because
9483 // overload resolution, as applied to B's corresponding special member,
9484 // results in an ambiguity or a function that is deleted or inaccessible
9485 // from the defaulted special member
9486 // C++11 [class.dtor]p5:
9487 // -- any direct or virtual base class [...] has a type with a destructor
9488 // that is deleted or inaccessible
9489 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9490 Field->hasInClassInitializer()) &&
9491 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9492 false))
9493 return true;
9494
9495 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9496 // -- any direct or virtual base class or non-static data member has a
9497 // type with a destructor that is deleted or inaccessible
9498 if (IsConstructor) {
9501 false, false, false, false);
9502 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9503 return true;
9504 }
9505
9506 return false;
9507}
9508
9509bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9510 FieldDecl *FD, QualType FieldType) {
9511 // The defaulted special functions are defined as deleted if this is a variant
9512 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9513 // type under ARC.
9514 if (!FieldType.hasNonTrivialObjCLifetime())
9515 return false;
9516
9517 // Don't make the defaulted default constructor defined as deleted if the
9518 // member has an in-class initializer.
9521 return false;
9522
9523 if (Diagnose) {
9524 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9525 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9526 << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9527 << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9528 << /*IsObjCPtr*/ true;
9529 }
9530
9531 return true;
9532}
9533
9534/// Check whether we should delete a special member function due to the class
9535/// having a particular direct or virtual base class.
9536bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9537 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9538 // If program is correct, BaseClass cannot be null, but if it is, the error
9539 // must be reported elsewhere.
9540 if (!BaseClass)
9541 return false;
9542 // If we have an inheriting constructor, check whether we're calling an
9543 // inherited constructor instead of a default constructor.
9544 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9545 if (auto *BaseCtor = SMOR.getMethod()) {
9546 // Note that we do not check access along this path; other than that,
9547 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9548 // FIXME: Check that the base has a usable destructor! Sink this into
9549 // shouldDeleteForClassSubobject.
9550 if (BaseCtor->isDeleted() && Diagnose) {
9551 S.Diag(Base->getBeginLoc(),
9552 diag::note_deleted_special_member_class_subobject)
9553 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9554 << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9555 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9556 S.NoteDeletedFunction(BaseCtor);
9557 }
9558 return BaseCtor->isDeleted();
9559 }
9560 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9561}
9562
9563/// Check whether we should delete a special member function due to the class
9564/// having a particular non-static data member.
9565bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9566 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9567 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9568
9569 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9570 return true;
9571
9573 // For a default constructor, all references must be initialized in-class
9574 // and, if a union, it must have a non-const member.
9575 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9576 if (Diagnose)
9577 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9578 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9579 return true;
9580 }
9581 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9582 // data member of const-qualified type (or array thereof) with no
9583 // brace-or-equal-initializer is not const-default-constructible.
9584 if (!inUnion() && FieldType.isConstQualified() &&
9585 !FD->hasInClassInitializer() &&
9586 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9587 if (Diagnose)
9588 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9589 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9590 return true;
9591 }
9592
9593 if (inUnion() && !FieldType.isConstQualified())
9594 AllFieldsAreConst = false;
9595 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9596 // For a copy constructor, data members must not be of rvalue reference
9597 // type.
9598 if (FieldType->isRValueReferenceType()) {
9599 if (Diagnose)
9600 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9601 << MD->getParent() << FD << FieldType;
9602 return true;
9603 }
9604 } else if (IsAssignment) {
9605 // For an assignment operator, data members must not be of reference type.
9606 if (FieldType->isReferenceType()) {
9607 if (Diagnose)
9608 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9609 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9610 return true;
9611 }
9612 if (!FieldRecord && FieldType.isConstQualified()) {
9613 // C++11 [class.copy]p23:
9614 // -- a non-static data member of const non-class type (or array thereof)
9615 if (Diagnose)
9616 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9617 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9618 return true;
9619 }
9620 }
9621
9622 if (FieldRecord) {
9623 // Some additional restrictions exist on the variant members.
9624 if (!inUnion() && FieldRecord->isUnion() &&
9625 FieldRecord->isAnonymousStructOrUnion()) {
9626 bool AllVariantFieldsAreConst = true;
9627
9628 // FIXME: Handle anonymous unions declared within anonymous unions.
9629 for (auto *UI : FieldRecord->fields()) {
9630 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9631
9632 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9633 return true;
9634
9635 if (!UnionFieldType.isConstQualified())
9636 AllVariantFieldsAreConst = false;
9637
9638 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9639 if (UnionFieldRecord &&
9640 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9641 UnionFieldType.getCVRQualifiers()))
9642 return true;
9643 }
9644
9645 // At least one member in each anonymous union must be non-const
9647 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9648 if (Diagnose)
9649 S.Diag(FieldRecord->getLocation(),
9650 diag::note_deleted_default_ctor_all_const)
9651 << !!ICI << MD->getParent() << /*anonymous union*/1;
9652 return true;
9653 }
9654
9655 // Don't check the implicit member of the anonymous union type.
9656 // This is technically non-conformant but supported, and we have a
9657 // diagnostic for this elsewhere.
9658 return false;
9659 }
9660
9661 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9662 FieldType.getCVRQualifiers()))
9663 return true;
9664 }
9665
9666 return false;
9667}
9668
9669/// C++11 [class.ctor] p5:
9670/// A defaulted default constructor for a class X is defined as deleted if
9671/// X is a union and all of its variant members are of const-qualified type.
9672bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9673 // This is a silly definition, because it gives an empty union a deleted
9674 // default constructor. Don't do that.
9675 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9676 AllFieldsAreConst) {
9677 bool AnyFields = false;
9678 for (auto *F : MD->getParent()->fields())
9679 if ((AnyFields = !F->isUnnamedBitField()))
9680 break;
9681 if (!AnyFields)
9682 return false;
9683 if (Diagnose)
9684 S.Diag(MD->getParent()->getLocation(),
9685 diag::note_deleted_default_ctor_all_const)
9686 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9687 return true;
9688 }
9689 return false;
9690}
9691
9692/// Determine whether a defaulted special member function should be defined as
9693/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9694/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9698 bool Diagnose) {
9699 if (MD->isInvalidDecl())
9700 return false;
9701 CXXRecordDecl *RD = MD->getParent();
9702 assert(!RD->isDependentType() && "do deletion after instantiation");
9703 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9704 RD->isInvalidDecl())
9705 return false;
9706
9707 // C++11 [expr.lambda.prim]p19:
9708 // The closure type associated with a lambda-expression has a
9709 // deleted (8.4.3) default constructor and a deleted copy
9710 // assignment operator.
9711 // C++2a adds back these operators if the lambda has no lambda-capture.
9715 if (Diagnose)
9716 Diag(RD->getLocation(), diag::note_lambda_decl);
9717 return true;
9718 }
9719
9720 // For an anonymous struct or union, the copy and assignment special members
9721 // will never be used, so skip the check. For an anonymous union declared at
9722 // namespace scope, the constructor and destructor are used.
9725 return false;
9726
9727 // C++11 [class.copy]p7, p18:
9728 // If the class definition declares a move constructor or move assignment
9729 // operator, an implicitly declared copy constructor or copy assignment
9730 // operator is defined as deleted.
9733 CXXMethodDecl *UserDeclaredMove = nullptr;
9734
9735 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9736 // deletion of the corresponding copy operation, not both copy operations.
9737 // MSVC 2015 has adopted the standards conforming behavior.
9738 bool DeletesOnlyMatchingCopy =
9739 getLangOpts().MSVCCompat &&
9741
9743 (!DeletesOnlyMatchingCopy ||
9745 if (!Diagnose) return true;
9746
9747 // Find any user-declared move constructor.
9748 for (auto *I : RD->ctors()) {
9749 if (I->isMoveConstructor()) {
9750 UserDeclaredMove = I;
9751 break;
9752 }
9753 }
9754 assert(UserDeclaredMove);
9755 } else if (RD->hasUserDeclaredMoveAssignment() &&
9756 (!DeletesOnlyMatchingCopy ||
9758 if (!Diagnose) return true;
9759
9760 // Find any user-declared move assignment operator.
9761 for (auto *I : RD->methods()) {
9762 if (I->isMoveAssignmentOperator()) {
9763 UserDeclaredMove = I;
9764 break;
9765 }
9766 }
9767 assert(UserDeclaredMove);
9768 }
9769
9770 if (UserDeclaredMove) {
9771 Diag(UserDeclaredMove->getLocation(),
9772 diag::note_deleted_copy_user_declared_move)
9773 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9774 << UserDeclaredMove->isMoveAssignmentOperator();
9775 return true;
9776 }
9777 }
9778
9779 // Do access control from the special member function
9780 ContextRAII MethodContext(*this, MD);
9781
9782 // C++11 [class.dtor]p5:
9783 // -- for a virtual destructor, lookup of the non-array deallocation function
9784 // results in an ambiguity or in a function that is deleted or inaccessible
9785 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9786 FunctionDecl *OperatorDelete = nullptr;
9787 DeclarationName Name =
9789 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9790 OperatorDelete, /*Diagnose*/false)) {
9791 if (Diagnose)
9792 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9793 return true;
9794 }
9795 }
9796
9797 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9798
9799 // Per DR1611, do not consider virtual bases of constructors of abstract
9800 // classes, since we are not going to construct them.
9801 // Per DR1658, do not consider virtual bases of destructors of abstract
9802 // classes either.
9803 // Per DR2180, for assignment operators we only assign (and thus only
9804 // consider) direct bases.
9805 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9806 : SMI.VisitPotentiallyConstructedBases))
9807 return true;
9808
9809 if (SMI.shouldDeleteForAllConstMembers())
9810 return true;
9811
9812 if (getLangOpts().CUDA) {
9813 // We should delete the special member in CUDA mode if target inference
9814 // failed.
9815 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9816 // is treated as certain special member, which may not reflect what special
9817 // member MD really is. However inferTargetForImplicitSpecialMember
9818 // expects CSM to match MD, therefore recalculate CSM.
9819 assert(ICI || CSM == getSpecialMember(MD));
9820 auto RealCSM = CSM;
9821 if (ICI)
9822 RealCSM = getSpecialMember(MD);
9823
9824 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9825 SMI.ConstArg, Diagnose);
9826 }
9827
9828 return false;
9829}
9830
9833 assert(DFK && "not a defaultable function");
9834 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9835
9836 if (DFK.isSpecialMember()) {
9837 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9838 nullptr, /*Diagnose=*/true);
9839 } else {
9840 DefaultedComparisonAnalyzer(
9841 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9842 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9843 .visit();
9844 }
9845}
9846
9847/// Perform lookup for a special member of the specified kind, and determine
9848/// whether it is trivial. If the triviality can be determined without the
9849/// lookup, skip it. This is intended for use when determining whether a
9850/// special member of a containing object is trivial, and thus does not ever
9851/// perform overload resolution for default constructors.
9852///
9853/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9854/// member that was most likely to be intended to be trivial, if any.
9855///
9856/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9857/// determine whether the special member is trivial.
9859 CXXSpecialMemberKind CSM, unsigned Quals,
9860 bool ConstRHS,
9862 CXXMethodDecl **Selected) {
9863 if (Selected)
9864 *Selected = nullptr;
9865
9866 switch (CSM) {
9868 llvm_unreachable("not a special member");
9869
9871 // C++11 [class.ctor]p5:
9872 // A default constructor is trivial if:
9873 // - all the [direct subobjects] have trivial default constructors
9874 //
9875 // Note, no overload resolution is performed in this case.
9877 return true;
9878
9879 if (Selected) {
9880 // If there's a default constructor which could have been trivial, dig it
9881 // out. Otherwise, if there's any user-provided default constructor, point
9882 // to that as an example of why there's not a trivial one.
9883 CXXConstructorDecl *DefCtor = nullptr;
9886 for (auto *CI : RD->ctors()) {
9887 if (!CI->isDefaultConstructor())
9888 continue;
9889 DefCtor = CI;
9890 if (!DefCtor->isUserProvided())
9891 break;
9892 }
9893
9894 *Selected = DefCtor;
9895 }
9896
9897 return false;
9898
9900 // C++11 [class.dtor]p5:
9901 // A destructor is trivial if:
9902 // - all the direct [subobjects] have trivial destructors
9903 if (RD->hasTrivialDestructor() ||
9906 return true;
9907
9908 if (Selected) {
9909 if (RD->needsImplicitDestructor())
9911 *Selected = RD->getDestructor();
9912 }
9913
9914 return false;
9915
9917 // C++11 [class.copy]p12:
9918 // A copy constructor is trivial if:
9919 // - the constructor selected to copy each direct [subobject] is trivial
9920 if (RD->hasTrivialCopyConstructor() ||
9923 if (Quals == Qualifiers::Const)
9924 // We must either select the trivial copy constructor or reach an
9925 // ambiguity; no need to actually perform overload resolution.
9926 return true;
9927 } else if (!Selected) {
9928 return false;
9929 }
9930 // In C++98, we are not supposed to perform overload resolution here, but we
9931 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9932 // cases like B as having a non-trivial copy constructor:
9933 // struct A { template<typename T> A(T&); };
9934 // struct B { mutable A a; };
9935 goto NeedOverloadResolution;
9936
9938 // C++11 [class.copy]p25:
9939 // A copy assignment operator is trivial if:
9940 // - the assignment operator selected to copy each direct [subobject] is
9941 // trivial
9942 if (RD->hasTrivialCopyAssignment()) {
9943 if (Quals == Qualifiers::Const)
9944 return true;
9945 } else if (!Selected) {
9946 return false;
9947 }
9948 // In C++98, we are not supposed to perform overload resolution here, but we
9949 // treat that as a language defect.
9950 goto NeedOverloadResolution;
9951
9954 NeedOverloadResolution:
9956 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9957
9958 // The standard doesn't describe how to behave if the lookup is ambiguous.
9959 // We treat it as not making the member non-trivial, just like the standard
9960 // mandates for the default constructor. This should rarely matter, because
9961 // the member will also be deleted.
9963 return true;
9964
9965 if (!SMOR.getMethod()) {
9966 assert(SMOR.getKind() ==
9968 return false;
9969 }
9970
9971 // We deliberately don't check if we found a deleted special member. We're
9972 // not supposed to!
9973 if (Selected)
9974 *Selected = SMOR.getMethod();
9975
9976 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9979 return SMOR.getMethod()->isTrivialForCall();
9980 return SMOR.getMethod()->isTrivial();
9981 }
9982
9983 llvm_unreachable("unknown special method kind");
9984}
9985
9987 for (auto *CI : RD->ctors())
9988 if (!CI->isImplicit())
9989 return CI;
9990
9991 // Look for constructor templates.
9993 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9994 if (CXXConstructorDecl *CD =
9995 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9996 return CD;
9997 }
9998
9999 return nullptr;
10000}
10001
10002/// The kind of subobject we are checking for triviality. The values of this
10003/// enumeration are used in diagnostics.
10005 /// The subobject is a base class.
10007 /// The subobject is a non-static data member.
10009 /// The object is actually the complete object.
10012
10013/// Check whether the special member selected for a given type would be trivial.
10015 QualType SubType, bool ConstRHS,
10019 bool Diagnose) {
10020 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10021 if (!SubRD)
10022 return true;
10023
10024 CXXMethodDecl *Selected;
10025 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10026 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10027 return true;
10028
10029 if (Diagnose) {
10030 if (ConstRHS)
10031 SubType.addConst();
10032
10033 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10034 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10035 << Kind << SubType.getUnqualifiedType();
10037 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10038 } else if (!Selected)
10039 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10040 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
10041 << SubType;
10042 else if (Selected->isUserProvided()) {
10043 if (Kind == TSK_CompleteObject)
10044 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10045 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10046 else {
10047 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10048 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10049 S.Diag(Selected->getLocation(), diag::note_declared_at);
10050 }
10051 } else {
10052 if (Kind != TSK_CompleteObject)
10053 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10054 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10055
10056 // Explain why the defaulted or deleted special member isn't trivial.
10058 Diagnose);
10059 }
10060 }
10061
10062 return false;
10063}
10064
10065/// Check whether the members of a class type allow a special member to be
10066/// trivial.
10068 CXXSpecialMemberKind CSM, bool ConstArg,
10070 bool Diagnose) {
10071 for (const auto *FI : RD->fields()) {
10072 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10073 continue;
10074
10075 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10076
10077 // Pretend anonymous struct or union members are members of this class.
10078 if (FI->isAnonymousStructOrUnion()) {
10079 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10080 CSM, ConstArg, TAH, Diagnose))
10081 return false;
10082 continue;
10083 }
10084
10085 // C++11 [class.ctor]p5:
10086 // A default constructor is trivial if [...]
10087 // -- no non-static data member of its class has a
10088 // brace-or-equal-initializer
10090 FI->hasInClassInitializer()) {
10091 if (Diagnose)
10092 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10093 << FI;
10094 return false;
10095 }
10096
10097 // Objective C ARC 4.3.5:
10098 // [...] nontrivally ownership-qualified types are [...] not trivially
10099 // default constructible, copy constructible, move constructible, copy
10100 // assignable, move assignable, or destructible [...]
10101 if (FieldType.hasNonTrivialObjCLifetime()) {
10102 if (Diagnose)
10103 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10104 << RD << FieldType.getObjCLifetime();
10105 return false;
10106 }
10107
10108 bool ConstRHS = ConstArg && !FI->isMutable();
10109 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10110 CSM, TSK_Field, TAH, Diagnose))
10111 return false;
10112 }
10113
10114 return true;
10115}
10116
10120
10121 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10123 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10125 /*Diagnose*/true);
10126}
10127
10129 TrivialABIHandling TAH, bool Diagnose) {
10130 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10131 "not special enough");
10132
10133 CXXRecordDecl *RD = MD->getParent();
10134
10135 bool ConstArg = false;
10136
10137 // C++11 [class.copy]p12, p25: [DR1593]
10138 // A [special member] is trivial if [...] its parameter-type-list is
10139 // equivalent to the parameter-type-list of an implicit declaration [...]
10140 switch (CSM) {
10143 // Trivial default constructors and destructors cannot have parameters.
10144 break;
10145
10148 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10149 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10150
10151 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10152 // if they are not user-provided and their parameter-type-list is equivalent
10153 // to the parameter-type-list of an implicit declaration. This maintains the
10154 // behavior before dr2171 was implemented.
10155 //
10156 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10157 // trivial, if they are not user-provided, regardless of the qualifiers on
10158 // the reference type.
10159 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10161 if (!RT ||
10163 ClangABICompat14)) {
10164 if (Diagnose)
10165 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10166 << Param0->getSourceRange() << Param0->getType()
10169 return false;
10170 }
10171
10172 ConstArg = RT->getPointeeType().isConstQualified();
10173 break;
10174 }
10175
10178 // Trivial move operations always have non-cv-qualified parameters.
10179 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10180 const RValueReferenceType *RT =
10181 Param0->getType()->getAs<RValueReferenceType>();
10182 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10183 if (Diagnose)
10184 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10185 << Param0->getSourceRange() << Param0->getType()
10187 return false;
10188 }
10189 break;
10190 }
10191
10193 llvm_unreachable("not a special member");
10194 }
10195
10196 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10197 if (Diagnose)
10199 diag::note_nontrivial_default_arg)
10201 return false;
10202 }
10203 if (MD->isVariadic()) {
10204 if (Diagnose)
10205 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10206 return false;
10207 }
10208
10209 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10210 // A copy/move [constructor or assignment operator] is trivial if
10211 // -- the [member] selected to copy/move each direct base class subobject
10212 // is trivial
10213 //
10214 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10215 // A [default constructor or destructor] is trivial if
10216 // -- all the direct base classes have trivial [default constructors or
10217 // destructors]
10218 for (const auto &BI : RD->bases())
10219 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10220 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10221 return false;
10222
10223 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10224 // A copy/move [constructor or assignment operator] for a class X is
10225 // trivial if
10226 // -- for each non-static data member of X that is of class type (or array
10227 // thereof), the constructor selected to copy/move that member is
10228 // trivial
10229 //
10230 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10231 // A [default constructor or destructor] is trivial if
10232 // -- for all of the non-static data members of its class that are of class
10233 // type (or array thereof), each such class has a trivial [default
10234 // constructor or destructor]
10235 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10236 return false;
10237
10238 // C++11 [class.dtor]p5:
10239 // A destructor is trivial if [...]
10240 // -- the destructor is not virtual
10241 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10242 if (Diagnose)
10243 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10244 return false;
10245 }
10246
10247 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10248 // A [special member] for class X is trivial if [...]
10249 // -- class X has no virtual functions and no virtual base classes
10251 MD->getParent()->isDynamicClass()) {
10252 if (!Diagnose)
10253 return false;
10254
10255 if (RD->getNumVBases()) {
10256 // Check for virtual bases. We already know that the corresponding
10257 // member in all bases is trivial, so vbases must all be direct.
10258 CXXBaseSpecifier &BS = *RD->vbases_begin();
10259 assert(BS.isVirtual());
10260 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10261 return false;
10262 }
10263
10264 // Must have a virtual method.
10265 for (const auto *MI : RD->methods()) {
10266 if (MI->isVirtual()) {
10267 SourceLocation MLoc = MI->getBeginLoc();
10268 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10269 return false;
10270 }
10271 }
10272
10273 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10274 }
10275
10276 // Looks like it's trivial!
10277 return true;
10278}
10279
10280namespace {
10281struct FindHiddenVirtualMethod {
10282 Sema *S;
10283 CXXMethodDecl *Method;
10284 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10285 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10286
10287private:
10288 /// Check whether any most overridden method from MD in Methods
10289 static bool CheckMostOverridenMethods(
10290 const CXXMethodDecl *MD,
10291 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10292 if (MD->size_overridden_methods() == 0)
10293 return Methods.count(MD->getCanonicalDecl());
10294 for (const CXXMethodDecl *O : MD->overridden_methods())
10295 if (CheckMostOverridenMethods(O, Methods))
10296 return true;
10297 return false;
10298 }
10299
10300public:
10301 /// Member lookup function that determines whether a given C++
10302 /// method overloads virtual methods in a base class without overriding any,
10303 /// to be used with CXXRecordDecl::lookupInBases().
10304 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10305 RecordDecl *BaseRecord =
10306 Specifier->getType()->castAs<RecordType>()->getDecl();
10307
10308 DeclarationName Name = Method->getDeclName();
10309 assert(Name.getNameKind() == DeclarationName::Identifier);
10310
10311 bool foundSameNameMethod = false;
10312 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10313 for (Path.Decls = BaseRecord->lookup(Name).begin();
10314 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10315 NamedDecl *D = *Path.Decls;
10316 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10317 MD = MD->getCanonicalDecl();
10318 foundSameNameMethod = true;
10319 // Interested only in hidden virtual methods.
10320 if (!MD->isVirtual())
10321 continue;
10322 // If the method we are checking overrides a method from its base
10323 // don't warn about the other overloaded methods. Clang deviates from
10324 // GCC by only diagnosing overloads of inherited virtual functions that
10325 // do not override any other virtual functions in the base. GCC's
10326 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10327 // function from a base class. These cases may be better served by a
10328 // warning (not specific to virtual functions) on call sites when the
10329 // call would select a different function from the base class, were it
10330 // visible.
10331 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10332 if (!S->IsOverload(Method, MD, false))
10333 return true;
10334 // Collect the overload only if its hidden.
10335 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10336 overloadedMethods.push_back(MD);
10337 }
10338 }
10339
10340 if (foundSameNameMethod)
10341 OverloadedMethods.append(overloadedMethods.begin(),
10342 overloadedMethods.end());
10343 return foundSameNameMethod;
10344 }
10345};
10346} // end anonymous namespace
10347
10348/// Add the most overridden methods from MD to Methods
10350 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10351 if (MD->size_overridden_methods() == 0)
10352 Methods.insert(MD->getCanonicalDecl());
10353 else
10354 for (const CXXMethodDecl *O : MD->overridden_methods())
10355 AddMostOverridenMethods(O, Methods);
10356}
10357
10359 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10360 if (!MD->getDeclName().isIdentifier())
10361 return;
10362
10363 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10364 /*bool RecordPaths=*/false,
10365 /*bool DetectVirtual=*/false);
10366 FindHiddenVirtualMethod FHVM;
10367 FHVM.Method = MD;
10368 FHVM.S = this;
10369
10370 // Keep the base methods that were overridden or introduced in the subclass
10371 // by 'using' in a set. A base method not in this set is hidden.
10372 CXXRecordDecl *DC = MD->getParent();
10374 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10375 NamedDecl *ND = *I;
10376 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10377 ND = shad->getTargetDecl();
10378 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10379 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10380 }
10381
10382 if (DC->lookupInBases(FHVM, Paths))
10383 OverloadedMethods = FHVM.OverloadedMethods;
10384}
10385
10387 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10388 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10389 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10391 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10392 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10393 Diag(overloadedMD->getLocation(), PD);
10394 }
10395}
10396
10398 if (MD->isInvalidDecl())
10399 return;
10400
10401 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10402 return;
10403
10404 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10405 FindHiddenVirtualMethods(MD, OverloadedMethods);
10406 if (!OverloadedMethods.empty()) {
10407 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10408 << MD << (OverloadedMethods.size() > 1);
10409
10410 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10411 }
10412}
10413
10415 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10416 // No diagnostics if this is a template instantiation.
10418 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10419 diag::ext_cannot_use_trivial_abi) << &RD;
10420 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10421 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10422 }
10423 RD.dropAttr<TrivialABIAttr>();
10424 };
10425
10426 // Ill-formed if the copy and move constructors are deleted.
10427 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10428 // If the type is dependent, then assume it might have
10429 // implicit copy or move ctor because we won't know yet at this point.
10430 if (RD.isDependentType())
10431 return true;
10434 return true;
10437 return true;
10438 for (const CXXConstructorDecl *CD : RD.ctors())
10439 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10440 return true;
10441 return false;
10442 };
10443
10444 if (!HasNonDeletedCopyOrMoveConstructor()) {
10445 PrintDiagAndRemoveAttr(0);
10446 return;
10447 }
10448
10449 // Ill-formed if the struct has virtual functions.
10450 if (RD.isPolymorphic()) {
10451 PrintDiagAndRemoveAttr(1);
10452 return;
10453 }
10454
10455 for (const auto &B : RD.bases()) {
10456 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10457 // virtual base.
10458 if (!B.getType()->isDependentType() &&
10459 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10460 PrintDiagAndRemoveAttr(2);
10461 return;
10462 }
10463
10464 if (B.isVirtual()) {
10465 PrintDiagAndRemoveAttr(3);
10466 return;
10467 }
10468 }
10469
10470 for (const auto *FD : RD.fields()) {
10471 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10472 // non-trivial for the purpose of calls.
10473 QualType FT = FD->getType();
10475 PrintDiagAndRemoveAttr(4);
10476 return;
10477 }
10478
10479 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10480 if (!RT->isDependentType() &&
10481 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10482 PrintDiagAndRemoveAttr(5);
10483 return;
10484 }
10485 }
10486}
10487
10489 CXXRecordDecl &RD) {
10491 diag::err_incomplete_type_vtable_pointer_auth))
10492 return;
10493
10494 const CXXRecordDecl *PrimaryBase = &RD;
10495 if (PrimaryBase->hasAnyDependentBases())
10496 return;
10497
10498 while (1) {
10499 assert(PrimaryBase);
10500 const CXXRecordDecl *Base = nullptr;
10501 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10502 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10503 continue;
10504 Base = BasePtr.getType()->getAsCXXRecordDecl();
10505 break;
10506 }
10507 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10508 break;
10509 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10510 diag::err_non_top_level_vtable_pointer_auth)
10511 << &RD << Base;
10512 PrimaryBase = Base;
10513 }
10514
10515 if (!RD.isPolymorphic())
10516 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10517 diag::err_non_polymorphic_vtable_pointer_auth)
10518 << &RD;
10519}
10520
10523 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10524 if (!TagDecl)
10525 return;
10526
10528
10529 for (const ParsedAttr &AL : AttrList) {
10530 if (AL.getKind() != ParsedAttr::AT_Visibility)
10531 continue;
10532 AL.setInvalid();
10533 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10534 }
10535
10536 ActOnFields(S, RLoc, TagDecl,
10538 // strict aliasing violation!
10539 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10540 FieldCollector->getCurNumFields()),
10541 LBrac, RBrac, AttrList);
10542
10543 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10544}
10545
10546/// Find the equality comparison functions that should be implicitly declared
10547/// in a given class definition, per C++2a [class.compare.default]p3.
10549 ASTContext &Ctx, CXXRecordDecl *RD,
10551 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10552 if (!RD->lookup(EqEq).empty())
10553 // Member operator== explicitly declared: no implicit operator==s.
10554 return;
10555
10556 // Traverse friends looking for an '==' or a '<=>'.
10557 for (FriendDecl *Friend : RD->friends()) {
10558 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10559 if (!FD) continue;
10560
10561 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10562 // Friend operator== explicitly declared: no implicit operator==s.
10563 Spaceships.clear();
10564 return;
10565 }
10566
10567 if (FD->getOverloadedOperator() == OO_Spaceship &&
10569 Spaceships.push_back(FD);
10570 }
10571
10572 // Look for members named 'operator<=>'.
10573 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10574 for (NamedDecl *ND : RD->lookup(Cmp)) {
10575 // Note that we could find a non-function here (either a function template
10576 // or a using-declaration). Neither case results in an implicit
10577 // 'operator=='.
10578 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10579 if (FD->isExplicitlyDefaulted())
10580 Spaceships.push_back(FD);
10581 }
10582}
10583
10585 // Don't add implicit special members to templated classes.
10586 // FIXME: This means unqualified lookups for 'operator=' within a class
10587 // template don't work properly.
10588 if (!ClassDecl->isDependentType()) {
10589 if (ClassDecl->needsImplicitDefaultConstructor()) {
10591
10592 if (ClassDecl->hasInheritedConstructor())
10594 }
10595
10596 if (ClassDecl->needsImplicitCopyConstructor()) {
10598
10599 // If the properties or semantics of the copy constructor couldn't be
10600 // determined while the class was being declared, force a declaration
10601 // of it now.
10603 ClassDecl->hasInheritedConstructor())
10605 // For the MS ABI we need to know whether the copy ctor is deleted. A
10606 // prerequisite for deleting the implicit copy ctor is that the class has
10607 // a move ctor or move assignment that is either user-declared or whose
10608 // semantics are inherited from a subobject. FIXME: We should provide a
10609 // more direct way for CodeGen to ask whether the constructor was deleted.
10610 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10611 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10613 ClassDecl->hasUserDeclaredMoveAssignment() ||
10616 }
10617
10618 if (getLangOpts().CPlusPlus11 &&
10619 ClassDecl->needsImplicitMoveConstructor()) {
10621
10623 ClassDecl->hasInheritedConstructor())
10625 }
10626
10627 if (ClassDecl->needsImplicitCopyAssignment()) {
10629
10630 // If we have a dynamic class, then the copy assignment operator may be
10631 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10632 // it shows up in the right place in the vtable and that we diagnose
10633 // problems with the implicit exception specification.
10634 if (ClassDecl->isDynamicClass() ||
10636 ClassDecl->hasInheritedAssignment())
10638 }
10639
10640 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10642
10643 // Likewise for the move assignment operator.
10644 if (ClassDecl->isDynamicClass() ||
10646 ClassDecl->hasInheritedAssignment())
10648 }
10649
10650 if (ClassDecl->needsImplicitDestructor()) {
10652
10653 // If we have a dynamic class, then the destructor may be virtual, so we
10654 // have to declare the destructor immediately. This ensures that, e.g., it
10655 // shows up in the right place in the vtable and that we diagnose problems
10656 // with the implicit exception specification.
10657 if (ClassDecl->isDynamicClass() ||
10659 DeclareImplicitDestructor(ClassDecl);
10660 }
10661 }
10662
10663 // C++2a [class.compare.default]p3:
10664 // If the member-specification does not explicitly declare any member or
10665 // friend named operator==, an == operator function is declared implicitly
10666 // for each defaulted three-way comparison operator function defined in
10667 // the member-specification
10668 // FIXME: Consider doing this lazily.
10669 // We do this during the initial parse for a class template, not during
10670 // instantiation, so that we can handle unqualified lookups for 'operator=='
10671 // when parsing the template.
10673 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10675 DefaultedSpaceships);
10676 for (auto *FD : DefaultedSpaceships)
10677 DeclareImplicitEqualityComparison(ClassDecl, FD);
10678 }
10679}
10680
10681unsigned
10683 llvm::function_ref<Scope *()> EnterScope) {
10684 if (!D)
10685 return 0;
10687
10688 // In order to get name lookup right, reenter template scopes in order from
10689 // outermost to innermost.
10691 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10692
10693 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10694 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10695 ParameterLists.push_back(DD->getTemplateParameterList(i));
10696
10697 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10698 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10699 ParameterLists.push_back(FTD->getTemplateParameters());
10700 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10701 LookupDC = VD->getDeclContext();
10702
10704 ParameterLists.push_back(VTD->getTemplateParameters());
10705 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10706 ParameterLists.push_back(PSD->getTemplateParameters());
10707 }
10708 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10709 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10710 ParameterLists.push_back(TD->getTemplateParameterList(i));
10711
10712 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10714 ParameterLists.push_back(CTD->getTemplateParameters());
10715 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10716 ParameterLists.push_back(PSD->getTemplateParameters());
10717 }
10718 }
10719 // FIXME: Alias declarations and concepts.
10720
10721 unsigned Count = 0;
10722 Scope *InnermostTemplateScope = nullptr;
10723 for (TemplateParameterList *Params : ParameterLists) {
10724 // Ignore explicit specializations; they don't contribute to the template
10725 // depth.
10726 if (Params->size() == 0)
10727 continue;
10728
10729 InnermostTemplateScope = EnterScope();
10730 for (NamedDecl *Param : *Params) {
10731 if (Param->getDeclName()) {
10732 InnermostTemplateScope->AddDecl(Param);
10733 IdResolver.AddDecl(Param);
10734 }
10735 }
10736 ++Count;
10737 }
10738
10739 // Associate the new template scopes with the corresponding entities.
10740 if (InnermostTemplateScope) {
10741 assert(LookupDC && "no enclosing DeclContext for template lookup");
10742 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10743 }
10744
10745 return Count;
10746}
10747
10749 if (!RecordD) return;
10750 AdjustDeclIfTemplate(RecordD);
10751 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10753}
10754
10756 if (!RecordD) return;
10758}
10759
10761 if (!Param)
10762 return;
10763
10764 S->AddDecl(Param);
10765 if (Param->getDeclName())
10766 IdResolver.AddDecl(Param);
10767}
10768
10770}
10771
10772/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10773/// C++ method declaration. We're (re-)introducing the given
10774/// function parameter into scope for use in parsing later parts of
10775/// the method declaration. For example, we could see an
10776/// ActOnParamDefaultArgument event for this parameter.
10778 if (!ParamD)
10779 return;
10780
10781 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10782
10783 S->AddDecl(Param);
10784 if (Param->getDeclName())
10785 IdResolver.AddDecl(Param);
10786}
10787
10789 if (!MethodD)
10790 return;
10791
10792 AdjustDeclIfTemplate(MethodD);
10793
10794 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10795
10796 // Now that we have our default arguments, check the constructor
10797 // again. It could produce additional diagnostics or affect whether
10798 // the class has implicitly-declared destructors, among other
10799 // things.
10800 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10801 CheckConstructor(Constructor);
10802
10803 // Check the default arguments, which we may have added.
10804 if (!Method->isInvalidDecl())
10806}
10807
10808// Emit the given diagnostic for each non-address-space qualifier.
10809// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10810static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10811 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10812 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10813 bool DiagOccured = false;
10815 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10816 SourceLocation SL) {
10817 // This diagnostic should be emitted on any qualifier except an addr
10818 // space qualifier. However, forEachQualifier currently doesn't visit
10819 // addr space qualifiers, so there's no way to write this condition
10820 // right now; we just diagnose on everything.
10821 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10822 DiagOccured = true;
10823 });
10824 if (DiagOccured)
10825 D.setInvalidType();
10826 }
10827}
10828
10830 unsigned Kind) {
10831 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
10832 return;
10833
10834 DeclaratorChunk &Chunk = D.getTypeObject(D.getNumTypeObjects() - 1);
10835 if (Chunk.Kind == DeclaratorChunk::Paren ||
10837 return;
10838
10839 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
10840 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
10841 << Kind << Chunk.getSourceRange();
10842 D.setInvalidType();
10843}
10844
10846 StorageClass &SC) {
10847 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10848
10849 // C++ [class.ctor]p3:
10850 // A constructor shall not be virtual (10.3) or static (9.4). A
10851 // constructor can be invoked for a const, volatile or const
10852 // volatile object. A constructor shall not be declared const,
10853 // volatile, or const volatile (9.3.2).
10854 if (isVirtual) {
10855 if (!D.isInvalidType())
10856 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10857 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10858 << SourceRange(D.getIdentifierLoc());
10859 D.setInvalidType();
10860 }
10861 if (SC == SC_Static) {
10862 if (!D.isInvalidType())
10863 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10864 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10865 << SourceRange(D.getIdentifierLoc());
10866 D.setInvalidType();
10867 SC = SC_None;
10868 }
10869
10870 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10872 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10873 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10874 D.getDeclSpec().getRestrictSpecLoc(),
10875 D.getDeclSpec().getAtomicSpecLoc());
10876 D.setInvalidType();
10877 }
10878
10879 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10880 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
10881
10882 // C++0x [class.ctor]p4:
10883 // A constructor shall not be declared with a ref-qualifier.
10884 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10885 if (FTI.hasRefQualifier()) {
10886 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10889 D.setInvalidType();
10890 }
10891
10892 // Rebuild the function type "R" without any type qualifiers (in
10893 // case any of the errors above fired) and with "void" as the
10894 // return type, since constructors don't have return types.
10895 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10896 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10897 return R;
10898
10900 EPI.TypeQuals = Qualifiers();
10901 EPI.RefQualifier = RQ_None;
10902
10903 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10904}
10905
10907 CXXRecordDecl *ClassDecl
10908 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10909 if (!ClassDecl)
10910 return Constructor->setInvalidDecl();
10911
10912 // C++ [class.copy]p3:
10913 // A declaration of a constructor for a class X is ill-formed if
10914 // its first parameter is of type (optionally cv-qualified) X and
10915 // either there are no other parameters or else all other
10916 // parameters have default arguments.
10917 if (!Constructor->isInvalidDecl() &&
10918 Constructor->hasOneParamOrDefaultArgs() &&
10919 Constructor->getTemplateSpecializationKind() !=
10921 QualType ParamType = Constructor->getParamDecl(0)->getType();
10922 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10923 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10924 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10925 const char *ConstRef
10926 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10927 : " const &";
10928 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10929 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10930
10931 // FIXME: Rather that making the constructor invalid, we should endeavor
10932 // to fix the type.
10933 Constructor->setInvalidDecl();
10934 }
10935 }
10936}
10937
10939 CXXRecordDecl *RD = Destructor->getParent();
10940
10941 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10943
10944 if (!Destructor->isImplicit())
10945 Loc = Destructor->getLocation();
10946 else
10947 Loc = RD->getLocation();
10948
10949 // If we have a virtual destructor, look up the deallocation function
10950 if (FunctionDecl *OperatorDelete =
10952 Expr *ThisArg = nullptr;
10953
10954 // If the notional 'delete this' expression requires a non-trivial
10955 // conversion from 'this' to the type of a destroying operator delete's
10956 // first parameter, perform that conversion now.
10957 if (OperatorDelete->isDestroyingOperatorDelete()) {
10958 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10959 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10960 // C++ [class.dtor]p13:
10961 // ... as if for the expression 'delete this' appearing in a
10962 // non-virtual destructor of the destructor's class.
10963 ContextRAII SwitchContext(*this, Destructor);
10964 ExprResult This =
10965 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10966 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10967 This = PerformImplicitConversion(This.get(), ParamType,
10969 if (This.isInvalid()) {
10970 // FIXME: Register this as a context note so that it comes out
10971 // in the right order.
10972 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10973 return true;
10974 }
10975 ThisArg = This.get();
10976 }
10977 }
10978
10979 DiagnoseUseOfDecl(OperatorDelete, Loc);
10980 MarkFunctionReferenced(Loc, OperatorDelete);
10981 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10982 }
10983 }
10984
10985 return false;
10986}
10987
10989 StorageClass& SC) {
10990 // C++ [class.dtor]p1:
10991 // [...] A typedef-name that names a class is a class-name
10992 // (7.1.3); however, a typedef-name that names a class shall not
10993 // be used as the identifier in the declarator for a destructor
10994 // declaration.
10995 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10996 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10997 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10998 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10999 else if (const TemplateSpecializationType *TST =
11000 DeclaratorType->getAs<TemplateSpecializationType>())
11001 if (TST->isTypeAlias())
11002 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11003 << DeclaratorType << 1;
11004
11005 // C++ [class.dtor]p2:
11006 // A destructor is used to destroy objects of its class type. A
11007 // destructor takes no parameters, and no return type can be
11008 // specified for it (not even void). The address of a destructor
11009 // shall not be taken. A destructor shall not be static. A
11010 // destructor can be invoked for a const, volatile or const
11011 // volatile object. A destructor shall not be declared const,
11012 // volatile or const volatile (9.3.2).
11013 if (SC == SC_Static) {
11014 if (!D.isInvalidType())
11015 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11016 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11017 << SourceRange(D.getIdentifierLoc())
11018 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11019
11020 SC = SC_None;
11021 }
11022 if (!D.isInvalidType()) {
11023 // Destructors don't have return types, but the parser will
11024 // happily parse something like:
11025 //
11026 // class X {
11027 // float ~X();
11028 // };
11029 //
11030 // The return type will be eliminated later.
11031 if (D.getDeclSpec().hasTypeSpecifier())
11032 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11033 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11034 << SourceRange(D.getIdentifierLoc());
11035 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11036 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11038 D.getDeclSpec().getConstSpecLoc(),
11039 D.getDeclSpec().getVolatileSpecLoc(),
11040 D.getDeclSpec().getRestrictSpecLoc(),
11041 D.getDeclSpec().getAtomicSpecLoc());
11042 D.setInvalidType();
11043 }
11044 }
11045
11046 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11047 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11048
11049 // C++0x [class.dtor]p2:
11050 // A destructor shall not be declared with a ref-qualifier.
11051 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11052 if (FTI.hasRefQualifier()) {
11053 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11056 D.setInvalidType();
11057 }
11058
11059 // Make sure we don't have any parameters.
11060 if (FTIHasNonVoidParameters(FTI)) {
11061 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11062
11063 // Delete the parameters.
11064 FTI.freeParams();
11065 D.setInvalidType();
11066 }
11067
11068 // Make sure the destructor isn't variadic.
11069 if (FTI.isVariadic) {
11070 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11071 D.setInvalidType();
11072 }
11073
11074 // Rebuild the function type "R" without any type qualifiers or
11075 // parameters (in case any of the errors above fired) and with
11076 // "void" as the return type, since destructors don't have return
11077 // types.
11078 if (!D.isInvalidType())
11079 return R;
11080
11081 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11083 EPI.Variadic = false;
11084 EPI.TypeQuals = Qualifiers();
11085 EPI.RefQualifier = RQ_None;
11086 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11087}
11088
11089static void extendLeft(SourceRange &R, SourceRange Before) {
11090 if (Before.isInvalid())
11091 return;
11092 R.setBegin(Before.getBegin());
11093 if (R.getEnd().isInvalid())
11094 R.setEnd(Before.getEnd());
11095}
11096
11097static void extendRight(SourceRange &R, SourceRange After) {
11098 if (After.isInvalid())
11099 return;
11100 if (R.getBegin().isInvalid())
11101 R.setBegin(After.getBegin());
11102 R.setEnd(After.getEnd());
11103}
11104
11106 StorageClass& SC) {
11107 // C++ [class.conv.fct]p1:
11108 // Neither parameter types nor return type can be specified. The
11109 // type of a conversion function (8.3.5) is "function taking no
11110 // parameter returning conversion-type-id."
11111 if (SC == SC_Static) {
11112 if (!D.isInvalidType())
11113 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11114 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11115 << D.getName().getSourceRange();
11116 D.setInvalidType();
11117 SC = SC_None;
11118 }
11119
11120 TypeSourceInfo *ConvTSI = nullptr;
11121 QualType ConvType =
11122 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11123
11124 const DeclSpec &DS = D.getDeclSpec();
11125 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11126 // Conversion functions don't have return types, but the parser will
11127 // happily parse something like:
11128 //
11129 // class X {
11130 // float operator bool();
11131 // };
11132 //
11133 // The return type will be changed later anyway.
11134 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11136 << SourceRange(D.getIdentifierLoc());
11137 D.setInvalidType();
11138 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11139 // It's also plausible that the user writes type qualifiers in the wrong
11140 // place, such as:
11141 // struct S { const operator int(); };
11142 // FIXME: we could provide a fixit to move the qualifiers onto the
11143 // conversion type.
11144 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11145 << SourceRange(D.getIdentifierLoc()) << 0;
11146 D.setInvalidType();
11147 }
11148 const auto *Proto = R->castAs<FunctionProtoType>();
11149 // Make sure we don't have any parameters.
11150 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11151 unsigned NumParam = Proto->getNumParams();
11152
11153 // [C++2b]
11154 // A conversion function shall have no non-object parameters.
11155 if (NumParam == 1) {
11156 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11157 if (const auto *First =
11158 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11159 First && First->isExplicitObjectParameter())
11160 NumParam--;
11161 }
11162
11163 if (NumParam != 0) {
11164 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11165 // Delete the parameters.
11166 FTI.freeParams();
11167 D.setInvalidType();
11168 } else if (Proto->isVariadic()) {
11169 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11170 D.setInvalidType();
11171 }
11172
11173 // Diagnose "&operator bool()" and other such nonsense. This
11174 // is actually a gcc extension which we don't support.
11175 if (Proto->getReturnType() != ConvType) {
11176 bool NeedsTypedef = false;
11177 SourceRange Before, After;
11178
11179 // Walk the chunks and extract information on them for our diagnostic.
11180 bool PastFunctionChunk = false;
11181 for (auto &Chunk : D.type_objects()) {
11182 switch (Chunk.Kind) {
11184 if (!PastFunctionChunk) {
11185 if (Chunk.Fun.HasTrailingReturnType) {
11186 TypeSourceInfo *TRT = nullptr;
11187 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11188 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11189 }
11190 PastFunctionChunk = true;
11191 break;
11192 }
11193 [[fallthrough]];
11195 NeedsTypedef = true;
11196 extendRight(After, Chunk.getSourceRange());
11197 break;
11198
11204 extendLeft(Before, Chunk.getSourceRange());
11205 break;
11206
11208 extendLeft(Before, Chunk.Loc);
11209 extendRight(After, Chunk.EndLoc);
11210 break;
11211 }
11212 }
11213
11214 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11215 After.isValid() ? After.getBegin() :
11216 D.getIdentifierLoc();
11217 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11218 DB << Before << After;
11219
11220 if (!NeedsTypedef) {
11221 DB << /*don't need a typedef*/0;
11222
11223 // If we can provide a correct fix-it hint, do so.
11224 if (After.isInvalid() && ConvTSI) {
11225 SourceLocation InsertLoc =
11227 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11229 InsertLoc, CharSourceRange::getTokenRange(Before))
11230 << FixItHint::CreateRemoval(Before);
11231 }
11232 } else if (!Proto->getReturnType()->isDependentType()) {
11233 DB << /*typedef*/1 << Proto->getReturnType();
11234 } else if (getLangOpts().CPlusPlus11) {
11235 DB << /*alias template*/2 << Proto->getReturnType();
11236 } else {
11237 DB << /*might not be fixable*/3;
11238 }
11239
11240 // Recover by incorporating the other type chunks into the result type.
11241 // Note, this does *not* change the name of the function. This is compatible
11242 // with the GCC extension:
11243 // struct S { &operator int(); } s;
11244 // int &r = s.operator int(); // ok in GCC
11245 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11246 ConvType = Proto->getReturnType();
11247 }
11248
11249 // C++ [class.conv.fct]p4:
11250 // The conversion-type-id shall not represent a function type nor
11251 // an array type.
11252 if (ConvType->isArrayType()) {
11253 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11254 ConvType = Context.getPointerType(ConvType);
11255 D.setInvalidType();
11256 } else if (ConvType->isFunctionType()) {
11257 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11258 ConvType = Context.getPointerType(ConvType);
11259 D.setInvalidType();
11260 }
11261
11262 // Rebuild the function type "R" without any parameters (in case any
11263 // of the errors above fired) and with the conversion type as the
11264 // return type.
11265 if (D.isInvalidType())
11266 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11267
11268 // C++0x explicit conversion operators.
11272 ? diag::warn_cxx98_compat_explicit_conversion_functions
11273 : diag::ext_explicit_conversion_functions)
11275}
11276
11278 assert(Conversion && "Expected to receive a conversion function declaration");
11279
11280 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11281
11282 // Make sure we aren't redeclaring the conversion function.
11283 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11284 // C++ [class.conv.fct]p1:
11285 // [...] A conversion function is never used to convert a
11286 // (possibly cv-qualified) object to the (possibly cv-qualified)
11287 // same object type (or a reference to it), to a (possibly
11288 // cv-qualified) base class of that type (or a reference to it),
11289 // or to (possibly cv-qualified) void.
11290 QualType ClassType
11292 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11293 ConvType = ConvTypeRef->getPointeeType();
11294 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11296 /* Suppress diagnostics for instantiations. */;
11297 else if (Conversion->size_overridden_methods() != 0)
11298 /* Suppress diagnostics for overriding virtual function in a base class. */;
11299 else if (ConvType->isRecordType()) {
11300 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11301 if (ConvType == ClassType)
11302 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11303 << ClassType;
11304 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11305 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11306 << ClassType << ConvType;
11307 } else if (ConvType->isVoidType()) {
11308 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11309 << ClassType << ConvType;
11310 }
11311
11312 if (FunctionTemplateDecl *ConversionTemplate =
11313 Conversion->getDescribedFunctionTemplate()) {
11314 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11315 ConvType = ConvTypePtr->getPointeeType();
11316 }
11317 if (ConvType->isUndeducedAutoType()) {
11318 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11319 << getReturnTypeLoc(Conversion).getSourceRange()
11320 << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11321 << /* in declaration of conversion function template= */ 24;
11322 }
11323
11324 return ConversionTemplate;
11325 }
11326
11327 return Conversion;
11328}
11329
11331 DeclarationName Name, QualType R) {
11332 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11333}
11334
11336 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11337}
11338
11340 DeclarationName Name, QualType R,
11341 bool IsLambda, DeclContext *DC) {
11342 if (!D.isFunctionDeclarator())
11343 return;
11344
11345 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11346 if (FTI.NumParams == 0)
11347 return;
11348 ParmVarDecl *ExplicitObjectParam = nullptr;
11349 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11350 const auto &ParamInfo = FTI.Params[Idx];
11351 if (!ParamInfo.Param)
11352 continue;
11353 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11354 if (!Param->isExplicitObjectParameter())
11355 continue;
11356 if (Idx == 0) {
11357 ExplicitObjectParam = Param;
11358 continue;
11359 } else {
11360 Diag(Param->getLocation(),
11361 diag::err_explicit_object_parameter_must_be_first)
11362 << IsLambda << Param->getSourceRange();
11363 }
11364 }
11365 if (!ExplicitObjectParam)
11366 return;
11367
11368 if (ExplicitObjectParam->hasDefaultArg()) {
11369 Diag(ExplicitObjectParam->getLocation(),
11370 diag::err_explicit_object_default_arg)
11371 << ExplicitObjectParam->getSourceRange();
11372 }
11373
11374 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11375 (D.getContext() == clang::DeclaratorContext::Member &&
11376 D.isStaticMember())) {
11377 Diag(ExplicitObjectParam->getBeginLoc(),
11378 diag::err_explicit_object_parameter_nonmember)
11379 << D.getSourceRange() << /*static=*/0 << IsLambda;
11380 D.setInvalidType();
11381 }
11382
11383 if (D.getDeclSpec().isVirtualSpecified()) {
11384 Diag(ExplicitObjectParam->getBeginLoc(),
11385 diag::err_explicit_object_parameter_nonmember)
11386 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11387 D.setInvalidType();
11388 }
11389
11390 // Friend declarations require some care. Consider:
11391 //
11392 // namespace N {
11393 // struct A{};
11394 // int f(A);
11395 // }
11396 //
11397 // struct S {
11398 // struct T {
11399 // int f(this T);
11400 // };
11401 //
11402 // friend int T::f(this T); // Allow this.
11403 // friend int f(this S); // But disallow this.
11404 // friend int N::f(this A); // And disallow this.
11405 // };
11406 //
11407 // Here, it seems to suffice to check whether the scope
11408 // specifier designates a class type.
11409 if (D.getDeclSpec().isFriendSpecified() &&
11410 !isa_and_present<CXXRecordDecl>(
11411 computeDeclContext(D.getCXXScopeSpec()))) {
11412 Diag(ExplicitObjectParam->getBeginLoc(),
11413 diag::err_explicit_object_parameter_nonmember)
11414 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11415 D.setInvalidType();
11416 }
11417
11418 if (IsLambda && FTI.hasMutableQualifier()) {
11419 Diag(ExplicitObjectParam->getBeginLoc(),
11420 diag::err_explicit_object_parameter_mutable)
11421 << D.getSourceRange();
11422 }
11423
11424 if (IsLambda)
11425 return;
11426
11427 if (!DC || !DC->isRecord()) {
11428 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11429 "should have been diagnosed already");
11430 return;
11431 }
11432
11433 // CWG2674: constructors and destructors cannot have explicit parameters.
11434 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11435 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11436 Diag(ExplicitObjectParam->getBeginLoc(),
11437 diag::err_explicit_object_parameter_constructor)
11438 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11439 << D.getSourceRange();
11440 D.setInvalidType();
11441 }
11442}
11443
11444namespace {
11445/// Utility class to accumulate and print a diagnostic listing the invalid
11446/// specifier(s) on a declaration.
11447struct BadSpecifierDiagnoser {
11448 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11449 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11450 ~BadSpecifierDiagnoser() {
11451 Diagnostic << Specifiers;
11452 }
11453
11454 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11455 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11456 }
11457 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11458 return check(SpecLoc,
11460 }
11461 void check(SourceLocation SpecLoc, const char *Spec) {
11462 if (SpecLoc.isInvalid()) return;
11463 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11464 if (!Specifiers.empty()) Specifiers += " ";
11465 Specifiers += Spec;
11466 }
11467
11468 Sema &S;
11470 std::string Specifiers;
11471};
11472}
11473
11475 StorageClass &SC) {
11476 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11477 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11478 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11479
11480 // C++ [temp.deduct.guide]p3:
11481 // A deduction-gide shall be declared in the same scope as the
11482 // corresponding class template.
11484 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11485 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11486 << GuidedTemplateDecl;
11487 NoteTemplateLocation(*GuidedTemplateDecl);
11488 }
11489
11490 auto &DS = D.getMutableDeclSpec();
11491 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11492 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11493 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11494 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11495 BadSpecifierDiagnoser Diagnoser(
11496 *this, D.getIdentifierLoc(),
11497 diag::err_deduction_guide_invalid_specifier);
11498
11499 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11500 DS.ClearStorageClassSpecs();
11501 SC = SC_None;
11502
11503 // 'explicit' is permitted.
11504 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11505 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11506 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11507 DS.ClearConstexprSpec();
11508
11509 Diagnoser.check(DS.getConstSpecLoc(), "const");
11510 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11511 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11512 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11513 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11514 DS.ClearTypeQualifiers();
11515
11516 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11517 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11518 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11519 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11520 DS.ClearTypeSpecType();
11521 }
11522
11523 if (D.isInvalidType())
11524 return true;
11525
11526 // Check the declarator is simple enough.
11527 bool FoundFunction = false;
11528 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11529 if (Chunk.Kind == DeclaratorChunk::Paren)
11530 continue;
11531 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11532 Diag(D.getDeclSpec().getBeginLoc(),
11533 diag::err_deduction_guide_with_complex_decl)
11534 << D.getSourceRange();
11535 break;
11536 }
11537 if (!Chunk.Fun.hasTrailingReturnType())
11538 return Diag(D.getName().getBeginLoc(),
11539 diag::err_deduction_guide_no_trailing_return_type);
11540
11541 // Check that the return type is written as a specialization of
11542 // the template specified as the deduction-guide's name.
11543 // The template name may not be qualified. [temp.deduct.guide]
11544 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11545 TypeSourceInfo *TSI = nullptr;
11546 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11547 assert(TSI && "deduction guide has valid type but invalid return type?");
11548 bool AcceptableReturnType = false;
11549 bool MightInstantiateToSpecialization = false;
11550 if (auto RetTST =
11552 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11553 bool TemplateMatches = Context.hasSameTemplateName(
11554 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11555
11557 SpecifiedName.getAsQualifiedTemplateName();
11558 assert(Qualifiers && "expected QualifiedTemplate");
11559 bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11560 Qualifiers->getQualifier() == nullptr;
11561 if (SimplyWritten && TemplateMatches)
11562 AcceptableReturnType = true;
11563 else {
11564 // This could still instantiate to the right type, unless we know it
11565 // names the wrong class template.
11566 auto *TD = SpecifiedName.getAsTemplateDecl();
11567 MightInstantiateToSpecialization =
11568 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11569 }
11570 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11571 MightInstantiateToSpecialization = true;
11572 }
11573
11574 if (!AcceptableReturnType)
11575 return Diag(TSI->getTypeLoc().getBeginLoc(),
11576 diag::err_deduction_guide_bad_trailing_return_type)
11577 << GuidedTemplate << TSI->getType()
11578 << MightInstantiateToSpecialization
11579 << TSI->getTypeLoc().getSourceRange();
11580
11581 // Keep going to check that we don't have any inner declarator pieces (we
11582 // could still have a function returning a pointer to a function).
11583 FoundFunction = true;
11584 }
11585
11586 if (D.isFunctionDefinition())
11587 // we can still create a valid deduction guide here.
11588 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11589 return false;
11590}
11591
11592//===----------------------------------------------------------------------===//
11593// Namespace Handling
11594//===----------------------------------------------------------------------===//
11595
11596/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11597/// reopened.
11600 IdentifierInfo *II, bool *IsInline,
11601 NamespaceDecl *PrevNS) {
11602 assert(*IsInline != PrevNS->isInline());
11603
11604 // 'inline' must appear on the original definition, but not necessarily
11605 // on all extension definitions, so the note should point to the first
11606 // definition to avoid confusion.
11607 PrevNS = PrevNS->getFirstDecl();
11608
11609 if (PrevNS->isInline())
11610 // The user probably just forgot the 'inline', so suggest that it
11611 // be added back.
11612 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11613 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11614 else
11615 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11616
11617 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11618 *IsInline = PrevNS->isInline();
11619}
11620
11621/// ActOnStartNamespaceDef - This is called at the start of a namespace
11622/// definition.
11624 SourceLocation InlineLoc,
11625 SourceLocation NamespaceLoc,
11626 SourceLocation IdentLoc, IdentifierInfo *II,
11627 SourceLocation LBrace,
11628 const ParsedAttributesView &AttrList,
11629 UsingDirectiveDecl *&UD, bool IsNested) {
11630 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11631 // For anonymous namespace, take the location of the left brace.
11632 SourceLocation Loc = II ? IdentLoc : LBrace;
11633 bool IsInline = InlineLoc.isValid();
11634 bool IsInvalid = false;
11635 bool IsStd = false;
11636 bool AddToKnown = false;
11637 Scope *DeclRegionScope = NamespcScope->getParent();
11638
11639 NamespaceDecl *PrevNS = nullptr;
11640 if (II) {
11641 // C++ [namespace.std]p7:
11642 // A translation unit shall not declare namespace std to be an inline
11643 // namespace (9.8.2).
11644 //
11645 // Precondition: the std namespace is in the file scope and is declared to
11646 // be inline
11647 auto DiagnoseInlineStdNS = [&]() {
11648 assert(IsInline && II->isStr("std") &&
11650 "Precondition of DiagnoseInlineStdNS not met");
11651 Diag(InlineLoc, diag::err_inline_namespace_std)
11652 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11653 IsInline = false;
11654 };
11655 // C++ [namespace.def]p2:
11656 // The identifier in an original-namespace-definition shall not
11657 // have been previously defined in the declarative region in
11658 // which the original-namespace-definition appears. The
11659 // identifier in an original-namespace-definition is the name of
11660 // the namespace. Subsequently in that declarative region, it is
11661 // treated as an original-namespace-name.
11662 //
11663 // Since namespace names are unique in their scope, and we don't
11664 // look through using directives, just look for any ordinary names
11665 // as if by qualified name lookup.
11666 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11667 RedeclarationKind::ForExternalRedeclaration);
11669 NamedDecl *PrevDecl =
11670 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11671 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11672
11673 if (PrevNS) {
11674 // This is an extended namespace definition.
11675 if (IsInline && II->isStr("std") &&
11677 DiagnoseInlineStdNS();
11678 else if (IsInline != PrevNS->isInline())
11679 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11680 &IsInline, PrevNS);
11681 } else if (PrevDecl) {
11682 // This is an invalid name redefinition.
11683 Diag(Loc, diag::err_redefinition_different_kind)
11684 << II;
11685 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11686 IsInvalid = true;
11687 // Continue on to push Namespc as current DeclContext and return it.
11688 } else if (II->isStr("std") &&
11690 if (IsInline)
11691 DiagnoseInlineStdNS();
11692 // This is the first "real" definition of the namespace "std", so update
11693 // our cache of the "std" namespace to point at this definition.
11694 PrevNS = getStdNamespace();
11695 IsStd = true;
11696 AddToKnown = !IsInline;
11697 } else {
11698 // We've seen this namespace for the first time.
11699 AddToKnown = !IsInline;
11700 }
11701 } else {
11702 // Anonymous namespaces.
11703
11704 // Determine whether the parent already has an anonymous namespace.
11706 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11707 PrevNS = TU->getAnonymousNamespace();
11708 } else {
11709 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11710 PrevNS = ND->getAnonymousNamespace();
11711 }
11712
11713 if (PrevNS && IsInline != PrevNS->isInline())
11714 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11715 &IsInline, PrevNS);
11716 }
11717
11719 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11720 if (IsInvalid)
11721 Namespc->setInvalidDecl();
11722
11723 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11724 AddPragmaAttributes(DeclRegionScope, Namespc);
11725 ProcessAPINotes(Namespc);
11726
11727 // FIXME: Should we be merging attributes?
11728 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11730
11731 if (IsStd)
11732 StdNamespace = Namespc;
11733 if (AddToKnown)
11734 KnownNamespaces[Namespc] = false;
11735
11736 if (II) {
11737 PushOnScopeChains(Namespc, DeclRegionScope);
11738 } else {
11739 // Link the anonymous namespace into its parent.
11741 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11742 TU->setAnonymousNamespace(Namespc);
11743 } else {
11744 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11745 }
11746
11747 CurContext->addDecl(Namespc);
11748
11749 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11750 // behaves as if it were replaced by
11751 // namespace unique { /* empty body */ }
11752 // using namespace unique;
11753 // namespace unique { namespace-body }
11754 // where all occurrences of 'unique' in a translation unit are
11755 // replaced by the same identifier and this identifier differs
11756 // from all other identifiers in the entire program.
11757
11758 // We just create the namespace with an empty name and then add an
11759 // implicit using declaration, just like the standard suggests.
11760 //
11761 // CodeGen enforces the "universally unique" aspect by giving all
11762 // declarations semantically contained within an anonymous
11763 // namespace internal linkage.
11764
11765 if (!PrevNS) {
11767 /* 'using' */ LBrace,
11768 /* 'namespace' */ SourceLocation(),
11769 /* qualifier */ NestedNameSpecifierLoc(),
11770 /* identifier */ SourceLocation(),
11771 Namespc,
11772 /* Ancestor */ Parent);
11773 UD->setImplicit();
11774 Parent->addDecl(UD);
11775 }
11776 }
11777
11778 ActOnDocumentableDecl(Namespc);
11779
11780 // Although we could have an invalid decl (i.e. the namespace name is a
11781 // redefinition), push it as current DeclContext and try to continue parsing.
11782 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11783 // for the namespace has the declarations that showed up in that particular
11784 // namespace definition.
11785 PushDeclContext(NamespcScope, Namespc);
11786 return Namespc;
11787}
11788
11789/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11790/// is a namespace alias, returns the namespace it points to.
11792 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11793 return AD->getNamespace();
11794 return dyn_cast_or_null<NamespaceDecl>(D);
11795}
11796
11798 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11799 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11800 Namespc->setRBraceLoc(RBrace);
11802 if (Namespc->hasAttr<VisibilityAttr>())
11803 PopPragmaVisibility(true, RBrace);
11804 // If this namespace contains an export-declaration, export it now.
11805 if (DeferredExportedNamespaces.erase(Namespc))
11807}
11808
11810 return cast_or_null<CXXRecordDecl>(
11812}
11813
11815 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11816}
11817
11819 return cast_or_null<NamespaceDecl>(
11821}
11822namespace {
11823
11824enum UnsupportedSTLSelect {
11825 USS_InvalidMember,
11826 USS_MissingMember,
11827 USS_NonTrivial,
11828 USS_Other
11829};
11830
11831struct InvalidSTLDiagnoser {
11832 Sema &S;
11834 QualType TyForDiags;
11835
11836 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11837 const VarDecl *VD = nullptr) {
11838 {
11839 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11840 << TyForDiags << ((int)Sel);
11841 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11842 assert(!Name.empty());
11843 D << Name;
11844 }
11845 }
11846 if (Sel == USS_InvalidMember) {
11847 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11848 << VD << VD->getSourceRange();
11849 }
11850 return QualType();
11851 }
11852};
11853} // namespace
11854
11858 assert(getLangOpts().CPlusPlus &&
11859 "Looking for comparison category type outside of C++.");
11860
11861 // Use an elaborated type for diagnostics which has a name containing the
11862 // prepended 'std' namespace but not any inline namespace names.
11863 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11864 auto *NNS =
11867 Info->getType());
11868 };
11869
11870 // Check if we've already successfully checked the comparison category type
11871 // before. If so, skip checking it again.
11873 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11874 // The only thing we need to check is that the type has a reachable
11875 // definition in the current context.
11876 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11877 return QualType();
11878
11879 return Info->getType();
11880 }
11881
11882 // If lookup failed
11883 if (!Info) {
11884 std::string NameForDiags = "std::";
11885 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11886 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11887 << NameForDiags << (int)Usage;
11888 return QualType();
11889 }
11890
11891 assert(Info->Kind == Kind);
11892 assert(Info->Record);
11893
11894 // Update the Record decl in case we encountered a forward declaration on our
11895 // first pass. FIXME: This is a bit of a hack.
11896 if (Info->Record->hasDefinition())
11897 Info->Record = Info->Record->getDefinition();
11898
11899 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11900 return QualType();
11901
11902 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11903
11904 if (!Info->Record->isTriviallyCopyable())
11905 return UnsupportedSTLError(USS_NonTrivial);
11906
11907 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11908 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11909 // Tolerate empty base classes.
11910 if (Base->isEmpty())
11911 continue;
11912 // Reject STL implementations which have at least one non-empty base.
11913 return UnsupportedSTLError();
11914 }
11915
11916 // Check that the STL has implemented the types using a single integer field.
11917 // This expectation allows better codegen for builtin operators. We require:
11918 // (1) The class has exactly one field.
11919 // (2) The field is an integral or enumeration type.
11920 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11921 if (std::distance(FIt, FEnd) != 1 ||
11922 !FIt->getType()->isIntegralOrEnumerationType()) {
11923 return UnsupportedSTLError();
11924 }
11925
11926 // Build each of the require values and store them in Info.
11927 for (ComparisonCategoryResult CCR :
11929 StringRef MemName = ComparisonCategories::getResultString(CCR);
11930 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11931
11932 if (!ValInfo)
11933 return UnsupportedSTLError(USS_MissingMember, MemName);
11934
11935 VarDecl *VD = ValInfo->VD;
11936 assert(VD && "should not be null!");
11937
11938 // Attempt to diagnose reasons why the STL definition of this type
11939 // might be foobar, including it failing to be a constant expression.
11940 // TODO Handle more ways the lookup or result can be invalid.
11941 if (!VD->isStaticDataMember() ||
11943 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11944
11945 // Attempt to evaluate the var decl as a constant expression and extract
11946 // the value of its first field as a ICE. If this fails, the STL
11947 // implementation is not supported.
11948 if (!ValInfo->hasValidIntValue())
11949 return UnsupportedSTLError();
11950
11952 }
11953
11954 // We've successfully built the required types and expressions. Update
11955 // the cache and return the newly cached value.
11956 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11957 return Info->getType();
11958}
11959
11961 if (!StdNamespace) {
11962 // The "std" namespace has not yet been defined, so build one implicitly.
11965 /*Inline=*/false, SourceLocation(), SourceLocation(),
11966 &PP.getIdentifierTable().get("std"),
11967 /*PrevDecl=*/nullptr, /*Nested=*/false);
11969 // We want the created NamespaceDecl to be available for redeclaration
11970 // lookups, but not for regular name lookups.
11973 }
11974
11975 return getStdNamespace();
11976}
11977
11979 assert(getLangOpts().CPlusPlus &&
11980 "Looking for std::initializer_list outside of C++.");
11981
11982 // We're looking for implicit instantiations of
11983 // template <typename E> class std::initializer_list.
11984
11985 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11986 return false;
11987
11988 ClassTemplateDecl *Template = nullptr;
11989 const TemplateArgument *Arguments = nullptr;
11990
11991 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11992
11994 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11995 if (!Specialization)
11996 return false;
11997
11998 Template = Specialization->getSpecializedTemplate();
11999 Arguments = Specialization->getTemplateArgs().data();
12000 } else {
12001 const TemplateSpecializationType *TST = nullptr;
12002 if (auto *ICN = Ty->getAs<InjectedClassNameType>())
12003 TST = ICN->getInjectedTST();
12004 else
12005 TST = Ty->getAs<TemplateSpecializationType>();
12006 if (TST) {
12007 Template = dyn_cast_or_null<ClassTemplateDecl>(
12009 Arguments = TST->template_arguments().begin();
12010 }
12011 }
12012 if (!Template)
12013 return false;
12014
12015 if (!StdInitializerList) {
12016 // Haven't recognized std::initializer_list yet, maybe this is it.
12017 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12018 if (TemplateClass->getIdentifier() !=
12019 &PP.getIdentifierTable().get("initializer_list") ||
12020 !getStdNamespace()->InEnclosingNamespaceSetOf(
12021 TemplateClass->getNonTransparentDeclContext()))
12022 return false;
12023 // This is a template called std::initializer_list, but is it the right
12024 // template?
12025 TemplateParameterList *Params = Template->getTemplateParameters();
12026 if (Params->getMinRequiredArguments() != 1)
12027 return false;
12028 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
12029 return false;
12030
12031 // It's the right template.
12032 StdInitializerList = Template;
12033 }
12034
12036 return false;
12037
12038 // This is an instance of std::initializer_list. Find the argument type.
12039 if (Element)
12040 *Element = Arguments[0].getAsType();
12041 return true;
12042}
12043
12046 if (!Std) {
12047 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12048 return nullptr;
12049 }
12050
12051 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
12053 if (!S.LookupQualifiedName(Result, Std)) {
12054 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12055 return nullptr;
12056 }
12057 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12058 if (!Template) {
12059 Result.suppressDiagnostics();
12060 // We found something weird. Complain about the first thing we found.
12061 NamedDecl *Found = *Result.begin();
12062 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12063 return nullptr;
12064 }
12065
12066 // We found some template called std::initializer_list. Now verify that it's
12067 // correct.
12068 TemplateParameterList *Params = Template->getTemplateParameters();
12069 if (Params->getMinRequiredArguments() != 1 ||
12070 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12071 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12072 return nullptr;
12073 }
12074
12075 return Template;
12076}
12077
12079 if (!StdInitializerList) {
12081 if (!StdInitializerList)
12082 return QualType();
12083 }
12084
12088 Loc)));
12093}
12094
12096 // C++ [dcl.init.list]p2:
12097 // A constructor is an initializer-list constructor if its first parameter
12098 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12099 // std::initializer_list<E> for some type E, and either there are no other
12100 // parameters or else all other parameters have default arguments.
12101 if (!Ctor->hasOneParamOrDefaultArgs())
12102 return false;
12103
12104 QualType ArgType = Ctor->getParamDecl(0)->getType();
12105 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12106 ArgType = RT->getPointeeType().getUnqualifiedType();
12107
12108 return isStdInitializerList(ArgType, nullptr);
12109}
12110
12111/// Determine whether a using statement is in a context where it will be
12112/// apply in all contexts.
12114 switch (CurContext->getDeclKind()) {
12115 case Decl::TranslationUnit:
12116 return true;
12117 case Decl::LinkageSpec:
12119 default:
12120 return false;
12121 }
12122}
12123
12124namespace {
12125
12126// Callback to only accept typo corrections that are namespaces.
12127class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12128public:
12129 bool ValidateCandidate(const TypoCorrection &candidate) override {
12130 if (NamedDecl *ND = candidate.getCorrectionDecl())
12131 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12132 return false;
12133 }
12134
12135 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12136 return std::make_unique<NamespaceValidatorCCC>(*this);
12137 }
12138};
12139
12140}
12141
12142static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12143 Sema &S) {
12144 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12145 Module *M = ND->getOwningModule();
12146 assert(M && "hidden namespace definition not in a module?");
12147
12148 if (M->isExplicitGlobalModule())
12149 S.Diag(Corrected.getCorrectionRange().getBegin(),
12150 diag::err_module_unimported_use_header)
12152 << /*Header Name*/ false;
12153 else
12154 S.Diag(Corrected.getCorrectionRange().getBegin(),
12155 diag::err_module_unimported_use)
12157 << M->getTopLevelModuleName();
12158}
12159
12161 CXXScopeSpec &SS,
12162 SourceLocation IdentLoc,
12163 IdentifierInfo *Ident) {
12164 R.clear();
12165 NamespaceValidatorCCC CCC{};
12166 if (TypoCorrection Corrected =
12167 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12169 // Generally we find it is confusing more than helpful to diagnose the
12170 // invisible namespace.
12171 // See https://github.com/llvm/llvm-project/issues/73893.
12172 //
12173 // However, we should diagnose when the users are trying to using an
12174 // invisible namespace. So we handle the case specially here.
12175 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12176 Corrected.requiresImport()) {
12177 DiagnoseInvisibleNamespace(Corrected, S);
12178 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12179 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12180 bool DroppedSpecifier =
12181 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12182 S.diagnoseTypo(Corrected,
12183 S.PDiag(diag::err_using_directive_member_suggest)
12184 << Ident << DC << DroppedSpecifier << SS.getRange(),
12185 S.PDiag(diag::note_namespace_defined_here));
12186 } else {
12187 S.diagnoseTypo(Corrected,
12188 S.PDiag(diag::err_using_directive_suggest) << Ident,
12189 S.PDiag(diag::note_namespace_defined_here));
12190 }
12191 R.addDecl(Corrected.getFoundDecl());
12192 return true;
12193 }
12194 return false;
12195}
12196
12198 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12199 SourceLocation IdentLoc,
12200 IdentifierInfo *NamespcName,
12201 const ParsedAttributesView &AttrList) {
12202 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12203 assert(NamespcName && "Invalid NamespcName.");
12204 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12205
12206 // Get the innermost enclosing declaration scope.
12207 S = S->getDeclParent();
12208
12209 UsingDirectiveDecl *UDir = nullptr;
12210 NestedNameSpecifier *Qualifier = nullptr;
12211 if (SS.isSet())
12212 Qualifier = SS.getScopeRep();
12213
12214 // Lookup namespace name.
12215 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12216 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12217 if (R.isAmbiguous())
12218 return nullptr;
12219
12220 if (R.empty()) {
12221 R.clear();
12222 // Allow "using namespace std;" or "using namespace ::std;" even if
12223 // "std" hasn't been defined yet, for GCC compatibility.
12224 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12225 NamespcName->isStr("std")) {
12226 Diag(IdentLoc, diag::ext_using_undefined_std);
12228 R.resolveKind();
12229 }
12230 // Otherwise, attempt typo correction.
12231 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12232 }
12233
12234 if (!R.empty()) {
12235 NamedDecl *Named = R.getRepresentativeDecl();
12237 assert(NS && "expected namespace decl");
12238
12239 // The use of a nested name specifier may trigger deprecation warnings.
12240 DiagnoseUseOfDecl(Named, IdentLoc);
12241
12242 // C++ [namespace.udir]p1:
12243 // A using-directive specifies that the names in the nominated
12244 // namespace can be used in the scope in which the
12245 // using-directive appears after the using-directive. During
12246 // unqualified name lookup (3.4.1), the names appear as if they
12247 // were declared in the nearest enclosing namespace which
12248 // contains both the using-directive and the nominated
12249 // namespace. [Note: in this context, "contains" means "contains
12250 // directly or indirectly". ]
12251
12252 // Find enclosing context containing both using-directive and
12253 // nominated namespace.
12254 DeclContext *CommonAncestor = NS;
12255 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12256 CommonAncestor = CommonAncestor->getParent();
12257
12258 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12260 IdentLoc, Named, CommonAncestor);
12261
12264 Diag(IdentLoc, diag::warn_using_directive_in_header);
12265 }
12266
12267 PushUsingDirective(S, UDir);
12268 } else {
12269 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12270 }
12271
12272 if (UDir) {
12273 ProcessDeclAttributeList(S, UDir, AttrList);
12274 ProcessAPINotes(UDir);
12275 }
12276
12277 return UDir;
12278}
12279
12281 // If the scope has an associated entity and the using directive is at
12282 // namespace or translation unit scope, add the UsingDirectiveDecl into
12283 // its lookup structure so qualified name lookup can find it.
12284 DeclContext *Ctx = S->getEntity();
12285 if (Ctx && !Ctx->isFunctionOrMethod())
12286 Ctx->addDecl(UDir);
12287 else
12288 // Otherwise, it is at block scope. The using-directives will affect lookup
12289 // only to the end of the scope.
12290 S->PushUsingDirective(UDir);
12291}
12292
12294 SourceLocation UsingLoc,
12295 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12296 UnqualifiedId &Name,
12297 SourceLocation EllipsisLoc,
12298 const ParsedAttributesView &AttrList) {
12299 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12300
12301 if (SS.isEmpty()) {
12302 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12303 return nullptr;
12304 }
12305
12306 switch (Name.getKind()) {
12312 break;
12313
12316 // C++11 inheriting constructors.
12317 Diag(Name.getBeginLoc(),
12319 ? diag::warn_cxx98_compat_using_decl_constructor
12320 : diag::err_using_decl_constructor)
12321 << SS.getRange();
12322
12323 if (getLangOpts().CPlusPlus11) break;
12324
12325 return nullptr;
12326
12328 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12329 return nullptr;
12330
12332 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12333 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12334 return nullptr;
12335
12337 llvm_unreachable("cannot parse qualified deduction guide name");
12338 }
12339
12340 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12341 DeclarationName TargetName = TargetNameInfo.getName();
12342 if (!TargetName)
12343 return nullptr;
12344
12345 // Warn about access declarations.
12346 if (UsingLoc.isInvalid()) {
12347 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12348 ? diag::err_access_decl
12349 : diag::warn_access_decl_deprecated)
12350 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12351 }
12352
12353 if (EllipsisLoc.isInvalid()) {
12356 return nullptr;
12357 } else {
12359 !TargetNameInfo.containsUnexpandedParameterPack()) {
12360 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12361 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12362 EllipsisLoc = SourceLocation();
12363 }
12364 }
12365
12366 NamedDecl *UD =
12367 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12368 SS, TargetNameInfo, EllipsisLoc, AttrList,
12369 /*IsInstantiation*/ false,
12370 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12371 if (UD)
12372 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12373
12374 return UD;
12375}
12376
12378 SourceLocation UsingLoc,
12379 SourceLocation EnumLoc, SourceRange TyLoc,
12380 const IdentifierInfo &II, ParsedType Ty,
12381 CXXScopeSpec *SS) {
12382 assert(SS && !SS->isInvalid() && "ScopeSpec is invalid");
12383 TypeSourceInfo *TSI = nullptr;
12384 SourceLocation IdentLoc = TyLoc.getBegin();
12385 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12386 if (EnumTy.isNull()) {
12387 Diag(IdentLoc, isDependentScopeSpecifier(*SS)
12388 ? diag::err_using_enum_is_dependent
12389 : diag::err_unknown_typename)
12390 << II.getName() << SourceRange(SS->getBeginLoc(), TyLoc.getEnd());
12391 return nullptr;
12392 }
12393
12394 if (EnumTy->isDependentType()) {
12395 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12396 return nullptr;
12397 }
12398
12399 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12400 if (!Enum) {
12401 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12402 return nullptr;
12403 }
12404
12405 if (auto *Def = Enum->getDefinition())
12406 Enum = Def;
12407
12408 if (TSI == nullptr)
12409 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12410
12411 auto *UD =
12412 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12413
12414 if (UD)
12415 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12416
12417 return UD;
12418}
12419
12420/// Determine whether a using declaration considers the given
12421/// declarations as "equivalent", e.g., if they are redeclarations of
12422/// the same entity or are both typedefs of the same type.
12423static bool
12425 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12426 return true;
12427
12428 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12429 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12430 return Context.hasSameType(TD1->getUnderlyingType(),
12431 TD2->getUnderlyingType());
12432
12433 // Two using_if_exists using-declarations are equivalent if both are
12434 // unresolved.
12435 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12436 isa<UnresolvedUsingIfExistsDecl>(D2))
12437 return true;
12438
12439 return false;
12440}
12441
12443 const LookupResult &Previous,
12444 UsingShadowDecl *&PrevShadow) {
12445 // Diagnose finding a decl which is not from a base class of the
12446 // current class. We do this now because there are cases where this
12447 // function will silently decide not to build a shadow decl, which
12448 // will pre-empt further diagnostics.
12449 //
12450 // We don't need to do this in C++11 because we do the check once on
12451 // the qualifier.
12452 //
12453 // FIXME: diagnose the following if we care enough:
12454 // struct A { int foo; };
12455 // struct B : A { using A::foo; };
12456 // template <class T> struct C : A {};
12457 // template <class T> struct D : C<T> { using B::foo; } // <---
12458 // This is invalid (during instantiation) in C++03 because B::foo
12459 // resolves to the using decl in B, which is not a base class of D<T>.
12460 // We can't diagnose it immediately because C<T> is an unknown
12461 // specialization. The UsingShadowDecl in D<T> then points directly
12462 // to A::foo, which will look well-formed when we instantiate.
12463 // The right solution is to not collapse the shadow-decl chain.
12465 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12466 DeclContext *OrigDC = Orig->getDeclContext();
12467
12468 // Handle enums and anonymous structs.
12469 if (isa<EnumDecl>(OrigDC))
12470 OrigDC = OrigDC->getParent();
12471 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12472 while (OrigRec->isAnonymousStructOrUnion())
12473 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12474
12475 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12476 if (OrigDC == CurContext) {
12477 Diag(Using->getLocation(),
12478 diag::err_using_decl_nested_name_specifier_is_current_class)
12479 << Using->getQualifierLoc().getSourceRange();
12480 Diag(Orig->getLocation(), diag::note_using_decl_target);
12481 Using->setInvalidDecl();
12482 return true;
12483 }
12484
12485 Diag(Using->getQualifierLoc().getBeginLoc(),
12486 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12487 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12488 << Using->getQualifierLoc().getSourceRange();
12489 Diag(Orig->getLocation(), diag::note_using_decl_target);
12490 Using->setInvalidDecl();
12491 return true;
12492 }
12493 }
12494
12495 if (Previous.empty()) return false;
12496
12497 NamedDecl *Target = Orig;
12498 if (isa<UsingShadowDecl>(Target))
12499 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12500
12501 // If the target happens to be one of the previous declarations, we
12502 // don't have a conflict.
12503 //
12504 // FIXME: but we might be increasing its access, in which case we
12505 // should redeclare it.
12506 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12507 bool FoundEquivalentDecl = false;
12508 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12509 I != E; ++I) {
12510 NamedDecl *D = (*I)->getUnderlyingDecl();
12511 // We can have UsingDecls in our Previous results because we use the same
12512 // LookupResult for checking whether the UsingDecl itself is a valid
12513 // redeclaration.
12514 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12515 continue;
12516
12517 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12518 // C++ [class.mem]p19:
12519 // If T is the name of a class, then [every named member other than
12520 // a non-static data member] shall have a name different from T
12521 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12522 !isa<IndirectFieldDecl>(Target) &&
12523 !isa<UnresolvedUsingValueDecl>(Target) &&
12525 CurContext,
12527 return true;
12528 }
12529
12531 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12532 PrevShadow = Shadow;
12533 FoundEquivalentDecl = true;
12535 // We don't conflict with an existing using shadow decl of an equivalent
12536 // declaration, but we're not a redeclaration of it.
12537 FoundEquivalentDecl = true;
12538 }
12539
12540 if (isVisible(D))
12541 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12542 }
12543
12544 if (FoundEquivalentDecl)
12545 return false;
12546
12547 // Always emit a diagnostic for a mismatch between an unresolved
12548 // using_if_exists and a resolved using declaration in either direction.
12549 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12550 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12551 if (!NonTag && !Tag)
12552 return false;
12553 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12554 Diag(Target->getLocation(), diag::note_using_decl_target);
12555 Diag((NonTag ? NonTag : Tag)->getLocation(),
12556 diag::note_using_decl_conflict);
12557 BUD->setInvalidDecl();
12558 return true;
12559 }
12560
12561 if (FunctionDecl *FD = Target->getAsFunction()) {
12562 NamedDecl *OldDecl = nullptr;
12563 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12564 /*IsForUsingDecl*/ true)) {
12565 case Ovl_Overload:
12566 return false;
12567
12568 case Ovl_NonFunction:
12569 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12570 break;
12571
12572 // We found a decl with the exact signature.
12573 case Ovl_Match:
12574 // If we're in a record, we want to hide the target, so we
12575 // return true (without a diagnostic) to tell the caller not to
12576 // build a shadow decl.
12577 if (CurContext->isRecord())
12578 return true;
12579
12580 // If we're not in a record, this is an error.
12581 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12582 break;
12583 }
12584
12585 Diag(Target->getLocation(), diag::note_using_decl_target);
12586 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12587 BUD->setInvalidDecl();
12588 return true;
12589 }
12590
12591 // Target is not a function.
12592
12593 if (isa<TagDecl>(Target)) {
12594 // No conflict between a tag and a non-tag.
12595 if (!Tag) return false;
12596
12597 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12598 Diag(Target->getLocation(), diag::note_using_decl_target);
12599 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12600 BUD->setInvalidDecl();
12601 return true;
12602 }
12603
12604 // No conflict between a tag and a non-tag.
12605 if (!NonTag) return false;
12606
12607 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12608 Diag(Target->getLocation(), diag::note_using_decl_target);
12609 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12610 BUD->setInvalidDecl();
12611 return true;
12612}
12613
12614/// Determine whether a direct base class is a virtual base class.
12616 if (!Derived->getNumVBases())
12617 return false;
12618 for (auto &B : Derived->bases())
12619 if (B.getType()->getAsCXXRecordDecl() == Base)
12620 return B.isVirtual();
12621 llvm_unreachable("not a direct base class");
12622}
12623
12625 NamedDecl *Orig,
12626 UsingShadowDecl *PrevDecl) {
12627 // If we resolved to another shadow declaration, just coalesce them.
12628 NamedDecl *Target = Orig;
12629 if (isa<UsingShadowDecl>(Target)) {
12630 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12631 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12632 }
12633
12634 NamedDecl *NonTemplateTarget = Target;
12635 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12636 NonTemplateTarget = TargetTD->getTemplatedDecl();
12637
12638 UsingShadowDecl *Shadow;
12639 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12640 UsingDecl *Using = cast<UsingDecl>(BUD);
12641 bool IsVirtualBase =
12642 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12643 Using->getQualifier()->getAsRecordDecl());
12645 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12646 } else {
12648 Target->getDeclName(), BUD, Target);
12649 }
12650 BUD->addShadowDecl(Shadow);
12651
12652 Shadow->setAccess(BUD->getAccess());
12653 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12654 Shadow->setInvalidDecl();
12655
12656 Shadow->setPreviousDecl(PrevDecl);
12657
12658 if (S)
12659 PushOnScopeChains(Shadow, S);
12660 else
12661 CurContext->addDecl(Shadow);
12662
12663
12664 return Shadow;
12665}
12666
12668 if (Shadow->getDeclName().getNameKind() ==
12670 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12671
12672 // Remove it from the DeclContext...
12673 Shadow->getDeclContext()->removeDecl(Shadow);
12674
12675 // ...and the scope, if applicable...
12676 if (S) {
12677 S->RemoveDecl(Shadow);
12678 IdResolver.RemoveDecl(Shadow);
12679 }
12680
12681 // ...and the using decl.
12682 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12683
12684 // TODO: complain somehow if Shadow was used. It shouldn't
12685 // be possible for this to happen, because...?
12686}
12687
12688/// Find the base specifier for a base class with the given type.
12690 QualType DesiredBase,
12691 bool &AnyDependentBases) {
12692 // Check whether the named type is a direct base class.
12693 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12695 for (auto &Base : Derived->bases()) {
12696 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12697 if (CanonicalDesiredBase == BaseType)
12698 return &Base;
12699 if (BaseType->isDependentType())
12700 AnyDependentBases = true;
12701 }
12702 return nullptr;
12703}
12704
12705namespace {
12706class UsingValidatorCCC final : public CorrectionCandidateCallback {
12707public:
12708 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12709 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12710 : HasTypenameKeyword(HasTypenameKeyword),
12711 IsInstantiation(IsInstantiation), OldNNS(NNS),
12712 RequireMemberOf(RequireMemberOf) {}
12713
12714 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12715 NamedDecl *ND = Candidate.getCorrectionDecl();
12716
12717 // Keywords are not valid here.
12718 if (!ND || isa<NamespaceDecl>(ND))
12719 return false;
12720
12721 // Completely unqualified names are invalid for a 'using' declaration.
12722 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12723 return false;
12724
12725 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12726 // reject.
12727
12728 if (RequireMemberOf) {
12729 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12730 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12731 // No-one ever wants a using-declaration to name an injected-class-name
12732 // of a base class, unless they're declaring an inheriting constructor.
12733 ASTContext &Ctx = ND->getASTContext();
12734 if (!Ctx.getLangOpts().CPlusPlus11)
12735 return false;
12736 QualType FoundType = Ctx.getRecordType(FoundRecord);
12737
12738 // Check that the injected-class-name is named as a member of its own
12739 // type; we don't want to suggest 'using Derived::Base;', since that
12740 // means something else.
12742 Candidate.WillReplaceSpecifier()
12743 ? Candidate.getCorrectionSpecifier()
12744 : OldNNS;
12745 if (!Specifier->getAsType() ||
12746 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12747 return false;
12748
12749 // Check that this inheriting constructor declaration actually names a
12750 // direct base class of the current class.
12751 bool AnyDependentBases = false;
12752 if (!findDirectBaseWithType(RequireMemberOf,
12753 Ctx.getRecordType(FoundRecord),
12754 AnyDependentBases) &&
12755 !AnyDependentBases)
12756 return false;
12757 } else {
12758 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12759 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12760 return false;
12761
12762 // FIXME: Check that the base class member is accessible?
12763 }
12764 } else {
12765 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12766 if (FoundRecord && FoundRecord->isInjectedClassName())
12767 return false;
12768 }
12769
12770 if (isa<TypeDecl>(ND))
12771 return HasTypenameKeyword || !IsInstantiation;
12772
12773 return !HasTypenameKeyword;
12774 }
12775
12776 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12777 return std::make_unique<UsingValidatorCCC>(*this);
12778 }
12779
12780private:
12781 bool HasTypenameKeyword;
12782 bool IsInstantiation;
12783 NestedNameSpecifier *OldNNS;
12784 CXXRecordDecl *RequireMemberOf;
12785};
12786} // end anonymous namespace
12787
12789 // It is really dumb that we have to do this.
12790 LookupResult::Filter F = Previous.makeFilter();
12791 while (F.hasNext()) {
12792 NamedDecl *D = F.next();
12793 if (!isDeclInScope(D, CurContext, S))
12794 F.erase();
12795 // If we found a local extern declaration that's not ordinarily visible,
12796 // and this declaration is being added to a non-block scope, ignore it.
12797 // We're only checking for scope conflicts here, not also for violations
12798 // of the linkage rules.
12799 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12801 F.erase();
12802 }
12803 F.done();
12804}
12805
12807 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12808 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12809 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12810 const ParsedAttributesView &AttrList, bool IsInstantiation,
12811 bool IsUsingIfExists) {
12812 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12813 SourceLocation IdentLoc = NameInfo.getLoc();
12814 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12815
12816 // FIXME: We ignore attributes for now.
12817
12818 // For an inheriting constructor declaration, the name of the using
12819 // declaration is the name of a constructor in this class, not in the
12820 // base class.
12821 DeclarationNameInfo UsingName = NameInfo;
12823 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12826
12827 // Do the redeclaration lookup in the current scope.
12828 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12829 RedeclarationKind::ForVisibleRedeclaration);
12830 Previous.setHideTags(false);
12831 if (S) {
12832 LookupName(Previous, S);
12833
12835 } else {
12836 assert(IsInstantiation && "no scope in non-instantiation");
12837 if (CurContext->isRecord())
12839 else {
12840 // No redeclaration check is needed here; in non-member contexts we
12841 // diagnosed all possible conflicts with other using-declarations when
12842 // building the template:
12843 //
12844 // For a dependent non-type using declaration, the only valid case is
12845 // if we instantiate to a single enumerator. We check for conflicts
12846 // between shadow declarations we introduce, and we check in the template
12847 // definition for conflicts between a non-type using declaration and any
12848 // other declaration, which together covers all cases.
12849 //
12850 // A dependent typename using declaration will never successfully
12851 // instantiate, since it will always name a class member, so we reject
12852 // that in the template definition.
12853 }
12854 }
12855
12856 // Check for invalid redeclarations.
12857 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12858 SS, IdentLoc, Previous))
12859 return nullptr;
12860
12861 // 'using_if_exists' doesn't make sense on an inherited constructor.
12862 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12864 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12865 return nullptr;
12866 }
12867
12868 DeclContext *LookupContext = computeDeclContext(SS);
12870 if (!LookupContext || EllipsisLoc.isValid()) {
12871 NamedDecl *D;
12872 // Dependent scope, or an unexpanded pack
12873 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12874 SS, NameInfo, IdentLoc))
12875 return nullptr;
12876
12877 if (HasTypenameKeyword) {
12878 // FIXME: not all declaration name kinds are legal here
12880 UsingLoc, TypenameLoc,
12881 QualifierLoc,
12882 IdentLoc, NameInfo.getName(),
12883 EllipsisLoc);
12884 } else {
12886 QualifierLoc, NameInfo, EllipsisLoc);
12887 }
12888 D->setAccess(AS);
12890 ProcessDeclAttributeList(S, D, AttrList);
12891 return D;
12892 }
12893
12894 auto Build = [&](bool Invalid) {
12895 UsingDecl *UD =
12896 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12897 UsingName, HasTypenameKeyword);
12898 UD->setAccess(AS);
12899 CurContext->addDecl(UD);
12900 ProcessDeclAttributeList(S, UD, AttrList);
12902 return UD;
12903 };
12904 auto BuildInvalid = [&]{ return Build(true); };
12905 auto BuildValid = [&]{ return Build(false); };
12906
12907 if (RequireCompleteDeclContext(SS, LookupContext))
12908 return BuildInvalid();
12909
12910 // Look up the target name.
12911 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12912
12913 // Unlike most lookups, we don't always want to hide tag
12914 // declarations: tag names are visible through the using declaration
12915 // even if hidden by ordinary names, *except* in a dependent context
12916 // where they may be used by two-phase lookup.
12917 if (!IsInstantiation)
12918 R.setHideTags(false);
12919
12920 // For the purposes of this lookup, we have a base object type
12921 // equal to that of the current context.
12922 if (CurContext->isRecord()) {
12924 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12925 }
12926
12927 LookupQualifiedName(R, LookupContext);
12928
12929 // Validate the context, now we have a lookup
12930 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12931 IdentLoc, &R))
12932 return nullptr;
12933
12934 if (R.empty() && IsUsingIfExists)
12936 UsingName.getName()),
12937 AS_public);
12938
12939 // Try to correct typos if possible. If constructor name lookup finds no
12940 // results, that means the named class has no explicit constructors, and we
12941 // suppressed declaring implicit ones (probably because it's dependent or
12942 // invalid).
12943 if (R.empty() &&
12945 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12946 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12947 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12948 auto *II = NameInfo.getName().getAsIdentifierInfo();
12949 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12951 isa<TranslationUnitDecl>(LookupContext) &&
12952 getSourceManager().isInSystemHeader(UsingLoc))
12953 return nullptr;
12954 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12955 dyn_cast<CXXRecordDecl>(CurContext));
12956 if (TypoCorrection Corrected =
12957 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12959 // We reject candidates where DroppedSpecifier == true, hence the
12960 // literal '0' below.
12961 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12962 << NameInfo.getName() << LookupContext << 0
12963 << SS.getRange());
12964
12965 // If we picked a correction with no attached Decl we can't do anything
12966 // useful with it, bail out.
12967 NamedDecl *ND = Corrected.getCorrectionDecl();
12968 if (!ND)
12969 return BuildInvalid();
12970
12971 // If we corrected to an inheriting constructor, handle it as one.
12972 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12973 if (RD && RD->isInjectedClassName()) {
12974 // The parent of the injected class name is the class itself.
12975 RD = cast<CXXRecordDecl>(RD->getParent());
12976
12977 // Fix up the information we'll use to build the using declaration.
12978 if (Corrected.WillReplaceSpecifier()) {
12980 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12981 QualifierLoc.getSourceRange());
12982 QualifierLoc = Builder.getWithLocInContext(Context);
12983 }
12984
12985 // In this case, the name we introduce is the name of a derived class
12986 // constructor.
12987 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12990 UsingName.setNamedTypeInfo(nullptr);
12991 for (auto *Ctor : LookupConstructors(RD))
12992 R.addDecl(Ctor);
12993 R.resolveKind();
12994 } else {
12995 // FIXME: Pick up all the declarations if we found an overloaded
12996 // function.
12997 UsingName.setName(ND->getDeclName());
12998 R.addDecl(ND);
12999 }
13000 } else {
13001 Diag(IdentLoc, diag::err_no_member)
13002 << NameInfo.getName() << LookupContext << SS.getRange();
13003 return BuildInvalid();
13004 }
13005 }
13006
13007 if (R.isAmbiguous())
13008 return BuildInvalid();
13009
13010 if (HasTypenameKeyword) {
13011 // If we asked for a typename and got a non-type decl, error out.
13012 if (!R.getAsSingle<TypeDecl>() &&
13014 Diag(IdentLoc, diag::err_using_typename_non_type);
13015 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13016 Diag((*I)->getUnderlyingDecl()->getLocation(),
13017 diag::note_using_decl_target);
13018 return BuildInvalid();
13019 }
13020 } else {
13021 // If we asked for a non-typename and we got a type, error out,
13022 // but only if this is an instantiation of an unresolved using
13023 // decl. Otherwise just silently find the type name.
13024 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13025 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13026 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13027 return BuildInvalid();
13028 }
13029 }
13030
13031 // C++14 [namespace.udecl]p6:
13032 // A using-declaration shall not name a namespace.
13033 if (R.getAsSingle<NamespaceDecl>()) {
13034 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13035 << SS.getRange();
13036 // Suggest using 'using namespace ...' instead.
13037 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13038 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13039 return BuildInvalid();
13040 }
13041
13042 UsingDecl *UD = BuildValid();
13043
13044 // Some additional rules apply to inheriting constructors.
13045 if (UsingName.getName().getNameKind() ==
13047 // Suppress access diagnostics; the access check is instead performed at the
13048 // point of use for an inheriting constructor.
13051 return UD;
13052 }
13053
13054 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13055 UsingShadowDecl *PrevDecl = nullptr;
13056 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13057 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13058 }
13059
13060 return UD;
13061}
13062
13064 SourceLocation UsingLoc,
13065 SourceLocation EnumLoc,
13066 SourceLocation NameLoc,
13068 EnumDecl *ED) {
13069 bool Invalid = false;
13070
13072 /// In class scope, check if this is a duplicate, for better a diagnostic.
13073 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13074 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13075 RedeclarationKind::ForVisibleRedeclaration);
13076
13077 LookupName(Previous, S);
13078
13079 for (NamedDecl *D : Previous)
13080 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13081 if (UED->getEnumDecl() == ED) {
13082 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13083 << SourceRange(EnumLoc, NameLoc);
13084 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13085 Invalid = true;
13086 break;
13087 }
13088 }
13089
13090 if (RequireCompleteEnumDecl(ED, NameLoc))
13091 Invalid = true;
13092
13094 EnumLoc, NameLoc, EnumType);
13095 UD->setAccess(AS);
13096 CurContext->addDecl(UD);
13097
13098 if (Invalid) {
13099 UD->setInvalidDecl();
13100 return UD;
13101 }
13102
13103 // Create the shadow decls for each enumerator
13104 for (EnumConstantDecl *EC : ED->enumerators()) {
13105 UsingShadowDecl *PrevDecl = nullptr;
13106 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13108 RedeclarationKind::ForVisibleRedeclaration);
13109 LookupName(Previous, S);
13111
13112 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13113 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13114 }
13115
13116 return UD;
13117}
13118
13120 ArrayRef<NamedDecl *> Expansions) {
13121 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13122 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13123 isa<UsingPackDecl>(InstantiatedFrom));
13124
13125 auto *UPD =
13126 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13127 UPD->setAccess(InstantiatedFrom->getAccess());
13128 CurContext->addDecl(UPD);
13129 return UPD;
13130}
13131
13133 assert(!UD->hasTypename() && "expecting a constructor name");
13134
13135 const Type *SourceType = UD->getQualifier()->getAsType();
13136 assert(SourceType &&
13137 "Using decl naming constructor doesn't have type in scope spec.");
13138 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13139
13140 // Check whether the named type is a direct base class.
13141 bool AnyDependentBases = false;
13142 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13143 AnyDependentBases);
13144 if (!Base && !AnyDependentBases) {
13145 Diag(UD->getUsingLoc(),
13146 diag::err_using_decl_constructor_not_in_direct_base)
13147 << UD->getNameInfo().getSourceRange()
13148 << QualType(SourceType, 0) << TargetClass;
13149 UD->setInvalidDecl();
13150 return true;
13151 }
13152
13153 if (Base)
13154 Base->setInheritConstructors();
13155
13156 return false;
13157}
13158
13160 bool HasTypenameKeyword,
13161 const CXXScopeSpec &SS,
13162 SourceLocation NameLoc,
13163 const LookupResult &Prev) {
13164 NestedNameSpecifier *Qual = SS.getScopeRep();
13165
13166 // C++03 [namespace.udecl]p8:
13167 // C++0x [namespace.udecl]p10:
13168 // A using-declaration is a declaration and can therefore be used
13169 // repeatedly where (and only where) multiple declarations are
13170 // allowed.
13171 //
13172 // That's in non-member contexts.
13174 // A dependent qualifier outside a class can only ever resolve to an
13175 // enumeration type. Therefore it conflicts with any other non-type
13176 // declaration in the same scope.
13177 // FIXME: How should we check for dependent type-type conflicts at block
13178 // scope?
13179 if (Qual->isDependent() && !HasTypenameKeyword) {
13180 for (auto *D : Prev) {
13181 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13182 bool OldCouldBeEnumerator =
13183 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13184 Diag(NameLoc,
13185 OldCouldBeEnumerator ? diag::err_redefinition
13186 : diag::err_redefinition_different_kind)
13187 << Prev.getLookupName();
13188 Diag(D->getLocation(), diag::note_previous_definition);
13189 return true;
13190 }
13191 }
13192 }
13193 return false;
13194 }
13195
13196 const NestedNameSpecifier *CNNS =
13198 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13199 NamedDecl *D = *I;
13200
13201 bool DTypename;
13202 NestedNameSpecifier *DQual;
13203 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13204 DTypename = UD->hasTypename();
13205 DQual = UD->getQualifier();
13206 } else if (UnresolvedUsingValueDecl *UD
13207 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13208 DTypename = false;
13209 DQual = UD->getQualifier();
13210 } else if (UnresolvedUsingTypenameDecl *UD
13211 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13212 DTypename = true;
13213 DQual = UD->getQualifier();
13214 } else continue;
13215
13216 // using decls differ if one says 'typename' and the other doesn't.
13217 // FIXME: non-dependent using decls?
13218 if (HasTypenameKeyword != DTypename) continue;
13219
13220 // using decls differ if they name different scopes (but note that
13221 // template instantiation can cause this check to trigger when it
13222 // didn't before instantiation).
13223 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13224 continue;
13225
13226 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13227 Diag(D->getLocation(), diag::note_using_decl) << 1;
13228 return true;
13229 }
13230
13231 return false;
13232}
13233
13234bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13235 const CXXScopeSpec &SS,
13236 const DeclarationNameInfo &NameInfo,
13237 SourceLocation NameLoc,
13238 const LookupResult *R, const UsingDecl *UD) {
13239 DeclContext *NamedContext = computeDeclContext(SS);
13240 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13241 "resolvable context must have exactly one set of decls");
13242
13243 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13244 // relationship.
13245 bool Cxx20Enumerator = false;
13246 if (NamedContext) {
13247 EnumConstantDecl *EC = nullptr;
13248 if (R)
13249 EC = R->getAsSingle<EnumConstantDecl>();
13250 else if (UD && UD->shadow_size() == 1)
13251 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13252 if (EC)
13253 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13254
13255 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13256 // C++14 [namespace.udecl]p7:
13257 // A using-declaration shall not name a scoped enumerator.
13258 // C++20 p1099 permits enumerators.
13259 if (EC && R && ED->isScoped())
13260 Diag(SS.getBeginLoc(),
13262 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13263 : diag::ext_using_decl_scoped_enumerator)
13264 << SS.getRange();
13265
13266 // We want to consider the scope of the enumerator
13267 NamedContext = ED->getDeclContext();
13268 }
13269 }
13270
13271 if (!CurContext->isRecord()) {
13272 // C++03 [namespace.udecl]p3:
13273 // C++0x [namespace.udecl]p8:
13274 // A using-declaration for a class member shall be a member-declaration.
13275 // C++20 [namespace.udecl]p7
13276 // ... other than an enumerator ...
13277
13278 // If we weren't able to compute a valid scope, it might validly be a
13279 // dependent class or enumeration scope. If we have a 'typename' keyword,
13280 // the scope must resolve to a class type.
13281 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13282 : !HasTypename)
13283 return false; // OK
13284
13285 Diag(NameLoc,
13286 Cxx20Enumerator
13287 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13288 : diag::err_using_decl_can_not_refer_to_class_member)
13289 << SS.getRange();
13290
13291 if (Cxx20Enumerator)
13292 return false; // OK
13293
13294 auto *RD = NamedContext
13295 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13296 : nullptr;
13297 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13298 // See if there's a helpful fixit
13299
13300 if (!R) {
13301 // We will have already diagnosed the problem on the template
13302 // definition, Maybe we should do so again?
13303 } else if (R->getAsSingle<TypeDecl>()) {
13304 if (getLangOpts().CPlusPlus11) {
13305 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13306 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13307 << diag::MemClassWorkaround::AliasDecl
13309 NameInfo.getName().getAsString() +
13310 " = ");
13311 } else {
13312 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13313 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13314 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13315 << diag::MemClassWorkaround::TypedefDecl
13316 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13318 InsertLoc, " " + NameInfo.getName().getAsString());
13319 }
13320 } else if (R->getAsSingle<VarDecl>()) {
13321 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13322 // repeating the type of the static data member here.
13323 FixItHint FixIt;
13324 if (getLangOpts().CPlusPlus11) {
13325 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13327 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13328 }
13329
13330 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13331 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13332 } else if (R->getAsSingle<EnumConstantDecl>()) {
13333 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13334 // repeating the type of the enumeration here, and we can't do so if
13335 // the type is anonymous.
13336 FixItHint FixIt;
13337 if (getLangOpts().CPlusPlus11) {
13338 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13340 UsingLoc,
13341 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13342 }
13343
13344 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13345 << (getLangOpts().CPlusPlus11
13346 ? diag::MemClassWorkaround::ConstexprVar
13347 : diag::MemClassWorkaround::ConstVar)
13348 << FixIt;
13349 }
13350 }
13351
13352 return true; // Fail
13353 }
13354
13355 // If the named context is dependent, we can't decide much.
13356 if (!NamedContext) {
13357 // FIXME: in C++0x, we can diagnose if we can prove that the
13358 // nested-name-specifier does not refer to a base class, which is
13359 // still possible in some cases.
13360
13361 // Otherwise we have to conservatively report that things might be
13362 // okay.
13363 return false;
13364 }
13365
13366 // The current scope is a record.
13367 if (!NamedContext->isRecord()) {
13368 // Ideally this would point at the last name in the specifier,
13369 // but we don't have that level of source info.
13370 Diag(SS.getBeginLoc(),
13371 Cxx20Enumerator
13372 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13373 : diag::err_using_decl_nested_name_specifier_is_not_class)
13374 << SS.getScopeRep() << SS.getRange();
13375
13376 if (Cxx20Enumerator)
13377 return false; // OK
13378
13379 return true;
13380 }
13381
13382 if (!NamedContext->isDependentContext() &&
13383 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13384 return true;
13385
13386 if (getLangOpts().CPlusPlus11) {
13387 // C++11 [namespace.udecl]p3:
13388 // In a using-declaration used as a member-declaration, the
13389 // nested-name-specifier shall name a base class of the class
13390 // being defined.
13391
13392 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13393 cast<CXXRecordDecl>(NamedContext))) {
13394
13395 if (Cxx20Enumerator) {
13396 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13397 << SS.getRange();
13398 return false;
13399 }
13400
13401 if (CurContext == NamedContext) {
13402 Diag(SS.getBeginLoc(),
13403 diag::err_using_decl_nested_name_specifier_is_current_class)
13404 << SS.getRange();
13405 return !getLangOpts().CPlusPlus20;
13406 }
13407
13408 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13409 Diag(SS.getBeginLoc(),
13410 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13411 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13412 << SS.getRange();
13413 }
13414 return true;
13415 }
13416
13417 return false;
13418 }
13419
13420 // C++03 [namespace.udecl]p4:
13421 // A using-declaration used as a member-declaration shall refer
13422 // to a member of a base class of the class being defined [etc.].
13423
13424 // Salient point: SS doesn't have to name a base class as long as
13425 // lookup only finds members from base classes. Therefore we can
13426 // diagnose here only if we can prove that can't happen,
13427 // i.e. if the class hierarchies provably don't intersect.
13428
13429 // TODO: it would be nice if "definitely valid" results were cached
13430 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13431 // need to be repeated.
13432
13434 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13435 Bases.insert(Base);
13436 return true;
13437 };
13438
13439 // Collect all bases. Return false if we find a dependent base.
13440 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13441 return false;
13442
13443 // Returns true if the base is dependent or is one of the accumulated base
13444 // classes.
13445 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13446 return !Bases.count(Base);
13447 };
13448
13449 // Return false if the class has a dependent base or if it or one
13450 // of its bases is present in the base set of the current context.
13451 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13452 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13453 return false;
13454
13455 Diag(SS.getRange().getBegin(),
13456 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13457 << SS.getScopeRep()
13458 << cast<CXXRecordDecl>(CurContext)
13459 << SS.getRange();
13460
13461 return true;
13462}
13463
13465 MultiTemplateParamsArg TemplateParamLists,
13466 SourceLocation UsingLoc, UnqualifiedId &Name,
13467 const ParsedAttributesView &AttrList,
13468 TypeResult Type, Decl *DeclFromDeclSpec) {
13469
13470 if (Type.isInvalid())
13471 return nullptr;
13472
13473 bool Invalid = false;
13475 TypeSourceInfo *TInfo = nullptr;
13476 GetTypeFromParser(Type.get(), &TInfo);
13477
13478 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13479 return nullptr;
13480
13481 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13483 Invalid = true;
13485 TInfo->getTypeLoc().getBeginLoc());
13486 }
13487
13488 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13489 TemplateParamLists.size()
13491 : RedeclarationKind::ForVisibleRedeclaration);
13492 LookupName(Previous, S);
13493
13494 // Warn about shadowing the name of a template parameter.
13495 if (Previous.isSingleResult() &&
13496 Previous.getFoundDecl()->isTemplateParameter()) {
13497 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13498 Previous.clear();
13499 }
13500
13501 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13502 "name in alias declaration must be an identifier");
13504 Name.StartLocation,
13505 Name.Identifier, TInfo);
13506
13507 NewTD->setAccess(AS);
13508
13509 if (Invalid)
13510 NewTD->setInvalidDecl();
13511
13512 ProcessDeclAttributeList(S, NewTD, AttrList);
13513 AddPragmaAttributes(S, NewTD);
13514 ProcessAPINotes(NewTD);
13515
13517 Invalid |= NewTD->isInvalidDecl();
13518
13519 // Get the innermost enclosing declaration scope.
13520 S = S->getDeclParent();
13521
13522 bool Redeclaration = false;
13523
13524 NamedDecl *NewND;
13525 if (TemplateParamLists.size()) {
13526 TypeAliasTemplateDecl *OldDecl = nullptr;
13527 TemplateParameterList *OldTemplateParams = nullptr;
13528
13529 if (TemplateParamLists.size() != 1) {
13530 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13531 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13532 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13533 Invalid = true;
13534 }
13535 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13536
13537 // Check that we can declare a template here.
13538 if (CheckTemplateDeclScope(S, TemplateParams))
13539 return nullptr;
13540
13541 // Only consider previous declarations in the same scope.
13542 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13543 /*ExplicitInstantiationOrSpecialization*/false);
13544 if (!Previous.empty()) {
13545 Redeclaration = true;
13546
13547 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13548 if (!OldDecl && !Invalid) {
13549 Diag(UsingLoc, diag::err_redefinition_different_kind)
13550 << Name.Identifier;
13551
13552 NamedDecl *OldD = Previous.getRepresentativeDecl();
13553 if (OldD->getLocation().isValid())
13554 Diag(OldD->getLocation(), diag::note_previous_definition);
13555
13556 Invalid = true;
13557 }
13558
13559 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13560 if (TemplateParameterListsAreEqual(TemplateParams,
13561 OldDecl->getTemplateParameters(),
13562 /*Complain=*/true,
13564 OldTemplateParams =
13566 else
13567 Invalid = true;
13568
13569 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13570 if (!Invalid &&
13572 NewTD->getUnderlyingType())) {
13573 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13574 // but we can't reasonably accept it.
13575 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13576 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13577 if (OldTD->getLocation().isValid())
13578 Diag(OldTD->getLocation(), diag::note_previous_definition);
13579 Invalid = true;
13580 }
13581 }
13582 }
13583
13584 // Merge any previous default template arguments into our parameters,
13585 // and check the parameter list.
13586 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13588 return nullptr;
13589
13590 TypeAliasTemplateDecl *NewDecl =
13592 Name.Identifier, TemplateParams,
13593 NewTD);
13594 NewTD->setDescribedAliasTemplate(NewDecl);
13595
13596 NewDecl->setAccess(AS);
13597
13598 if (Invalid)
13599 NewDecl->setInvalidDecl();
13600 else if (OldDecl) {
13601 NewDecl->setPreviousDecl(OldDecl);
13602 CheckRedeclarationInModule(NewDecl, OldDecl);
13603 }
13604
13605 NewND = NewDecl;
13606 } else {
13607 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13609 handleTagNumbering(TD, S);
13610 }
13611 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13612 NewND = NewTD;
13613 }
13614
13615 PushOnScopeChains(NewND, S);
13616 ActOnDocumentableDecl(NewND);
13617 return NewND;
13618}
13619
13621 SourceLocation AliasLoc,
13622 IdentifierInfo *Alias, CXXScopeSpec &SS,
13623 SourceLocation IdentLoc,
13624 IdentifierInfo *Ident) {
13625
13626 // Lookup the namespace name.
13627 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13628 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13629
13630 if (R.isAmbiguous())
13631 return nullptr;
13632
13633 if (R.empty()) {
13634 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13635 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13636 return nullptr;
13637 }
13638 }
13639 assert(!R.isAmbiguous() && !R.empty());
13641
13642 // Check if we have a previous declaration with the same name.
13643 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13644 RedeclarationKind::ForVisibleRedeclaration);
13645 LookupName(PrevR, S);
13646
13647 // Check we're not shadowing a template parameter.
13648 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13650 PrevR.clear();
13651 }
13652
13653 // Filter out any other lookup result from an enclosing scope.
13654 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13655 /*AllowInlineNamespace*/false);
13656
13657 // Find the previous declaration and check that we can redeclare it.
13658 NamespaceAliasDecl *Prev = nullptr;
13659 if (PrevR.isSingleResult()) {
13660 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13661 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13662 // We already have an alias with the same name that points to the same
13663 // namespace; check that it matches.
13664 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13665 Prev = AD;
13666 } else if (isVisible(PrevDecl)) {
13667 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13668 << Alias;
13669 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13670 << AD->getNamespace();
13671 return nullptr;
13672 }
13673 } else if (isVisible(PrevDecl)) {
13674 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13675 ? diag::err_redefinition
13676 : diag::err_redefinition_different_kind;
13677 Diag(AliasLoc, DiagID) << Alias;
13678 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13679 return nullptr;
13680 }
13681 }
13682
13683 // The use of a nested name specifier may trigger deprecation warnings.
13684 DiagnoseUseOfDecl(ND, IdentLoc);
13685
13687 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13688 Alias, SS.getWithLocInContext(Context),
13689 IdentLoc, ND);
13690 if (Prev)
13691 AliasDecl->setPreviousDecl(Prev);
13692
13694 return AliasDecl;
13695}
13696
13697namespace {
13698struct SpecialMemberExceptionSpecInfo
13699 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13702
13703 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13707 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13708
13709 bool visitBase(CXXBaseSpecifier *Base);
13710 bool visitField(FieldDecl *FD);
13711
13712 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13713 unsigned Quals);
13714
13715 void visitSubobjectCall(Subobject Subobj,
13717};
13718}
13719
13720bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13721 auto *RT = Base->getType()->getAs<RecordType>();
13722 if (!RT)
13723 return false;
13724
13725 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13726 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13727 if (auto *BaseCtor = SMOR.getMethod()) {
13728 visitSubobjectCall(Base, BaseCtor);
13729 return false;
13730 }
13731
13732 visitClassSubobject(BaseClass, Base, 0);
13733 return false;
13734}
13735
13736bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13738 FD->hasInClassInitializer()) {
13739 Expr *E = FD->getInClassInitializer();
13740 if (!E)
13741 // FIXME: It's a little wasteful to build and throw away a
13742 // CXXDefaultInitExpr here.
13743 // FIXME: We should have a single context note pointing at Loc, and
13744 // this location should be MD->getLocation() instead, since that's
13745 // the location where we actually use the default init expression.
13746 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13747 if (E)
13748 ExceptSpec.CalledExpr(E);
13749 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13750 ->getAs<RecordType>()) {
13751 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13752 FD->getType().getCVRQualifiers());
13753 }
13754 return false;
13755}
13756
13757void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13758 Subobject Subobj,
13759 unsigned Quals) {
13760 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13761 bool IsMutable = Field && Field->isMutable();
13762 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13763}
13764
13765void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13766 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13767 // Note, if lookup fails, it doesn't matter what exception specification we
13768 // choose because the special member will be deleted.
13769 if (CXXMethodDecl *MD = SMOR.getMethod())
13770 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13771}
13772
13774 llvm::APSInt Result;
13776 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13777 ExplicitSpec.setExpr(Converted.get());
13778 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13779 ExplicitSpec.setKind(Result.getBoolValue()
13782 return true;
13783 }
13785 return false;
13786}
13787
13790 if (!ExplicitExpr->isTypeDependent())
13792 return ES;
13793}
13794
13799 ComputingExceptionSpec CES(S, MD, Loc);
13800
13801 CXXRecordDecl *ClassDecl = MD->getParent();
13802
13803 // C++ [except.spec]p14:
13804 // An implicitly declared special member function (Clause 12) shall have an
13805 // exception-specification. [...]
13806 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13807 if (ClassDecl->isInvalidDecl())
13808 return Info.ExceptSpec;
13809
13810 // FIXME: If this diagnostic fires, we're probably missing a check for
13811 // attempting to resolve an exception specification before it's known
13812 // at a higher level.
13813 if (S.RequireCompleteType(MD->getLocation(),
13814 S.Context.getRecordType(ClassDecl),
13815 diag::err_exception_spec_incomplete_type))
13816 return Info.ExceptSpec;
13817
13818 // C++1z [except.spec]p7:
13819 // [Look for exceptions thrown by] a constructor selected [...] to
13820 // initialize a potentially constructed subobject,
13821 // C++1z [except.spec]p8:
13822 // The exception specification for an implicitly-declared destructor, or a
13823 // destructor without a noexcept-specifier, is potentially-throwing if and
13824 // only if any of the destructors for any of its potentially constructed
13825 // subojects is potentially throwing.
13826 // FIXME: We respect the first rule but ignore the "potentially constructed"
13827 // in the second rule to resolve a core issue (no number yet) that would have
13828 // us reject:
13829 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13830 // struct B : A {};
13831 // struct C : B { void f(); };
13832 // ... due to giving B::~B() a non-throwing exception specification.
13833 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13834 : Info.VisitAllBases);
13835
13836 return Info.ExceptSpec;
13837}
13838
13839namespace {
13840/// RAII object to register a special member as being currently declared.
13841struct DeclaringSpecialMember {
13842 Sema &S;
13844 Sema::ContextRAII SavedContext;
13845 bool WasAlreadyBeingDeclared;
13846
13847 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13848 : S(S), D(RD, CSM), SavedContext(S, RD) {
13849 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13850 if (WasAlreadyBeingDeclared)
13851 // This almost never happens, but if it does, ensure that our cache
13852 // doesn't contain a stale result.
13853 S.SpecialMemberCache.clear();
13854 else {
13855 // Register a note to be produced if we encounter an error while
13856 // declaring the special member.
13859 // FIXME: We don't have a location to use here. Using the class's
13860 // location maintains the fiction that we declare all special members
13861 // with the class, but (1) it's not clear that lying about that helps our
13862 // users understand what's going on, and (2) there may be outer contexts
13863 // on the stack (some of which are relevant) and printing them exposes
13864 // our lies.
13865 Ctx.PointOfInstantiation = RD->getLocation();
13866 Ctx.Entity = RD;
13867 Ctx.SpecialMember = CSM;
13869 }
13870 }
13871 ~DeclaringSpecialMember() {
13872 if (!WasAlreadyBeingDeclared) {
13875 }
13876 }
13877
13878 /// Are we already trying to declare this special member?
13879 bool isAlreadyBeingDeclared() const {
13880 return WasAlreadyBeingDeclared;
13881 }
13882};
13883}
13884
13886 // Look up any existing declarations, but don't trigger declaration of all
13887 // implicit special members with this name.
13888 DeclarationName Name = FD->getDeclName();
13890 RedeclarationKind::ForExternalRedeclaration);
13891 for (auto *D : FD->getParent()->lookup(Name))
13892 if (auto *Acceptable = R.getAcceptableDecl(D))
13893 R.addDecl(Acceptable);
13894 R.resolveKind();
13896
13897 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13899}
13900
13901void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13902 QualType ResultTy,
13903 ArrayRef<QualType> Args) {
13904 // Build an exception specification pointing back at this constructor.
13906
13908 if (AS != LangAS::Default) {
13909 EPI.TypeQuals.addAddressSpace(AS);
13910 }
13911
13912 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13913 SpecialMem->setType(QT);
13914
13915 // During template instantiation of implicit special member functions we need
13916 // a reliable TypeSourceInfo for the function prototype in order to allow
13917 // functions to be substituted.
13918 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
13919 TypeSourceInfo *TSI =
13921 SpecialMem->setTypeSourceInfo(TSI);
13922 }
13923}
13924
13926 CXXRecordDecl *ClassDecl) {
13927 // C++ [class.ctor]p5:
13928 // A default constructor for a class X is a constructor of class X
13929 // that can be called without an argument. If there is no
13930 // user-declared constructor for class X, a default constructor is
13931 // implicitly declared. An implicitly-declared default constructor
13932 // is an inline public member of its class.
13933 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13934 "Should not build implicit default constructor!");
13935
13936 DeclaringSpecialMember DSM(*this, ClassDecl,
13938 if (DSM.isAlreadyBeingDeclared())
13939 return nullptr;
13940
13942 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
13943
13944 // Create the actual constructor declaration.
13945 CanQualType ClassType
13947 SourceLocation ClassLoc = ClassDecl->getLocation();
13948 DeclarationName Name
13950 DeclarationNameInfo NameInfo(Name, ClassLoc);
13952 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13953 /*TInfo=*/nullptr, ExplicitSpecifier(),
13954 getCurFPFeatures().isFPConstrained(),
13955 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13958 DefaultCon->setAccess(AS_public);
13959 DefaultCon->setDefaulted();
13960
13961 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
13962
13963 if (getLangOpts().CUDA)
13965 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
13966 /* ConstRHS */ false,
13967 /* Diagnose */ false);
13968
13969 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13970 // constructors is easy to compute.
13971 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13972
13973 // Note that we have declared this constructor.
13975
13976 Scope *S = getScopeForContext(ClassDecl);
13978
13979 if (ShouldDeleteSpecialMember(DefaultCon,
13981 SetDeclDeleted(DefaultCon, ClassLoc);
13982
13983 if (S)
13984 PushOnScopeChains(DefaultCon, S, false);
13985 ClassDecl->addDecl(DefaultCon);
13986
13987 return DefaultCon;
13988}
13989
13991 CXXConstructorDecl *Constructor) {
13992 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13993 !Constructor->doesThisDeclarationHaveABody() &&
13994 !Constructor->isDeleted()) &&
13995 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13996 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13997 return;
13998
13999 CXXRecordDecl *ClassDecl = Constructor->getParent();
14000 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14001 if (ClassDecl->isInvalidDecl()) {
14002 return;
14003 }
14004
14005 SynthesizedFunctionScope Scope(*this, Constructor);
14006
14007 // The exception specification is needed because we are defining the
14008 // function.
14009 ResolveExceptionSpec(CurrentLocation,
14010 Constructor->getType()->castAs<FunctionProtoType>());
14011 MarkVTableUsed(CurrentLocation, ClassDecl);
14012
14013 // Add a context note for diagnostics produced after this point.
14014 Scope.addContextNote(CurrentLocation);
14015
14016 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14017 Constructor->setInvalidDecl();
14018 return;
14019 }
14020
14021 SourceLocation Loc = Constructor->getEndLoc().isValid()
14022 ? Constructor->getEndLoc()
14023 : Constructor->getLocation();
14024 Constructor->setBody(new (Context) CompoundStmt(Loc));
14025 Constructor->markUsed(Context);
14026
14028 L->CompletedImplicitDefinition(Constructor);
14029 }
14030
14031 DiagnoseUninitializedFields(*this, Constructor);
14032}
14033
14035 // Perform any delayed checks on exception specifications.
14037}
14038
14039/// Find or create the fake constructor we synthesize to model constructing an
14040/// object of a derived class via a constructor of a base class.
14043 CXXConstructorDecl *BaseCtor,
14045 CXXRecordDecl *Derived = Shadow->getParent();
14046 SourceLocation UsingLoc = Shadow->getLocation();
14047
14048 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14049 // For now we use the name of the base class constructor as a member of the
14050 // derived class to indicate a (fake) inherited constructor name.
14051 DeclarationName Name = BaseCtor->getDeclName();
14052
14053 // Check to see if we already have a fake constructor for this inherited
14054 // constructor call.
14055 for (NamedDecl *Ctor : Derived->lookup(Name))
14056 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14057 ->getInheritedConstructor()
14058 .getConstructor(),
14059 BaseCtor))
14060 return cast<CXXConstructorDecl>(Ctor);
14061
14062 DeclarationNameInfo NameInfo(Name, UsingLoc);
14063 TypeSourceInfo *TInfo =
14064 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14065 FunctionProtoTypeLoc ProtoLoc =
14067
14068 // Check the inherited constructor is valid and find the list of base classes
14069 // from which it was inherited.
14070 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14071
14072 bool Constexpr = BaseCtor->isConstexpr() &&
14075 false, BaseCtor, &ICI);
14076
14078 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14079 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14080 /*isInline=*/true,
14081 /*isImplicitlyDeclared=*/true,
14083 InheritedConstructor(Shadow, BaseCtor),
14084 BaseCtor->getTrailingRequiresClause());
14085 if (Shadow->isInvalidDecl())
14086 DerivedCtor->setInvalidDecl();
14087
14088 // Build an unevaluated exception specification for this fake constructor.
14089 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14092 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14093 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14094 FPT->getParamTypes(), EPI));
14095
14096 // Build the parameter declarations.
14098 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14099 TypeSourceInfo *TInfo =
14102 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14103 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14104 PD->setScopeInfo(0, I);
14105 PD->setImplicit();
14106 // Ensure attributes are propagated onto parameters (this matters for
14107 // format, pass_object_size, ...).
14108 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14109 ParamDecls.push_back(PD);
14110 ProtoLoc.setParam(I, PD);
14111 }
14112
14113 // Set up the new constructor.
14114 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14115 DerivedCtor->setAccess(BaseCtor->getAccess());
14116 DerivedCtor->setParams(ParamDecls);
14117 Derived->addDecl(DerivedCtor);
14118
14119 if (ShouldDeleteSpecialMember(DerivedCtor,
14121 SetDeclDeleted(DerivedCtor, UsingLoc);
14122
14123 return DerivedCtor;
14124}
14125
14127 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14130 &ICI,
14131 /*Diagnose*/ true);
14132}
14133
14135 CXXConstructorDecl *Constructor) {
14136 CXXRecordDecl *ClassDecl = Constructor->getParent();
14137 assert(Constructor->getInheritedConstructor() &&
14138 !Constructor->doesThisDeclarationHaveABody() &&
14139 !Constructor->isDeleted());
14140 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14141 return;
14142
14143 // Initializations are performed "as if by a defaulted default constructor",
14144 // so enter the appropriate scope.
14145 SynthesizedFunctionScope Scope(*this, Constructor);
14146
14147 // The exception specification is needed because we are defining the
14148 // function.
14149 ResolveExceptionSpec(CurrentLocation,
14150 Constructor->getType()->castAs<FunctionProtoType>());
14151 MarkVTableUsed(CurrentLocation, ClassDecl);
14152
14153 // Add a context note for diagnostics produced after this point.
14154 Scope.addContextNote(CurrentLocation);
14155
14157 Constructor->getInheritedConstructor().getShadowDecl();
14158 CXXConstructorDecl *InheritedCtor =
14159 Constructor->getInheritedConstructor().getConstructor();
14160
14161 // [class.inhctor.init]p1:
14162 // initialization proceeds as if a defaulted default constructor is used to
14163 // initialize the D object and each base class subobject from which the
14164 // constructor was inherited
14165
14166 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14167 CXXRecordDecl *RD = Shadow->getParent();
14168 SourceLocation InitLoc = Shadow->getLocation();
14169
14170 // Build explicit initializers for all base classes from which the
14171 // constructor was inherited.
14173 for (bool VBase : {false, true}) {
14174 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14175 if (B.isVirtual() != VBase)
14176 continue;
14177
14178 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14179 if (!BaseRD)
14180 continue;
14181
14182 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14183 if (!BaseCtor.first)
14184 continue;
14185
14186 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14188 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14189
14190 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14191 Inits.push_back(new (Context) CXXCtorInitializer(
14192 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14193 SourceLocation()));
14194 }
14195 }
14196
14197 // We now proceed as if for a defaulted default constructor, with the relevant
14198 // initializers replaced.
14199
14200 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14201 Constructor->setInvalidDecl();
14202 return;
14203 }
14204
14205 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14206 Constructor->markUsed(Context);
14207
14209 L->CompletedImplicitDefinition(Constructor);
14210 }
14211
14212 DiagnoseUninitializedFields(*this, Constructor);
14213}
14214
14216 // C++ [class.dtor]p2:
14217 // If a class has no user-declared destructor, a destructor is
14218 // declared implicitly. An implicitly-declared destructor is an
14219 // inline public member of its class.
14220 assert(ClassDecl->needsImplicitDestructor());
14221
14222 DeclaringSpecialMember DSM(*this, ClassDecl,
14224 if (DSM.isAlreadyBeingDeclared())
14225 return nullptr;
14226
14228 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14229
14230 // Create the actual destructor declaration.
14231 CanQualType ClassType
14233 SourceLocation ClassLoc = ClassDecl->getLocation();
14234 DeclarationName Name
14236 DeclarationNameInfo NameInfo(Name, ClassLoc);
14238 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14239 getCurFPFeatures().isFPConstrained(),
14240 /*isInline=*/true,
14241 /*isImplicitlyDeclared=*/true,
14244 Destructor->setAccess(AS_public);
14245 Destructor->setDefaulted();
14246
14247 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14248
14249 if (getLangOpts().CUDA)
14252 /* ConstRHS */ false,
14253 /* Diagnose */ false);
14254
14255 // We don't need to use SpecialMemberIsTrivial here; triviality for
14256 // destructors is easy to compute.
14257 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14258 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14259 ClassDecl->hasTrivialDestructorForCall());
14260
14261 // Note that we have declared this destructor.
14263
14264 Scope *S = getScopeForContext(ClassDecl);
14266
14267 // We can't check whether an implicit destructor is deleted before we complete
14268 // the definition of the class, because its validity depends on the alignment
14269 // of the class. We'll check this from ActOnFields once the class is complete.
14270 if (ClassDecl->isCompleteDefinition() &&
14272 SetDeclDeleted(Destructor, ClassLoc);
14273
14274 // Introduce this destructor into its scope.
14275 if (S)
14276 PushOnScopeChains(Destructor, S, false);
14277 ClassDecl->addDecl(Destructor);
14278
14279 return Destructor;
14280}
14281
14284 assert((Destructor->isDefaulted() &&
14285 !Destructor->doesThisDeclarationHaveABody() &&
14286 !Destructor->isDeleted()) &&
14287 "DefineImplicitDestructor - call it for implicit default dtor");
14288 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14289 return;
14290
14291 CXXRecordDecl *ClassDecl = Destructor->getParent();
14292 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14293
14295
14296 // The exception specification is needed because we are defining the
14297 // function.
14298 ResolveExceptionSpec(CurrentLocation,
14299 Destructor->getType()->castAs<FunctionProtoType>());
14300 MarkVTableUsed(CurrentLocation, ClassDecl);
14301
14302 // Add a context note for diagnostics produced after this point.
14303 Scope.addContextNote(CurrentLocation);
14304
14306 Destructor->getParent());
14307
14309 Destructor->setInvalidDecl();
14310 return;
14311 }
14312
14313 SourceLocation Loc = Destructor->getEndLoc().isValid()
14314 ? Destructor->getEndLoc()
14315 : Destructor->getLocation();
14316 Destructor->setBody(new (Context) CompoundStmt(Loc));
14317 Destructor->markUsed(Context);
14318
14320 L->CompletedImplicitDefinition(Destructor);
14321 }
14322}
14323
14326 if (Destructor->isInvalidDecl())
14327 return;
14328
14329 CXXRecordDecl *ClassDecl = Destructor->getParent();
14331 "implicit complete dtors unneeded outside MS ABI");
14332 assert(ClassDecl->getNumVBases() > 0 &&
14333 "complete dtor only exists for classes with vbases");
14334
14336
14337 // Add a context note for diagnostics produced after this point.
14338 Scope.addContextNote(CurrentLocation);
14339
14340 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14341}
14342
14344 // If the context is an invalid C++ class, just suppress these checks.
14345 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14346 if (Record->isInvalidDecl()) {
14349 return;
14350 }
14352 }
14353}
14354
14357
14358 if (!DelayedDllExportMemberFunctions.empty()) {
14360 std::swap(DelayedDllExportMemberFunctions, WorkList);
14361 for (CXXMethodDecl *M : WorkList) {
14362 DefineDefaultedFunction(*this, M, M->getLocation());
14363
14364 // Pass the method to the consumer to get emitted. This is not necessary
14365 // for explicit instantiation definitions, as they will get emitted
14366 // anyway.
14367 if (M->getParent()->getTemplateSpecializationKind() !=
14370 }
14371 }
14372}
14373
14375 if (!DelayedDllExportClasses.empty()) {
14376 // Calling ReferenceDllExportedMembers might cause the current function to
14377 // be called again, so use a local copy of DelayedDllExportClasses.
14379 std::swap(DelayedDllExportClasses, WorkList);
14380 for (CXXRecordDecl *Class : WorkList)
14382 }
14383}
14384
14386 assert(getLangOpts().CPlusPlus11 &&
14387 "adjusting dtor exception specs was introduced in c++11");
14388
14389 if (Destructor->isDependentContext())
14390 return;
14391
14392 // C++11 [class.dtor]p3:
14393 // A declaration of a destructor that does not have an exception-
14394 // specification is implicitly considered to have the same exception-
14395 // specification as an implicit declaration.
14396 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14397 if (DtorType->hasExceptionSpec())
14398 return;
14399
14400 // Replace the destructor's type, building off the existing one. Fortunately,
14401 // the only thing of interest in the destructor type is its extended info.
14402 // The return and arguments are fixed.
14403 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14406 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14407
14408 // FIXME: If the destructor has a body that could throw, and the newly created
14409 // spec doesn't allow exceptions, we should emit a warning, because this
14410 // change in behavior can break conforming C++03 programs at runtime.
14411 // However, we don't have a body or an exception specification yet, so it
14412 // needs to be done somewhere else.
14413}
14414
14415namespace {
14416/// An abstract base class for all helper classes used in building the
14417// copy/move operators. These classes serve as factory functions and help us
14418// avoid using the same Expr* in the AST twice.
14419class ExprBuilder {
14420 ExprBuilder(const ExprBuilder&) = delete;
14421 ExprBuilder &operator=(const ExprBuilder&) = delete;
14422
14423protected:
14424 static Expr *assertNotNull(Expr *E) {
14425 assert(E && "Expression construction must not fail.");
14426 return E;
14427 }
14428
14429public:
14430 ExprBuilder() {}
14431 virtual ~ExprBuilder() {}
14432
14433 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14434};
14435
14436class RefBuilder: public ExprBuilder {
14437 VarDecl *Var;
14438 QualType VarType;
14439
14440public:
14441 Expr *build(Sema &S, SourceLocation Loc) const override {
14442 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14443 }
14444
14445 RefBuilder(VarDecl *Var, QualType VarType)
14446 : Var(Var), VarType(VarType) {}
14447};
14448
14449class ThisBuilder: public ExprBuilder {
14450public:
14451 Expr *build(Sema &S, SourceLocation Loc) const override {
14452 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14453 }
14454};
14455
14456class CastBuilder: public ExprBuilder {
14457 const ExprBuilder &Builder;
14458 QualType Type;
14460 const CXXCastPath &Path;
14461
14462public:
14463 Expr *build(Sema &S, SourceLocation Loc) const override {
14464 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14465 CK_UncheckedDerivedToBase, Kind,
14466 &Path).get());
14467 }
14468
14469 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14470 const CXXCastPath &Path)
14471 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14472};
14473
14474class DerefBuilder: public ExprBuilder {
14475 const ExprBuilder &Builder;
14476
14477public:
14478 Expr *build(Sema &S, SourceLocation Loc) const override {
14479 return assertNotNull(
14480 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14481 }
14482
14483 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14484};
14485
14486class MemberBuilder: public ExprBuilder {
14487 const ExprBuilder &Builder;
14488 QualType Type;
14489 CXXScopeSpec SS;
14490 bool IsArrow;
14491 LookupResult &MemberLookup;
14492
14493public:
14494 Expr *build(Sema &S, SourceLocation Loc) const override {
14495 return assertNotNull(S.BuildMemberReferenceExpr(
14496 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14497 nullptr, MemberLookup, nullptr, nullptr).get());
14498 }
14499
14500 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14501 LookupResult &MemberLookup)
14502 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14503 MemberLookup(MemberLookup) {}
14504};
14505
14506class MoveCastBuilder: public ExprBuilder {
14507 const ExprBuilder &Builder;
14508
14509public:
14510 Expr *build(Sema &S, SourceLocation Loc) const override {
14511 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14512 }
14513
14514 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14515};
14516
14517class LvalueConvBuilder: public ExprBuilder {
14518 const ExprBuilder &Builder;
14519
14520public:
14521 Expr *build(Sema &S, SourceLocation Loc) const override {
14522 return assertNotNull(
14523 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14524 }
14525
14526 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14527};
14528
14529class SubscriptBuilder: public ExprBuilder {
14530 const ExprBuilder &Base;
14531 const ExprBuilder &Index;
14532
14533public:
14534 Expr *build(Sema &S, SourceLocation Loc) const override {
14535 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14536 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14537 }
14538
14539 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14540 : Base(Base), Index(Index) {}
14541};
14542
14543} // end anonymous namespace
14544
14545/// When generating a defaulted copy or move assignment operator, if a field
14546/// should be copied with __builtin_memcpy rather than via explicit assignments,
14547/// do so. This optimization only applies for arrays of scalars, and for arrays
14548/// of class type where the selected copy/move-assignment operator is trivial.
14549static StmtResult
14551 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14552 // Compute the size of the memory buffer to be copied.
14553 QualType SizeType = S.Context.getSizeType();
14554 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14556
14557 // Take the address of the field references for "from" and "to". We
14558 // directly construct UnaryOperators here because semantic analysis
14559 // does not permit us to take the address of an xvalue.
14560 Expr *From = FromB.build(S, Loc);
14561 From = UnaryOperator::Create(
14562 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14564 Expr *To = ToB.build(S, Loc);
14566 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14568
14569 const Type *E = T->getBaseElementTypeUnsafe();
14570 bool NeedsCollectableMemCpy =
14571 E->isRecordType() &&
14572 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14573
14574 // Create a reference to the __builtin_objc_memmove_collectable function
14575 StringRef MemCpyName = NeedsCollectableMemCpy ?
14576 "__builtin_objc_memmove_collectable" :
14577 "__builtin_memcpy";
14578 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14580 S.LookupName(R, S.TUScope, true);
14581
14582 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14583 if (!MemCpy)
14584 // Something went horribly wrong earlier, and we will have complained
14585 // about it.
14586 return StmtError();
14587
14588 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14589 VK_PRValue, Loc, nullptr);
14590 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14591
14592 Expr *CallArgs[] = {
14593 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14594 };
14595 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14596 Loc, CallArgs, Loc);
14597
14598 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14599 return Call.getAs<Stmt>();
14600}
14601
14602/// Builds a statement that copies/moves the given entity from \p From to
14603/// \c To.
14604///
14605/// This routine is used to copy/move the members of a class with an
14606/// implicitly-declared copy/move assignment operator. When the entities being
14607/// copied are arrays, this routine builds for loops to copy them.
14608///
14609/// \param S The Sema object used for type-checking.
14610///
14611/// \param Loc The location where the implicit copy/move is being generated.
14612///
14613/// \param T The type of the expressions being copied/moved. Both expressions
14614/// must have this type.
14615///
14616/// \param To The expression we are copying/moving to.
14617///
14618/// \param From The expression we are copying/moving from.
14619///
14620/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14621/// Otherwise, it's a non-static member subobject.
14622///
14623/// \param Copying Whether we're copying or moving.
14624///
14625/// \param Depth Internal parameter recording the depth of the recursion.
14626///
14627/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14628/// if a memcpy should be used instead.
14629static StmtResult
14631 const ExprBuilder &To, const ExprBuilder &From,
14632 bool CopyingBaseSubobject, bool Copying,
14633 unsigned Depth = 0) {
14634 // C++11 [class.copy]p28:
14635 // Each subobject is assigned in the manner appropriate to its type:
14636 //
14637 // - if the subobject is of class type, as if by a call to operator= with
14638 // the subobject as the object expression and the corresponding
14639 // subobject of x as a single function argument (as if by explicit
14640 // qualification; that is, ignoring any possible virtual overriding
14641 // functions in more derived classes);
14642 //
14643 // C++03 [class.copy]p13:
14644 // - if the subobject is of class type, the copy assignment operator for
14645 // the class is used (as if by explicit qualification; that is,
14646 // ignoring any possible virtual overriding functions in more derived
14647 // classes);
14648 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14649 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14650
14651 // Look for operator=.
14652 DeclarationName Name
14654 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14655 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14656
14657 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14658 // operator.
14659 if (!S.getLangOpts().CPlusPlus11) {
14660 LookupResult::Filter F = OpLookup.makeFilter();
14661 while (F.hasNext()) {
14662 NamedDecl *D = F.next();
14663 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14664 if (Method->isCopyAssignmentOperator() ||
14665 (!Copying && Method->isMoveAssignmentOperator()))
14666 continue;
14667
14668 F.erase();
14669 }
14670 F.done();
14671 }
14672
14673 // Suppress the protected check (C++ [class.protected]) for each of the
14674 // assignment operators we found. This strange dance is required when
14675 // we're assigning via a base classes's copy-assignment operator. To
14676 // ensure that we're getting the right base class subobject (without
14677 // ambiguities), we need to cast "this" to that subobject type; to
14678 // ensure that we don't go through the virtual call mechanism, we need
14679 // to qualify the operator= name with the base class (see below). However,
14680 // this means that if the base class has a protected copy assignment
14681 // operator, the protected member access check will fail. So, we
14682 // rewrite "protected" access to "public" access in this case, since we
14683 // know by construction that we're calling from a derived class.
14684 if (CopyingBaseSubobject) {
14685 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14686 L != LEnd; ++L) {
14687 if (L.getAccess() == AS_protected)
14688 L.setAccess(AS_public);
14689 }
14690 }
14691
14692 // Create the nested-name-specifier that will be used to qualify the
14693 // reference to operator=; this is required to suppress the virtual
14694 // call mechanism.
14695 CXXScopeSpec SS;
14696 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14697 SS.MakeTrivial(S.Context,
14698 NestedNameSpecifier::Create(S.Context, nullptr, false,
14699 CanonicalT),
14700 Loc);
14701
14702 // Create the reference to operator=.
14703 ExprResult OpEqualRef
14704 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14705 SS, /*TemplateKWLoc=*/SourceLocation(),
14706 /*FirstQualifierInScope=*/nullptr,
14707 OpLookup,
14708 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14709 /*SuppressQualifierCheck=*/true);
14710 if (OpEqualRef.isInvalid())
14711 return StmtError();
14712
14713 // Build the call to the assignment operator.
14714
14715 Expr *FromInst = From.build(S, Loc);
14716 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14717 OpEqualRef.getAs<Expr>(),
14718 Loc, FromInst, Loc);
14719 if (Call.isInvalid())
14720 return StmtError();
14721
14722 // If we built a call to a trivial 'operator=' while copying an array,
14723 // bail out. We'll replace the whole shebang with a memcpy.
14724 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14725 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14726 return StmtResult((Stmt*)nullptr);
14727
14728 // Convert to an expression-statement, and clean up any produced
14729 // temporaries.
14730 return S.ActOnExprStmt(Call);
14731 }
14732
14733 // - if the subobject is of scalar type, the built-in assignment
14734 // operator is used.
14736 if (!ArrayTy) {
14737 ExprResult Assignment = S.CreateBuiltinBinOp(
14738 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14739 if (Assignment.isInvalid())
14740 return StmtError();
14741 return S.ActOnExprStmt(Assignment);
14742 }
14743
14744 // - if the subobject is an array, each element is assigned, in the
14745 // manner appropriate to the element type;
14746
14747 // Construct a loop over the array bounds, e.g.,
14748 //
14749 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14750 //
14751 // that will copy each of the array elements.
14752 QualType SizeType = S.Context.getSizeType();
14753
14754 // Create the iteration variable.
14755 IdentifierInfo *IterationVarName = nullptr;
14756 {
14757 SmallString<8> Str;
14758 llvm::raw_svector_ostream OS(Str);
14759 OS << "__i" << Depth;
14760 IterationVarName = &S.Context.Idents.get(OS.str());
14761 }
14762 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14763 IterationVarName, SizeType,
14765 SC_None);
14766
14767 // Initialize the iteration variable to zero.
14768 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14769 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14770
14771 // Creates a reference to the iteration variable.
14772 RefBuilder IterationVarRef(IterationVar, SizeType);
14773 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14774
14775 // Create the DeclStmt that holds the iteration variable.
14776 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14777
14778 // Subscript the "from" and "to" expressions with the iteration variable.
14779 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14780 MoveCastBuilder FromIndexMove(FromIndexCopy);
14781 const ExprBuilder *FromIndex;
14782 if (Copying)
14783 FromIndex = &FromIndexCopy;
14784 else
14785 FromIndex = &FromIndexMove;
14786
14787 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14788
14789 // Build the copy/move for an individual element of the array.
14792 ToIndex, *FromIndex, CopyingBaseSubobject,
14793 Copying, Depth + 1);
14794 // Bail out if copying fails or if we determined that we should use memcpy.
14795 if (Copy.isInvalid() || !Copy.get())
14796 return Copy;
14797
14798 // Create the comparison against the array bound.
14799 llvm::APInt Upper
14800 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14801 Expr *Comparison = BinaryOperator::Create(
14802 S.Context, IterationVarRefRVal.build(S, Loc),
14803 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14806
14807 // Create the pre-increment of the iteration variable. We can determine
14808 // whether the increment will overflow based on the value of the array
14809 // bound.
14810 Expr *Increment = UnaryOperator::Create(
14811 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14812 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14813
14814 // Construct the loop that copies all elements of this array.
14815 return S.ActOnForStmt(
14816 Loc, Loc, InitStmt,
14817 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14818 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14819}
14820
14821static StmtResult
14823 const ExprBuilder &To, const ExprBuilder &From,
14824 bool CopyingBaseSubobject, bool Copying) {
14825 // Maybe we should use a memcpy?
14826 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14827 T.isTriviallyCopyableType(S.Context))
14828 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14829
14831 CopyingBaseSubobject,
14832 Copying, 0));
14833
14834 // If we ended up picking a trivial assignment operator for an array of a
14835 // non-trivially-copyable class type, just emit a memcpy.
14836 if (!Result.isInvalid() && !Result.get())
14837 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14838
14839 return Result;
14840}
14841
14843 // Note: The following rules are largely analoguous to the copy
14844 // constructor rules. Note that virtual bases are not taken into account
14845 // for determining the argument type of the operator. Note also that
14846 // operators taking an object instead of a reference are allowed.
14847 assert(ClassDecl->needsImplicitCopyAssignment());
14848
14849 DeclaringSpecialMember DSM(*this, ClassDecl,
14851 if (DSM.isAlreadyBeingDeclared())
14852 return nullptr;
14853
14854 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14856 ArgType, nullptr);
14858 if (AS != LangAS::Default)
14859 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14860 QualType RetType = Context.getLValueReferenceType(ArgType);
14861 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14862 if (Const)
14863 ArgType = ArgType.withConst();
14864
14865 ArgType = Context.getLValueReferenceType(ArgType);
14866
14868 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14869
14870 // An implicitly-declared copy assignment operator is an inline public
14871 // member of its class.
14873 SourceLocation ClassLoc = ClassDecl->getLocation();
14874 DeclarationNameInfo NameInfo(Name, ClassLoc);
14876 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14877 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14878 getCurFPFeatures().isFPConstrained(),
14879 /*isInline=*/true,
14881 SourceLocation());
14882 CopyAssignment->setAccess(AS_public);
14883 CopyAssignment->setDefaulted();
14884 CopyAssignment->setImplicit();
14885
14886 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14887
14888 if (getLangOpts().CUDA)
14891 /* ConstRHS */ Const,
14892 /* Diagnose */ false);
14893
14894 // Add the parameter to the operator.
14896 ClassLoc, ClassLoc,
14897 /*Id=*/nullptr, ArgType,
14898 /*TInfo=*/nullptr, SC_None,
14899 nullptr);
14900 CopyAssignment->setParams(FromParam);
14901
14902 CopyAssignment->setTrivial(
14906 : ClassDecl->hasTrivialCopyAssignment());
14907
14908 // Note that we have added this copy-assignment operator.
14910
14911 Scope *S = getScopeForContext(ClassDecl);
14913
14917 SetDeclDeleted(CopyAssignment, ClassLoc);
14918 }
14919
14920 if (S)
14922 ClassDecl->addDecl(CopyAssignment);
14923
14924 return CopyAssignment;
14925}
14926
14927/// Diagnose an implicit copy operation for a class which is odr-used, but
14928/// which is deprecated because the class has a user-declared copy constructor,
14929/// copy assignment operator, or destructor.
14931 assert(CopyOp->isImplicit());
14932
14933 CXXRecordDecl *RD = CopyOp->getParent();
14934 CXXMethodDecl *UserDeclaredOperation = nullptr;
14935
14936 if (RD->hasUserDeclaredDestructor()) {
14937 UserDeclaredOperation = RD->getDestructor();
14938 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14940 // Find any user-declared copy constructor.
14941 for (auto *I : RD->ctors()) {
14942 if (I->isCopyConstructor()) {
14943 UserDeclaredOperation = I;
14944 break;
14945 }
14946 }
14947 assert(UserDeclaredOperation);
14948 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14950 // Find any user-declared move assignment operator.
14951 for (auto *I : RD->methods()) {
14952 if (I->isCopyAssignmentOperator()) {
14953 UserDeclaredOperation = I;
14954 break;
14955 }
14956 }
14957 assert(UserDeclaredOperation);
14958 }
14959
14960 if (UserDeclaredOperation) {
14961 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14962 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14963 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14964 unsigned DiagID =
14965 (UDOIsUserProvided && UDOIsDestructor)
14966 ? diag::warn_deprecated_copy_with_user_provided_dtor
14967 : (UDOIsUserProvided && !UDOIsDestructor)
14968 ? diag::warn_deprecated_copy_with_user_provided_copy
14969 : (!UDOIsUserProvided && UDOIsDestructor)
14970 ? diag::warn_deprecated_copy_with_dtor
14971 : diag::warn_deprecated_copy;
14972 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14973 << RD << IsCopyAssignment;
14974 }
14975}
14976
14978 CXXMethodDecl *CopyAssignOperator) {
14979 assert((CopyAssignOperator->isDefaulted() &&
14980 CopyAssignOperator->isOverloadedOperator() &&
14981 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14982 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14983 !CopyAssignOperator->isDeleted()) &&
14984 "DefineImplicitCopyAssignment called for wrong function");
14985 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14986 return;
14987
14988 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14989 if (ClassDecl->isInvalidDecl()) {
14990 CopyAssignOperator->setInvalidDecl();
14991 return;
14992 }
14993
14994 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14995
14996 // The exception specification is needed because we are defining the
14997 // function.
14998 ResolveExceptionSpec(CurrentLocation,
14999 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15000
15001 // Add a context note for diagnostics produced after this point.
15002 Scope.addContextNote(CurrentLocation);
15003
15004 // C++11 [class.copy]p18:
15005 // The [definition of an implicitly declared copy assignment operator] is
15006 // deprecated if the class has a user-declared copy constructor or a
15007 // user-declared destructor.
15008 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15009 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15010
15011 // C++0x [class.copy]p30:
15012 // The implicitly-defined or explicitly-defaulted copy assignment operator
15013 // for a non-union class X performs memberwise copy assignment of its
15014 // subobjects. The direct base classes of X are assigned first, in the
15015 // order of their declaration in the base-specifier-list, and then the
15016 // immediate non-static data members of X are assigned, in the order in
15017 // which they were declared in the class definition.
15018
15019 // The statements that form the synthesized function body.
15020 SmallVector<Stmt*, 8> Statements;
15021
15022 // The parameter for the "other" object, which we are copying from.
15023 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15024 Qualifiers OtherQuals = Other->getType().getQualifiers();
15025 QualType OtherRefType = Other->getType();
15026 if (OtherRefType->isLValueReferenceType()) {
15027 OtherRefType = OtherRefType->getPointeeType();
15028 OtherQuals = OtherRefType.getQualifiers();
15029 }
15030
15031 // Our location for everything implicitly-generated.
15032 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15033 ? CopyAssignOperator->getEndLoc()
15034 : CopyAssignOperator->getLocation();
15035
15036 // Builds a DeclRefExpr for the "other" object.
15037 RefBuilder OtherRef(Other, OtherRefType);
15038
15039 // Builds the function object parameter.
15040 std::optional<ThisBuilder> This;
15041 std::optional<DerefBuilder> DerefThis;
15042 std::optional<RefBuilder> ExplicitObject;
15043 bool IsArrow = false;
15044 QualType ObjectType;
15045 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15046 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15047 if (ObjectType->isReferenceType())
15048 ObjectType = ObjectType->getPointeeType();
15049 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15050 } else {
15051 ObjectType = getCurrentThisType();
15052 This.emplace();
15053 DerefThis.emplace(*This);
15054 IsArrow = !LangOpts.HLSL;
15055 }
15056 ExprBuilder &ObjectParameter =
15057 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15058 : static_cast<ExprBuilder &>(*This);
15059
15060 // Assign base classes.
15061 bool Invalid = false;
15062 for (auto &Base : ClassDecl->bases()) {
15063 // Form the assignment:
15064 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15065 QualType BaseType = Base.getType().getUnqualifiedType();
15066 if (!BaseType->isRecordType()) {
15067 Invalid = true;
15068 continue;
15069 }
15070
15071 CXXCastPath BasePath;
15072 BasePath.push_back(&Base);
15073
15074 // Construct the "from" expression, which is an implicit cast to the
15075 // appropriately-qualified base type.
15076 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15077 VK_LValue, BasePath);
15078
15079 // Dereference "this".
15080 CastBuilder To(
15081 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15082 : static_cast<ExprBuilder &>(*DerefThis),
15083 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15084 VK_LValue, BasePath);
15085
15086 // Build the copy.
15087 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15088 To, From,
15089 /*CopyingBaseSubobject=*/true,
15090 /*Copying=*/true);
15091 if (Copy.isInvalid()) {
15092 CopyAssignOperator->setInvalidDecl();
15093 return;
15094 }
15095
15096 // Success! Record the copy.
15097 Statements.push_back(Copy.getAs<Expr>());
15098 }
15099
15100 // Assign non-static members.
15101 for (auto *Field : ClassDecl->fields()) {
15102 // FIXME: We should form some kind of AST representation for the implied
15103 // memcpy in a union copy operation.
15104 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15105 continue;
15106
15107 if (Field->isInvalidDecl()) {
15108 Invalid = true;
15109 continue;
15110 }
15111
15112 // Check for members of reference type; we can't copy those.
15113 if (Field->getType()->isReferenceType()) {
15114 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15115 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15116 Diag(Field->getLocation(), diag::note_declared_at);
15117 Invalid = true;
15118 continue;
15119 }
15120
15121 // Check for members of const-qualified, non-class type.
15122 QualType BaseType = Context.getBaseElementType(Field->getType());
15123 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15124 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15125 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15126 Diag(Field->getLocation(), diag::note_declared_at);
15127 Invalid = true;
15128 continue;
15129 }
15130
15131 // Suppress assigning zero-width bitfields.
15132 if (Field->isZeroLengthBitField())
15133 continue;
15134
15135 QualType FieldType = Field->getType().getNonReferenceType();
15136 if (FieldType->isIncompleteArrayType()) {
15137 assert(ClassDecl->hasFlexibleArrayMember() &&
15138 "Incomplete array type is not valid");
15139 continue;
15140 }
15141
15142 // Build references to the field in the object we're copying from and to.
15143 CXXScopeSpec SS; // Intentionally empty
15144 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15146 MemberLookup.addDecl(Field);
15147 MemberLookup.resolveKind();
15148
15149 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15150 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15151 // Build the copy of this field.
15152 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15153 To, From,
15154 /*CopyingBaseSubobject=*/false,
15155 /*Copying=*/true);
15156 if (Copy.isInvalid()) {
15157 CopyAssignOperator->setInvalidDecl();
15158 return;
15159 }
15160
15161 // Success! Record the copy.
15162 Statements.push_back(Copy.getAs<Stmt>());
15163 }
15164
15165 if (!Invalid) {
15166 // Add a "return *this;"
15167 Expr *ThisExpr =
15168 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15169 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15170 : static_cast<ExprBuilder &>(*DerefThis))
15171 .build(*this, Loc);
15172 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15173 if (Return.isInvalid())
15174 Invalid = true;
15175 else
15176 Statements.push_back(Return.getAs<Stmt>());
15177 }
15178
15179 if (Invalid) {
15180 CopyAssignOperator->setInvalidDecl();
15181 return;
15182 }
15183
15184 StmtResult Body;
15185 {
15186 CompoundScopeRAII CompoundScope(*this);
15187 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15188 /*isStmtExpr=*/false);
15189 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15190 }
15191 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15192 CopyAssignOperator->markUsed(Context);
15193
15195 L->CompletedImplicitDefinition(CopyAssignOperator);
15196 }
15197}
15198
15200 assert(ClassDecl->needsImplicitMoveAssignment());
15201
15202 DeclaringSpecialMember DSM(*this, ClassDecl,
15204 if (DSM.isAlreadyBeingDeclared())
15205 return nullptr;
15206
15207 // Note: The following rules are largely analoguous to the move
15208 // constructor rules.
15209
15210 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15212 ArgType, nullptr);
15214 if (AS != LangAS::Default)
15215 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15216 QualType RetType = Context.getLValueReferenceType(ArgType);
15217 ArgType = Context.getRValueReferenceType(ArgType);
15218
15220 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15221
15222 // An implicitly-declared move assignment operator is an inline public
15223 // member of its class.
15225 SourceLocation ClassLoc = ClassDecl->getLocation();
15226 DeclarationNameInfo NameInfo(Name, ClassLoc);
15228 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15229 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15230 getCurFPFeatures().isFPConstrained(),
15231 /*isInline=*/true,
15233 SourceLocation());
15234 MoveAssignment->setAccess(AS_public);
15235 MoveAssignment->setDefaulted();
15236 MoveAssignment->setImplicit();
15237
15238 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15239
15240 if (getLangOpts().CUDA)
15243 /* ConstRHS */ false,
15244 /* Diagnose */ false);
15245
15246 // Add the parameter to the operator.
15248 ClassLoc, ClassLoc,
15249 /*Id=*/nullptr, ArgType,
15250 /*TInfo=*/nullptr, SC_None,
15251 nullptr);
15252 MoveAssignment->setParams(FromParam);
15253
15254 MoveAssignment->setTrivial(
15258 : ClassDecl->hasTrivialMoveAssignment());
15259
15260 // Note that we have added this copy-assignment operator.
15262
15263 Scope *S = getScopeForContext(ClassDecl);
15265
15269 SetDeclDeleted(MoveAssignment, ClassLoc);
15270 }
15271
15272 if (S)
15274 ClassDecl->addDecl(MoveAssignment);
15275
15276 return MoveAssignment;
15277}
15278
15279/// Check if we're implicitly defining a move assignment operator for a class
15280/// with virtual bases. Such a move assignment might move-assign the virtual
15281/// base multiple times.
15283 SourceLocation CurrentLocation) {
15284 assert(!Class->isDependentContext() && "should not define dependent move");
15285
15286 // Only a virtual base could get implicitly move-assigned multiple times.
15287 // Only a non-trivial move assignment can observe this. We only want to
15288 // diagnose if we implicitly define an assignment operator that assigns
15289 // two base classes, both of which move-assign the same virtual base.
15290 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15291 Class->getNumBases() < 2)
15292 return;
15293
15295 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15296 VBaseMap VBases;
15297
15298 for (auto &BI : Class->bases()) {
15299 Worklist.push_back(&BI);
15300 while (!Worklist.empty()) {
15301 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15302 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15303
15304 // If the base has no non-trivial move assignment operators,
15305 // we don't care about moves from it.
15306 if (!Base->hasNonTrivialMoveAssignment())
15307 continue;
15308
15309 // If there's nothing virtual here, skip it.
15310 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15311 continue;
15312
15313 // If we're not actually going to call a move assignment for this base,
15314 // or the selected move assignment is trivial, skip it.
15317 /*ConstArg*/ false, /*VolatileArg*/ false,
15318 /*RValueThis*/ true, /*ConstThis*/ false,
15319 /*VolatileThis*/ false);
15320 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15322 continue;
15323
15324 if (BaseSpec->isVirtual()) {
15325 // We're going to move-assign this virtual base, and its move
15326 // assignment operator is not trivial. If this can happen for
15327 // multiple distinct direct bases of Class, diagnose it. (If it
15328 // only happens in one base, we'll diagnose it when synthesizing
15329 // that base class's move assignment operator.)
15330 CXXBaseSpecifier *&Existing =
15331 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15332 .first->second;
15333 if (Existing && Existing != &BI) {
15334 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15335 << Class << Base;
15336 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15337 << (Base->getCanonicalDecl() ==
15339 << Base << Existing->getType() << Existing->getSourceRange();
15340 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15341 << (Base->getCanonicalDecl() ==
15342 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15343 << Base << BI.getType() << BaseSpec->getSourceRange();
15344
15345 // Only diagnose each vbase once.
15346 Existing = nullptr;
15347 }
15348 } else {
15349 // Only walk over bases that have defaulted move assignment operators.
15350 // We assume that any user-provided move assignment operator handles
15351 // the multiple-moves-of-vbase case itself somehow.
15352 if (!SMOR.getMethod()->isDefaulted())
15353 continue;
15354
15355 // We're going to move the base classes of Base. Add them to the list.
15356 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15357 }
15358 }
15359 }
15360}
15361
15363 CXXMethodDecl *MoveAssignOperator) {
15364 assert((MoveAssignOperator->isDefaulted() &&
15365 MoveAssignOperator->isOverloadedOperator() &&
15366 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15367 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15368 !MoveAssignOperator->isDeleted()) &&
15369 "DefineImplicitMoveAssignment called for wrong function");
15370 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15371 return;
15372
15373 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15374 if (ClassDecl->isInvalidDecl()) {
15375 MoveAssignOperator->setInvalidDecl();
15376 return;
15377 }
15378
15379 // C++0x [class.copy]p28:
15380 // The implicitly-defined or move assignment operator for a non-union class
15381 // X performs memberwise move assignment of its subobjects. The direct base
15382 // classes of X are assigned first, in the order of their declaration in the
15383 // base-specifier-list, and then the immediate non-static data members of X
15384 // are assigned, in the order in which they were declared in the class
15385 // definition.
15386
15387 // Issue a warning if our implicit move assignment operator will move
15388 // from a virtual base more than once.
15389 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15390
15391 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15392
15393 // The exception specification is needed because we are defining the
15394 // function.
15395 ResolveExceptionSpec(CurrentLocation,
15396 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15397
15398 // Add a context note for diagnostics produced after this point.
15399 Scope.addContextNote(CurrentLocation);
15400
15401 // The statements that form the synthesized function body.
15402 SmallVector<Stmt*, 8> Statements;
15403
15404 // The parameter for the "other" object, which we are move from.
15405 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15406 QualType OtherRefType =
15407 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15408
15409 // Our location for everything implicitly-generated.
15410 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15411 ? MoveAssignOperator->getEndLoc()
15412 : MoveAssignOperator->getLocation();
15413
15414 // Builds a reference to the "other" object.
15415 RefBuilder OtherRef(Other, OtherRefType);
15416 // Cast to rvalue.
15417 MoveCastBuilder MoveOther(OtherRef);
15418
15419 // Builds the function object parameter.
15420 std::optional<ThisBuilder> This;
15421 std::optional<DerefBuilder> DerefThis;
15422 std::optional<RefBuilder> ExplicitObject;
15423 QualType ObjectType;
15424 bool IsArrow = false;
15425 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15426 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15427 if (ObjectType->isReferenceType())
15428 ObjectType = ObjectType->getPointeeType();
15429 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15430 } else {
15431 ObjectType = getCurrentThisType();
15432 This.emplace();
15433 DerefThis.emplace(*This);
15434 IsArrow = !getLangOpts().HLSL;
15435 }
15436 ExprBuilder &ObjectParameter =
15437 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15438
15439 // Assign base classes.
15440 bool Invalid = false;
15441 for (auto &Base : ClassDecl->bases()) {
15442 // C++11 [class.copy]p28:
15443 // It is unspecified whether subobjects representing virtual base classes
15444 // are assigned more than once by the implicitly-defined copy assignment
15445 // operator.
15446 // FIXME: Do not assign to a vbase that will be assigned by some other base
15447 // class. For a move-assignment, this can result in the vbase being moved
15448 // multiple times.
15449
15450 // Form the assignment:
15451 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15452 QualType BaseType = Base.getType().getUnqualifiedType();
15453 if (!BaseType->isRecordType()) {
15454 Invalid = true;
15455 continue;
15456 }
15457
15458 CXXCastPath BasePath;
15459 BasePath.push_back(&Base);
15460
15461 // Construct the "from" expression, which is an implicit cast to the
15462 // appropriately-qualified base type.
15463 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15464
15465 // Implicitly cast "this" to the appropriately-qualified base type.
15466 // Dereference "this".
15467 CastBuilder To(
15468 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15469 : static_cast<ExprBuilder &>(*DerefThis),
15470 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15471 VK_LValue, BasePath);
15472
15473 // Build the move.
15474 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15475 To, From,
15476 /*CopyingBaseSubobject=*/true,
15477 /*Copying=*/false);
15478 if (Move.isInvalid()) {
15479 MoveAssignOperator->setInvalidDecl();
15480 return;
15481 }
15482
15483 // Success! Record the move.
15484 Statements.push_back(Move.getAs<Expr>());
15485 }
15486
15487 // Assign non-static members.
15488 for (auto *Field : ClassDecl->fields()) {
15489 // FIXME: We should form some kind of AST representation for the implied
15490 // memcpy in a union copy operation.
15491 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15492 continue;
15493
15494 if (Field->isInvalidDecl()) {
15495 Invalid = true;
15496 continue;
15497 }
15498
15499 // Check for members of reference type; we can't move those.
15500 if (Field->getType()->isReferenceType()) {
15501 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15502 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15503 Diag(Field->getLocation(), diag::note_declared_at);
15504 Invalid = true;
15505 continue;
15506 }
15507
15508 // Check for members of const-qualified, non-class type.
15509 QualType BaseType = Context.getBaseElementType(Field->getType());
15510 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15511 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15512 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15513 Diag(Field->getLocation(), diag::note_declared_at);
15514 Invalid = true;
15515 continue;
15516 }
15517
15518 // Suppress assigning zero-width bitfields.
15519 if (Field->isZeroLengthBitField())
15520 continue;
15521
15522 QualType FieldType = Field->getType().getNonReferenceType();
15523 if (FieldType->isIncompleteArrayType()) {
15524 assert(ClassDecl->hasFlexibleArrayMember() &&
15525 "Incomplete array type is not valid");
15526 continue;
15527 }
15528
15529 // Build references to the field in the object we're copying from and to.
15530 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15532 MemberLookup.addDecl(Field);
15533 MemberLookup.resolveKind();
15534 MemberBuilder From(MoveOther, OtherRefType,
15535 /*IsArrow=*/false, MemberLookup);
15536 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15537
15538 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15539 "Member reference with rvalue base must be rvalue except for reference "
15540 "members, which aren't allowed for move assignment.");
15541
15542 // Build the move of this field.
15543 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15544 To, From,
15545 /*CopyingBaseSubobject=*/false,
15546 /*Copying=*/false);
15547 if (Move.isInvalid()) {
15548 MoveAssignOperator->setInvalidDecl();
15549 return;
15550 }
15551
15552 // Success! Record the copy.
15553 Statements.push_back(Move.getAs<Stmt>());
15554 }
15555
15556 if (!Invalid) {
15557 // Add a "return *this;"
15558 Expr *ThisExpr =
15559 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15560 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15561 : static_cast<ExprBuilder &>(*DerefThis))
15562 .build(*this, Loc);
15563
15564 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15565 if (Return.isInvalid())
15566 Invalid = true;
15567 else
15568 Statements.push_back(Return.getAs<Stmt>());
15569 }
15570
15571 if (Invalid) {
15572 MoveAssignOperator->setInvalidDecl();
15573 return;
15574 }
15575
15576 StmtResult Body;
15577 {
15578 CompoundScopeRAII CompoundScope(*this);
15579 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15580 /*isStmtExpr=*/false);
15581 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15582 }
15583 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15584 MoveAssignOperator->markUsed(Context);
15585
15587 L->CompletedImplicitDefinition(MoveAssignOperator);
15588 }
15589}
15590
15592 CXXRecordDecl *ClassDecl) {
15593 // C++ [class.copy]p4:
15594 // If the class definition does not explicitly declare a copy
15595 // constructor, one is declared implicitly.
15596 assert(ClassDecl->needsImplicitCopyConstructor());
15597
15598 DeclaringSpecialMember DSM(*this, ClassDecl,
15600 if (DSM.isAlreadyBeingDeclared())
15601 return nullptr;
15602
15603 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15604 QualType ArgType = ClassType;
15606 ArgType, nullptr);
15607 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15608 if (Const)
15609 ArgType = ArgType.withConst();
15610
15612 if (AS != LangAS::Default)
15613 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15614
15615 ArgType = Context.getLValueReferenceType(ArgType);
15616
15618 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15619
15620 DeclarationName Name
15622 Context.getCanonicalType(ClassType));
15623 SourceLocation ClassLoc = ClassDecl->getLocation();
15624 DeclarationNameInfo NameInfo(Name, ClassLoc);
15625
15626 // An implicitly-declared copy constructor is an inline public
15627 // member of its class.
15629 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15630 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15631 /*isInline=*/true,
15632 /*isImplicitlyDeclared=*/true,
15635 CopyConstructor->setAccess(AS_public);
15636 CopyConstructor->setDefaulted();
15637
15638 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15639
15640 if (getLangOpts().CUDA)
15643 /* ConstRHS */ Const,
15644 /* Diagnose */ false);
15645
15646 // During template instantiation of special member functions we need a
15647 // reliable TypeSourceInfo for the parameter types in order to allow functions
15648 // to be substituted.
15649 TypeSourceInfo *TSI = nullptr;
15650 if (inTemplateInstantiation() && ClassDecl->isLambda())
15651 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15652
15653 // Add the parameter to the constructor.
15654 ParmVarDecl *FromParam =
15655 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15656 /*IdentifierInfo=*/nullptr, ArgType,
15657 /*TInfo=*/TSI, SC_None, nullptr);
15658 CopyConstructor->setParams(FromParam);
15659
15660 CopyConstructor->setTrivial(
15664 : ClassDecl->hasTrivialCopyConstructor());
15665
15666 CopyConstructor->setTrivialForCall(
15667 ClassDecl->hasAttr<TrivialABIAttr>() ||
15672 : ClassDecl->hasTrivialCopyConstructorForCall()));
15673
15674 // Note that we have declared this constructor.
15676
15677 Scope *S = getScopeForContext(ClassDecl);
15679
15684 }
15685
15686 if (S)
15688 ClassDecl->addDecl(CopyConstructor);
15689
15690 return CopyConstructor;
15691}
15692
15695 assert((CopyConstructor->isDefaulted() &&
15696 CopyConstructor->isCopyConstructor() &&
15697 !CopyConstructor->doesThisDeclarationHaveABody() &&
15698 !CopyConstructor->isDeleted()) &&
15699 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15700 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15701 return;
15702
15703 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15704 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15705
15707
15708 // The exception specification is needed because we are defining the
15709 // function.
15710 ResolveExceptionSpec(CurrentLocation,
15711 CopyConstructor->getType()->castAs<FunctionProtoType>());
15712 MarkVTableUsed(CurrentLocation, ClassDecl);
15713
15714 // Add a context note for diagnostics produced after this point.
15715 Scope.addContextNote(CurrentLocation);
15716
15717 // C++11 [class.copy]p7:
15718 // The [definition of an implicitly declared copy constructor] is
15719 // deprecated if the class has a user-declared copy assignment operator
15720 // or a user-declared destructor.
15721 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15723
15724 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15725 CopyConstructor->setInvalidDecl();
15726 } else {
15727 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15728 ? CopyConstructor->getEndLoc()
15729 : CopyConstructor->getLocation();
15730 Sema::CompoundScopeRAII CompoundScope(*this);
15731 CopyConstructor->setBody(
15732 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
15733 CopyConstructor->markUsed(Context);
15734 }
15735
15737 L->CompletedImplicitDefinition(CopyConstructor);
15738 }
15739}
15740
15742 CXXRecordDecl *ClassDecl) {
15743 assert(ClassDecl->needsImplicitMoveConstructor());
15744
15745 DeclaringSpecialMember DSM(*this, ClassDecl,
15747 if (DSM.isAlreadyBeingDeclared())
15748 return nullptr;
15749
15750 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15751
15752 QualType ArgType = ClassType;
15754 ArgType, nullptr);
15756 if (AS != LangAS::Default)
15757 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15758 ArgType = Context.getRValueReferenceType(ArgType);
15759
15761 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15762
15763 DeclarationName Name
15765 Context.getCanonicalType(ClassType));
15766 SourceLocation ClassLoc = ClassDecl->getLocation();
15767 DeclarationNameInfo NameInfo(Name, ClassLoc);
15768
15769 // C++11 [class.copy]p11:
15770 // An implicitly-declared copy/move constructor is an inline public
15771 // member of its class.
15773 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15774 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15775 /*isInline=*/true,
15776 /*isImplicitlyDeclared=*/true,
15779 MoveConstructor->setAccess(AS_public);
15780 MoveConstructor->setDefaulted();
15781
15782 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15783
15784 if (getLangOpts().CUDA)
15787 /* ConstRHS */ false,
15788 /* Diagnose */ false);
15789
15790 // Add the parameter to the constructor.
15792 ClassLoc, ClassLoc,
15793 /*IdentifierInfo=*/nullptr,
15794 ArgType, /*TInfo=*/nullptr,
15795 SC_None, nullptr);
15796 MoveConstructor->setParams(FromParam);
15797
15798 MoveConstructor->setTrivial(
15802 : ClassDecl->hasTrivialMoveConstructor());
15803
15804 MoveConstructor->setTrivialForCall(
15805 ClassDecl->hasAttr<TrivialABIAttr>() ||
15810 : ClassDecl->hasTrivialMoveConstructorForCall()));
15811
15812 // Note that we have declared this constructor.
15814
15815 Scope *S = getScopeForContext(ClassDecl);
15817
15822 }
15823
15824 if (S)
15826 ClassDecl->addDecl(MoveConstructor);
15827
15828 return MoveConstructor;
15829}
15830
15833 assert((MoveConstructor->isDefaulted() &&
15834 MoveConstructor->isMoveConstructor() &&
15835 !MoveConstructor->doesThisDeclarationHaveABody() &&
15836 !MoveConstructor->isDeleted()) &&
15837 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15838 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15839 return;
15840
15841 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15842 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15843
15845
15846 // The exception specification is needed because we are defining the
15847 // function.
15848 ResolveExceptionSpec(CurrentLocation,
15849 MoveConstructor->getType()->castAs<FunctionProtoType>());
15850 MarkVTableUsed(CurrentLocation, ClassDecl);
15851
15852 // Add a context note for diagnostics produced after this point.
15853 Scope.addContextNote(CurrentLocation);
15854
15855 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15856 MoveConstructor->setInvalidDecl();
15857 } else {
15858 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15859 ? MoveConstructor->getEndLoc()
15860 : MoveConstructor->getLocation();
15861 Sema::CompoundScopeRAII CompoundScope(*this);
15862 MoveConstructor->setBody(
15863 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
15864 MoveConstructor->markUsed(Context);
15865 }
15866
15868 L->CompletedImplicitDefinition(MoveConstructor);
15869 }
15870}
15871
15873 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15874}
15875
15877 SourceLocation CurrentLocation,
15878 CXXConversionDecl *Conv) {
15879 SynthesizedFunctionScope Scope(*this, Conv);
15880 assert(!Conv->getReturnType()->isUndeducedType());
15881
15882 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15883 CallingConv CC =
15884 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15885
15886 CXXRecordDecl *Lambda = Conv->getParent();
15887 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15888 FunctionDecl *Invoker =
15889 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15890 ? CallOp
15891 : Lambda->getLambdaStaticInvoker(CC);
15892
15893 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15895 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15896 if (!CallOp)
15897 return;
15898
15899 if (CallOp != Invoker) {
15901 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15902 CurrentLocation);
15903 if (!Invoker)
15904 return;
15905 }
15906 }
15907
15908 if (CallOp->isInvalidDecl())
15909 return;
15910
15911 // Mark the call operator referenced (and add to pending instantiations
15912 // if necessary).
15913 // For both the conversion and static-invoker template specializations
15914 // we construct their body's in this function, so no need to add them
15915 // to the PendingInstantiations.
15916 MarkFunctionReferenced(CurrentLocation, CallOp);
15917
15918 if (Invoker != CallOp) {
15919 // Fill in the __invoke function with a dummy implementation. IR generation
15920 // will fill in the actual details. Update its type in case it contained
15921 // an 'auto'.
15922 Invoker->markUsed(Context);
15923 Invoker->setReferenced();
15924 Invoker->setType(Conv->getReturnType()->getPointeeType());
15925 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15926 }
15927
15928 // Construct the body of the conversion function { return __invoke; }.
15929 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15930 Conv->getLocation());
15931 assert(FunctionRef && "Can't refer to __invoke function?");
15932 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15934 Conv->getLocation(), Conv->getLocation()));
15935 Conv->markUsed(Context);
15936 Conv->setReferenced();
15937
15939 L->CompletedImplicitDefinition(Conv);
15940 if (Invoker != CallOp)
15941 L->CompletedImplicitDefinition(Invoker);
15942 }
15943}
15944
15946 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15947 assert(!Conv->getParent()->isGenericLambda());
15948
15949 SynthesizedFunctionScope Scope(*this, Conv);
15950
15951 // Copy-initialize the lambda object as needed to capture it.
15952 Expr *This = ActOnCXXThis(CurrentLocation).get();
15953 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15954
15955 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15956 Conv->getLocation(),
15957 Conv, DerefThis);
15958
15959 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15960 // behavior. Note that only the general conversion function does this
15961 // (since it's unusable otherwise); in the case where we inline the
15962 // block literal, it has block literal lifetime semantics.
15963 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15964 BuildBlock = ImplicitCastExpr::Create(
15965 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15966 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15967
15968 if (BuildBlock.isInvalid()) {
15969 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15970 Conv->setInvalidDecl();
15971 return;
15972 }
15973
15974 // Create the return statement that returns the block from the conversion
15975 // function.
15976 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15977 if (Return.isInvalid()) {
15978 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15979 Conv->setInvalidDecl();
15980 return;
15981 }
15982
15983 // Set the body of the conversion function.
15984 Stmt *ReturnS = Return.get();
15986 Conv->getLocation(), Conv->getLocation()));
15987 Conv->markUsed(Context);
15988
15989 // We're done; notify the mutation listener, if any.
15991 L->CompletedImplicitDefinition(Conv);
15992 }
15993}
15994
15995/// Determine whether the given list arguments contains exactly one
15996/// "real" (non-default) argument.
15998 switch (Args.size()) {
15999 case 0:
16000 return false;
16001
16002 default:
16003 if (!Args[1]->isDefaultArgument())
16004 return false;
16005
16006 [[fallthrough]];
16007 case 1:
16008 return !Args[0]->isDefaultArgument();
16009 }
16010
16011 return false;
16012}
16013
16015 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16016 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16017 bool HadMultipleCandidates, bool IsListInitialization,
16018 bool IsStdInitListInitialization, bool RequiresZeroInit,
16019 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16020 bool Elidable = false;
16021
16022 // C++0x [class.copy]p34:
16023 // When certain criteria are met, an implementation is allowed to
16024 // omit the copy/move construction of a class object, even if the
16025 // copy/move constructor and/or destructor for the object have
16026 // side effects. [...]
16027 // - when a temporary class object that has not been bound to a
16028 // reference (12.2) would be copied/moved to a class object
16029 // with the same cv-unqualified type, the copy/move operation
16030 // can be omitted by constructing the temporary object
16031 // directly into the target of the omitted copy/move
16032 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16033 // FIXME: Converting constructors should also be accepted.
16034 // But to fix this, the logic that digs down into a CXXConstructExpr
16035 // to find the source object needs to handle it.
16036 // Right now it assumes the source object is passed directly as the
16037 // first argument.
16038 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16039 Expr *SubExpr = ExprArgs[0];
16040 // FIXME: Per above, this is also incorrect if we want to accept
16041 // converting constructors, as isTemporaryObject will
16042 // reject temporaries with different type from the
16043 // CXXRecord itself.
16044 Elidable = SubExpr->isTemporaryObject(
16045 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16046 }
16047
16048 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16049 FoundDecl, Constructor,
16050 Elidable, ExprArgs, HadMultipleCandidates,
16051 IsListInitialization,
16052 IsStdInitListInitialization, RequiresZeroInit,
16053 ConstructKind, ParenRange);
16054}
16055
16057 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16058 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16059 bool HadMultipleCandidates, bool IsListInitialization,
16060 bool IsStdInitListInitialization, bool RequiresZeroInit,
16061 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16062 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16063 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16064 // The only way to get here is if we did overload resolution to find the
16065 // shadow decl, so we don't need to worry about re-checking the trailing
16066 // requires clause.
16067 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16068 return ExprError();
16069 }
16070
16071 return BuildCXXConstructExpr(
16072 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16073 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16074 RequiresZeroInit, ConstructKind, ParenRange);
16075}
16076
16077/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16078/// including handling of its default argument expressions.
16080 SourceLocation ConstructLoc, QualType DeclInitType,
16081 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16082 bool HadMultipleCandidates, bool IsListInitialization,
16083 bool IsStdInitListInitialization, bool RequiresZeroInit,
16084 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16085 assert(declaresSameEntity(
16086 Constructor->getParent(),
16087 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16088 "given constructor for wrong type");
16089 MarkFunctionReferenced(ConstructLoc, Constructor);
16090 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16091 return ExprError();
16092
16095 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16096 HadMultipleCandidates, IsListInitialization,
16097 IsStdInitListInitialization, RequiresZeroInit,
16098 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16099 Constructor);
16100}
16101
16103 if (VD->isInvalidDecl()) return;
16104 // If initializing the variable failed, don't also diagnose problems with
16105 // the destructor, they're likely related.
16106 if (VD->getInit() && VD->getInit()->containsErrors())
16107 return;
16108
16109 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16110 if (ClassDecl->isInvalidDecl()) return;
16111 if (ClassDecl->hasIrrelevantDestructor()) return;
16112 if (ClassDecl->isDependentContext()) return;
16113
16114 if (VD->isNoDestroy(getASTContext()))
16115 return;
16116
16118 // The result of `LookupDestructor` might be nullptr if the destructor is
16119 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16120 // will not be selected by `CXXRecordDecl::getDestructor()`.
16121 if (!Destructor)
16122 return;
16123 // If this is an array, we'll require the destructor during initialization, so
16124 // we can skip over this. We still want to emit exit-time destructor warnings
16125 // though.
16126 if (!VD->getType()->isArrayType()) {
16129 PDiag(diag::err_access_dtor_var)
16130 << VD->getDeclName() << VD->getType());
16132 }
16133
16134 if (Destructor->isTrivial()) return;
16135
16136 // If the destructor is constexpr, check whether the variable has constant
16137 // destruction now.
16138 if (Destructor->isConstexpr()) {
16139 bool HasConstantInit = false;
16140 if (VD->getInit() && !VD->getInit()->isValueDependent())
16141 HasConstantInit = VD->evaluateValue();
16143 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16144 HasConstantInit) {
16145 Diag(VD->getLocation(),
16146 diag::err_constexpr_var_requires_const_destruction) << VD;
16147 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16148 Diag(Notes[I].first, Notes[I].second);
16149 }
16150 }
16151
16152 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16153 return;
16154
16155 // Emit warning for non-trivial dtor in global scope (a real global,
16156 // class-static, function-static).
16157 if (!VD->hasAttr<AlwaysDestroyAttr>())
16158 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16159
16160 // TODO: this should be re-enabled for static locals by !CXAAtExit
16161 if (!VD->isStaticLocal())
16162 Diag(VD->getLocation(), diag::warn_global_destructor);
16163}
16164
16166 QualType DeclInitType, MultiExprArg ArgsPtr,
16168 SmallVectorImpl<Expr *> &ConvertedArgs,
16169 bool AllowExplicit,
16170 bool IsListInitialization) {
16171 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16172 unsigned NumArgs = ArgsPtr.size();
16173 Expr **Args = ArgsPtr.data();
16174
16175 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16176 unsigned NumParams = Proto->getNumParams();
16177
16178 // If too few arguments are available, we'll fill in the rest with defaults.
16179 if (NumArgs < NumParams)
16180 ConvertedArgs.reserve(NumParams);
16181 else
16182 ConvertedArgs.reserve(NumArgs);
16183
16184 VariadicCallType CallType =
16185 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16186 SmallVector<Expr *, 8> AllArgs;
16188 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16189 CallType, AllowExplicit, IsListInitialization);
16190 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16191
16192 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16193
16194 CheckConstructorCall(Constructor, DeclInitType,
16195 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16196 Loc);
16197
16198 return Invalid;
16199}
16200
16201static inline bool
16203 const FunctionDecl *FnDecl) {
16204 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16205 if (isa<NamespaceDecl>(DC)) {
16206 return SemaRef.Diag(FnDecl->getLocation(),
16207 diag::err_operator_new_delete_declared_in_namespace)
16208 << FnDecl->getDeclName();
16209 }
16210
16211 if (isa<TranslationUnitDecl>(DC) &&
16212 FnDecl->getStorageClass() == SC_Static) {
16213 return SemaRef.Diag(FnDecl->getLocation(),
16214 diag::err_operator_new_delete_declared_static)
16215 << FnDecl->getDeclName();
16216 }
16217
16218 return false;
16219}
16220
16222 const PointerType *PtrTy) {
16223 auto &Ctx = SemaRef.Context;
16224 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16225 PtrQuals.removeAddressSpace();
16227 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16228}
16229
16230static inline bool
16232 CanQualType ExpectedResultType,
16233 CanQualType ExpectedFirstParamType,
16234 unsigned DependentParamTypeDiag,
16235 unsigned InvalidParamTypeDiag) {
16236 QualType ResultType =
16237 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16238
16239 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16240 // The operator is valid on any address space for OpenCL.
16241 // Drop address space from actual and expected result types.
16242 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16243 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16244
16245 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16246 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16247 }
16248
16249 // Check that the result type is what we expect.
16250 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16251 // Reject even if the type is dependent; an operator delete function is
16252 // required to have a non-dependent result type.
16253 return SemaRef.Diag(
16254 FnDecl->getLocation(),
16255 ResultType->isDependentType()
16256 ? diag::err_operator_new_delete_dependent_result_type
16257 : diag::err_operator_new_delete_invalid_result_type)
16258 << FnDecl->getDeclName() << ExpectedResultType;
16259 }
16260
16261 // A function template must have at least 2 parameters.
16262 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16263 return SemaRef.Diag(FnDecl->getLocation(),
16264 diag::err_operator_new_delete_template_too_few_parameters)
16265 << FnDecl->getDeclName();
16266
16267 // The function decl must have at least 1 parameter.
16268 if (FnDecl->getNumParams() == 0)
16269 return SemaRef.Diag(FnDecl->getLocation(),
16270 diag::err_operator_new_delete_too_few_parameters)
16271 << FnDecl->getDeclName();
16272
16273 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16274 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16275 // The operator is valid on any address space for OpenCL.
16276 // Drop address space from actual and expected first parameter types.
16277 if (const auto *PtrTy =
16278 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16279 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16280
16281 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16282 ExpectedFirstParamType =
16283 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16284 }
16285
16286 // Check that the first parameter type is what we expect.
16287 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16288 ExpectedFirstParamType) {
16289 // The first parameter type is not allowed to be dependent. As a tentative
16290 // DR resolution, we allow a dependent parameter type if it is the right
16291 // type anyway, to allow destroying operator delete in class templates.
16292 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16293 ? DependentParamTypeDiag
16294 : InvalidParamTypeDiag)
16295 << FnDecl->getDeclName() << ExpectedFirstParamType;
16296 }
16297
16298 return false;
16299}
16300
16301static bool
16303 // C++ [basic.stc.dynamic.allocation]p1:
16304 // A program is ill-formed if an allocation function is declared in a
16305 // namespace scope other than global scope or declared static in global
16306 // scope.
16308 return true;
16309
16310 CanQualType SizeTy =
16312
16313 // C++ [basic.stc.dynamic.allocation]p1:
16314 // The return type shall be void*. The first parameter shall have type
16315 // std::size_t.
16317 SizeTy,
16318 diag::err_operator_new_dependent_param_type,
16319 diag::err_operator_new_param_type))
16320 return true;
16321
16322 // C++ [basic.stc.dynamic.allocation]p1:
16323 // The first parameter shall not have an associated default argument.
16324 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16325 return SemaRef.Diag(FnDecl->getLocation(),
16326 diag::err_operator_new_default_arg)
16327 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16328
16329 return false;
16330}
16331
16332static bool
16334 // C++ [basic.stc.dynamic.deallocation]p1:
16335 // A program is ill-formed if deallocation functions are declared in a
16336 // namespace scope other than global scope or declared static in global
16337 // scope.
16339 return true;
16340
16341 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16342
16343 // C++ P0722:
16344 // Within a class C, the first parameter of a destroying operator delete
16345 // shall be of type C *. The first parameter of any other deallocation
16346 // function shall be of type void *.
16347 CanQualType ExpectedFirstParamType =
16348 MD && MD->isDestroyingOperatorDelete()
16352
16353 // C++ [basic.stc.dynamic.deallocation]p2:
16354 // Each deallocation function shall return void
16356 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16357 diag::err_operator_delete_dependent_param_type,
16358 diag::err_operator_delete_param_type))
16359 return true;
16360
16361 // C++ P0722:
16362 // A destroying operator delete shall be a usual deallocation function.
16363 if (MD && !MD->getParent()->isDependentContext() &&
16366 SemaRef.Diag(MD->getLocation(),
16367 diag::err_destroying_operator_delete_not_usual);
16368 return true;
16369 }
16370
16371 return false;
16372}
16373
16375 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16376 "Expected an overloaded operator declaration");
16377
16379
16380 // C++ [over.oper]p5:
16381 // The allocation and deallocation functions, operator new,
16382 // operator new[], operator delete and operator delete[], are
16383 // described completely in 3.7.3. The attributes and restrictions
16384 // found in the rest of this subclause do not apply to them unless
16385 // explicitly stated in 3.7.3.
16386 if (Op == OO_Delete || Op == OO_Array_Delete)
16387 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16388
16389 if (Op == OO_New || Op == OO_Array_New)
16390 return CheckOperatorNewDeclaration(*this, FnDecl);
16391
16392 // C++ [over.oper]p7:
16393 // An operator function shall either be a member function or
16394 // be a non-member function and have at least one parameter
16395 // whose type is a class, a reference to a class, an enumeration,
16396 // or a reference to an enumeration.
16397 // Note: Before C++23, a member function could not be static. The only member
16398 // function allowed to be static is the call operator function.
16399 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16400 if (MethodDecl->isStatic()) {
16401 if (Op == OO_Call || Op == OO_Subscript)
16402 Diag(FnDecl->getLocation(),
16403 (LangOpts.CPlusPlus23
16404 ? diag::warn_cxx20_compat_operator_overload_static
16405 : diag::ext_operator_overload_static))
16406 << FnDecl;
16407 else
16408 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16409 << FnDecl;
16410 }
16411 } else {
16412 bool ClassOrEnumParam = false;
16413 for (auto *Param : FnDecl->parameters()) {
16414 QualType ParamType = Param->getType().getNonReferenceType();
16415 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16416 ParamType->isEnumeralType()) {
16417 ClassOrEnumParam = true;
16418 break;
16419 }
16420 }
16421
16422 if (!ClassOrEnumParam)
16423 return Diag(FnDecl->getLocation(),
16424 diag::err_operator_overload_needs_class_or_enum)
16425 << FnDecl->getDeclName();
16426 }
16427
16428 // C++ [over.oper]p8:
16429 // An operator function cannot have default arguments (8.3.6),
16430 // except where explicitly stated below.
16431 //
16432 // Only the function-call operator (C++ [over.call]p1) and the subscript
16433 // operator (CWG2507) allow default arguments.
16434 if (Op != OO_Call) {
16435 ParmVarDecl *FirstDefaultedParam = nullptr;
16436 for (auto *Param : FnDecl->parameters()) {
16437 if (Param->hasDefaultArg()) {
16438 FirstDefaultedParam = Param;
16439 break;
16440 }
16441 }
16442 if (FirstDefaultedParam) {
16443 if (Op == OO_Subscript) {
16444 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16445 ? diag::ext_subscript_overload
16446 : diag::error_subscript_overload)
16447 << FnDecl->getDeclName() << 1
16448 << FirstDefaultedParam->getDefaultArgRange();
16449 } else {
16450 return Diag(FirstDefaultedParam->getLocation(),
16451 diag::err_operator_overload_default_arg)
16452 << FnDecl->getDeclName()
16453 << FirstDefaultedParam->getDefaultArgRange();
16454 }
16455 }
16456 }
16457
16458 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16459 { false, false, false }
16460#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16461 , { Unary, Binary, MemberOnly }
16462#include "clang/Basic/OperatorKinds.def"
16463 };
16464
16465 bool CanBeUnaryOperator = OperatorUses[Op][0];
16466 bool CanBeBinaryOperator = OperatorUses[Op][1];
16467 bool MustBeMemberOperator = OperatorUses[Op][2];
16468
16469 // C++ [over.oper]p8:
16470 // [...] Operator functions cannot have more or fewer parameters
16471 // than the number required for the corresponding operator, as
16472 // described in the rest of this subclause.
16473 unsigned NumParams = FnDecl->getNumParams() +
16474 (isa<CXXMethodDecl>(FnDecl) &&
16476 ? 1
16477 : 0);
16478 if (Op != OO_Call && Op != OO_Subscript &&
16479 ((NumParams == 1 && !CanBeUnaryOperator) ||
16480 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16481 (NumParams > 2))) {
16482 // We have the wrong number of parameters.
16483 unsigned ErrorKind;
16484 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16485 ErrorKind = 2; // 2 -> unary or binary.
16486 } else if (CanBeUnaryOperator) {
16487 ErrorKind = 0; // 0 -> unary
16488 } else {
16489 assert(CanBeBinaryOperator &&
16490 "All non-call overloaded operators are unary or binary!");
16491 ErrorKind = 1; // 1 -> binary
16492 }
16493 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16494 << FnDecl->getDeclName() << NumParams << ErrorKind;
16495 }
16496
16497 if (Op == OO_Subscript && NumParams != 2) {
16498 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16499 ? diag::ext_subscript_overload
16500 : diag::error_subscript_overload)
16501 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16502 }
16503
16504 // Overloaded operators other than operator() and operator[] cannot be
16505 // variadic.
16506 if (Op != OO_Call &&
16507 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16508 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16509 << FnDecl->getDeclName();
16510 }
16511
16512 // Some operators must be member functions.
16513 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16514 return Diag(FnDecl->getLocation(),
16515 diag::err_operator_overload_must_be_member)
16516 << FnDecl->getDeclName();
16517 }
16518
16519 // C++ [over.inc]p1:
16520 // The user-defined function called operator++ implements the
16521 // prefix and postfix ++ operator. If this function is a member
16522 // function with no parameters, or a non-member function with one
16523 // parameter of class or enumeration type, it defines the prefix
16524 // increment operator ++ for objects of that type. If the function
16525 // is a member function with one parameter (which shall be of type
16526 // int) or a non-member function with two parameters (the second
16527 // of which shall be of type int), it defines the postfix
16528 // increment operator ++ for objects of that type.
16529 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16530 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16531 QualType ParamType = LastParam->getType();
16532
16533 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16534 !ParamType->isDependentType())
16535 return Diag(LastParam->getLocation(),
16536 diag::err_operator_overload_post_incdec_must_be_int)
16537 << LastParam->getType() << (Op == OO_MinusMinus);
16538 }
16539
16540 return false;
16541}
16542
16543static bool
16545 FunctionTemplateDecl *TpDecl) {
16546 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16547
16548 // Must have one or two template parameters.
16549 if (TemplateParams->size() == 1) {
16550 NonTypeTemplateParmDecl *PmDecl =
16551 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16552
16553 // The template parameter must be a char parameter pack.
16554 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16556 return false;
16557
16558 // C++20 [over.literal]p5:
16559 // A string literal operator template is a literal operator template
16560 // whose template-parameter-list comprises a single non-type
16561 // template-parameter of class type.
16562 //
16563 // As a DR resolution, we also allow placeholders for deduced class
16564 // template specializations.
16565 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16566 !PmDecl->isTemplateParameterPack() &&
16567 (PmDecl->getType()->isRecordType() ||
16569 return false;
16570 } else if (TemplateParams->size() == 2) {
16571 TemplateTypeParmDecl *PmType =
16572 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16573 NonTypeTemplateParmDecl *PmArgs =
16574 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16575
16576 // The second template parameter must be a parameter pack with the
16577 // first template parameter as its type.
16578 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16579 PmArgs->isTemplateParameterPack()) {
16580 const TemplateTypeParmType *TArgs =
16581 PmArgs->getType()->getAs<TemplateTypeParmType>();
16582 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16583 TArgs->getIndex() == PmType->getIndex()) {
16585 SemaRef.Diag(TpDecl->getLocation(),
16586 diag::ext_string_literal_operator_template);
16587 return false;
16588 }
16589 }
16590 }
16591
16593 diag::err_literal_operator_template)
16594 << TpDecl->getTemplateParameters()->getSourceRange();
16595 return true;
16596}
16597
16599 if (isa<CXXMethodDecl>(FnDecl)) {
16600 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16601 << FnDecl->getDeclName();
16602 return true;
16603 }
16604
16605 if (FnDecl->isExternC()) {
16606 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16607 if (const LinkageSpecDecl *LSD =
16608 FnDecl->getDeclContext()->getExternCContext())
16609 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16610 return true;
16611 }
16612
16613 // This might be the definition of a literal operator template.
16615
16616 // This might be a specialization of a literal operator template.
16617 if (!TpDecl)
16618 TpDecl = FnDecl->getPrimaryTemplate();
16619
16620 // template <char...> type operator "" name() and
16621 // template <class T, T...> type operator "" name() are the only valid
16622 // template signatures, and the only valid signatures with no parameters.
16623 //
16624 // C++20 also allows template <SomeClass T> type operator "" name().
16625 if (TpDecl) {
16626 if (FnDecl->param_size() != 0) {
16627 Diag(FnDecl->getLocation(),
16628 diag::err_literal_operator_template_with_params);
16629 return true;
16630 }
16631
16633 return true;
16634
16635 } else if (FnDecl->param_size() == 1) {
16636 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16637
16638 QualType ParamType = Param->getType().getUnqualifiedType();
16639
16640 // Only unsigned long long int, long double, any character type, and const
16641 // char * are allowed as the only parameters.
16642 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16643 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16644 Context.hasSameType(ParamType, Context.CharTy) ||
16645 Context.hasSameType(ParamType, Context.WideCharTy) ||
16646 Context.hasSameType(ParamType, Context.Char8Ty) ||
16647 Context.hasSameType(ParamType, Context.Char16Ty) ||
16648 Context.hasSameType(ParamType, Context.Char32Ty)) {
16649 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16650 QualType InnerType = Ptr->getPointeeType();
16651
16652 // Pointer parameter must be a const char *.
16653 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16654 Context.CharTy) &&
16655 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16656 Diag(Param->getSourceRange().getBegin(),
16657 diag::err_literal_operator_param)
16658 << ParamType << "'const char *'" << Param->getSourceRange();
16659 return true;
16660 }
16661
16662 } else if (ParamType->isRealFloatingType()) {
16663 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16664 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16665 return true;
16666
16667 } else if (ParamType->isIntegerType()) {
16668 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16669 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16670 return true;
16671
16672 } else {
16673 Diag(Param->getSourceRange().getBegin(),
16674 diag::err_literal_operator_invalid_param)
16675 << ParamType << Param->getSourceRange();
16676 return true;
16677 }
16678
16679 } else if (FnDecl->param_size() == 2) {
16680 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16681
16682 // First, verify that the first parameter is correct.
16683
16684 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16685
16686 // Two parameter function must have a pointer to const as a
16687 // first parameter; let's strip those qualifiers.
16688 const PointerType *PT = FirstParamType->getAs<PointerType>();
16689
16690 if (!PT) {
16691 Diag((*Param)->getSourceRange().getBegin(),
16692 diag::err_literal_operator_param)
16693 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16694 return true;
16695 }
16696
16697 QualType PointeeType = PT->getPointeeType();
16698 // First parameter must be const
16699 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16700 Diag((*Param)->getSourceRange().getBegin(),
16701 diag::err_literal_operator_param)
16702 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16703 return true;
16704 }
16705
16706 QualType InnerType = PointeeType.getUnqualifiedType();
16707 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16708 // const char32_t* are allowed as the first parameter to a two-parameter
16709 // function
16710 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16711 Context.hasSameType(InnerType, Context.WideCharTy) ||
16712 Context.hasSameType(InnerType, Context.Char8Ty) ||
16713 Context.hasSameType(InnerType, Context.Char16Ty) ||
16714 Context.hasSameType(InnerType, Context.Char32Ty))) {
16715 Diag((*Param)->getSourceRange().getBegin(),
16716 diag::err_literal_operator_param)
16717 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16718 return true;
16719 }
16720
16721 // Move on to the second and final parameter.
16722 ++Param;
16723
16724 // The second parameter must be a std::size_t.
16725 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16726 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16727 Diag((*Param)->getSourceRange().getBegin(),
16728 diag::err_literal_operator_param)
16729 << SecondParamType << Context.getSizeType()
16730 << (*Param)->getSourceRange();
16731 return true;
16732 }
16733 } else {
16734 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16735 return true;
16736 }
16737
16738 // Parameters are good.
16739
16740 // A parameter-declaration-clause containing a default argument is not
16741 // equivalent to any of the permitted forms.
16742 for (auto *Param : FnDecl->parameters()) {
16743 if (Param->hasDefaultArg()) {
16744 Diag(Param->getDefaultArgRange().getBegin(),
16745 diag::err_literal_operator_default_argument)
16746 << Param->getDefaultArgRange();
16747 break;
16748 }
16749 }
16750
16751 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16754 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16755 // C++23 [usrlit.suffix]p1:
16756 // Literal suffix identifiers that do not start with an underscore are
16757 // reserved for future standardization. Literal suffix identifiers that
16758 // contain a double underscore __ are reserved for use by C++
16759 // implementations.
16760 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16761 << static_cast<int>(Status)
16763 }
16764
16765 return false;
16766}
16767
16769 Expr *LangStr,
16770 SourceLocation LBraceLoc) {
16771 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16772 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16773
16774 StringRef Lang = Lit->getString();
16776 if (Lang == "C")
16778 else if (Lang == "C++")
16780 else {
16781 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16782 << LangStr->getSourceRange();
16783 return nullptr;
16784 }
16785
16786 // FIXME: Add all the various semantics of linkage specifications
16787
16789 LangStr->getExprLoc(), Language,
16790 LBraceLoc.isValid());
16791
16792 /// C++ [module.unit]p7.2.3
16793 /// - Otherwise, if the declaration
16794 /// - ...
16795 /// - ...
16796 /// - appears within a linkage-specification,
16797 /// it is attached to the global module.
16798 ///
16799 /// If the declaration is already in global module fragment, we don't
16800 /// need to attach it again.
16801 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16802 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16803 D->setLocalOwningModule(GlobalModule);
16804 }
16805
16807 PushDeclContext(S, D);
16808 return D;
16809}
16810
16812 Decl *LinkageSpec,
16813 SourceLocation RBraceLoc) {
16814 if (RBraceLoc.isValid()) {
16815 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16816 LSDecl->setRBraceLoc(RBraceLoc);
16817 }
16818
16819 // If the current module doesn't has Parent, it implies that the
16820 // LinkageSpec isn't in the module created by itself. So we don't
16821 // need to pop it.
16822 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16823 getCurrentModule()->isImplicitGlobalModule() &&
16825 PopImplicitGlobalModuleFragment();
16826
16828 return LinkageSpec;
16829}
16830
16832 const ParsedAttributesView &AttrList,
16833 SourceLocation SemiLoc) {
16834 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16835 // Attribute declarations appertain to empty declaration so we handle
16836 // them here.
16837 ProcessDeclAttributeList(S, ED, AttrList);
16838
16839 CurContext->addDecl(ED);
16840 return ED;
16841}
16842
16844 SourceLocation StartLoc,
16846 const IdentifierInfo *Name) {
16847 bool Invalid = false;
16848 QualType ExDeclType = TInfo->getType();
16849
16850 // Arrays and functions decay.
16851 if (ExDeclType->isArrayType())
16852 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16853 else if (ExDeclType->isFunctionType())
16854 ExDeclType = Context.getPointerType(ExDeclType);
16855
16856 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16857 // The exception-declaration shall not denote a pointer or reference to an
16858 // incomplete type, other than [cv] void*.
16859 // N2844 forbids rvalue references.
16860 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16861 Diag(Loc, diag::err_catch_rvalue_ref);
16862 Invalid = true;
16863 }
16864
16865 if (ExDeclType->isVariablyModifiedType()) {
16866 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16867 Invalid = true;
16868 }
16869
16870 QualType BaseType = ExDeclType;
16871 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16872 unsigned DK = diag::err_catch_incomplete;
16873 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16874 BaseType = Ptr->getPointeeType();
16875 Mode = 1;
16876 DK = diag::err_catch_incomplete_ptr;
16877 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16878 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16879 BaseType = Ref->getPointeeType();
16880 Mode = 2;
16881 DK = diag::err_catch_incomplete_ref;
16882 }
16883 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16884 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16885 Invalid = true;
16886
16887 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16888 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16889 Invalid = true;
16890 }
16891
16892 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16893 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16894 Invalid = true;
16895 }
16896
16897 if (!Invalid && !ExDeclType->isDependentType() &&
16898 RequireNonAbstractType(Loc, ExDeclType,
16899 diag::err_abstract_type_in_decl,
16901 Invalid = true;
16902
16903 // Only the non-fragile NeXT runtime currently supports C++ catches
16904 // of ObjC types, and no runtime supports catching ObjC types by value.
16905 if (!Invalid && getLangOpts().ObjC) {
16906 QualType T = ExDeclType;
16907 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16908 T = RT->getPointeeType();
16909
16910 if (T->isObjCObjectType()) {
16911 Diag(Loc, diag::err_objc_object_catch);
16912 Invalid = true;
16913 } else if (T->isObjCObjectPointerType()) {
16914 // FIXME: should this be a test for macosx-fragile specifically?
16916 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16917 }
16918 }
16919
16920 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16921 ExDeclType, TInfo, SC_None);
16922 ExDecl->setExceptionVariable(true);
16923
16924 // In ARC, infer 'retaining' for variables of retainable type.
16925 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
16926 Invalid = true;
16927
16928 if (!Invalid && !ExDeclType->isDependentType()) {
16929 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16930 // Insulate this from anything else we might currently be parsing.
16933
16934 // C++ [except.handle]p16:
16935 // The object declared in an exception-declaration or, if the
16936 // exception-declaration does not specify a name, a temporary (12.2) is
16937 // copy-initialized (8.5) from the exception object. [...]
16938 // The object is destroyed when the handler exits, after the destruction
16939 // of any automatic objects initialized within the handler.
16940 //
16941 // We just pretend to initialize the object with itself, then make sure
16942 // it can be destroyed later.
16943 QualType initType = Context.getExceptionObjectType(ExDeclType);
16944
16945 InitializedEntity entity =
16947 InitializationKind initKind =
16949
16950 Expr *opaqueValue =
16951 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16952 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16953 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16954 if (result.isInvalid())
16955 Invalid = true;
16956 else {
16957 // If the constructor used was non-trivial, set this as the
16958 // "initializer".
16959 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16960 if (!construct->getConstructor()->isTrivial()) {
16961 Expr *init = MaybeCreateExprWithCleanups(construct);
16962 ExDecl->setInit(init);
16963 }
16964
16965 // And make sure it's destructable.
16967 }
16968 }
16969 }
16970
16971 if (Invalid)
16972 ExDecl->setInvalidDecl();
16973
16974 return ExDecl;
16975}
16976
16979 bool Invalid = D.isInvalidType();
16980
16981 // Check for unexpanded parameter packs.
16982 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16985 D.getIdentifierLoc());
16986 Invalid = true;
16987 }
16988
16989 const IdentifierInfo *II = D.getIdentifier();
16990 if (NamedDecl *PrevDecl =
16991 LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
16992 RedeclarationKind::ForVisibleRedeclaration)) {
16993 // The scope should be freshly made just for us. There is just no way
16994 // it contains any previous declaration, except for function parameters in
16995 // a function-try-block's catch statement.
16996 assert(!S->isDeclScope(PrevDecl));
16997 if (isDeclInScope(PrevDecl, CurContext, S)) {
16998 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16999 << D.getIdentifier();
17000 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17001 Invalid = true;
17002 } else if (PrevDecl->isTemplateParameter())
17003 // Maybe we will complain about the shadowed template parameter.
17004 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17005 }
17006
17007 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17008 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17009 << D.getCXXScopeSpec().getRange();
17010 Invalid = true;
17011 }
17012
17014 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17015 if (Invalid)
17016 ExDecl->setInvalidDecl();
17017
17018 // Add the exception declaration into this scope.
17019 if (II)
17020 PushOnScopeChains(ExDecl, S);
17021 else
17022 CurContext->addDecl(ExDecl);
17023
17024 ProcessDeclAttributes(S, ExDecl, D);
17025 return ExDecl;
17026}
17027
17029 Expr *AssertExpr,
17030 Expr *AssertMessageExpr,
17031 SourceLocation RParenLoc) {
17033 return nullptr;
17034
17035 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17036 AssertMessageExpr, RParenLoc, false);
17037}
17038
17039static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17040 switch (BTK) {
17041 case BuiltinType::Char_S:
17042 case BuiltinType::Char_U:
17043 break;
17044 case BuiltinType::Char8:
17045 OS << "u8";
17046 break;
17047 case BuiltinType::Char16:
17048 OS << 'u';
17049 break;
17050 case BuiltinType::Char32:
17051 OS << 'U';
17052 break;
17053 case BuiltinType::WChar_S:
17054 case BuiltinType::WChar_U:
17055 OS << 'L';
17056 break;
17057 default:
17058 llvm_unreachable("Non-character type");
17059 }
17060}
17061
17062/// Convert character's value, interpreted as a code unit, to a string.
17063/// The value needs to be zero-extended to 32-bits.
17064/// FIXME: This assumes Unicode literal encodings
17065static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17066 unsigned TyWidth,
17067 SmallVectorImpl<char> &Str) {
17068 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17069 char *Ptr = Arr;
17070 BuiltinType::Kind K = BTy->getKind();
17071 llvm::raw_svector_ostream OS(Str);
17072
17073 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17074 // other types.
17075 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17076 K == BuiltinType::Char8 || Value <= 0x7F) {
17077 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17078 if (!Escaped.empty())
17079 EscapeStringForDiagnostic(Escaped, Str);
17080 else
17081 OS << static_cast<char>(Value);
17082 return;
17083 }
17084
17085 switch (K) {
17086 case BuiltinType::Char16:
17087 case BuiltinType::Char32:
17088 case BuiltinType::WChar_S:
17089 case BuiltinType::WChar_U: {
17090 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17091 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17092 else
17093 OS << "\\x"
17094 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17095 break;
17096 }
17097 default:
17098 llvm_unreachable("Non-character type is passed");
17099 }
17100}
17101
17102/// Convert \V to a string we can present to the user in a diagnostic
17103/// \T is the type of the expression that has been evaluated into \V
17107 if (!V.hasValue())
17108 return false;
17109
17110 switch (V.getKind()) {
17112 if (T->isBooleanType()) {
17113 // Bools are reduced to ints during evaluation, but for
17114 // diagnostic purposes we want to print them as
17115 // true or false.
17116 int64_t BoolValue = V.getInt().getExtValue();
17117 assert((BoolValue == 0 || BoolValue == 1) &&
17118 "Bool type, but value is not 0 or 1");
17119 llvm::raw_svector_ostream OS(Str);
17120 OS << (BoolValue ? "true" : "false");
17121 } else {
17122 llvm::raw_svector_ostream OS(Str);
17123 // Same is true for chars.
17124 // We want to print the character representation for textual types
17125 const auto *BTy = T->getAs<BuiltinType>();
17126 if (BTy) {
17127 switch (BTy->getKind()) {
17128 case BuiltinType::Char_S:
17129 case BuiltinType::Char_U:
17130 case BuiltinType::Char8:
17131 case BuiltinType::Char16:
17132 case BuiltinType::Char32:
17133 case BuiltinType::WChar_S:
17134 case BuiltinType::WChar_U: {
17135 unsigned TyWidth = Context.getIntWidth(T);
17136 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17137 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17138 WriteCharTypePrefix(BTy->getKind(), OS);
17139 OS << '\'';
17140 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17141 OS << "' (0x"
17142 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17143 /*Upper=*/true)
17144 << ", " << V.getInt() << ')';
17145 return true;
17146 }
17147 default:
17148 break;
17149 }
17150 }
17151 V.getInt().toString(Str);
17152 }
17153
17154 break;
17155
17157 V.getFloat().toString(Str);
17158 break;
17159
17161 if (V.isNullPointer()) {
17162 llvm::raw_svector_ostream OS(Str);
17163 OS << "nullptr";
17164 } else
17165 return false;
17166 break;
17167
17169 llvm::raw_svector_ostream OS(Str);
17170 OS << '(';
17171 V.getComplexFloatReal().toString(Str);
17172 OS << " + ";
17173 V.getComplexFloatImag().toString(Str);
17174 OS << "i)";
17175 } break;
17176
17178 llvm::raw_svector_ostream OS(Str);
17179 OS << '(';
17180 V.getComplexIntReal().toString(Str);
17181 OS << " + ";
17182 V.getComplexIntImag().toString(Str);
17183 OS << "i)";
17184 } break;
17185
17186 default:
17187 return false;
17188 }
17189
17190 return true;
17191}
17192
17193/// Some Expression types are not useful to print notes about,
17194/// e.g. literals and values that have already been expanded
17195/// before such as int-valued template parameters.
17196static bool UsefulToPrintExpr(const Expr *E) {
17197 E = E->IgnoreParenImpCasts();
17198 // Literals are pretty easy for humans to understand.
17201 return false;
17202
17203 // These have been substituted from template parameters
17204 // and appear as literals in the static assert error.
17205 if (isa<SubstNonTypeTemplateParmExpr>(E))
17206 return false;
17207
17208 // -5 is also simple to understand.
17209 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17210 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17211
17212 // Only print nested arithmetic operators.
17213 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17214 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17215 BO->isBitwiseOp());
17216
17217 return true;
17218}
17219
17221 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17222 Op && Op->getOpcode() != BO_LOr) {
17223 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17224 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17225
17226 // Ignore comparisons of boolean expressions with a boolean literal.
17227 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17228 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17229 return;
17230
17231 // Don't print obvious expressions.
17232 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17233 return;
17234
17235 struct {
17236 const clang::Expr *Cond;
17238 SmallString<12> ValueString;
17239 bool Print;
17240 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17241 {RHS, Expr::EvalResult(), {}, false}};
17242 for (unsigned I = 0; I < 2; I++) {
17243 const Expr *Side = DiagSide[I].Cond;
17244
17245 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17246
17247 DiagSide[I].Print =
17248 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17249 DiagSide[I].ValueString, Context);
17250 }
17251 if (DiagSide[0].Print && DiagSide[1].Print) {
17252 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17253 << DiagSide[0].ValueString << Op->getOpcodeStr()
17254 << DiagSide[1].ValueString << Op->getSourceRange();
17255 }
17256 }
17257}
17258
17260 std::string &Result,
17261 ASTContext &Ctx,
17262 bool ErrorOnInvalidMessage) {
17263 assert(Message);
17264 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17265 "can't evaluate a dependant static assert message");
17266
17267 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17268 assert(SL->isUnevaluated() && "expected an unevaluated string");
17269 Result.assign(SL->getString().begin(), SL->getString().end());
17270 return true;
17271 }
17272
17273 SourceLocation Loc = Message->getBeginLoc();
17274 QualType T = Message->getType().getNonReferenceType();
17275 auto *RD = T->getAsCXXRecordDecl();
17276 if (!RD) {
17277 Diag(Loc, diag::err_static_assert_invalid_message);
17278 return false;
17279 }
17280
17281 auto FindMember = [&](StringRef Member, bool &Empty,
17282 bool Diag = false) -> std::optional<LookupResult> {
17284 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17285 LookupQualifiedName(MemberLookup, RD);
17286 Empty = MemberLookup.empty();
17287 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17289 if (MemberLookup.empty())
17290 return std::nullopt;
17291 return std::move(MemberLookup);
17292 };
17293
17294 bool SizeNotFound, DataNotFound;
17295 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17296 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17297 if (SizeNotFound || DataNotFound) {
17298 Diag(Loc, diag::err_static_assert_missing_member_function)
17299 << ((SizeNotFound && DataNotFound) ? 2
17300 : SizeNotFound ? 0
17301 : 1);
17302 return false;
17303 }
17304
17305 if (!SizeMember || !DataMember) {
17306 if (!SizeMember)
17307 FindMember("size", SizeNotFound, /*Diag=*/true);
17308 if (!DataMember)
17309 FindMember("data", DataNotFound, /*Diag=*/true);
17310 return false;
17311 }
17312
17313 auto BuildExpr = [&](LookupResult &LR) {
17315 Message, Message->getType(), Message->getBeginLoc(), false,
17316 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17317 if (Res.isInvalid())
17318 return ExprError();
17319 Res = BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr, false, true);
17320 if (Res.isInvalid())
17321 return ExprError();
17322 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17323 return ExprError();
17325 };
17326
17327 ExprResult SizeE = BuildExpr(*SizeMember);
17328 ExprResult DataE = BuildExpr(*DataMember);
17329
17330 QualType SizeT = Context.getSizeType();
17331 QualType ConstCharPtr =
17333
17334 ExprResult EvaluatedSize =
17335 SizeE.isInvalid() ? ExprError()
17337 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17338 if (EvaluatedSize.isInvalid()) {
17339 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17340 return false;
17341 }
17342
17343 ExprResult EvaluatedData =
17344 DataE.isInvalid()
17345 ? ExprError()
17346 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17348 if (EvaluatedData.isInvalid()) {
17349 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17350 return false;
17351 }
17352
17353 if (!ErrorOnInvalidMessage &&
17354 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17355 return true;
17356
17357 Expr::EvalResult Status;
17359 Status.Diag = &Notes;
17360 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17361 EvaluatedData.get(), Ctx, Status) ||
17362 !Notes.empty()) {
17363 Diag(Message->getBeginLoc(),
17364 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17365 : diag::warn_static_assert_message_constexpr);
17366 for (const auto &Note : Notes)
17367 Diag(Note.first, Note.second);
17368 return !ErrorOnInvalidMessage;
17369 }
17370 return true;
17371}
17372
17374 Expr *AssertExpr, Expr *AssertMessage,
17375 SourceLocation RParenLoc,
17376 bool Failed) {
17377 assert(AssertExpr != nullptr && "Expected non-null condition");
17378 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17379 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17380 !AssertMessage->isValueDependent())) &&
17381 !Failed) {
17382 // In a static_assert-declaration, the constant-expression shall be a
17383 // constant expression that can be contextually converted to bool.
17384 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17385 if (Converted.isInvalid())
17386 Failed = true;
17387
17388 ExprResult FullAssertExpr =
17389 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17390 /*DiscardedValue*/ false,
17391 /*IsConstexpr*/ true);
17392 if (FullAssertExpr.isInvalid())
17393 Failed = true;
17394 else
17395 AssertExpr = FullAssertExpr.get();
17396
17397 llvm::APSInt Cond;
17398 Expr *BaseExpr = AssertExpr;
17399 AllowFoldKind FoldKind = NoFold;
17400
17401 if (!getLangOpts().CPlusPlus) {
17402 // In C mode, allow folding as an extension for better compatibility with
17403 // C++ in terms of expressions like static_assert("test") or
17404 // static_assert(nullptr).
17405 FoldKind = AllowFold;
17406 }
17407
17408 if (!Failed && VerifyIntegerConstantExpression(
17409 BaseExpr, &Cond,
17410 diag::err_static_assert_expression_is_not_constant,
17411 FoldKind).isInvalid())
17412 Failed = true;
17413
17414 // If the static_assert passes, only verify that
17415 // the message is grammatically valid without evaluating it.
17416 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17417 std::string Str;
17418 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17419 /*ErrorOnInvalidMessage=*/false);
17420 }
17421
17422 // CWG2518
17423 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17424 // template definition, the declaration has no effect.
17425 bool InTemplateDefinition =
17426 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17427
17428 if (!Failed && !Cond && !InTemplateDefinition) {
17429 SmallString<256> MsgBuffer;
17430 llvm::raw_svector_ostream Msg(MsgBuffer);
17431 bool HasMessage = AssertMessage;
17432 if (AssertMessage) {
17433 std::string Str;
17434 HasMessage =
17436 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17437 !Str.empty();
17438 Msg << Str;
17439 }
17440 Expr *InnerCond = nullptr;
17441 std::string InnerCondDescription;
17442 std::tie(InnerCond, InnerCondDescription) =
17443 findFailedBooleanCondition(Converted.get());
17444 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17445 // Drill down into concept specialization expressions to see why they
17446 // weren't satisfied.
17447 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17448 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17449 ConstraintSatisfaction Satisfaction;
17450 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17451 DiagnoseUnsatisfiedConstraint(Satisfaction);
17452 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17453 && !isa<IntegerLiteral>(InnerCond)) {
17454 Diag(InnerCond->getBeginLoc(),
17455 diag::err_static_assert_requirement_failed)
17456 << InnerCondDescription << !HasMessage << Msg.str()
17457 << InnerCond->getSourceRange();
17458 DiagnoseStaticAssertDetails(InnerCond);
17459 } else {
17460 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17461 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17463 }
17464 Failed = true;
17465 }
17466 } else {
17467 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17468 /*DiscardedValue*/false,
17469 /*IsConstexpr*/true);
17470 if (FullAssertExpr.isInvalid())
17471 Failed = true;
17472 else
17473 AssertExpr = FullAssertExpr.get();
17474 }
17475
17477 AssertExpr, AssertMessage, RParenLoc,
17478 Failed);
17479
17481 return Decl;
17482}
17483
17485 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17486 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17487 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17488 MultiTemplateParamsArg TempParamLists) {
17490
17491 bool IsMemberSpecialization = false;
17492 bool Invalid = false;
17493
17494 if (TemplateParameterList *TemplateParams =
17496 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17497 IsMemberSpecialization, Invalid)) {
17498 if (TemplateParams->size() > 0) {
17499 // This is a declaration of a class template.
17500 if (Invalid)
17501 return true;
17502
17503 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17504 Name, NameLoc, Attr, TemplateParams, AS_public,
17505 /*ModulePrivateLoc=*/SourceLocation(),
17506 FriendLoc, TempParamLists.size() - 1,
17507 TempParamLists.data())
17508 .get();
17509 } else {
17510 // The "template<>" header is extraneous.
17511 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17512 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17513 IsMemberSpecialization = true;
17514 }
17515 }
17516
17517 if (Invalid) return true;
17518
17519 bool isAllExplicitSpecializations = true;
17520 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17521 if (TempParamLists[I]->size()) {
17522 isAllExplicitSpecializations = false;
17523 break;
17524 }
17525 }
17526
17527 // FIXME: don't ignore attributes.
17528
17529 // If it's explicit specializations all the way down, just forget
17530 // about the template header and build an appropriate non-templated
17531 // friend. TODO: for source fidelity, remember the headers.
17533 if (isAllExplicitSpecializations) {
17534 if (SS.isEmpty()) {
17535 bool Owned = false;
17536 bool IsDependent = false;
17537 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17538 Attr, AS_public,
17539 /*ModulePrivateLoc=*/SourceLocation(),
17540 MultiTemplateParamsArg(), Owned, IsDependent,
17541 /*ScopedEnumKWLoc=*/SourceLocation(),
17542 /*ScopedEnumUsesClassTag=*/false,
17543 /*UnderlyingType=*/TypeResult(),
17544 /*IsTypeSpecifier=*/false,
17545 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17546 }
17547
17548 ElaboratedTypeKeyword Keyword
17550 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17551 *Name, NameLoc);
17552 if (T.isNull())
17553 return true;
17554
17556 if (isa<DependentNameType>(T)) {
17559 TL.setElaboratedKeywordLoc(TagLoc);
17560 TL.setQualifierLoc(QualifierLoc);
17561 TL.setNameLoc(NameLoc);
17562 } else {
17564 TL.setElaboratedKeywordLoc(TagLoc);
17565 TL.setQualifierLoc(QualifierLoc);
17566 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17567 }
17568
17570 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17571 EllipsisLoc, TempParamLists);
17572 Friend->setAccess(AS_public);
17574 return Friend;
17575 }
17576
17577 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17578
17579 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
17580 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
17581 // shall not have been introduced by the template-declaration.
17583 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
17584 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
17585 for (UnexpandedParameterPack &U : Unexpanded) {
17586 if (getDepthAndIndex(U).first >= FriendDeclDepth) {
17587 auto *ND = dyn_cast<NamedDecl *>(U.first);
17588 if (!ND)
17589 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
17590 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
17591 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
17592 return true;
17593 }
17594 }
17595
17596 // Handle the case of a templated-scope friend class. e.g.
17597 // template <class T> class A<T>::B;
17598 // FIXME: we don't support these right now.
17599 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17600 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17605 TL.setElaboratedKeywordLoc(TagLoc);
17607 TL.setNameLoc(NameLoc);
17608
17610 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17611 EllipsisLoc, TempParamLists);
17612 Friend->setAccess(AS_public);
17613 Friend->setUnsupportedFriend(true);
17615 return Friend;
17616}
17617
17619 MultiTemplateParamsArg TempParams,
17620 SourceLocation EllipsisLoc) {
17622 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17623
17624 assert(DS.isFriendSpecified());
17626
17627 // C++ [class.friend]p3:
17628 // A friend declaration that does not declare a function shall have one of
17629 // the following forms:
17630 // friend elaborated-type-specifier ;
17631 // friend simple-type-specifier ;
17632 // friend typename-specifier ;
17633 //
17634 // If the friend keyword isn't first, or if the declarations has any type
17635 // qualifiers, then the declaration doesn't have that form.
17637 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17638 if (DS.getTypeQualifiers()) {
17640 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17642 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17644 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17646 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17648 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17649 }
17650
17651 // Try to convert the decl specifier to a type. This works for
17652 // friend templates because ActOnTag never produces a ClassTemplateDecl
17653 // for a TagUseKind::Friend.
17654 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17656 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17657 QualType T = TSI->getType();
17658 if (TheDeclarator.isInvalidType())
17659 return nullptr;
17660
17661 // If '...' is present, the type must contain an unexpanded parameter
17662 // pack, and vice versa.
17663 bool Invalid = false;
17664 if (EllipsisLoc.isInvalid() &&
17666 return nullptr;
17667 if (EllipsisLoc.isValid() &&
17669 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
17670 << TSI->getTypeLoc().getSourceRange();
17671 Invalid = true;
17672 }
17673
17674 if (!T->isElaboratedTypeSpecifier()) {
17675 if (TempParams.size()) {
17676 // C++23 [dcl.pre]p5:
17677 // In a simple-declaration, the optional init-declarator-list can be
17678 // omitted only when declaring a class or enumeration, that is, when
17679 // the decl-specifier-seq contains either a class-specifier, an
17680 // elaborated-type-specifier with a class-key, or an enum-specifier.
17681 //
17682 // The declaration of a template-declaration or explicit-specialization
17683 // is never a member-declaration, so this must be a simple-declaration
17684 // with no init-declarator-list. Therefore, this is ill-formed.
17685 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17686 return nullptr;
17687 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17688 SmallString<16> InsertionText(" ");
17689 InsertionText += RD->getKindName();
17690
17692 ? diag::warn_cxx98_compat_unelaborated_friend_type
17693 : diag::ext_unelaborated_friend_type)
17694 << (unsigned)RD->getTagKind() << T
17696 InsertionText);
17697 } else {
17698 Diag(FriendLoc, getLangOpts().CPlusPlus11
17699 ? diag::warn_cxx98_compat_nonclass_type_friend
17700 : diag::ext_nonclass_type_friend)
17701 << T << DS.getSourceRange();
17702 }
17703 }
17704
17705 // C++98 [class.friend]p1: A friend of a class is a function
17706 // or class that is not a member of the class . . .
17707 // This is fixed in DR77, which just barely didn't make the C++03
17708 // deadline. It's also a very silly restriction that seriously
17709 // affects inner classes and which nobody else seems to implement;
17710 // thus we never diagnose it, not even in -pedantic.
17711 //
17712 // But note that we could warn about it: it's always useless to
17713 // friend one of your own members (it's not, however, worthless to
17714 // friend a member of an arbitrary specialization of your template).
17715
17716 Decl *D;
17717 if (!TempParams.empty())
17718 // TODO: Support variadic friend template decls?
17719 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17720 FriendLoc);
17721 else
17723 TSI, FriendLoc, EllipsisLoc);
17724
17725 if (!D)
17726 return nullptr;
17727
17730
17731 if (Invalid)
17732 D->setInvalidDecl();
17733
17734 return D;
17735}
17736
17738 MultiTemplateParamsArg TemplateParams) {
17739 const DeclSpec &DS = D.getDeclSpec();
17740
17741 assert(DS.isFriendSpecified());
17743
17744 SourceLocation Loc = D.getIdentifierLoc();
17746
17747 // C++ [class.friend]p1
17748 // A friend of a class is a function or class....
17749 // Note that this sees through typedefs, which is intended.
17750 // It *doesn't* see through dependent types, which is correct
17751 // according to [temp.arg.type]p3:
17752 // If a declaration acquires a function type through a
17753 // type dependent on a template-parameter and this causes
17754 // a declaration that does not use the syntactic form of a
17755 // function declarator to have a function type, the program
17756 // is ill-formed.
17757 if (!TInfo->getType()->isFunctionType()) {
17758 Diag(Loc, diag::err_unexpected_friend);
17759
17760 // It might be worthwhile to try to recover by creating an
17761 // appropriate declaration.
17762 return nullptr;
17763 }
17764
17765 // C++ [namespace.memdef]p3
17766 // - If a friend declaration in a non-local class first declares a
17767 // class or function, the friend class or function is a member
17768 // of the innermost enclosing namespace.
17769 // - The name of the friend is not found by simple name lookup
17770 // until a matching declaration is provided in that namespace
17771 // scope (either before or after the class declaration granting
17772 // friendship).
17773 // - If a friend function is called, its name may be found by the
17774 // name lookup that considers functions from namespaces and
17775 // classes associated with the types of the function arguments.
17776 // - When looking for a prior declaration of a class or a function
17777 // declared as a friend, scopes outside the innermost enclosing
17778 // namespace scope are not considered.
17779
17780 CXXScopeSpec &SS = D.getCXXScopeSpec();
17782 assert(NameInfo.getName());
17783
17784 // Check for unexpanded parameter packs.
17788 return nullptr;
17789
17790 // The context we found the declaration in, or in which we should
17791 // create the declaration.
17792 DeclContext *DC;
17793 Scope *DCScope = S;
17794 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17795 RedeclarationKind::ForExternalRedeclaration);
17796
17797 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17798
17799 // There are five cases here.
17800 // - There's no scope specifier and we're in a local class. Only look
17801 // for functions declared in the immediately-enclosing block scope.
17802 // We recover from invalid scope qualifiers as if they just weren't there.
17803 FunctionDecl *FunctionContainingLocalClass = nullptr;
17804 if ((SS.isInvalid() || !SS.isSet()) &&
17805 (FunctionContainingLocalClass =
17806 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17807 // C++11 [class.friend]p11:
17808 // If a friend declaration appears in a local class and the name
17809 // specified is an unqualified name, a prior declaration is
17810 // looked up without considering scopes that are outside the
17811 // innermost enclosing non-class scope. For a friend function
17812 // declaration, if there is no prior declaration, the program is
17813 // ill-formed.
17814
17815 // Find the innermost enclosing non-class scope. This is the block
17816 // scope containing the local class definition (or for a nested class,
17817 // the outer local class).
17818 DCScope = S->getFnParent();
17819
17820 // Look up the function name in the scope.
17822 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17823
17824 if (!Previous.empty()) {
17825 // All possible previous declarations must have the same context:
17826 // either they were declared at block scope or they are members of
17827 // one of the enclosing local classes.
17828 DC = Previous.getRepresentativeDecl()->getDeclContext();
17829 } else {
17830 // This is ill-formed, but provide the context that we would have
17831 // declared the function in, if we were permitted to, for error recovery.
17832 DC = FunctionContainingLocalClass;
17833 }
17835
17836 // - There's no scope specifier, in which case we just go to the
17837 // appropriate scope and look for a function or function template
17838 // there as appropriate.
17839 } else if (SS.isInvalid() || !SS.isSet()) {
17840 // C++11 [namespace.memdef]p3:
17841 // If the name in a friend declaration is neither qualified nor
17842 // a template-id and the declaration is a function or an
17843 // elaborated-type-specifier, the lookup to determine whether
17844 // the entity has been previously declared shall not consider
17845 // any scopes outside the innermost enclosing namespace.
17846
17847 // Find the appropriate context according to the above.
17848 DC = CurContext;
17849
17850 // Skip class contexts. If someone can cite chapter and verse
17851 // for this behavior, that would be nice --- it's what GCC and
17852 // EDG do, and it seems like a reasonable intent, but the spec
17853 // really only says that checks for unqualified existing
17854 // declarations should stop at the nearest enclosing namespace,
17855 // not that they should only consider the nearest enclosing
17856 // namespace.
17857 while (DC->isRecord())
17858 DC = DC->getParent();
17859
17860 DeclContext *LookupDC = DC->getNonTransparentContext();
17861 while (true) {
17862 LookupQualifiedName(Previous, LookupDC);
17863
17864 if (!Previous.empty()) {
17865 DC = LookupDC;
17866 break;
17867 }
17868
17869 if (isTemplateId) {
17870 if (isa<TranslationUnitDecl>(LookupDC)) break;
17871 } else {
17872 if (LookupDC->isFileContext()) break;
17873 }
17874 LookupDC = LookupDC->getParent();
17875 }
17876
17877 DCScope = getScopeForDeclContext(S, DC);
17878
17879 // - There's a non-dependent scope specifier, in which case we
17880 // compute it and do a previous lookup there for a function
17881 // or function template.
17882 } else if (!SS.getScopeRep()->isDependent()) {
17883 DC = computeDeclContext(SS);
17884 if (!DC) return nullptr;
17885
17886 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17887
17889
17890 // C++ [class.friend]p1: A friend of a class is a function or
17891 // class that is not a member of the class . . .
17892 if (DC->Equals(CurContext))
17895 diag::warn_cxx98_compat_friend_is_member :
17896 diag::err_friend_is_member);
17897
17898 // - There's a scope specifier that does not match any template
17899 // parameter lists, in which case we use some arbitrary context,
17900 // create a method or method template, and wait for instantiation.
17901 // - There's a scope specifier that does match some template
17902 // parameter lists, which we don't handle right now.
17903 } else {
17904 DC = CurContext;
17905 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17906 }
17907
17908 if (!DC->isRecord()) {
17909 int DiagArg = -1;
17910 switch (D.getName().getKind()) {
17913 DiagArg = 0;
17914 break;
17916 DiagArg = 1;
17917 break;
17919 DiagArg = 2;
17920 break;
17922 DiagArg = 3;
17923 break;
17929 break;
17930 }
17931 // This implies that it has to be an operator or function.
17932 if (DiagArg >= 0) {
17933 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17934 return nullptr;
17935 }
17936 }
17937
17938 // FIXME: This is an egregious hack to cope with cases where the scope stack
17939 // does not contain the declaration context, i.e., in an out-of-line
17940 // definition of a class.
17941 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17942 if (!DCScope) {
17943 FakeDCScope.setEntity(DC);
17944 DCScope = &FakeDCScope;
17945 }
17946
17947 bool AddToScope = true;
17948 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17949 TemplateParams, AddToScope);
17950 if (!ND) return nullptr;
17951
17952 assert(ND->getLexicalDeclContext() == CurContext);
17953
17954 // If we performed typo correction, we might have added a scope specifier
17955 // and changed the decl context.
17956 DC = ND->getDeclContext();
17957
17958 // Add the function declaration to the appropriate lookup tables,
17959 // adjusting the redeclarations list as necessary. We don't
17960 // want to do this yet if the friending class is dependent.
17961 //
17962 // Also update the scope-based lookup if the target context's
17963 // lookup context is in lexical scope.
17965 DC = DC->getRedeclContext();
17967 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17968 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17969 }
17970
17972 D.getIdentifierLoc(), ND,
17973 DS.getFriendSpecLoc());
17974 FrD->setAccess(AS_public);
17975 CurContext->addDecl(FrD);
17976
17977 if (ND->isInvalidDecl()) {
17978 FrD->setInvalidDecl();
17979 } else {
17980 if (DC->isRecord()) CheckFriendAccess(ND);
17981
17982 FunctionDecl *FD;
17983 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17984 FD = FTD->getTemplatedDecl();
17985 else
17986 FD = cast<FunctionDecl>(ND);
17987
17988 // C++ [class.friend]p6:
17989 // A function may be defined in a friend declaration of a class if and
17990 // only if the class is a non-local class, and the function name is
17991 // unqualified.
17992 if (D.isFunctionDefinition()) {
17993 // Qualified friend function definition.
17994 if (SS.isNotEmpty()) {
17995 // FIXME: We should only do this if the scope specifier names the
17996 // innermost enclosing namespace; otherwise the fixit changes the
17997 // meaning of the code.
17999 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18000
18001 DB << SS.getScopeRep();
18002 if (DC->isFileContext())
18004
18005 // Friend function defined in a local class.
18006 } else if (FunctionContainingLocalClass) {
18007 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18008
18009 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18010 // a template-id, the function name is not unqualified because these is
18011 // no name. While the wording requires some reading in-between the
18012 // lines, GCC, MSVC, and EDG all consider a friend function
18013 // specialization definitions // to be de facto explicit specialization
18014 // and diagnose them as such.
18015 } else if (isTemplateId) {
18016 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18017 }
18018 }
18019
18020 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18021 // default argument expression, that declaration shall be a definition
18022 // and shall be the only declaration of the function or function
18023 // template in the translation unit.
18025 // We can't look at FD->getPreviousDecl() because it may not have been set
18026 // if we're in a dependent context. If the function is known to be a
18027 // redeclaration, we will have narrowed Previous down to the right decl.
18028 if (D.isRedeclaration()) {
18029 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18030 Diag(Previous.getRepresentativeDecl()->getLocation(),
18031 diag::note_previous_declaration);
18032 } else if (!D.isFunctionDefinition())
18033 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18034 }
18035
18036 // Mark templated-scope function declarations as unsupported.
18037 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18038 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18039 << SS.getScopeRep() << SS.getRange()
18040 << cast<CXXRecordDecl>(CurContext);
18041 FrD->setUnsupportedFriend(true);
18042 }
18043 }
18044
18046
18047 return ND;
18048}
18049
18051 StringLiteral *Message) {
18053
18054 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18055 if (!Fn) {
18056 Diag(DelLoc, diag::err_deleted_non_function);
18057 return;
18058 }
18059
18060 // Deleted function does not have a body.
18061 Fn->setWillHaveBody(false);
18062
18063 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18064 // Don't consider the implicit declaration we generate for explicit
18065 // specializations. FIXME: Do not generate these implicit declarations.
18066 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18067 Prev->getPreviousDecl()) &&
18068 !Prev->isDefined()) {
18069 Diag(DelLoc, diag::err_deleted_decl_not_first);
18070 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18071 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18072 : diag::note_previous_declaration);
18073 // We can't recover from this; the declaration might have already
18074 // been used.
18075 Fn->setInvalidDecl();
18076 return;
18077 }
18078
18079 // To maintain the invariant that functions are only deleted on their first
18080 // declaration, mark the implicitly-instantiated declaration of the
18081 // explicitly-specialized function as deleted instead of marking the
18082 // instantiated redeclaration.
18083 Fn = Fn->getCanonicalDecl();
18084 }
18085
18086 // dllimport/dllexport cannot be deleted.
18087 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18088 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18089 Fn->setInvalidDecl();
18090 }
18091
18092 // C++11 [basic.start.main]p3:
18093 // A program that defines main as deleted [...] is ill-formed.
18094 if (Fn->isMain())
18095 Diag(DelLoc, diag::err_deleted_main);
18096
18097 // C++11 [dcl.fct.def.delete]p4:
18098 // A deleted function is implicitly inline.
18099 Fn->setImplicitlyInline();
18100 Fn->setDeletedAsWritten(true, Message);
18101}
18102
18104 if (!Dcl || Dcl->isInvalidDecl())
18105 return;
18106
18107 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18108 if (!FD) {
18109 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18110 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18111 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18112 return;
18113 }
18114 }
18115
18116 Diag(DefaultLoc, diag::err_default_special_members)
18117 << getLangOpts().CPlusPlus20;
18118 return;
18119 }
18120
18121 // Reject if this can't possibly be a defaultable function.
18123 if (!DefKind &&
18124 // A dependent function that doesn't locally look defaultable can
18125 // still instantiate to a defaultable function if it's a constructor
18126 // or assignment operator.
18127 (!FD->isDependentContext() ||
18128 (!isa<CXXConstructorDecl>(FD) &&
18129 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18130 Diag(DefaultLoc, diag::err_default_special_members)
18131 << getLangOpts().CPlusPlus20;
18132 return;
18133 }
18134
18135 // Issue compatibility warning. We already warned if the operator is
18136 // 'operator<=>' when parsing the '<=>' token.
18137 if (DefKind.isComparison() &&
18139 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18140 ? diag::warn_cxx17_compat_defaulted_comparison
18141 : diag::ext_defaulted_comparison);
18142 }
18143
18144 FD->setDefaulted();
18145 FD->setExplicitlyDefaulted();
18146 FD->setDefaultLoc(DefaultLoc);
18147
18148 // Defer checking functions that are defaulted in a dependent context.
18149 if (FD->isDependentContext())
18150 return;
18151
18152 // Unset that we will have a body for this function. We might not,
18153 // if it turns out to be trivial, and we don't need this marking now
18154 // that we've marked it as defaulted.
18155 FD->setWillHaveBody(false);
18156
18157 if (DefKind.isComparison()) {
18158 // If this comparison's defaulting occurs within the definition of its
18159 // lexical class context, we have to do the checking when complete.
18160 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18161 if (!RD->isCompleteDefinition())
18162 return;
18163 }
18164
18165 // If this member fn was defaulted on its first declaration, we will have
18166 // already performed the checking in CheckCompletedCXXClass. Such a
18167 // declaration doesn't trigger an implicit definition.
18168 if (isa<CXXMethodDecl>(FD)) {
18169 const FunctionDecl *Primary = FD;
18170 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18171 // Ask the template instantiation pattern that actually had the
18172 // '= default' on it.
18173 Primary = Pattern;
18174 if (Primary->getCanonicalDecl()->isDefaulted())
18175 return;
18176 }
18177
18178 if (DefKind.isComparison()) {
18179 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18180 FD->setInvalidDecl();
18181 else
18182 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18183 } else {
18184 auto *MD = cast<CXXMethodDecl>(FD);
18185
18187 DefaultLoc))
18188 MD->setInvalidDecl();
18189 else
18190 DefineDefaultedFunction(*this, MD, DefaultLoc);
18191 }
18192}
18193
18195 for (Stmt *SubStmt : S->children()) {
18196 if (!SubStmt)
18197 continue;
18198 if (isa<ReturnStmt>(SubStmt))
18199 Self.Diag(SubStmt->getBeginLoc(),
18200 diag::err_return_in_constructor_handler);
18201 if (!isa<Expr>(SubStmt))
18202 SearchForReturnInStmt(Self, SubStmt);
18203 }
18204}
18205
18207 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18208 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18209 SearchForReturnInStmt(*this, Handler);
18210 }
18211}
18212
18214 StringLiteral *DeletedMessage) {
18215 switch (BodyKind) {
18216 case FnBodyKind::Delete:
18217 SetDeclDeleted(D, Loc, DeletedMessage);
18218 break;
18221 break;
18222 case FnBodyKind::Other:
18223 llvm_unreachable(
18224 "Parsed function body should be '= delete;' or '= default;'");
18225 }
18226}
18227
18229 const CXXMethodDecl *Old) {
18230 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18231 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18232
18233 if (OldFT->hasExtParameterInfos()) {
18234 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18235 // A parameter of the overriding method should be annotated with noescape
18236 // if the corresponding parameter of the overridden method is annotated.
18237 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18238 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18239 Diag(New->getParamDecl(I)->getLocation(),
18240 diag::warn_overriding_method_missing_noescape);
18241 Diag(Old->getParamDecl(I)->getLocation(),
18242 diag::note_overridden_marked_noescape);
18243 }
18244 }
18245
18246 // SME attributes must match when overriding a function declaration.
18247 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18248 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18249 << New << New->getType() << Old->getType();
18250 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18251 return true;
18252 }
18253
18254 // Virtual overrides must have the same code_seg.
18255 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18256 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18257 if ((NewCSA || OldCSA) &&
18258 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18259 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18260 Diag(Old->getLocation(), diag::note_previous_declaration);
18261 return true;
18262 }
18263
18264 // Virtual overrides: check for matching effects.
18266 const auto OldFX = Old->getFunctionEffects();
18267 const auto NewFXOrig = New->getFunctionEffects();
18268
18269 if (OldFX != NewFXOrig) {
18270 FunctionEffectSet NewFX(NewFXOrig);
18271 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18273 for (const auto &Diff : Diffs) {
18274 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18276 break;
18278 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18279 << Diff.effectName();
18280 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18281 << Old->getReturnTypeSourceRange();
18282 break;
18284 NewFX.insert(Diff.Old.value(), Errs);
18285 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18286 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18288 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18289 NewFT->getParamTypes(), EPI);
18290 New->setType(ModQT);
18291 break;
18292 }
18293 }
18294 }
18295 if (!Errs.empty())
18297 Old->getLocation());
18298 }
18299 }
18300
18301 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18302
18303 // If the calling conventions match, everything is fine
18304 if (NewCC == OldCC)
18305 return false;
18306
18307 // If the calling conventions mismatch because the new function is static,
18308 // suppress the calling convention mismatch error; the error about static
18309 // function override (err_static_overrides_virtual from
18310 // Sema::CheckFunctionDeclaration) is more clear.
18311 if (New->getStorageClass() == SC_Static)
18312 return false;
18313
18314 Diag(New->getLocation(),
18315 diag::err_conflicting_overriding_cc_attributes)
18316 << New->getDeclName() << New->getType() << Old->getType();
18317 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18318 return true;
18319}
18320
18322 const CXXMethodDecl *Old) {
18323 // CWG2553
18324 // A virtual function shall not be an explicit object member function.
18326 return true;
18327 Diag(New->getParamDecl(0)->getBeginLoc(),
18328 diag::err_explicit_object_parameter_nonmember)
18329 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18330 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18331 New->setInvalidDecl();
18332 return false;
18333}
18334
18336 const CXXMethodDecl *Old) {
18337 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18338 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18339
18340 if (Context.hasSameType(NewTy, OldTy) ||
18341 NewTy->isDependentType() || OldTy->isDependentType())
18342 return false;
18343
18344 // Check if the return types are covariant
18345 QualType NewClassTy, OldClassTy;
18346
18347 /// Both types must be pointers or references to classes.
18348 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18349 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18350 NewClassTy = NewPT->getPointeeType();
18351 OldClassTy = OldPT->getPointeeType();
18352 }
18353 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18354 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18355 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18356 NewClassTy = NewRT->getPointeeType();
18357 OldClassTy = OldRT->getPointeeType();
18358 }
18359 }
18360 }
18361
18362 // The return types aren't either both pointers or references to a class type.
18363 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18364 Diag(New->getLocation(),
18365 diag::err_different_return_type_for_overriding_virtual_function)
18366 << New->getDeclName() << NewTy << OldTy
18367 << New->getReturnTypeSourceRange();
18368 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18369 << Old->getReturnTypeSourceRange();
18370
18371 return true;
18372 }
18373
18374 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18375 // C++14 [class.virtual]p8:
18376 // If the class type in the covariant return type of D::f differs from
18377 // that of B::f, the class type in the return type of D::f shall be
18378 // complete at the point of declaration of D::f or shall be the class
18379 // type D.
18380 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18381 if (!RT->isBeingDefined() &&
18382 RequireCompleteType(New->getLocation(), NewClassTy,
18383 diag::err_covariant_return_incomplete,
18384 New->getDeclName()))
18385 return true;
18386 }
18387
18388 // Check if the new class derives from the old class.
18389 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18390 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18391 << New->getDeclName() << NewTy << OldTy
18392 << New->getReturnTypeSourceRange();
18393 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18394 << Old->getReturnTypeSourceRange();
18395 return true;
18396 }
18397
18398 // Check if we the conversion from derived to base is valid.
18400 NewClassTy, OldClassTy,
18401 diag::err_covariant_return_inaccessible_base,
18402 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18404 New->getDeclName(), nullptr)) {
18405 // FIXME: this note won't trigger for delayed access control
18406 // diagnostics, and it's impossible to get an undelayed error
18407 // here from access control during the original parse because
18408 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18409 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18410 << Old->getReturnTypeSourceRange();
18411 return true;
18412 }
18413 }
18414
18415 // The qualifiers of the return types must be the same.
18416 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18417 Diag(New->getLocation(),
18418 diag::err_covariant_return_type_different_qualifications)
18419 << New->getDeclName() << NewTy << OldTy
18420 << New->getReturnTypeSourceRange();
18421 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18422 << Old->getReturnTypeSourceRange();
18423 return true;
18424 }
18425
18426
18427 // The new class type must have the same or less qualifiers as the old type.
18428 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
18429 Diag(New->getLocation(),
18430 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18431 << New->getDeclName() << NewTy << OldTy
18432 << New->getReturnTypeSourceRange();
18433 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18434 << Old->getReturnTypeSourceRange();
18435 return true;
18436 }
18437
18438 return false;
18439}
18440
18442 SourceLocation EndLoc = InitRange.getEnd();
18443 if (EndLoc.isValid())
18444 Method->setRangeEnd(EndLoc);
18445
18446 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18447 Method->setIsPureVirtual();
18448 return false;
18449 }
18450
18451 if (!Method->isInvalidDecl())
18452 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18453 << Method->getDeclName() << InitRange;
18454 return true;
18455}
18456
18458 if (D->getFriendObjectKind())
18459 Diag(D->getLocation(), diag::err_pure_friend);
18460 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18461 CheckPureMethod(M, ZeroLoc);
18462 else
18463 Diag(D->getLocation(), diag::err_illegal_initializer);
18464}
18465
18466/// Invoked when we are about to parse an initializer for the declaration
18467/// 'Dcl'.
18468///
18469/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18470/// static data member of class X, names should be looked up in the scope of
18471/// class X. If the declaration had a scope specifier, a scope will have
18472/// been created and passed in for this purpose. Otherwise, S will be null.
18474 assert(D && !D->isInvalidDecl());
18475
18476 // We will always have a nested name specifier here, but this declaration
18477 // might not be out of line if the specifier names the current namespace:
18478 // extern int n;
18479 // int ::n = 0;
18480 if (S && D->isOutOfLine())
18482
18485}
18486
18488 assert(D);
18489
18490 if (S && D->isOutOfLine())
18492
18493 if (getLangOpts().CPlusPlus23) {
18494 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18495 // [...]
18496 // - the initializer of a variable that is usable in constant expressions or
18497 // has constant initialization.
18498 if (auto *VD = dyn_cast<VarDecl>(D);
18501 // An expression or conversion is in an 'immediate function context' if it
18502 // is potentially evaluated and either:
18503 // [...]
18504 // - it is a subexpression of a manifestly constant-evaluated expression
18505 // or conversion.
18506 ExprEvalContexts.back().InImmediateFunctionContext = true;
18507 }
18508 }
18509
18510 // Unless the initializer is in an immediate function context (as determined
18511 // above), this will evaluate all contained immediate function calls as
18512 // constant expressions. If the initializer IS an immediate function context,
18513 // the initializer has been determined to be a constant expression, and all
18514 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18515 // it was a constant expression).
18517}
18518
18520 // C++ 6.4p2:
18521 // The declarator shall not specify a function or an array.
18522 // The type-specifier-seq shall not contain typedef and shall not declare a
18523 // new class or enumeration.
18524 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18525 "Parser allowed 'typedef' as storage class of condition decl.");
18526
18527 Decl *Dcl = ActOnDeclarator(S, D);
18528 if (!Dcl)
18529 return true;
18530
18531 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18532 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18533 << D.getSourceRange();
18534 return true;
18535 }
18536
18537 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18538 VD->setCXXCondDecl();
18539
18540 return Dcl;
18541}
18542
18544 if (!ExternalSource)
18545 return;
18546
18548 ExternalSource->ReadUsedVTables(VTables);
18550 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18551 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18552 = VTablesUsed.find(VTables[I].Record);
18553 // Even if a definition wasn't required before, it may be required now.
18554 if (Pos != VTablesUsed.end()) {
18555 if (!Pos->second && VTables[I].DefinitionRequired)
18556 Pos->second = true;
18557 continue;
18558 }
18559
18560 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18561 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18562 }
18563
18564 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18565}
18566
18568 bool DefinitionRequired) {
18569 // Ignore any vtable uses in unevaluated operands or for classes that do
18570 // not have a vtable.
18571 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18573 return;
18574 // Do not mark as used if compiling for the device outside of the target
18575 // region.
18576 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18577 !OpenMP().isInOpenMPDeclareTargetContext() &&
18578 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18579 if (!DefinitionRequired)
18581 return;
18582 }
18583
18584 // Try to insert this class into the map.
18586 Class = Class->getCanonicalDecl();
18587 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18588 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18589 if (!Pos.second) {
18590 // If we already had an entry, check to see if we are promoting this vtable
18591 // to require a definition. If so, we need to reappend to the VTableUses
18592 // list, since we may have already processed the first entry.
18593 if (DefinitionRequired && !Pos.first->second) {
18594 Pos.first->second = true;
18595 } else {
18596 // Otherwise, we can early exit.
18597 return;
18598 }
18599 } else {
18600 // The Microsoft ABI requires that we perform the destructor body
18601 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18602 // the deleting destructor is emitted with the vtable, not with the
18603 // destructor definition as in the Itanium ABI.
18605 CXXDestructorDecl *DD = Class->getDestructor();
18606 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18607 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18608 // If this is an out-of-line declaration, marking it referenced will
18609 // not do anything. Manually call CheckDestructor to look up operator
18610 // delete().
18611 ContextRAII SavedContext(*this, DD);
18612 CheckDestructor(DD);
18613 } else {
18614 MarkFunctionReferenced(Loc, Class->getDestructor());
18615 }
18616 }
18617 }
18618 }
18619
18620 // Local classes need to have their virtual members marked
18621 // immediately. For all other classes, we mark their virtual members
18622 // at the end of the translation unit.
18623 if (Class->isLocalClass())
18624 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18625 else
18626 VTableUses.push_back(std::make_pair(Class, Loc));
18627}
18628
18631 if (VTableUses.empty())
18632 return false;
18633
18634 // Note: The VTableUses vector could grow as a result of marking
18635 // the members of a class as "used", so we check the size each
18636 // time through the loop and prefer indices (which are stable) to
18637 // iterators (which are not).
18638 bool DefinedAnything = false;
18639 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18640 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18641 if (!Class)
18642 continue;
18644 Class->getTemplateSpecializationKind();
18645
18646 SourceLocation Loc = VTableUses[I].second;
18647
18648 bool DefineVTable = true;
18649
18650 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18651 // V-tables for non-template classes with an owning module are always
18652 // uniquely emitted in that module.
18653 if (Class->isInCurrentModuleUnit()) {
18654 DefineVTable = true;
18655 } else if (KeyFunction && !KeyFunction->hasBody()) {
18656 // If this class has a key function, but that key function is
18657 // defined in another translation unit, we don't need to emit the
18658 // vtable even though we're using it.
18659 // The key function is in another translation unit.
18660 DefineVTable = false;
18662 KeyFunction->getTemplateSpecializationKind();
18665 "Instantiations don't have key functions");
18666 (void)TSK;
18667 } else if (!KeyFunction) {
18668 // If we have a class with no key function that is the subject
18669 // of an explicit instantiation declaration, suppress the
18670 // vtable; it will live with the explicit instantiation
18671 // definition.
18672 bool IsExplicitInstantiationDeclaration =
18674 for (auto *R : Class->redecls()) {
18676 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18678 IsExplicitInstantiationDeclaration = true;
18679 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18680 IsExplicitInstantiationDeclaration = false;
18681 break;
18682 }
18683 }
18684
18685 if (IsExplicitInstantiationDeclaration)
18686 DefineVTable = false;
18687 }
18688
18689 // The exception specifications for all virtual members may be needed even
18690 // if we are not providing an authoritative form of the vtable in this TU.
18691 // We may choose to emit it available_externally anyway.
18692 if (!DefineVTable) {
18694 continue;
18695 }
18696
18697 // Mark all of the virtual members of this class as referenced, so
18698 // that we can build a vtable. Then, tell the AST consumer that a
18699 // vtable for this class is required.
18700 DefinedAnything = true;
18702 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18703 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
18705
18706 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18707 // no key function or the key function is inlined. Don't warn in C++ ABIs
18708 // that lack key functions, since the user won't be able to make one.
18710 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18712 const FunctionDecl *KeyFunctionDef = nullptr;
18713 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18714 KeyFunctionDef->isInlined()))
18715 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18716 }
18717 }
18718 VTableUses.clear();
18719
18720 return DefinedAnything;
18721}
18722
18724 const CXXRecordDecl *RD) {
18725 for (const auto *I : RD->methods())
18726 if (I->isVirtual() && !I->isPureVirtual())
18727 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18728}
18729
18731 const CXXRecordDecl *RD,
18732 bool ConstexprOnly) {
18733 // Mark all functions which will appear in RD's vtable as used.
18734 CXXFinalOverriderMap FinalOverriders;
18735 RD->getFinalOverriders(FinalOverriders);
18736 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18737 E = FinalOverriders.end();
18738 I != E; ++I) {
18739 for (OverridingMethods::const_iterator OI = I->second.begin(),
18740 OE = I->second.end();
18741 OI != OE; ++OI) {
18742 assert(OI->second.size() > 0 && "no final overrider");
18743 CXXMethodDecl *Overrider = OI->second.front().Method;
18744
18745 // C++ [basic.def.odr]p2:
18746 // [...] A virtual member function is used if it is not pure. [...]
18747 if (!Overrider->isPureVirtual() &&
18748 (!ConstexprOnly || Overrider->isConstexpr()))
18749 MarkFunctionReferenced(Loc, Overrider);
18750 }
18751 }
18752
18753 // Only classes that have virtual bases need a VTT.
18754 if (RD->getNumVBases() == 0)
18755 return;
18756
18757 for (const auto &I : RD->bases()) {
18758 const auto *Base =
18759 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18760 if (Base->getNumVBases() == 0)
18761 continue;
18763 }
18764}
18765
18766static
18771 Sema &S) {
18772 if (Ctor->isInvalidDecl())
18773 return;
18774
18776
18777 // Target may not be determinable yet, for instance if this is a dependent
18778 // call in an uninstantiated template.
18779 if (Target) {
18780 const FunctionDecl *FNTarget = nullptr;
18781 (void)Target->hasBody(FNTarget);
18782 Target = const_cast<CXXConstructorDecl*>(
18783 cast_or_null<CXXConstructorDecl>(FNTarget));
18784 }
18785
18786 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18787 // Avoid dereferencing a null pointer here.
18788 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18789
18790 if (!Current.insert(Canonical).second)
18791 return;
18792
18793 // We know that beyond here, we aren't chaining into a cycle.
18794 if (!Target || !Target->isDelegatingConstructor() ||
18795 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18796 Valid.insert(Current.begin(), Current.end());
18797 Current.clear();
18798 // We've hit a cycle.
18799 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18800 Current.count(TCanonical)) {
18801 // If we haven't diagnosed this cycle yet, do so now.
18802 if (!Invalid.count(TCanonical)) {
18803 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18804 diag::warn_delegating_ctor_cycle)
18805 << Ctor;
18806
18807 // Don't add a note for a function delegating directly to itself.
18808 if (TCanonical != Canonical)
18809 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18810
18812 while (C->getCanonicalDecl() != Canonical) {
18813 const FunctionDecl *FNTarget = nullptr;
18814 (void)C->getTargetConstructor()->hasBody(FNTarget);
18815 assert(FNTarget && "Ctor cycle through bodiless function");
18816
18817 C = const_cast<CXXConstructorDecl*>(
18818 cast<CXXConstructorDecl>(FNTarget));
18819 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18820 }
18821 }
18822
18823 Invalid.insert(Current.begin(), Current.end());
18824 Current.clear();
18825 } else {
18826 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18827 }
18828}
18829
18830
18833
18834 for (DelegatingCtorDeclsType::iterator
18837 I != E; ++I)
18838 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18839
18840 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18841 (*CI)->setInvalidDecl();
18842}
18843
18844namespace {
18845 /// AST visitor that finds references to the 'this' expression.
18846class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
18847 Sema &S;
18848
18849public:
18850 explicit FindCXXThisExpr(Sema &S) : S(S) {}
18851
18852 bool VisitCXXThisExpr(CXXThisExpr *E) override {
18853 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18854 << E->isImplicit();
18855 return false;
18856 }
18857};
18858}
18859
18861 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18862 if (!TSInfo)
18863 return false;
18864
18865 TypeLoc TL = TSInfo->getTypeLoc();
18867 if (!ProtoTL)
18868 return false;
18869
18870 // C++11 [expr.prim.general]p3:
18871 // [The expression this] shall not appear before the optional
18872 // cv-qualifier-seq and it shall not appear within the declaration of a
18873 // static member function (although its type and value category are defined
18874 // within a static member function as they are within a non-static member
18875 // function). [ Note: this is because declaration matching does not occur
18876 // until the complete declarator is known. - end note ]
18877 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18878 FindCXXThisExpr Finder(*this);
18879
18880 // If the return type came after the cv-qualifier-seq, check it now.
18881 if (Proto->hasTrailingReturn() &&
18882 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18883 return true;
18884
18885 // Check the exception specification.
18887 return true;
18888
18889 // Check the trailing requires clause
18890 if (Expr *E = Method->getTrailingRequiresClause())
18891 if (!Finder.TraverseStmt(E))
18892 return true;
18893
18895}
18896
18898 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18899 if (!TSInfo)
18900 return false;
18901
18902 TypeLoc TL = TSInfo->getTypeLoc();
18904 if (!ProtoTL)
18905 return false;
18906
18907 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18908 FindCXXThisExpr Finder(*this);
18909
18910 switch (Proto->getExceptionSpecType()) {
18911 case EST_Unparsed:
18912 case EST_Uninstantiated:
18913 case EST_Unevaluated:
18914 case EST_BasicNoexcept:
18915 case EST_NoThrow:
18916 case EST_DynamicNone:
18917 case EST_MSAny:
18918 case EST_None:
18919 break;
18920
18922 case EST_NoexceptFalse:
18923 case EST_NoexceptTrue:
18924 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18925 return true;
18926 [[fallthrough]];
18927
18928 case EST_Dynamic:
18929 for (const auto &E : Proto->exceptions()) {
18930 if (!Finder.TraverseType(E))
18931 return true;
18932 }
18933 break;
18934 }
18935
18936 return false;
18937}
18938
18940 FindCXXThisExpr Finder(*this);
18941
18942 // Check attributes.
18943 for (const auto *A : Method->attrs()) {
18944 // FIXME: This should be emitted by tblgen.
18945 Expr *Arg = nullptr;
18946 ArrayRef<Expr *> Args;
18947 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18948 Arg = G->getArg();
18949 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18950 Arg = G->getArg();
18951 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18952 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18953 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18954 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18955 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18956 Arg = ETLF->getSuccessValue();
18957 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18958 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18959 Arg = STLF->getSuccessValue();
18960 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18961 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18962 Arg = LR->getArg();
18963 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18964 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18965 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18966 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18967 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18968 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18969 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18970 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18971 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18972 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18973
18974 if (Arg && !Finder.TraverseStmt(Arg))
18975 return true;
18976
18977 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18978 if (!Finder.TraverseStmt(Args[I]))
18979 return true;
18980 }
18981 }
18982
18983 return false;
18984}
18985
18987 bool IsTopLevel, ExceptionSpecificationType EST,
18988 ArrayRef<ParsedType> DynamicExceptions,
18989 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18990 SmallVectorImpl<QualType> &Exceptions,
18992 Exceptions.clear();
18993 ESI.Type = EST;
18994 if (EST == EST_Dynamic) {
18995 Exceptions.reserve(DynamicExceptions.size());
18996 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18997 // FIXME: Preserve type source info.
18998 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18999
19000 if (IsTopLevel) {
19002 collectUnexpandedParameterPacks(ET, Unexpanded);
19003 if (!Unexpanded.empty()) {
19005 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19006 Unexpanded);
19007 continue;
19008 }
19009 }
19010
19011 // Check that the type is valid for an exception spec, and
19012 // drop it if not.
19013 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19014 Exceptions.push_back(ET);
19015 }
19016 ESI.Exceptions = Exceptions;
19017 return;
19018 }
19019
19020 if (isComputedNoexcept(EST)) {
19021 assert((NoexceptExpr->isTypeDependent() ||
19022 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19023 Context.BoolTy) &&
19024 "Parser should have made sure that the expression is boolean");
19025 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19026 ESI.Type = EST_BasicNoexcept;
19027 return;
19028 }
19029
19030 ESI.NoexceptExpr = NoexceptExpr;
19031 return;
19032 }
19033}
19034
19036 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19037 ArrayRef<ParsedType> DynamicExceptions,
19038 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19039 if (!D)
19040 return;
19041
19042 // Dig out the function we're referring to.
19043 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19044 D = FTD->getTemplatedDecl();
19045
19046 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19047 if (!FD)
19048 return;
19049
19050 // Check the exception specification.
19053 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19054 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19055 ESI);
19056
19057 // Update the exception specification on the function type.
19058 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19059
19060 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19061 if (MD->isStatic())
19063
19064 if (MD->isVirtual()) {
19065 // Check overrides, which we previously had to delay.
19066 for (const CXXMethodDecl *O : MD->overridden_methods())
19068 }
19069 }
19070}
19071
19072/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19073///
19075 SourceLocation DeclStart, Declarator &D,
19076 Expr *BitWidth,
19077 InClassInitStyle InitStyle,
19078 AccessSpecifier AS,
19079 const ParsedAttr &MSPropertyAttr) {
19080 const IdentifierInfo *II = D.getIdentifier();
19081 if (!II) {
19082 Diag(DeclStart, diag::err_anonymous_property);
19083 return nullptr;
19084 }
19085 SourceLocation Loc = D.getIdentifierLoc();
19086
19088 QualType T = TInfo->getType();
19089 if (getLangOpts().CPlusPlus) {
19091
19092 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19094 D.setInvalidType();
19095 T = Context.IntTy;
19097 }
19098 }
19099
19100 DiagnoseFunctionSpecifiers(D.getDeclSpec());
19101
19102 if (D.getDeclSpec().isInlineSpecified())
19103 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19104 << getLangOpts().CPlusPlus17;
19105 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19106 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19107 diag::err_invalid_thread)
19109
19110 // Check to see if this name was declared as a member previously
19111 NamedDecl *PrevDecl = nullptr;
19113 RedeclarationKind::ForVisibleRedeclaration);
19114 LookupName(Previous, S);
19115 switch (Previous.getResultKind()) {
19118 PrevDecl = Previous.getAsSingle<NamedDecl>();
19119 break;
19120
19122 PrevDecl = Previous.getRepresentativeDecl();
19123 break;
19124
19128 break;
19129 }
19130
19131 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19132 // Maybe we will complain about the shadowed template parameter.
19133 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19134 // Just pretend that we didn't see the previous declaration.
19135 PrevDecl = nullptr;
19136 }
19137
19138 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19139 PrevDecl = nullptr;
19140
19141 SourceLocation TSSL = D.getBeginLoc();
19142 MSPropertyDecl *NewPD =
19143 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19144 MSPropertyAttr.getPropertyDataGetter(),
19145 MSPropertyAttr.getPropertyDataSetter());
19147 NewPD->setAccess(AS);
19148
19149 if (NewPD->isInvalidDecl())
19150 Record->setInvalidDecl();
19151
19152 if (D.getDeclSpec().isModulePrivateSpecified())
19153 NewPD->setModulePrivate();
19154
19155 if (NewPD->isInvalidDecl() && PrevDecl) {
19156 // Don't introduce NewFD into scope; there's already something
19157 // with the same name in the same scope.
19158 } else if (II) {
19159 PushOnScopeChains(NewPD, S);
19160 } else
19161 Record->addDecl(NewPD);
19162
19163 return NewPD;
19164}
19165
19167 Declarator &Declarator, unsigned TemplateParameterDepth) {
19168 auto &Info = InventedParameterInfos.emplace_back();
19169 TemplateParameterList *ExplicitParams = nullptr;
19170 ArrayRef<TemplateParameterList *> ExplicitLists =
19172 if (!ExplicitLists.empty()) {
19173 bool IsMemberSpecialization, IsInvalid;
19176 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19177 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19178 /*SuppressDiagnostic=*/true);
19179 }
19180 // C++23 [dcl.fct]p23:
19181 // An abbreviated function template can have a template-head. The invented
19182 // template-parameters are appended to the template-parameter-list after
19183 // the explicitly declared template-parameters.
19184 //
19185 // A template-head must have one or more template-parameters (read:
19186 // 'template<>' is *not* a template-head). Only append the invented
19187 // template parameters if we matched the nested-name-specifier to a non-empty
19188 // TemplateParameterList.
19189 if (ExplicitParams && !ExplicitParams->empty()) {
19190 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19191 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19192 Info.NumExplicitTemplateParams = ExplicitParams->size();
19193 } else {
19194 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19195 Info.NumExplicitTemplateParams = 0;
19196 }
19197}
19198
19200 auto &FSI = InventedParameterInfos.back();
19201 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19202 if (FSI.NumExplicitTemplateParams != 0) {
19203 TemplateParameterList *ExplicitParams =
19207 Context, ExplicitParams->getTemplateLoc(),
19208 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19209 ExplicitParams->getRAngleLoc(),
19210 ExplicitParams->getRequiresClause()));
19211 } else {
19214 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19215 SourceLocation(), /*RequiresClause=*/nullptr));
19216 }
19217 }
19218 InventedParameterInfos.pop_back();
19219}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
NodeId Parent
Definition: ASTDiff.cpp:191
DynTypedNode Node
StringRef P
enum clang::sema::@1704::IndirectLocalPathEntry::EntryKind Kind
const Decl * D
IndirectLocalPath & Path
Expr * E
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:3059
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
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 bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool RefersToRValueRef(Expr *MemRef)
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
#define CheckPolymorphic(Type)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool 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 bool IsUnusedPrivateField(const FieldDecl *FD)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static bool HasAttribute(const QualType &T)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
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 CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType, ArrayRef< BindingDecl * > Bindings, unsigned MemberCount)
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
bool Indirect
Definition: SemaObjC.cpp:760
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
const NestedNameSpecifier * Specifier
StateNode * Previous
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:124
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
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:684
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3410
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3424
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType Char16Ty
Definition: ASTContext.h:1167
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:1187
void Deallocate(void *Ptr) const
Definition: ASTContext.h:760
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:1188
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:1703
CanQualType WideCharTy
Definition: ASTContext.h:1164
IdentifierTable & Idents
Definition: ASTContext.h:680
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1392
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:2420
QualType AutoDeductTy
Definition: ASTContext.h:1223
CanQualType BoolTy
Definition: ASTContext.h:1161
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3389
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3021
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1162
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3403
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3396
CanQualType IntTy
Definition: ASTContext.h:1169
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3420
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
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:733
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
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:2489
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3385
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:3417
CanQualType VoidTy
Definition: ASTContext.h:1160
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3399
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
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:1681
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:3182
CanQualType Char32Ty
Definition: ASTContext.h:1168
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3392
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:1274
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3406
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:1166
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3413
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:1593
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1623
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3578
QualType getElementType() const
Definition: Type.h:3590
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
bool isInherited() const
Definition: Attr.h:98
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition: Attr.h:96
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6562
AutoTypeKeyword getKeyword() const
Definition: Type.h:6593
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3479
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3557
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3278
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3549
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3287
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
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:4902
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2157
A binding in a decomposition declaration.
Definition: DeclCXX.h:4169
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition: DeclCXX.cpp:3471
void setBinding(QualType DeclaredType, Expr *Binding)
Set the binding for this BindingDecl, along with its declared type (which should be a possibly-cv-qua...
Definition: DeclCXX.h:4207
void setDecomposedDecl(ValueDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition: DeclCXX.h:4213
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1346
This class is used for builtin types like 'int'.
Definition: Type.h:3035
Kind getKind() const
Definition: Type.h:3083
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
std::list< CXXBasePath >::iterator paths_iterator
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition: ExprCXX.cpp:1159
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1609
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2592
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2834
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:2904
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2663
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2688
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2881
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:2899
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2890
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2829
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:2860
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2924
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2964
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2357
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2529
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2809
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2796
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2503
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2856
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:2994
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1737
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:722
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2117
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:2594
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:2601
bool isVirtual() const
Definition: DeclCXX.h:2172
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2271
bool isVolatile() const
Definition: DeclCXX.h:2170
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2220
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2671
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2665
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2713
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2293
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2655
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2243
bool isInstance() const
Definition: DeclCXX.h:2144
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2627
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:2413
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2267
bool isStatic() const
Definition: DeclCXX.cpp:2325
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2605
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2213
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:1282
friend_range friends() const
Definition: DeclFriend.h:261
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1353
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:619
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1641
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1013
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:832
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition: DeclCXX.h:1432
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1403
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1382
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:718
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.cpp:1467
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:973
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1368
base_class_range bases()
Definition: DeclCXX.h:620
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:612
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1030
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1313
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:778
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:904
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:922
method_range methods() const
Definition: DeclCXX.h:662
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:943
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1738
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1275
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1290
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:985
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:607
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1226
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:709
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1294
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:738
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2012
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1340
base_class_range vbases()
Definition: DeclCXX.h:637
base_class_iterator vbases_begin()
Definition: DeclCXX.h:644
ctor_range ctors() const
Definition: DeclCXX.h:682
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:879
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1233
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1248
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:870
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1160
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:811
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1414
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1212
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:805
bool hasDefinition() const
Definition: DeclCXX.h:572
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:928
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1019
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:2004
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:914
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:1006
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2083
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1025
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1426
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1712
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:817
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:858
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:995
bool isInterfaceLike() const
Definition: DeclCXX.cpp:2112
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:937
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1318
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1700
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
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:958
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
Represents the this expression in C++.
Definition: ExprCXX.h:1152
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1172
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:108
unsigned getNumHandlers() const
Definition: StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
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:84
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:3146
QualType getElementType() const
Definition: Type.h:3156
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
body_range body()
Definition: Stmt.h:1691
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:391
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:196
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3616
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3672
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:3660
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3724
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:3260
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:1375
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2387
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1442
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2107
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2236
bool isFileContext() const
Definition: DeclBase.h:2178
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2067
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1347
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1868
bool isTranslationUnit() const
Definition: DeclBase.h:2183
bool isRecord() const
Definition: DeclBase.h:2187
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2012
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1701
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1782
decl_iterator decls_end() const
Definition: DeclBase.h:2369
bool isStdNamespace() const
Definition: DeclBase.cpp:1331
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2367
bool isFunctionOrMethod() const
Definition: DeclBase.h:2159
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1402
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1417
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1756
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2100
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1428
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1638
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:550
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:487
ValueDecl * getDecl()
Definition: Expr.h:1333
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1457
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:691
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:560
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:827
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:825
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:623
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:655
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
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 getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
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 getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_auto
Definition: DeclSpec.h:318
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1519
decl_range decls()
Definition: Stmt.h:1567
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1545
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:1054
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:528
void addAttr(Attr *A)
Definition: DeclBase.cpp:1019
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1207
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:572
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1212
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1210
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:254
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2787
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1228
bool isInvalidDecl() const
Definition: DeclBase.h:591
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:882
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1162
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:237
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:597
void setReferenced(bool R=true)
Definition: DeclBase.h:626
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:557
DeclContext * getDeclContext()
Definition: DeclBase.h:451
attr_range attrs() const
Definition: DeclBase.h:538
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void dropAttr()
Definition: DeclBase.h:559
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Kind getKind() const
Definition: DeclBase.h:445
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:874
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
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:739
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:790
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:826
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:773
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:768
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1904
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2340
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2087
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2066
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2653
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2660
bool isInvalidType() const
Definition: DeclSpec.h:2718
A decomposition declaration.
Definition: DeclCXX.h:4233
llvm::ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4274
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1840
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1838
Represents a C++17 deduced template specialization type.
Definition: Type.h:6610
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2455
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2435
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2444
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Definition: Diagnostic.h:1516
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:795
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:943
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
Recursively visit a constructor initializer.
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2355
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2393
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2369
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5706
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:3291
Represents an enum.
Definition: Decl.h:3861
enumerator_range enumerators() const
Definition: Decl.h:3994
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6104
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
const Expr * getExpr() const
Definition: DeclCXX.h:1921
void setExpr(Expr *E)
Definition: DeclCXX.h:1946
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1945
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:3096
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3084
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:3092
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:3230
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:981
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4595
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3208
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4585
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3202
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4605
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3118
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3275
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3139
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:114
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
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, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:189
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:3099
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3239
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2744
bool isTrivialForCall() const
Definition: Decl.h:2308
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3734
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4075
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4063
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3258
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
bool isImmediateFunction() const
Definition: Decl.cpp:3296
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3120
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3894
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3491
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3752
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
SourceLocation getDefaultLoc() const
Definition: Decl.h:2326
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2317
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4183
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2657
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3634
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3888
param_iterator param_begin()
Definition: Decl.h:2661
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3092
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2261
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2414
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4199
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3009
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4127
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2763
bool isStatic() const
Definition: Decl.h:2804
void setTrivial(bool IT)
Definition: Decl.h:2306
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4014
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2288
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3509
bool isImmediateEscalating() const
Definition: Decl.cpp:3271
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3183
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4420
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4000
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2401
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4288
void setDefaulted(bool D=true)
Definition: Decl.h:2314
bool isConsteval() const
Definition: Decl.h:2410
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2338
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:2737
void setBody(Stmt *B)
Definition: Decl.cpp:3251
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2279
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3766
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3713
size_t param_size() const
Definition: Decl.h:2665
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3159
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:3206
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2774
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3154
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2680
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:5045
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition: Type.cpp:5284
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4909
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5574
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5388
unsigned getNumParams() const
Definition: Type.h:5361
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5501
QualType getParamType(unsigned i) const
Definition: Type.h:5363
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5446
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5368
ArrayRef< QualType > exceptions() const
Definition: Type.h:5531
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5546
Declaration of a template function.
Definition: DeclTemplate.h:958
Wrapper for source info for functions.
Definition: TypeLoc.h:1460
unsigned getNumParams() const
Definition: TypeLoc.h:1532
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1538
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1539
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1541
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4548
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
CallingConv getCallConv() const
Definition: Type.h:4660
QualType getReturnType() const
Definition: Type.h:4649
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:2165
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2088
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5841
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
void setInherited(bool I)
Definition: Attr.h:155
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2563
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2575
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:515
Describes an C or C++ initializer list.
Definition: Expr.h:5088
unsigned getNumInits() const
Definition: Expr.h:5118
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5134
child_range children()
Definition: Expr.h:5280
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:7639
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:3605
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6799
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:979
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3484
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1339
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1352
@ 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:675
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:1023
Represents a linkage specification.
Definition: DeclCXX.h:2996
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:3079
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:3038
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:469
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:311
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:408
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
iterator end() const
Definition: Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4335
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3544
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
Expr * getBase() const
Definition: Expr.h:3313
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3431
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1364
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3520
Describes a module or submodule.
Definition: Module.h:115
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:703
bool isExplicitGlobalModule() const
Definition: Module.h:213
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:699
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represents a C++ namespace alias.
Definition: DeclCXX.h:3182
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3174
Represent a C++ namespace.
Definition: Decl.h:551
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:607
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3134
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition: Decl.h:634
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:653
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
PtrTy get() const
Definition: Ownership.h:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1021
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1025
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1032
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1198
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:255
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4774
Represents a parameter to a function.
Definition: Decl.h:1725
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2983
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1821
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1866
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2988
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3008
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
bool hasInheritedDefaultArg() const
Definition: Decl.h:1870
bool isExplicitObjectParameter() const
Definition: Decl.h:1813
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:2918
Expr * getDefaultArg()
Definition: Decl.cpp:2971
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3013
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3019
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1874
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2941
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:485
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:479
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:836
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:916
Wrapper for source info for pointers.
Definition: TypeLoc.h:1333
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3199
QualType getPointeeType() const
Definition: Type.h:3209
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:6546
ArrayRef< Expr * > semantics()
Definition: Expr.h:6625
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8021
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8026
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:996
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7977
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
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:8140
QualType getCanonicalType() const
Definition: Type.h:7989
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8031
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2883
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1081
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8010
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7983
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2639
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:8120
Represents a template name as written in source code.
Definition: TemplateName.h:491
The collection of all-type qualifiers we support.
Definition: Type.h:324
void addAddressSpace(LangAS space)
Definition: Type.h:590
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
void removeConst()
Definition: Type.h:452
void removeAddressSpace()
Definition: Type.h:589
void addConst()
Definition: Type.h:453
void removeVolatile()
Definition: Type.h:462
std::string getAsString() const
LangAS getAddressSpace() const
Definition: Type.h:564
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3502
Represents a struct/union/class.
Definition: Decl.h:4162
bool hasFlexibleArrayMember() const
Definition: Decl.h:4195
field_iterator field_end() const
Definition: Decl.h:4379
field_range fields() const
Definition: Decl.h:4376
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5076
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4214
bool field_empty() const
Definition: Decl.h:4384
field_iterator field_begin() const
Definition: Decl.cpp:5110
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
RecordDecl * getDecl() const
Definition: Type.h:6088
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5080
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3440
QualType getPointeeType() const
Definition: Type.h:3458
static ResolvedUnexpandedPackExpr * Create(ASTContext &C, SourceLocation BeginLoc, QualType T, unsigned NumExprs)
Definition: ExprCXX.cpp:1991
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3046
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:393
void AddDecl(Decl *D)
Definition: Scope.h:346
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:370
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:918
bool isInvalid() const
Definition: Sema.h:7335
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3013
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5894
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5926
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5923
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:4998
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:8956
CXXMethodDecl * getMethod() const
Definition: Sema.h:8968
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:13119
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7233
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:466
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:11049
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6719
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:12675
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9819
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:6078
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:1561
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15522
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:5838
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9004
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9031
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9039
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:9027
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9012
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:412
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6652
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, CXXScopeSpec *SS=nullptr)
VariadicCallType
Definition: Sema.h:2317
@ VariadicDoesNotApply
Definition: Sema.h:2322
@ VariadicConstructor
Definition: Sema.h:2321
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:6129
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:13263
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
Definition: SemaDecl.cpp:7473
SemaOpenMP & OpenMP()
Definition: Sema.h:1128
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:5813
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:6114
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:869
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:6055
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:6036
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:1190
SemaCUDA & CUDA()
Definition: Sema.h:1073
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:17418
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:1272
@ AR_accessible
Definition: Sema.h:1270
@ AR_inaccessible
Definition: Sema.h:1271
@ AR_delayed
Definition: Sema.h:1273
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:2293
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2162
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6257
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:17176
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4844
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:49
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:18425
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1667
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:911
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:5821
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:531
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1113
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:4954
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
AllowFoldKind
Definition: Sema.h:7247
@ AllowFold
Definition: Sema.h:7249
@ NoFold
Definition: Sema.h:7248
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1499
ASTContext & getASTContext() const
Definition: Sema.h:534
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:6062
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:19939
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:6140
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:17851
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:692
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:5609
@ 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:9489
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:6073
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
ValueDecl * tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase)
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:819
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2217
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
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:11830
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1589
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7976
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1581
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2181
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:529
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20442
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
@ UPPC_RequiresClause
Definition: Sema.h:14017
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:13972
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:13990
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13981
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:13951
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13975
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13984
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13954
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13957
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:13963
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:527
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:5399
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:1390
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:910
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:6489
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:8282
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:14426
const LangOptions & LangOpts
Definition: Sema.h:909
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:17535
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7602
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6040
SemaHLSL & HLSL()
Definition: Sema.h:1078
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:11959
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:5405
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:4795
@ 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:6033
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20090
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:3712
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:6132
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6066
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:9585
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:1377
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:1858
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:12687
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:5395
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
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:3202
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15034
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:9602
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:15455
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:6496
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:6047
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15379
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1046
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:14946
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5826
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
TrivialABIHandling
Definition: Sema.h:5878
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:5880
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:5883
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7791
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:20039
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2255
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:13534
SourceManager & getSourceManager() const
Definition: Sema.h:532
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1342
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:8984
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9739
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
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:1471
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:216
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:8305
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:3885
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14989
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:9398
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14310
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:6058
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:10020
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10018
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:10022
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3095
ASTConsumer & Consumer
Definition: Sema.h:912
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:4230
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9801
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9793
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9797
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5134
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9707
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5705
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:17166
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:9122
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:874
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19026
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:1480
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:7458
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:17928
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7931
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1310
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:914
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:913
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:7305
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7296
@ TPC_TypeAliasTemplate
Definition: Sema.h:11303
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:6756
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Definition: SemaExpr.cpp:3611
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5595
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1317
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:2872
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6070
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:1581
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8898
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1566
@ OOK_Outside
Definition: Sema.h:3871
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13383
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:296
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:5812
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:18109
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:5967
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:21192
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6088
AbstractDiagSelID
Definition: Sema.h:5758
@ AbstractVariableType
Definition: Sema.h:5762
@ AbstractReturnType
Definition: Sema.h:5760
@ AbstractNone
Definition: Sema.h:5759
@ AbstractFieldType
Definition: Sema.h:5763
@ AbstractArrayType
Definition: Sema.h:5766
@ AbstractParamType
Definition: Sema.h:5761
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:962
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1705
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7980
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:14792
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:5954
@ 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:2752
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:451
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:3006
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:6075
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
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:5346
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:590
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...
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8282
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3444
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
child_range children()
Definition: Stmt.cpp:295
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
bool isUnevaluated() const
Definition: Expr.h:1907
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3701
StringRef getKindName() const
Definition: Decl.h:3769
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4766
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4760
bool isUnion() const
Definition: Decl.h:3784
TagKind getTagKind() const
Definition: Decl.h:3773
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3732
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:1263
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:611
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1334
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1301
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:398
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
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:183
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1727
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6667
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6735
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6733
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:6349
unsigned getDepth() const
Definition: Type.h:6348
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3549
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5631
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3568
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:3384
const Type * getTypeForDecl() const
Definition: Decl.h:3409
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:1257
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:2716
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7908
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:7919
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:529
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3194
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6930
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3176
The base class of the type hierarchy.
Definition: Type.h:1828
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:2511
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isVoidType() const
Definition: Type.h:8516
bool isBooleanType() const
Definition: Type.h:8648
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2935
bool isIncompleteArrayType() const
Definition: Type.h:8272
bool isUndeducedAutoType() const
Definition: Type.h:8351
bool isRValueReferenceType() const
Definition: Type.h:8218
bool isArrayType() const
Definition: Type.h:8264
bool isPointerType() const
Definition: Type.h:8192
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8560
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8810
bool isReferenceType() const
Definition: Type.h:8210
bool isEnumeralType() const
Definition: Type.h:8296
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3301
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isLValueReferenceType() const
Definition: Type.h:8214
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8485
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
QualType getCanonicalTypeInternal() const
Definition: Type.h:2990
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2701
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8691
bool isFunctionProtoType() const
Definition: Type.h:2536
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8661
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2725
bool isObjCObjectType() const
Definition: Type.h:8338
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8654
bool isFunctionType() const
Definition: Type.h:8188
bool isObjCObjectPointerType() const
Definition: Type.h:8334
bool isStructureOrClassType() const
Definition: Type.cpp:690
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
bool isRecordType() const
Definition: Type.h:8292
bool isUnionType() const
Definition: Type.cpp:704
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:1924
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
QualType getUnderlyingType() const
Definition: Decl.h:3482
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:2232
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:4959
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
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:4102
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3423
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:4021
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3402
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3924
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3374
Represents a C++ using-declaration.
Definition: DeclCXX.h:3574
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3623
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3615
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3309
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3611
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3601
Represents C++ using-directive.
Definition: DeclCXX.h:3077
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:3096
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3775
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3330
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3353
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3382
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3418
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3446
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3249
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition: Decl.cpp:5419
Represents a variable declaration or definition.
Definition: Decl.h:886
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2782
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1517
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2179
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:2808
void setCXXCondDecl()
Definition: Decl.h:1563
bool isInlineSpecified() const
Definition: Decl.h:1502
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2547
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1238
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1181
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2620
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:1163
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2823
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1132
const Expr * getInit() const
Definition: Decl.h:1323
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:912
void setInit(Expr *I)
Definition: Decl.cpp:2449
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1123
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:2500
void setExceptionVariable(bool EV)
Definition: Decl.h:1445
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:4035
unsigned getNumElements() const
Definition: Type.h:4050
QualType getElementType() const
Definition: Type.h:4049
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2784
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2804
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2816
bool isOverrideSpecified() const
Definition: DeclSpec.h:2803
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2808
bool isFinalSpecified() const
Definition: DeclSpec.h:2806
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2807
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition: ScopeInfo.h:179
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:820
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2346
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:921
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.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_decltype
Definition: Specifiers.h:89
@ TST_typename_pack_indexing
Definition: Specifiers.h:97
@ TST_decltype_auto
Definition: Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isa(CodeGen::Address addr)
Definition: Address.h:328
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ 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:2988
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_ListInit
Direct list-initialization.
Definition: Specifiers.h:274
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
CXXConstructionKind
Definition: ExprCXX.h:1538
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
BinaryOperatorKind
@ 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.
@ 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:248
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
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.
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, ResolvedUnexpandedPackExpr * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:238
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.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:991
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6877
@ 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:1105
ComparisonCategoryType
An enumeration representing the different comparison categories types.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:425
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1281
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:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6852
@ 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 isLambdaMethod(const DeclContext *DC)
Definition: ASTLambda.h:39
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:123
@ AS_public
Definition: Specifiers.h:124
@ AS_protected
Definition: Specifiers.h:125
@ AS_none
Definition: Specifiers.h:127
@ AS_private
Definition: Specifiers.h:126
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition: DeclSpec.h:1368
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1428
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1377
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1431
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1529
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1558
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1561
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1467
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1554
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1343
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
SourceRange getSourceRange() const
Definition: DeclSpec.h:1263
enum clang::DeclaratorChunk::@223 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1642
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:5165
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5177
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5167
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5170
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5173
Extra information about a function prototype.
Definition: Type.h:5193
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5200
FunctionEffectsRef FunctionEffects
Definition: Type.h:5203
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5194
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:1051
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:12692
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12786
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12783
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12736
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12750
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12754
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7872
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.