clang 23.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaCUDA.h"
47#include "clang/Sema/SemaObjC.h"
49#include "clang/Sema/Template.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86 bool VisitCoawaitExpr(const CoawaitExpr *E);
87 bool VisitCoyieldExpr(const CoyieldExpr *E);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = DRE->getDecl();
104
105 if (!isa<VarDecl, BindingDecl>(Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(DRE->getBeginLoc(),
119 diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(DRE->getBeginLoc(),
136 diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(ThisE->getBeginLoc(),
148 diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(&LC))
176 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(LC.getCapturedVar());
179 Invalid |= Visit(D->getInit());
180 }
181 return Invalid;
182}
183
184bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
185 // [expr.await] An await-expression shall not appear in a default argument.
186 // Note that this is generally diagnosed by isValidCoroutineContext,
187 // however isValidCoroutineContext misses default argument in nested
188 // function declarations.
189 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
190 << "co_await" << E->getSourceRange();
191 return true;
192}
193
194bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
195 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
196 << "co_yield" << E->getSourceRange();
197 return true;
198}
199
200} // namespace
201
202void
204 const CXXMethodDecl *Method) {
205 // If we have an MSAny spec already, don't bother.
206 if (!Method || ComputedEST == EST_MSAny)
207 return;
208
209 const FunctionProtoType *Proto
210 = Method->getType()->getAs<FunctionProtoType>();
211 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
212 if (!Proto)
213 return;
214
216
217 // If we have a throw-all spec at this point, ignore the function.
218 if (ComputedEST == EST_None)
219 return;
220
221 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
222 EST = EST_BasicNoexcept;
223
224 switch (EST) {
225 case EST_Unparsed:
227 case EST_Unevaluated:
228 llvm_unreachable("should not see unresolved exception specs here");
229
230 // If this function can throw any exceptions, make a note of that.
231 case EST_MSAny:
232 case EST_None:
233 // FIXME: Whichever we see last of MSAny and None determines our result.
234 // We should make a consistent, order-independent choice here.
235 ClearExceptions();
236 ComputedEST = EST;
237 return;
239 ClearExceptions();
240 ComputedEST = EST_None;
241 return;
242 // FIXME: If the call to this decl is using any of its default arguments, we
243 // need to search them for potentially-throwing calls.
244 // If this function has a basic noexcept, it doesn't affect the outcome.
246 case EST_NoexceptTrue:
247 case EST_NoThrow:
248 return;
249 // If we're still at noexcept(true) and there's a throw() callee,
250 // change to that specification.
251 case EST_DynamicNone:
252 if (ComputedEST == EST_BasicNoexcept)
253 ComputedEST = EST_DynamicNone;
254 return;
256 llvm_unreachable(
257 "should not generate implicit declarations for dependent cases");
258 case EST_Dynamic:
259 break;
260 }
261 assert(EST == EST_Dynamic && "EST case not considered earlier.");
262 assert(ComputedEST != EST_None &&
263 "Shouldn't collect exceptions when throw-all is guaranteed.");
264 ComputedEST = EST_Dynamic;
265 // Record the exceptions in this function's exception specification.
266 for (const auto &E : Proto->exceptions())
267 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
268 Exceptions.push_back(E);
269}
270
272 if (!S || ComputedEST == EST_MSAny)
273 return;
274
275 // FIXME:
276 //
277 // C++0x [except.spec]p14:
278 // [An] implicit exception-specification specifies the type-id T if and
279 // only if T is allowed by the exception-specification of a function directly
280 // invoked by f's implicit definition; f shall allow all exceptions if any
281 // function it directly invokes allows all exceptions, and f shall allow no
282 // exceptions if every function it directly invokes allows no exceptions.
283 //
284 // Note in particular that if an implicit exception-specification is generated
285 // for a function containing a throw-expression, that specification can still
286 // be noexcept(true).
287 //
288 // Note also that 'directly invoked' is not defined in the standard, and there
289 // is no indication that we should only consider potentially-evaluated calls.
290 //
291 // Ultimately we should implement the intent of the standard: the exception
292 // specification should be the set of exceptions which can be thrown by the
293 // implicit definition. For now, we assume that any non-nothrow expression can
294 // throw any exception.
295
296 if (Self->canThrow(S))
297 ComputedEST = EST_None;
298}
299
301 SourceLocation EqualLoc) {
302 if (RequireCompleteType(Param->getLocation(), Param->getType(),
303 diag::err_typecheck_decl_incomplete_type))
304 return true;
305
306 // C++ [dcl.fct.default]p5
307 // A default argument expression is implicitly converted (clause
308 // 4) to the parameter type. The default argument expression has
309 // the same semantic constraints as the initializer expression in
310 // a declaration of a variable of the parameter type, using the
311 // copy-initialization semantics (8.5).
313 Param);
314 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
315 EqualLoc);
316 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
317 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
318 if (Result.isInvalid())
319 return true;
320 Arg = Result.getAs<Expr>();
321
322 CheckCompletedExpr(Arg, EqualLoc);
324
325 return Arg;
326}
327
329 SourceLocation EqualLoc) {
330 // Add the default argument to the parameter
331 Param->setDefaultArg(Arg);
332
333 // We have already instantiated this parameter; provide each of the
334 // instantiations with the uninstantiated default argument.
335 UnparsedDefaultArgInstantiationsMap::iterator InstPos
337 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
338 for (auto &Instantiation : InstPos->second)
339 Instantiation->setUninstantiatedDefaultArg(Arg);
340
341 // We're done tracking this parameter's instantiations.
343 }
344}
345
346void
348 Expr *DefaultArg) {
349 if (!param || !DefaultArg)
350 return;
351
352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
353 UnparsedDefaultArgLocs.erase(Param);
354
355 // Default arguments are only permitted in C++
356 if (!getLangOpts().CPlusPlus) {
357 Diag(EqualLoc, diag::err_param_default_argument)
358 << DefaultArg->getSourceRange();
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360 }
361
362 // Check for unexpanded parameter packs.
364 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
365
366 // C++11 [dcl.fct.default]p3
367 // A default argument expression [...] shall not be specified for a
368 // parameter pack.
369 if (Param->isParameterPack()) {
370 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
371 << DefaultArg->getSourceRange();
372 // Recover by discarding the default argument.
373 Param->setDefaultArg(nullptr);
374 return;
375 }
376
377 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
378 if (Result.isInvalid())
379 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
380
381 DefaultArg = Result.getAs<Expr>();
382
383 // Check that the default argument is well-formed
384 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
385 if (DefaultArgChecker.Visit(DefaultArg))
386 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
387
388 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
389}
390
392 SourceLocation EqualLoc,
393 SourceLocation ArgLoc) {
394 if (!param)
395 return;
396
397 ParmVarDecl *Param = cast<ParmVarDecl>(param);
398 Param->setUnparsedDefaultArg();
399 UnparsedDefaultArgLocs[Param] = ArgLoc;
400}
401
403 Expr *DefaultArg) {
404 if (!param)
405 return;
406
407 ParmVarDecl *Param = cast<ParmVarDecl>(param);
408 Param->setInvalidDecl();
409 UnparsedDefaultArgLocs.erase(Param);
410 ExprResult RE;
411 if (DefaultArg) {
412 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
413 Param->getType().getNonReferenceType());
414 } else {
415 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
416 Param->getType().getNonReferenceType());
417 }
418 Param->setDefaultArg(RE.get());
419}
420
422 // C++ [dcl.fct.default]p3
423 // A default argument expression shall be specified only in the
424 // parameter-declaration-clause of a function declaration or in a
425 // template-parameter (14.1). It shall not be specified for a
426 // parameter pack. If it is specified in a
427 // parameter-declaration-clause, it shall not occur within a
428 // declarator or abstract-declarator of a parameter-declaration.
429 bool MightBeFunction = D.isFunctionDeclarationContext();
430 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
431 DeclaratorChunk &chunk = D.getTypeObject(i);
432 if (chunk.Kind == DeclaratorChunk::Function) {
433 if (MightBeFunction) {
434 // This is a function declaration. It can have default arguments, but
435 // keep looking in case its return type is a function type with default
436 // arguments.
437 MightBeFunction = false;
438 continue;
439 }
440 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
441 ++argIdx) {
442 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
443 if (Param->hasUnparsedDefaultArg()) {
444 std::unique_ptr<CachedTokens> Toks =
445 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
446 SourceRange SR;
447 if (Toks->size() > 1)
448 SR = SourceRange((*Toks)[1].getLocation(),
449 Toks->back().getLocation());
450 else
451 SR = UnparsedDefaultArgLocs[Param];
452 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
453 << SR;
454 } else if (Param->getDefaultArg()) {
455 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
456 << Param->getDefaultArg()->getSourceRange();
457 Param->setDefaultArg(nullptr);
458 }
459 }
460 } else if (chunk.Kind != DeclaratorChunk::Paren) {
461 MightBeFunction = false;
462 }
463 }
464}
465
467 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
468 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
469 });
470}
471
473 Scope *S) {
474 bool Invalid = false;
475
476 // The declaration context corresponding to the scope is the semantic
477 // parent, unless this is a local function declaration, in which case
478 // it is that surrounding function.
479 DeclContext *ScopeDC = New->isLocalExternDecl()
480 ? New->getLexicalDeclContext()
481 : New->getDeclContext();
482
483 // Find the previous declaration for the purpose of default arguments.
484 FunctionDecl *PrevForDefaultArgs = Old;
485 for (/**/; PrevForDefaultArgs;
486 // Don't bother looking back past the latest decl if this is a local
487 // extern declaration; nothing else could work.
488 PrevForDefaultArgs = New->isLocalExternDecl()
489 ? nullptr
490 : PrevForDefaultArgs->getPreviousDecl()) {
491 // Ignore hidden declarations.
492 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
493 continue;
494
495 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
496 !New->isCXXClassMember()) {
497 // Ignore default arguments of old decl if they are not in
498 // the same scope and this is not an out-of-line definition of
499 // a member function.
500 continue;
501 }
502
503 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
504 // If only one of these is a local function declaration, then they are
505 // declared in different scopes, even though isDeclInScope may think
506 // they're in the same scope. (If both are local, the scope check is
507 // sufficient, and if neither is local, then they are in the same scope.)
508 continue;
509 }
510
511 // We found the right previous declaration.
512 break;
513 }
514
515 // C++ [dcl.fct.default]p4:
516 // For non-template functions, default arguments can be added in
517 // later declarations of a function in the same
518 // scope. Declarations in different scopes have completely
519 // distinct sets of default arguments. That is, declarations in
520 // inner scopes do not acquire default arguments from
521 // declarations in outer scopes, and vice versa. In a given
522 // function declaration, all parameters subsequent to a
523 // parameter with a default argument shall have default
524 // arguments supplied in this or previous declarations. A
525 // default argument shall not be redefined by a later
526 // declaration (not even to the same value).
527 //
528 // C++ [dcl.fct.default]p6:
529 // Except for member functions of class templates, the default arguments
530 // in a member function definition that appears outside of the class
531 // definition are added to the set of default arguments provided by the
532 // member function declaration in the class definition.
533 for (unsigned p = 0, NumParams = PrevForDefaultArgs
534 ? PrevForDefaultArgs->getNumParams()
535 : 0;
536 p < NumParams; ++p) {
537 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
538 ParmVarDecl *NewParam = New->getParamDecl(p);
539
540 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
541 bool NewParamHasDfl = NewParam->hasDefaultArg();
542
543 if (OldParamHasDfl && NewParamHasDfl) {
544 unsigned DiagDefaultParamID =
545 diag::err_param_default_argument_redefinition;
546
547 // MSVC accepts that default parameters be redefined for member functions
548 // of template class. The new default parameter's value is ignored.
549 Invalid = true;
550 if (getLangOpts().MicrosoftExt) {
551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
552 if (MD && MD->getParent()->getDescribedClassTemplate()) {
553 // Merge the old default argument into the new parameter.
554 NewParam->setHasInheritedDefaultArg();
555 if (OldParam->hasUninstantiatedDefaultArg())
557 OldParam->getUninstantiatedDefaultArg());
558 else
559 NewParam->setDefaultArg(OldParam->getInit());
560 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
561 Invalid = false;
562 }
563 }
564
565 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
566 // hint here. Alternatively, we could walk the type-source information
567 // for NewParam to find the last source location in the type... but it
568 // isn't worth the effort right now. This is the kind of test case that
569 // is hard to get right:
570 // int f(int);
571 // void g(int (*fp)(int) = f);
572 // void g(int (*fp)(int) = &f);
573 Diag(NewParam->getLocation(), DiagDefaultParamID)
574 << NewParam->getDefaultArgRange();
575
576 // Look for the function declaration where the default argument was
577 // actually written, which may be a declaration prior to Old.
578 for (auto Older = PrevForDefaultArgs;
579 OldParam->hasInheritedDefaultArg(); /**/) {
580 Older = Older->getPreviousDecl();
581 OldParam = Older->getParamDecl(p);
582 }
583
584 Diag(OldParam->getLocation(), diag::note_previous_definition)
585 << OldParam->getDefaultArgRange();
586 } else if (OldParamHasDfl) {
587 // Merge the old default argument into the new parameter unless the new
588 // function is a friend declaration in a template class. In the latter
589 // case the default arguments will be inherited when the friend
590 // declaration will be instantiated.
591 if (New->getFriendObjectKind() == Decl::FOK_None ||
592 !New->getLexicalDeclContext()->isDependentContext()) {
593 // It's important to use getInit() here; getDefaultArg()
594 // strips off any top-level ExprWithCleanups.
595 NewParam->setHasInheritedDefaultArg();
596 if (OldParam->hasUnparsedDefaultArg())
597 NewParam->setUnparsedDefaultArg();
598 else if (OldParam->hasUninstantiatedDefaultArg())
600 OldParam->getUninstantiatedDefaultArg());
601 else
602 NewParam->setDefaultArg(OldParam->getInit());
603 }
604 } else if (NewParamHasDfl) {
605 if (New->getDescribedFunctionTemplate()) {
606 // Paragraph 4, quoted above, only applies to non-template functions.
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_template_redecl)
609 << NewParam->getDefaultArgRange();
610 Diag(PrevForDefaultArgs->getLocation(),
611 diag::note_template_prev_declaration)
612 << false;
613 } else if (New->getTemplateSpecializationKind()
615 New->getTemplateSpecializationKind() != TSK_Undeclared) {
616 // C++ [temp.expr.spec]p21:
617 // Default function arguments shall not be specified in a declaration
618 // or a definition for one of the following explicit specializations:
619 // - the explicit specialization of a function template;
620 // - the explicit specialization of a member function template;
621 // - the explicit specialization of a member function of a class
622 // template where the class template specialization to which the
623 // member function specialization belongs is implicitly
624 // instantiated.
625 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
626 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
627 << New->getDeclName()
628 << NewParam->getDefaultArgRange();
629 } else if (New->getDeclContext()->isDependentContext()) {
630 // C++ [dcl.fct.default]p6 (DR217):
631 // Default arguments for a member function of a class template shall
632 // be specified on the initial declaration of the member function
633 // within the class template.
634 //
635 // Reading the tea leaves a bit in DR217 and its reference to DR205
636 // leads me to the conclusion that one cannot add default function
637 // arguments for an out-of-line definition of a member function of a
638 // dependent type.
639 int WhichKind = 2;
641 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
642 if (Record->getDescribedClassTemplate())
643 WhichKind = 0;
645 WhichKind = 1;
646 else
647 WhichKind = 2;
648 }
649
650 Diag(NewParam->getLocation(),
651 diag::err_param_default_argument_member_template_redecl)
652 << WhichKind
653 << NewParam->getDefaultArgRange();
654 }
655 }
656 }
657
658 // DR1344: If a default argument is added outside a class definition and that
659 // default argument makes the function a special member function, the program
660 // is ill-formed. This can only happen for constructors.
662 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
665 if (NewSM != OldSM) {
666 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
667 assert(NewParam->hasDefaultArg());
668 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
669 << NewParam->getDefaultArgRange() << NewSM;
670 Diag(Old->getLocation(), diag::note_previous_declaration);
671 }
672 }
673
674 const FunctionDecl *Def;
675 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
676 // template has a constexpr specifier then all its declarations shall
677 // contain the constexpr specifier.
678 if (New->getConstexprKind() != Old->getConstexprKind()) {
679 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
680 << New << static_cast<int>(New->getConstexprKind())
681 << static_cast<int>(Old->getConstexprKind());
682 Diag(Old->getLocation(), diag::note_previous_declaration);
683 Invalid = true;
684 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
685 Old->isDefined(Def) &&
686 // If a friend function is inlined but does not have 'inline'
687 // specifier, it is a definition. Do not report attribute conflict
688 // in this case, redefinition will be diagnosed later.
689 (New->isInlineSpecified() ||
690 New->getFriendObjectKind() == Decl::FOK_None)) {
691 // C++11 [dcl.fcn.spec]p4:
692 // If the definition of a function appears in a translation unit before its
693 // first declaration as inline, the program is ill-formed.
694 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
695 Diag(Def->getLocation(), diag::note_previous_definition);
696 Invalid = true;
697 }
698
699 // C++17 [temp.deduct.guide]p3:
700 // Two deduction guide declarations in the same translation unit
701 // for the same class template shall not have equivalent
702 // parameter-declaration-clauses.
704 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
705 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
706 Diag(Old->getLocation(), diag::note_previous_declaration);
707 }
708
709 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
710 // argument expression, that declaration shall be a definition and shall be
711 // the only declaration of the function or function template in the
712 // translation unit.
715 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
716 Diag(Old->getLocation(), diag::note_previous_declaration);
717 Invalid = true;
718 }
719
720 // C++11 [temp.friend]p4 (DR329):
721 // When a function is defined in a friend function declaration in a class
722 // template, the function is instantiated when the function is odr-used.
723 // The same restrictions on multiple declarations and definitions that
724 // apply to non-template function declarations and definitions also apply
725 // to these implicit definitions.
726 const FunctionDecl *OldDefinition = nullptr;
727 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
728 Old->isDefined(OldDefinition, true))
729 CheckForFunctionRedefinition(New, OldDefinition);
730
731 return Invalid;
732}
733
736 ? diag::warn_cxx23_placeholder_var_definition
737 : diag::ext_placeholder_var_definition);
738}
739
740NamedDecl *
742 MultiTemplateParamsArg TemplateParamLists) {
743 assert(D.isDecompositionDeclarator());
745
746 // The syntax only allows a decomposition declarator as a simple-declaration,
747 // a for-range-declaration, or a condition in Clang, but we parse it in more
748 // cases than that.
750 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
751 << Decomp.getSourceRange();
752 return nullptr;
753 }
754
755 if (!TemplateParamLists.empty()) {
756 // C++17 [temp]/1:
757 // A template defines a family of class, functions, or variables, or an
758 // alias for a family of types.
759 //
760 // Structured bindings are not included.
761 Diag(TemplateParamLists.front()->getTemplateLoc(),
762 diag::err_decomp_decl_template);
763 return nullptr;
764 }
765
766 unsigned DiagID;
768 DiagID = diag::compat_pre_cxx17_decomp_decl;
770 DiagID = getLangOpts().CPlusPlus26
771 ? diag::compat_cxx26_decomp_decl_cond
772 : diag::compat_pre_cxx26_decomp_decl_cond;
773 else
774 DiagID = diag::compat_cxx17_decomp_decl;
775
776 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
777
778 // The semantic context is always just the current context.
779 DeclContext *const DC = CurContext;
780
781 // C++17 [dcl.dcl]/8:
782 // The decl-specifier-seq shall contain only the type-specifier auto
783 // and cv-qualifiers.
784 // C++20 [dcl.dcl]/8:
785 // If decl-specifier-seq contains any decl-specifier other than static,
786 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
787 // C++23 [dcl.pre]/6:
788 // Each decl-specifier in the decl-specifier-seq shall be static,
789 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
790 // C++23 [dcl.pre]/7:
791 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
792 // constinit, static, thread_local, auto, or a cv-qualifier
793 auto &DS = D.getDeclSpec();
794 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
795 Diag(Loc, diag::err_decomp_decl_spec) << Name;
796 };
797
798 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
799 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
800 };
801
802 if (auto SCS = DS.getStorageClassSpec()) {
803 if (SCS == DeclSpec::SCS_static)
804 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
805 DS.getStorageClassSpecLoc());
806 else
807 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
808 DS.getStorageClassSpecLoc());
809 }
810 if (auto TSCS = DS.getThreadStorageClassSpec())
811 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
812 DS.getThreadStorageClassSpecLoc());
813
814 if (DS.isInlineSpecified())
815 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
816
817 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
818 ConstexprSpec != ConstexprSpecKind::Unspecified) {
819 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
821 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
822 DS.getConstexprSpecLoc());
823 }
824
825 // We can't recover from it being declared as a typedef.
826 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
827 return nullptr;
828
829 // C++2a [dcl.struct.bind]p1:
830 // A cv that includes volatile is deprecated
831 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
833 Diag(DS.getVolatileSpecLoc(),
834 diag::warn_deprecated_volatile_structured_binding);
835
837 QualType R = TInfo->getType();
838
841 D.setInvalidType();
842
843 // The syntax only allows a single ref-qualifier prior to the decomposition
844 // declarator. No other declarator chunks are permitted. Also check the type
845 // specifier here.
846 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
847 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
848 (D.getNumTypeObjects() == 1 &&
850 Diag(Decomp.getLSquareLoc(),
851 (D.hasGroupingParens() ||
852 (D.getNumTypeObjects() &&
854 ? diag::err_decomp_decl_parens
855 : diag::err_decomp_decl_type)
856 << R;
857
858 // In most cases, there's no actual problem with an explicitly-specified
859 // type, but a function type won't work here, and ActOnVariableDeclarator
860 // shouldn't be called for such a type.
861 if (R->isFunctionType())
862 D.setInvalidType();
863 }
864
865 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
866 if (DS.isConstrainedAuto()) {
867 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
868 assert(TemplRep->Kind == TNK_Concept_template &&
869 "No other template kind should be possible for a constrained auto");
870
871 SourceRange TemplRange{TemplRep->TemplateNameLoc,
872 TemplRep->RAngleLoc.isValid()
873 ? TemplRep->RAngleLoc
874 : TemplRep->TemplateNameLoc};
875 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
876 << TemplRange << FixItHint::CreateRemoval(TemplRange);
877 }
878
879 // Build the BindingDecls.
881
882 // Build the BindingDecls.
883 for (auto &B : D.getDecompositionDeclarator().bindings()) {
884 // Check for name conflicts.
885 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
886 IdentifierInfo *VarName = B.Name;
887 assert(VarName && "Cannot have an unnamed binding declaration");
888
892 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
893
894 // It's not permitted to shadow a template parameter name.
895 if (Previous.isSingleResult() &&
896 Previous.getFoundDecl()->isTemplateParameter()) {
897 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
898 Previous.clear();
899 }
900
901 QualType QT;
902 if (B.EllipsisLoc.isValid()) {
903 if (!cast<Decl>(DC)->isTemplated())
904 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
905 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
906 /*ExpectsPackInType=*/false);
907 }
908
909 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
910
911 ProcessDeclAttributeList(S, BD, *B.Attrs);
912
913 // Find the shadowed declaration before filtering for scope.
914 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
916 : nullptr;
917
918 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
919 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
920 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
921 /*AllowInlineNamespace*/false);
922
923 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
924 DC->isFunctionOrMethod() && VarName->isPlaceholder();
925 if (!Previous.empty()) {
926 if (IsPlaceholder) {
927 bool sameDC = (Previous.end() - 1)
928 ->getDeclContext()
929 ->getRedeclContext()
930 ->Equals(DC->getRedeclContext());
931 if (sameDC &&
932 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
933 Previous.clear();
935 }
936 } else {
937 auto *Old = Previous.getRepresentativeDecl();
938 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
939 Diag(Old->getLocation(), diag::note_previous_definition);
940 }
941 } else if (ShadowedDecl && !D.isRedeclaration()) {
942 CheckShadow(BD, ShadowedDecl, Previous);
943 }
944 PushOnScopeChains(BD, S, true);
945 Bindings.push_back(BD);
946 ParsingInitForAutoVars.insert(BD);
947 }
948
949 // There are no prior lookup results for the variable itself, because it
950 // is unnamed.
951 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
952 Decomp.getLSquareLoc());
955
956 // Build the variable that holds the non-decomposed object.
957 bool AddToScope = true;
958 NamedDecl *New =
959 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
960 MultiTemplateParamsArg(), AddToScope, Bindings);
961 if (AddToScope) {
962 S->AddDecl(New);
963 CurContext->addHiddenDecl(New);
964 }
965
966 if (OpenMP().isInOpenMPDeclareTargetContext())
967 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
968
969 return New;
970}
971
972// Check the arity of the structured bindings.
973// Create the resolved pack expr if needed.
975 QualType DecompType,
977 unsigned MemberCount) {
978 auto BindingWithPackItr = llvm::find_if(
979 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
980 bool HasPack = BindingWithPackItr != Bindings.end();
981 bool IsValid;
982 if (!HasPack) {
983 IsValid = Bindings.size() == MemberCount;
984 } else {
985 // There may not be more members than non-pack bindings.
986 IsValid = MemberCount >= Bindings.size() - 1;
987 }
988
989 if (IsValid && HasPack) {
990 // Create the pack expr and assign it to the binding.
991 unsigned PackSize = MemberCount - Bindings.size() + 1;
992
993 BindingDecl *BPack = *BindingWithPackItr;
994 BPack->setDecomposedDecl(DD);
995 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
996 // Create the nested BindingDecls.
997 for (unsigned I = 0; I < PackSize; ++I) {
999 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1000 BPack->getIdentifier(), QualType());
1001 NestedBD->setDecomposedDecl(DD);
1002 NestedBDs[I] = NestedBD;
1003 }
1004
1006 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1007 auto *PackExpr = FunctionParmPackExpr::Create(
1008 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1009 BPack->setBinding(PackType, PackExpr);
1010 }
1011
1012 if (IsValid)
1013 return false;
1014
1015 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1016 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1017 << (MemberCount < Bindings.size());
1018 return true;
1019}
1020
1023 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1024 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1025 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1026 auto *DD = cast<DecompositionDecl>(Src);
1027
1028 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1029 return true;
1030
1031 unsigned I = 0;
1032 for (auto *B : DD->flat_bindings()) {
1033 SourceLocation Loc = B->getLocation();
1034 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1035 if (E.isInvalid())
1036 return true;
1037 E = GetInit(Loc, E.get(), I++);
1038 if (E.isInvalid())
1039 return true;
1040 B->setBinding(ElemType, E.get());
1041 }
1042
1043 return false;
1044}
1045
1048 ValueDecl *Src, QualType DecompType,
1049 const llvm::APSInt &NumElems,
1050 QualType ElemType) {
1052 S, Bindings, Src, DecompType, NumElems, ElemType,
1053 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1054 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1055 if (E.isInvalid())
1056 return ExprError();
1057 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1058 });
1059}
1060
1062 ValueDecl *Src, QualType DecompType,
1063 const ConstantArrayType *CAT) {
1064 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1065 llvm::APSInt(CAT->getSize()),
1066 CAT->getElementType());
1067}
1068
1070 ValueDecl *Src, QualType DecompType,
1071 const VectorType *VT) {
1073 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1075 DecompType.getQualifiers()));
1076}
1077
1080 ValueDecl *Src, QualType DecompType,
1081 const ComplexType *CT) {
1083 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1085 DecompType.getQualifiers()),
1086 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1087 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1088 });
1089}
1090
1093 const TemplateParameterList *Params) {
1095 llvm::raw_svector_ostream OS(SS);
1096 bool First = true;
1097 unsigned I = 0;
1098 for (auto &Arg : Args.arguments()) {
1099 if (!First)
1100 OS << ", ";
1101 Arg.getArgument().print(PrintingPolicy, OS,
1103 PrintingPolicy, Params, I));
1104 First = false;
1105 I++;
1106 }
1107 return std::string(OS.str());
1108}
1109
1110static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1111 TemplateArgumentListInfo &Args, unsigned DiagID) {
1112 auto DiagnoseMissing = [&] {
1113 if (DiagID)
1114 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1115 Args, /*Params*/ nullptr);
1116 return QualType();
1117 };
1118
1119 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1120 NamespaceDecl *Std = S.getStdNamespace();
1121 if (!Std)
1122 return DiagnoseMissing();
1123
1124 // Look up the trait itself, within namespace std. We can diagnose various
1125 // problems with this lookup even if we've been asked to not diagnose a
1126 // missing specialization, because this can only fail if the user has been
1127 // declaring their own names in namespace std or we don't support the
1128 // standard library implementation in use.
1129 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1131 if (!S.LookupQualifiedName(Result, Std))
1132 return DiagnoseMissing();
1133 if (Result.isAmbiguous())
1134 return QualType();
1135
1136 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1137 if (!TraitTD) {
1138 Result.suppressDiagnostics();
1139 NamedDecl *Found = *Result.begin();
1140 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1141 S.Diag(Found->getLocation(), diag::note_declared_at);
1142 return QualType();
1143 }
1144
1145 // Build the template-id.
1146 QualType TraitTy = S.CheckTemplateIdType(
1147 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1148 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1149 if (TraitTy.isNull())
1150 return QualType();
1151
1152 if (!S.isCompleteType(Loc, TraitTy)) {
1153 if (DiagID)
1155 Loc, TraitTy, DiagID,
1157 TraitTD->getTemplateParameters()));
1158 return QualType();
1159 }
1160 return TraitTy;
1161}
1162
1163static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1164 LookupResult &MemberLookup) {
1165 assert(RD && "specialization of class template is not a class?");
1166 S.LookupQualifiedName(MemberLookup, RD);
1167 return MemberLookup.isAmbiguous();
1168}
1169
1170static TemplateArgumentLoc
1172 uint64_t I) {
1173 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1174 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1175}
1176
1177static TemplateArgumentLoc
1181
1182namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1183
1184static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1185 unsigned &OutSize) {
1188
1189 // Form template argument list for tuple_size<T>.
1190 TemplateArgumentListInfo Args(Loc, Loc);
1192
1193 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1194 if (TraitTy.isNull())
1195 return IsTupleLike::NotTupleLike;
1196
1199
1200 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1201 // it's not tuple-like.
1202 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1203 return IsTupleLike::NotTupleLike;
1204
1205 // If we get this far, we've committed to the tuple interpretation, but
1206 // we can still fail if there actually isn't a usable ::value.
1207
1208 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1209 LookupResult &R;
1211 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1212 : R(R), Args(Args) {}
1213 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1214 SourceLocation Loc) override {
1215 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1217 /*Params*/ nullptr);
1218 }
1219 } Diagnoser(R, Args);
1220
1221 ExprResult E =
1222 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1223 if (E.isInvalid())
1224 return IsTupleLike::Error;
1225
1226 llvm::APSInt Size;
1227 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1228 if (E.isInvalid())
1229 return IsTupleLike::Error;
1230
1231 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1232 // an UnsignedOrNone.
1233 if (Size < 0 || Size >= UINT_MAX) {
1235 Size.toString(Str);
1236 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1238 /*Params=*/nullptr)
1239 << StringRef(Str.data(), Str.size());
1240 return IsTupleLike::Error;
1241 }
1242
1243 OutSize = Size.getExtValue();
1244 return IsTupleLike::TupleLike;
1245}
1246
1247/// \return std::tuple_element<I, T>::type.
1249 unsigned I, QualType T) {
1250 // Form template argument list for tuple_element<I, T>.
1251 TemplateArgumentListInfo Args(Loc, Loc);
1252 Args.addArgument(
1255
1256 QualType TraitTy =
1257 getStdTrait(S, Loc, "tuple_element", Args,
1258 diag::err_decomp_decl_std_tuple_element_not_specialized);
1259 if (TraitTy.isNull())
1260 return QualType();
1261
1262 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1263 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1264 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1265 return QualType();
1266
1267 auto *TD = R.getAsSingle<TypeDecl>();
1268 if (!TD) {
1269 R.suppressDiagnostics();
1270 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1272 /*Params*/ nullptr);
1273 if (!R.empty())
1274 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1275 return QualType();
1276 }
1277
1278 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1279 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1280}
1281
1282namespace {
1283struct InitializingBinding {
1284 Sema &S;
1285 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1286 Sema::CodeSynthesisContext Ctx;
1289 Ctx.Entity = BD;
1291 }
1292 ~InitializingBinding() {
1294 }
1295};
1296}
1297
1300 VarDecl *Src, QualType DecompType,
1301 unsigned NumElems) {
1302 auto *DD = cast<DecompositionDecl>(Src);
1303 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1304 return true;
1305
1306 if (Bindings.empty())
1307 return false;
1308
1309 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1310
1311 // [dcl.decomp]p3:
1312 // The unqualified-id get is looked up in the scope of E by class member
1313 // access lookup ...
1314 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1315 bool UseMemberGet = false;
1316 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1317 if (auto *RD = DecompType->getAsCXXRecordDecl())
1318 S.LookupQualifiedName(MemberGet, RD);
1319 if (MemberGet.isAmbiguous())
1320 return true;
1321 // ... and if that finds at least one declaration that is a function
1322 // template whose first template parameter is a non-type parameter ...
1323 for (NamedDecl *D : MemberGet) {
1324 if (FunctionTemplateDecl *FTD =
1325 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1326 TemplateParameterList *TPL = FTD->getTemplateParameters();
1327 if (TPL->size() != 0 &&
1329 // ... the initializer is e.get<i>().
1330 UseMemberGet = true;
1331 break;
1332 }
1333 }
1334 }
1335 }
1336
1337 unsigned I = 0;
1338 for (auto *B : DD->flat_bindings()) {
1339 InitializingBinding InitContext(S, B);
1340 SourceLocation Loc = B->getLocation();
1341
1342 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1343 if (E.isInvalid())
1344 return true;
1345
1346 // e is an lvalue if the type of the entity is an lvalue reference and
1347 // an xvalue otherwise
1348 if (!Src->getType()->isLValueReferenceType())
1349 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1350 E.get(), nullptr, VK_XValue,
1352
1353 TemplateArgumentListInfo Args(Loc, Loc);
1354 Args.addArgument(
1356
1357 if (UseMemberGet) {
1358 // if [lookup of member get] finds at least one declaration, the
1359 // initializer is e.get<i-1>().
1360 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1361 CXXScopeSpec(), SourceLocation(), nullptr,
1362 MemberGet, &Args, nullptr);
1363 if (E.isInvalid())
1364 return true;
1365
1366 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1367 } else {
1368 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1369 // in the associated namespaces.
1372 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1374 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1375
1376 Expr *Arg = E.get();
1377 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1378 }
1379 if (E.isInvalid())
1380 return true;
1381 Expr *Init = E.get();
1382
1383 // Given the type T designated by std::tuple_element<i - 1, E>::type
1384 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1385 if (T.isNull())
1386 return true;
1387
1388 // C++26 [dcl.struct.bind]p7:
1389 // and the type Ui, defined as Ti if the initializer is a prvalue,
1390 // as "lvalue reference to Ti" if the initializer is an lvalue,
1391 // or as "rvalue reference to Ti" otherwise
1392 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1393 QualType U = E.get()->isPRValue()
1394 ? T
1395 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1396 B->getDeclName());
1397 if (U.isNull())
1398 return true;
1399
1400 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1401 // entity and this type was never written in source code.
1402 auto *BindingVD =
1403 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1404 B->getDeclName().getAsIdentifierInfo(), U,
1405 /*TInfo=*/nullptr, Src->getStorageClass());
1406 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1407 BindingVD->setTSCSpec(Src->getTSCSpec());
1408 BindingVD->setConstexpr(Src->isConstexpr());
1409 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1410 BindingVD->addAttr(CIAttr->clone(S.Context));
1411 BindingVD->setImplicit();
1412 if (Src->isInlineSpecified())
1413 BindingVD->setInlineSpecified();
1414 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1415
1418 InitializationSequence Seq(S, Entity, Kind, Init);
1419 E = Seq.Perform(S, Entity, Kind, Init);
1420 if (E.isInvalid())
1421 return true;
1422 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1423 if (E.isInvalid())
1424 return true;
1425 BindingVD->setInit(E.get());
1427
1429 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1430 if (E.isInvalid())
1431 return true;
1432
1433 B->setBinding(T, E.get());
1434 I++;
1435 }
1436
1437 return false;
1438}
1439
1440/// Find the base class to decompose in a built-in decomposition of a class type.
1441/// This base class search is, unfortunately, not quite like any other that we
1442/// perform anywhere else in C++.
1444 const CXXRecordDecl *RD,
1445 CXXCastPath &BasePath) {
1446 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1447 CXXBasePath &Path) {
1448 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1449 };
1450
1451 const CXXRecordDecl *ClassWithFields = nullptr;
1453 if (RD->hasDirectFields())
1454 // [dcl.decomp]p4:
1455 // Otherwise, all of E's non-static data members shall be public direct
1456 // members of E ...
1457 ClassWithFields = RD;
1458 else {
1459 // ... or of ...
1460 CXXBasePaths Paths;
1461 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1462 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1463 // If no classes have fields, just decompose RD itself. (This will work
1464 // if and only if zero bindings were provided.)
1465 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1466 }
1467
1468 CXXBasePath *BestPath = nullptr;
1469 for (auto &P : Paths) {
1470 if (!BestPath)
1471 BestPath = &P;
1472 else if (!S.Context.hasSameType(P.back().Base->getType(),
1473 BestPath->back().Base->getType())) {
1474 // ... the same ...
1475 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1476 << false << RD << BestPath->back().Base->getType()
1477 << P.back().Base->getType();
1478 return DeclAccessPair();
1479 } else if (P.Access < BestPath->Access) {
1480 BestPath = &P;
1481 }
1482 }
1483
1484 // ... unambiguous ...
1485 QualType BaseType = BestPath->back().Base->getType();
1486 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1487 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1488 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1489 return DeclAccessPair();
1490 }
1491
1492 // ... [accessible, implied by other rules] base class of E.
1493 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1494 *BestPath, diag::err_decomp_decl_inaccessible_base);
1495 AS = BestPath->Access;
1496
1497 ClassWithFields = BaseType->getAsCXXRecordDecl();
1498 S.BuildBasePathArray(Paths, BasePath);
1499 }
1500
1501 // The above search did not check whether the selected class itself has base
1502 // classes with fields, so check that now.
1503 CXXBasePaths Paths;
1504 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1505 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1506 << (ClassWithFields == RD) << RD << ClassWithFields
1507 << Paths.front().back().Base->getType();
1508 return DeclAccessPair();
1509 }
1510
1511 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1512}
1513
1515 const CXXRecordDecl *OrigRD,
1516 QualType DecompType,
1517 DeclAccessPair BasePair) {
1518 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1519 if (!RD)
1520 return true;
1521
1522 for (auto *FD : RD->fields()) {
1523 if (FD->isUnnamedBitField())
1524 continue;
1525
1526 // All the non-static data members are required to be nameable, so they
1527 // must all have names.
1528 if (!FD->getDeclName()) {
1529 if (RD->isLambda()) {
1530 S.Diag(Loc, diag::err_decomp_decl_lambda);
1531 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1532 return true;
1533 }
1534
1535 if (FD->isAnonymousStructOrUnion()) {
1536 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1537 << DecompType << FD->getType()->isUnionType();
1538 S.Diag(FD->getLocation(), diag::note_declared_at);
1539 return true;
1540 }
1541
1542 // FIXME: Are there any other ways we could have an anonymous member?
1543 }
1544 // The field must be accessible in the context of the structured binding.
1545 // We already checked that the base class is accessible.
1546 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1547 // const_cast here.
1549 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1551 BasePair.getAccess(), FD->getAccess())));
1552 }
1553 return false;
1554}
1555
1557 ValueDecl *Src, QualType DecompType,
1558 const CXXRecordDecl *OrigRD) {
1559 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1560 diag::err_incomplete_type))
1561 return true;
1562
1563 CXXCastPath BasePath;
1564 DeclAccessPair BasePair =
1565 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1566 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1567 if (!RD)
1568 return true;
1569 QualType BaseType = S.Context.getQualifiedType(
1570 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1571
1572 auto *DD = cast<DecompositionDecl>(Src);
1573 unsigned NumFields = llvm::count_if(
1574 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1575 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1576 return true;
1577
1578 // all of E's non-static data members shall be [...] well-formed
1579 // when named as e.name in the context of the structured binding,
1580 // E shall not have an anonymous union member, ...
1581 auto FlatBindings = DD->flat_bindings();
1582 assert(llvm::range_size(FlatBindings) == NumFields);
1583 auto FlatBindingsItr = FlatBindings.begin();
1584
1585 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1586 BasePair))
1587 return true;
1588
1589 for (auto *FD : RD->fields()) {
1590 if (FD->isUnnamedBitField())
1591 continue;
1592
1593 // We have a real field to bind.
1594 assert(FlatBindingsItr != FlatBindings.end());
1595 BindingDecl *B = *(FlatBindingsItr++);
1596 SourceLocation Loc = B->getLocation();
1597
1598 // Initialize the binding to Src.FD.
1599 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1600 if (E.isInvalid())
1601 return true;
1602 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1603 VK_LValue, &BasePath);
1604 if (E.isInvalid())
1605 return true;
1606 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1607 CXXScopeSpec(), FD,
1609 DeclarationNameInfo(FD->getDeclName(), Loc));
1610 if (E.isInvalid())
1611 return true;
1612
1613 // If the type of the member is T, the referenced type is cv T, where cv is
1614 // the cv-qualification of the decomposition expression.
1615 //
1616 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1617 // 'const' to the type of the field.
1618 Qualifiers Q = DecompType.getQualifiers();
1619 if (FD->isMutable())
1620 Q.removeConst();
1621 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1622 }
1623
1624 return false;
1625}
1626
1628 QualType DecompType = DD->getType();
1629
1630 // If the type of the decomposition is dependent, then so is the type of
1631 // each binding.
1632 if (DecompType->isDependentType()) {
1633 // Note that all of the types are still Null or PackExpansionType.
1634 for (auto *B : DD->bindings()) {
1635 // Do not overwrite any pack type.
1636 if (B->getType().isNull())
1637 B->setType(Context.DependentTy);
1638 }
1639 return;
1640 }
1641
1642 DecompType = DecompType.getNonReferenceType();
1644
1645 // C++1z [dcl.decomp]/2:
1646 // If E is an array type [...]
1647 // As an extension, we also support decomposition of built-in complex and
1648 // vector types.
1649 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1650 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1651 DD->setInvalidDecl();
1652 return;
1653 }
1654 if (auto *VT = DecompType->getAs<VectorType>()) {
1655 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1656 DD->setInvalidDecl();
1657 return;
1658 }
1659 if (auto *CT = DecompType->getAs<ComplexType>()) {
1660 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1661 DD->setInvalidDecl();
1662 return;
1663 }
1664
1665 // C++1z [dcl.decomp]/3:
1666 // if the expression std::tuple_size<E>::value is a well-formed integral
1667 // constant expression, [...]
1668 unsigned TupleSize;
1669 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1670 case IsTupleLike::Error:
1671 DD->setInvalidDecl();
1672 return;
1673
1674 case IsTupleLike::TupleLike:
1675 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1676 DD->setInvalidDecl();
1677 return;
1678
1679 case IsTupleLike::NotTupleLike:
1680 break;
1681 }
1682
1683 // C++1z [dcl.dcl]/8:
1684 // [E shall be of array or non-union class type]
1685 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1686 if (!RD || RD->isUnion()) {
1687 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1688 << DD << !RD << DecompType;
1689 DD->setInvalidDecl();
1690 return;
1691 }
1692
1693 // C++1z [dcl.decomp]/4:
1694 // all of E's non-static data members shall be [...] direct members of
1695 // E or of the same unambiguous public base class of E, ...
1696 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1697 DD->setInvalidDecl();
1698}
1699
1701 SourceLocation Loc) {
1702 const ASTContext &Ctx = getASTContext();
1703 assert(!T->isDependentType());
1704
1705 Qualifiers Quals;
1706 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1707 Quals.removeCVRQualifiers();
1708 T = Context.getQualifiedType(Unqual, Quals);
1709
1710 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1711 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1712 if (auto *VT = T->getAs<VectorType>())
1713 return VT->getNumElements();
1714 if (T->getAs<ComplexType>())
1715 return 2u;
1716
1717 unsigned TupleSize;
1718 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1719 case IsTupleLike::Error:
1720 return std::nullopt;
1721 case IsTupleLike::TupleLike:
1722 return TupleSize;
1723 case IsTupleLike::NotTupleLike:
1724 break;
1725 }
1726
1727 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1728 if (!OrigRD || OrigRD->isUnion())
1729 return std::nullopt;
1730
1731 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1732 return std::nullopt;
1733
1734 CXXCastPath BasePath;
1735 DeclAccessPair BasePair =
1736 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1737 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1738 if (!RD)
1739 return std::nullopt;
1740
1741 unsigned NumFields = llvm::count_if(
1742 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1743
1744 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1745 return std::nullopt;
1746
1747 return NumFields;
1748}
1749
1751 // Shortcut if exceptions are disabled.
1752 if (!getLangOpts().CXXExceptions)
1753 return;
1754
1755 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1756 "Should only be called if types are otherwise the same.");
1757
1758 QualType NewType = New->getType();
1759 QualType OldType = Old->getType();
1760
1761 // We're only interested in pointers and references to functions, as well
1762 // as pointers to member functions.
1763 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1764 NewType = R->getPointeeType();
1765 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1766 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1767 NewType = P->getPointeeType();
1768 OldType = OldType->castAs<PointerType>()->getPointeeType();
1769 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1770 NewType = M->getPointeeType();
1771 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1772 }
1773
1774 if (!NewType->isFunctionProtoType())
1775 return;
1776
1777 // There's lots of special cases for functions. For function pointers, system
1778 // libraries are hopefully not as broken so that we don't need these
1779 // workarounds.
1781 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1782 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1783 New->setInvalidDecl();
1784 }
1785}
1786
1787/// CheckCXXDefaultArguments - Verify that the default arguments for a
1788/// function declaration are well-formed according to C++
1789/// [dcl.fct.default].
1791 // This checking doesn't make sense for explicit specializations; their
1792 // default arguments are determined by the declaration we're specializing,
1793 // not by FD.
1795 return;
1796 if (auto *FTD = FD->getDescribedFunctionTemplate())
1797 if (FTD->isMemberSpecialization())
1798 return;
1799
1800 unsigned NumParams = FD->getNumParams();
1801 unsigned ParamIdx = 0;
1802
1803 // Find first parameter with a default argument
1804 for (; ParamIdx < NumParams; ++ParamIdx) {
1805 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1806 if (Param->hasDefaultArg())
1807 break;
1808 }
1809
1810 // C++20 [dcl.fct.default]p4:
1811 // In a given function declaration, each parameter subsequent to a parameter
1812 // with a default argument shall have a default argument supplied in this or
1813 // a previous declaration, unless the parameter was expanded from a
1814 // parameter pack, or shall be a function parameter pack.
1815 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1816 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1817 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1819 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1820 continue;
1821 if (Param->isInvalidDecl())
1822 /* We already complained about this parameter. */;
1823 else if (Param->getIdentifier())
1824 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1825 << Param->getIdentifier();
1826 else
1827 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1828 }
1829}
1830
1831/// Check that the given type is a literal type. Issue a diagnostic if not,
1832/// if Kind is Diagnose.
1833/// \return \c true if a problem has been found (and optionally diagnosed).
1834template <typename... Ts>
1836 SourceLocation Loc, QualType T, unsigned DiagID,
1837 Ts &&...DiagArgs) {
1838 if (T->isDependentType())
1839 return false;
1840
1841 switch (Kind) {
1843 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1844 std::forward<Ts>(DiagArgs)...);
1845
1847 return !T->isLiteralType(SemaRef.Context);
1848 }
1849
1850 llvm_unreachable("unknown CheckConstexprKind");
1851}
1852
1853/// Determine whether a destructor cannot be constexpr due to
1855 const CXXDestructorDecl *DD,
1857 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1858 "this check is obsolete for C++23");
1859 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1860 const CXXRecordDecl *RD =
1861 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1862 if (!RD || RD->hasConstexprDestructor())
1863 return true;
1864
1866 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1867 << static_cast<int>(DD->getConstexprKind()) << !FD
1868 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1869 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1870 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1871 }
1872 return false;
1873 };
1874
1875 const CXXRecordDecl *RD = DD->getParent();
1876 for (const CXXBaseSpecifier &B : RD->bases())
1877 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1878 return false;
1879 for (const FieldDecl *FD : RD->fields())
1880 if (!Check(FD->getLocation(), FD->getType(), FD))
1881 return false;
1882 return true;
1883}
1884
1885/// Check whether a function's parameter types are all literal types. If so,
1886/// return true. If not, produce a suitable diagnostic and return false.
1888 const FunctionDecl *FD,
1890 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1891 "this check is obsolete for C++23");
1892 unsigned ArgIndex = 0;
1893 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1894 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1895 e = FT->param_type_end();
1896 i != e; ++i, ++ArgIndex) {
1897 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1898 assert(PD && "null in a parameter list");
1899 SourceLocation ParamLoc = PD->getLocation();
1900 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1901 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1903 FD->isConsteval()))
1904 return false;
1905 }
1906 return true;
1907}
1908
1909/// Check whether a function's return type is a literal type. If so, return
1910/// true. If not, produce a suitable diagnostic and return false.
1911static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1913 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1914 "this check is obsolete for C++23");
1915 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1916 diag::err_constexpr_non_literal_return,
1917 FD->isConsteval()))
1918 return false;
1919 return true;
1920}
1921
1922/// Get diagnostic %select index for tag kind for
1923/// record diagnostic message.
1924/// WARNING: Indexes apply to particular diagnostics only!
1925///
1926/// \returns diagnostic %select index.
1928 switch (Tag) {
1930 return 0;
1932 return 1;
1933 case TagTypeKind::Class:
1934 return 2;
1935 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1936 }
1937}
1938
1939static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1940 Stmt *Body,
1942static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1943
1945 CheckConstexprKind Kind) {
1946 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1947 if (MD && MD->isInstance()) {
1948 // C++11 [dcl.constexpr]p4:
1949 // The definition of a constexpr constructor shall satisfy the following
1950 // constraints:
1951 // - the class shall not have any virtual base classes;
1952 //
1953 // FIXME: This only applies to constructors and destructors, not arbitrary
1954 // member functions.
1955 const CXXRecordDecl *RD = MD->getParent();
1956 if (RD->getNumVBases()) {
1958 return false;
1959
1960 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1961 << isa<CXXConstructorDecl>(NewFD)
1963 for (const auto &I : RD->vbases())
1964 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1965 << I.getSourceRange();
1966 return false;
1967 }
1968 }
1969
1970 if (!isa<CXXConstructorDecl>(NewFD)) {
1971 // C++11 [dcl.constexpr]p3:
1972 // The definition of a constexpr function shall satisfy the following
1973 // constraints:
1974 // - it shall not be virtual; (removed in C++20)
1975 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1976 if (Method && Method->isVirtual()) {
1977 if (getLangOpts().CPlusPlus20) {
1978 if (Kind == CheckConstexprKind::Diagnose)
1979 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1980 } else {
1982 return false;
1983
1984 Method = Method->getCanonicalDecl();
1985 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1986
1987 // If it's not obvious why this function is virtual, find an overridden
1988 // function which uses the 'virtual' keyword.
1989 const CXXMethodDecl *WrittenVirtual = Method;
1990 while (!WrittenVirtual->isVirtualAsWritten())
1991 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1992 if (WrittenVirtual != Method)
1993 Diag(WrittenVirtual->getLocation(),
1994 diag::note_overridden_virtual_function);
1995 return false;
1996 }
1997 }
1998
1999 // - its return type shall be a literal type; (removed in C++23)
2000 if (!getLangOpts().CPlusPlus23 &&
2001 !CheckConstexprReturnType(*this, NewFD, Kind))
2002 return false;
2003 }
2004
2005 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2006 // A destructor can be constexpr only if the defaulted destructor could be;
2007 // we don't need to check the members and bases if we already know they all
2008 // have constexpr destructors. (removed in C++23)
2009 if (!getLangOpts().CPlusPlus23 &&
2010 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2012 return false;
2013 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2014 return false;
2015 }
2016 }
2017
2018 // - each of its parameter types shall be a literal type; (removed in C++23)
2019 if (!getLangOpts().CPlusPlus23 &&
2020 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2021 return false;
2022
2023 Stmt *Body = NewFD->getBody();
2024 assert(Body &&
2025 "CheckConstexprFunctionDefinition called on function with no body");
2026 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2027}
2028
2029/// Check the given declaration statement is legal within a constexpr function
2030/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2031///
2032/// \return true if the body is OK (maybe only as an extension), false if we
2033/// have diagnosed a problem.
2034static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2035 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2037 // C++11 [dcl.constexpr]p3 and p4:
2038 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2039 // contain only
2040 for (const auto *DclIt : DS->decls()) {
2041 switch (DclIt->getKind()) {
2042 case Decl::StaticAssert:
2043 case Decl::Using:
2044 case Decl::UsingShadow:
2045 case Decl::UsingDirective:
2046 case Decl::UnresolvedUsingTypename:
2047 case Decl::UnresolvedUsingValue:
2048 case Decl::UsingEnum:
2049 // - static_assert-declarations
2050 // - using-declarations,
2051 // - using-directives,
2052 // - using-enum-declaration
2053 continue;
2054
2055 case Decl::Typedef:
2056 case Decl::TypeAlias: {
2057 // - typedef declarations and alias-declarations that do not define
2058 // classes or enumerations,
2059 const auto *TN = cast<TypedefNameDecl>(DclIt);
2060 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2061 // Don't allow variably-modified types in constexpr functions.
2063 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2064 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2065 << TL.getSourceRange() << TL.getType()
2067 }
2068 return false;
2069 }
2070 continue;
2071 }
2072
2073 case Decl::Enum:
2074 case Decl::CXXRecord:
2075 // C++1y allows types to be defined, not just declared.
2076 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2078 SemaRef.DiagCompat(DS->getBeginLoc(),
2079 diag_compat::constexpr_type_definition)
2081 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2082 return false;
2083 }
2084 }
2085 continue;
2086
2087 case Decl::EnumConstant:
2088 case Decl::IndirectField:
2089 case Decl::ParmVar:
2090 // These can only appear with other declarations which are banned in
2091 // C++11 and permitted in C++1y, so ignore them.
2092 continue;
2093
2094 case Decl::Var:
2095 case Decl::Decomposition: {
2096 // C++1y [dcl.constexpr]p3 allows anything except:
2097 // a definition of a variable of non-literal type or of static or
2098 // thread storage duration or [before C++2a] for which no
2099 // initialization is performed.
2100 const auto *VD = cast<VarDecl>(DclIt);
2101 if (VD->isThisDeclarationADefinition()) {
2102 if (VD->isStaticLocal()) {
2104 SemaRef.DiagCompat(VD->getLocation(),
2105 diag_compat::constexpr_static_var)
2107 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2108 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2109 return false;
2110 }
2111 }
2112 if (SemaRef.LangOpts.CPlusPlus23) {
2113 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2114 diag::warn_cxx20_compat_constexpr_var,
2116 } else if (CheckLiteralType(
2117 SemaRef, Kind, VD->getLocation(), VD->getType(),
2118 diag::err_constexpr_local_var_non_literal_type,
2120 return false;
2121 }
2122 if (!VD->getType()->isDependentType() &&
2123 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2125 SemaRef.DiagCompat(VD->getLocation(),
2126 diag_compat::constexpr_local_var_no_init)
2128 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2129 return false;
2130 }
2131 continue;
2132 }
2133 }
2135 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2137 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2138 return false;
2139 }
2140 continue;
2141 }
2142
2143 case Decl::NamespaceAlias:
2144 case Decl::Function:
2145 // These are disallowed in C++11 and permitted in C++1y. Allow them
2146 // everywhere as an extension.
2147 if (!Cxx1yLoc.isValid())
2148 Cxx1yLoc = DS->getBeginLoc();
2149 continue;
2150
2151 default:
2153 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2154 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2155 }
2156 return false;
2157 }
2158 }
2159
2160 return true;
2161}
2162
2163/// Check that the given field is initialized within a constexpr constructor.
2164///
2165/// \param Dcl The constexpr constructor being checked.
2166/// \param Field The field being checked. This may be a member of an anonymous
2167/// struct or union nested within the class being checked.
2168/// \param Inits All declarations, including anonymous struct/union members and
2169/// indirect members, for which any initialization was provided.
2170/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2171/// multiple notes for different members to the same error.
2172/// \param Kind Whether we're diagnosing a constructor as written or determining
2173/// whether the formal requirements are satisfied.
2174/// \return \c false if we're checking for validity and the constructor does
2175/// not satisfy the requirements on a constexpr constructor.
2177 const FunctionDecl *Dcl,
2178 FieldDecl *Field,
2180 bool &Diagnosed,
2182 // In C++20 onwards, there's nothing to check for validity.
2184 SemaRef.getLangOpts().CPlusPlus20)
2185 return true;
2186
2187 if (Field->isInvalidDecl())
2188 return true;
2189
2190 if (Field->isUnnamedBitField())
2191 return true;
2192
2193 // Anonymous unions with no variant members and empty anonymous structs do not
2194 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2195 // indirect fields don't need initializing.
2196 if (Field->isAnonymousStructOrUnion() &&
2197 (Field->getType()->isUnionType()
2198 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2199 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2200 return true;
2201
2202 if (!Inits.count(Field)) {
2204 if (!Diagnosed) {
2205 SemaRef.DiagCompat(Dcl->getLocation(),
2206 diag_compat::constexpr_ctor_missing_init);
2207 Diagnosed = true;
2208 }
2209 SemaRef.Diag(Field->getLocation(),
2210 diag::note_constexpr_ctor_missing_init);
2211 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2212 return false;
2213 }
2214 } else if (Field->isAnonymousStructOrUnion()) {
2215 const auto *RD = Field->getType()->castAsRecordDecl();
2216 for (auto *I : RD->fields())
2217 // If an anonymous union contains an anonymous struct of which any member
2218 // is initialized, all members must be initialized.
2219 if (!RD->isUnion() || Inits.count(I))
2220 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2221 Kind))
2222 return false;
2223 }
2224 return true;
2225}
2226
2227/// Check the provided statement is allowed in a constexpr function
2228/// definition.
2229static bool
2232 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2233 SourceLocation &Cxx2bLoc,
2235 // - its function-body shall be [...] a compound-statement that contains only
2236 switch (S->getStmtClass()) {
2237 case Stmt::NullStmtClass:
2238 // - null statements,
2239 return true;
2240
2241 case Stmt::DeclStmtClass:
2242 // - static_assert-declarations
2243 // - using-declarations,
2244 // - using-directives,
2245 // - typedef declarations and alias-declarations that do not define
2246 // classes or enumerations,
2247 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2248 return false;
2249 return true;
2250
2251 case Stmt::ReturnStmtClass:
2252 // - and exactly one return statement;
2253 if (isa<CXXConstructorDecl>(Dcl)) {
2254 // C++1y allows return statements in constexpr constructors.
2255 if (!Cxx1yLoc.isValid())
2256 Cxx1yLoc = S->getBeginLoc();
2257 return true;
2258 }
2259
2260 ReturnStmts.push_back(S->getBeginLoc());
2261 return true;
2262
2263 case Stmt::AttributedStmtClass:
2264 // Attributes on a statement don't affect its formal kind and hence don't
2265 // affect its validity in a constexpr function.
2267 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2268 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2269
2270 case Stmt::CompoundStmtClass: {
2271 // C++1y allows compound-statements.
2272 if (!Cxx1yLoc.isValid())
2273 Cxx1yLoc = S->getBeginLoc();
2274
2275 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2276 for (auto *BodyIt : CompStmt->body()) {
2277 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2278 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2279 return false;
2280 }
2281 return true;
2282 }
2283
2284 case Stmt::IfStmtClass: {
2285 // C++1y allows if-statements.
2286 if (!Cxx1yLoc.isValid())
2287 Cxx1yLoc = S->getBeginLoc();
2288
2289 IfStmt *If = cast<IfStmt>(S);
2290 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2291 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2292 return false;
2293 if (If->getElse() &&
2294 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2295 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2296 return false;
2297 return true;
2298 }
2299
2300 case Stmt::WhileStmtClass:
2301 case Stmt::DoStmtClass:
2302 case Stmt::ForStmtClass:
2303 case Stmt::CXXForRangeStmtClass:
2304 case Stmt::ContinueStmtClass:
2305 // C++1y allows all of these. We don't allow them as extensions in C++11,
2306 // because they don't make sense without variable mutation.
2307 if (!SemaRef.getLangOpts().CPlusPlus14)
2308 break;
2309 if (!Cxx1yLoc.isValid())
2310 Cxx1yLoc = S->getBeginLoc();
2311 for (Stmt *SubStmt : S->children()) {
2312 if (SubStmt &&
2313 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2314 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2315 return false;
2316 }
2317 return true;
2318
2319 case Stmt::SwitchStmtClass:
2320 case Stmt::CaseStmtClass:
2321 case Stmt::DefaultStmtClass:
2322 case Stmt::BreakStmtClass:
2323 // C++1y allows switch-statements, and since they don't need variable
2324 // mutation, we can reasonably allow them in C++11 as an extension.
2325 if (!Cxx1yLoc.isValid())
2326 Cxx1yLoc = S->getBeginLoc();
2327 for (Stmt *SubStmt : S->children()) {
2328 if (SubStmt &&
2329 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2330 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2331 return false;
2332 }
2333 return true;
2334
2335 case Stmt::LabelStmtClass:
2336 case Stmt::GotoStmtClass:
2337 if (Cxx2bLoc.isInvalid())
2338 Cxx2bLoc = S->getBeginLoc();
2339 for (Stmt *SubStmt : S->children()) {
2340 if (SubStmt &&
2341 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2342 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2343 return false;
2344 }
2345 return true;
2346
2347 case Stmt::GCCAsmStmtClass:
2348 case Stmt::MSAsmStmtClass:
2349 // C++2a allows inline assembly statements.
2350 case Stmt::CXXTryStmtClass:
2351 if (Cxx2aLoc.isInvalid())
2352 Cxx2aLoc = S->getBeginLoc();
2353 for (Stmt *SubStmt : S->children()) {
2354 if (SubStmt &&
2355 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2356 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2357 return false;
2358 }
2359 return true;
2360
2361 case Stmt::CXXCatchStmtClass:
2362 // Do not bother checking the language mode (already covered by the
2363 // try block check).
2365 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2366 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2367 return false;
2368 return true;
2369
2370 default:
2371 if (!isa<Expr>(S))
2372 break;
2373
2374 // C++1y allows expression-statements.
2375 if (!Cxx1yLoc.isValid())
2376 Cxx1yLoc = S->getBeginLoc();
2377 return true;
2378 }
2379
2381 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2382 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2383 }
2384 return false;
2385}
2386
2387/// Check the body for the given constexpr function declaration only contains
2388/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2389///
2390/// \return true if the body is OK, false if we have found or diagnosed a
2391/// problem.
2392static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2393 Stmt *Body,
2396
2397 if (isa<CXXTryStmt>(Body)) {
2398 // C++11 [dcl.constexpr]p3:
2399 // The definition of a constexpr function shall satisfy the following
2400 // constraints: [...]
2401 // - its function-body shall be = delete, = default, or a
2402 // compound-statement
2403 //
2404 // C++11 [dcl.constexpr]p4:
2405 // In the definition of a constexpr constructor, [...]
2406 // - its function-body shall not be a function-try-block;
2407 //
2408 // This restriction is lifted in C++2a, as long as inner statements also
2409 // apply the general constexpr rules.
2410 switch (Kind) {
2412 if (!SemaRef.getLangOpts().CPlusPlus20)
2413 return false;
2414 break;
2415
2417 SemaRef.DiagCompat(Body->getBeginLoc(),
2418 diag_compat::constexpr_function_try_block)
2420 break;
2421 }
2422 }
2423
2424 // - its function-body shall be [...] a compound-statement that contains only
2425 // [... list of cases ...]
2426 //
2427 // Note that walking the children here is enough to properly check for
2428 // CompoundStmt and CXXTryStmt body.
2429 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2430 for (Stmt *SubStmt : Body->children()) {
2431 if (SubStmt &&
2432 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2433 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2434 return false;
2435 }
2436
2438 // If this is only valid as an extension, report that we don't satisfy the
2439 // constraints of the current language.
2440 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2441 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2442 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2443 return false;
2444 } else if (Cxx2bLoc.isValid()) {
2445 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2447 } else if (Cxx2aLoc.isValid()) {
2448 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2450 } else if (Cxx1yLoc.isValid()) {
2451 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2453 }
2454
2456 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2457 const CXXRecordDecl *RD = Constructor->getParent();
2458 // DR1359:
2459 // - every non-variant non-static data member and base class sub-object
2460 // shall be initialized;
2461 // DR1460:
2462 // - if the class is a union having variant members, exactly one of them
2463 // shall be initialized;
2464 if (RD->isUnion()) {
2465 if (Constructor->getNumCtorInitializers() == 0 &&
2466 RD->hasVariantMembers()) {
2468 SemaRef.DiagCompat(Dcl->getLocation(),
2469 diag_compat::constexpr_union_ctor_no_init);
2470 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2471 return false;
2472 }
2473 }
2474 } else if (!Constructor->isDependentContext() &&
2475 !Constructor->isDelegatingConstructor()) {
2476 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2477
2478 // Skip detailed checking if we have enough initializers, and we would
2479 // allow at most one initializer per member.
2480 bool AnyAnonStructUnionMembers = false;
2481 unsigned Fields = 0;
2483 E = RD->field_end(); I != E; ++I, ++Fields) {
2484 if (I->isAnonymousStructOrUnion()) {
2485 AnyAnonStructUnionMembers = true;
2486 break;
2487 }
2488 }
2489 // DR1460:
2490 // - if the class is a union-like class, but is not a union, for each of
2491 // its anonymous union members having variant members, exactly one of
2492 // them shall be initialized;
2493 if (AnyAnonStructUnionMembers ||
2494 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2495 // Check initialization of non-static data members. Base classes are
2496 // always initialized so do not need to be checked. Dependent bases
2497 // might not have initializers in the member initializer list.
2499 for (const auto *I: Constructor->inits()) {
2500 if (FieldDecl *FD = I->getMember())
2501 Inits.insert(FD);
2502 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2503 Inits.insert(ID->chain_begin(), ID->chain_end());
2504 }
2505
2506 bool Diagnosed = false;
2507 for (auto *I : RD->fields())
2508 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2509 Kind))
2510 return false;
2511 }
2512 }
2513 } else {
2514 if (ReturnStmts.empty()) {
2515 switch (Kind) {
2517 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2518 return false;
2519 break;
2520
2522 // The formal requirements don't include this rule in C++14, even
2523 // though the "must be able to produce a constant expression" rules
2524 // still imply it in some cases.
2525 if (!SemaRef.getLangOpts().CPlusPlus14)
2526 return false;
2527 break;
2528 }
2529 } else if (ReturnStmts.size() > 1) {
2530 switch (Kind) {
2532 SemaRef.DiagCompat(ReturnStmts.back(),
2533 diag_compat::constexpr_body_multiple_return);
2534 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2535 SemaRef.Diag(ReturnStmts[I],
2536 diag::note_constexpr_body_previous_return);
2537 break;
2538
2540 if (!SemaRef.getLangOpts().CPlusPlus14)
2541 return false;
2542 break;
2543 }
2544 }
2545 }
2546
2547 // C++11 [dcl.constexpr]p5:
2548 // if no function argument values exist such that the function invocation
2549 // substitution would produce a constant expression, the program is
2550 // ill-formed; no diagnostic required.
2551 // C++11 [dcl.constexpr]p3:
2552 // - every constructor call and implicit conversion used in initializing the
2553 // return value shall be one of those allowed in a constant expression.
2554 // C++11 [dcl.constexpr]p4:
2555 // - every constructor involved in initializing non-static data members and
2556 // base class sub-objects shall be a constexpr constructor.
2557 //
2558 // Note that this rule is distinct from the "requirements for a constexpr
2559 // function", so is not checked in CheckValid mode. Because the check for
2560 // constexpr potential is expensive, skip the check if the diagnostic is
2561 // disabled, the function is declared in a system header, or we're in C++23
2562 // or later mode (see https://wg21.link/P2448).
2563 bool SkipCheck =
2564 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2565 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2566 SemaRef.getDiagnostics().isIgnored(
2567 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2569 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2570 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2571 SemaRef.Diag(Dcl->getLocation(),
2572 diag::ext_constexpr_function_never_constant_expr)
2573 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2574 << Dcl->getNameInfo().getSourceRange();
2575 for (const auto &Diag : Diags)
2576 SemaRef.Diag(Diag.first, Diag.second);
2577 // Don't return false here: we allow this for compatibility in
2578 // system headers.
2579 }
2580
2581 return true;
2582}
2583
2585 const FunctionDecl *Dcl) {
2586 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2588 // Skip emitting a missing return error diagnostic for non-void functions
2589 // since C++23 no longer mandates constexpr functions to yield constant
2590 // expressions.
2591 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2592 return true;
2593
2594 // C++14 doesn't require constexpr functions to contain a 'return'
2595 // statement. We still do, unless the return type might be void, because
2596 // otherwise if there's no return statement, the function cannot
2597 // be used in a core constant expression.
2598 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2599 SemaRef.Diag(Dcl->getLocation(),
2600 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2601 : diag::err_constexpr_body_no_return)
2602 << Dcl->isConsteval();
2603 return OK;
2604}
2605
2607 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2609 return true;
2613 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2614 if (it != UndefinedButUsed.end()) {
2615 Diag(it->second, diag::err_immediate_function_used_before_definition)
2616 << it->first;
2617 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2618 if (FD->isImmediateFunction() && !FD->isConsteval())
2620 return false;
2621 }
2622 }
2623 return true;
2624}
2625
2627 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2628 "expected an immediate function");
2629 assert(FD->hasBody() && "expected the function to have a body");
2630 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2631 Sema &SemaRef;
2632
2633 const FunctionDecl *ImmediateFn;
2634 bool ImmediateFnIsConstructor;
2635 CXXConstructorDecl *CurrentConstructor = nullptr;
2636 CXXCtorInitializer *CurrentInit = nullptr;
2637
2638 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2639 : SemaRef(SemaRef), ImmediateFn(FD),
2640 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2641 ShouldVisitImplicitCode = true;
2642 ShouldVisitLambdaBody = false;
2643 }
2644
2645 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2646 SourceLocation Loc = E->getBeginLoc();
2647 SourceRange Range = E->getSourceRange();
2648 if (CurrentConstructor && CurrentInit) {
2649 Loc = CurrentConstructor->getLocation();
2650 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2651 : SourceRange();
2652 }
2653
2654 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2655
2656 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2657 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2658 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2659 << (InitializedField != nullptr)
2660 << (CurrentInit && !CurrentInit->isWritten())
2661 << InitializedField << Range;
2662 }
2663 bool TraverseCallExpr(CallExpr *E) override {
2664 if (const auto *DR =
2665 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2666 DR && DR->isImmediateEscalating()) {
2667 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2668 return false;
2669 }
2670
2671 for (Expr *A : E->arguments())
2672 if (!TraverseStmt(A))
2673 return false;
2674
2675 return true;
2676 }
2677
2678 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2679 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2680 ReferencedFn && E->isImmediateEscalating()) {
2681 Diag(E, ReferencedFn, /*IsCall=*/false);
2682 return false;
2683 }
2684
2685 return true;
2686 }
2687
2688 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2690 if (E->isImmediateEscalating()) {
2691 Diag(E, D, /*IsCall=*/true);
2692 return false;
2693 }
2694 return true;
2695 }
2696
2697 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2698 llvm::SaveAndRestore RAII(CurrentInit, Init);
2700 }
2701
2702 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2703 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2704 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2705 }
2706
2707 bool TraverseType(QualType T, bool TraverseQualifier) override {
2708 return true;
2709 }
2710 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2711
2712 } Visitor(*this, FD);
2713 Visitor.TraverseDecl(FD);
2714}
2715
2717 assert(getLangOpts().CPlusPlus && "No class names in C!");
2718
2719 if (SS && SS->isInvalid())
2720 return nullptr;
2721
2722 if (SS && SS->isNotEmpty()) {
2723 DeclContext *DC = computeDeclContext(*SS, true);
2724 return dyn_cast_or_null<CXXRecordDecl>(DC);
2725 }
2726
2727 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2728}
2729
2731 const CXXScopeSpec *SS) {
2732 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2733 return CurDecl && &II == CurDecl->getIdentifier();
2734}
2735
2737 assert(getLangOpts().CPlusPlus && "No class names in C!");
2738
2739 if (!getLangOpts().SpellChecking)
2740 return false;
2741
2742 CXXRecordDecl *CurDecl;
2743 if (SS && SS->isSet() && !SS->isInvalid()) {
2744 DeclContext *DC = computeDeclContext(*SS, true);
2745 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2746 } else
2747 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2748
2749 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2750 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2751 < II->getLength()) {
2752 II = CurDecl->getIdentifier();
2753 return true;
2754 }
2755
2756 return false;
2757}
2758
2760 SourceRange SpecifierRange,
2761 bool Virtual, AccessSpecifier Access,
2762 TypeSourceInfo *TInfo,
2763 SourceLocation EllipsisLoc) {
2764 QualType BaseType = TInfo->getType();
2765 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2766 if (BaseType->containsErrors()) {
2767 // Already emitted a diagnostic when parsing the error type.
2768 return nullptr;
2769 }
2770
2771 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2772 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2773 << TInfo->getTypeLoc().getSourceRange();
2774 EllipsisLoc = SourceLocation();
2775 }
2776
2777 auto *BaseDecl =
2778 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2779 // C++ [class.derived.general]p2:
2780 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2781 // that is not an incompletely defined class; any cv-qualifiers are
2782 // ignored.
2783 if (BaseDecl) {
2784 // C++ [class.union.general]p4:
2785 // [...] A union shall not be used as a base class.
2786 if (BaseDecl->isUnion()) {
2787 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2788 return nullptr;
2789 }
2790
2791 if (BaseType.hasQualifiers()) {
2792 std::string Quals =
2793 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2794 Diag(BaseLoc, diag::warn_qual_base_type)
2795 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2796 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2797 }
2798
2799 // For the MS ABI, propagate DLL attributes to base class templates.
2800 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2801 Context.getTargetInfo().getTriple().isPS()) {
2802 if (Attr *ClassAttr = getDLLAttr(Class)) {
2803 if (auto *BaseSpec =
2804 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2805 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2806 BaseLoc);
2807 }
2808 }
2809 }
2810
2811 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2812 SpecifierRange)) {
2813 Class->setInvalidDecl();
2814 return nullptr;
2815 }
2816
2817 BaseDecl = BaseDecl->getDefinition();
2818 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2819
2820 // Microsoft docs say:
2821 // "If a base-class has a code_seg attribute, derived classes must have the
2822 // same attribute."
2823 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2824 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2825 if ((DerivedCSA || BaseCSA) &&
2826 (!BaseCSA || !DerivedCSA ||
2827 BaseCSA->getName() != DerivedCSA->getName())) {
2828 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2829 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2830 << BaseDecl;
2831 return nullptr;
2832 }
2833
2834 // A class which contains a flexible array member is not suitable for use as
2835 // a base class:
2836 // - If the layout determines that a base comes before another base,
2837 // the flexible array member would index into the subsequent base.
2838 // - If the layout determines that base comes before the derived class,
2839 // the flexible array member would index into the derived class.
2840 if (BaseDecl->hasFlexibleArrayMember()) {
2841 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2842 << BaseDecl->getDeclName();
2843 return nullptr;
2844 }
2845
2846 // C++ [class]p3:
2847 // If a class is marked final and it appears as a base-type-specifier in
2848 // base-clause, the program is ill-formed.
2849 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2850 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2851 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2852 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2853 << BaseDecl->getDeclName() << FA->getRange();
2854 return nullptr;
2855 }
2856
2857 // If the base class is invalid the derived class is as well.
2858 if (BaseDecl->isInvalidDecl())
2859 Class->setInvalidDecl();
2860 } else if (BaseType->isDependentType()) {
2861 // Make sure that we don't make an ill-formed AST where the type of the
2862 // Class is non-dependent and its attached base class specifier is an
2863 // dependent type, which violates invariants in many clang code paths (e.g.
2864 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2865 // explicitly mark the Class decl invalid. The diagnostic was already
2866 // emitted.
2867 if (!Class->isDependentContext())
2868 Class->setInvalidDecl();
2869 } else {
2870 // The base class is some non-dependent non-class type.
2871 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2872 return nullptr;
2873 }
2874
2875 // In HLSL, unspecified class access is public rather than private.
2876 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2877 Access == AS_none)
2878 Access = AS_public;
2879
2880 // Create the base specifier.
2881 return new (Context) CXXBaseSpecifier(
2882 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2883 Access, TInfo, EllipsisLoc);
2884}
2885
2887 const ParsedAttributesView &Attributes,
2888 bool Virtual, AccessSpecifier Access,
2889 ParsedType basetype, SourceLocation BaseLoc,
2890 SourceLocation EllipsisLoc) {
2891 if (!classdecl)
2892 return true;
2893
2894 AdjustDeclIfTemplate(classdecl);
2895 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2896 if (!Class)
2897 return true;
2898
2899 // We haven't yet attached the base specifiers.
2900 Class->setIsParsingBaseSpecifiers();
2901
2902 // We do not support any C++11 attributes on base-specifiers yet.
2903 // Diagnose any attributes we see.
2904 for (const ParsedAttr &AL : Attributes) {
2905 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2906 continue;
2907 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2909 else
2910 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2911 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2912 }
2913
2914 TypeSourceInfo *TInfo = nullptr;
2915 GetTypeFromParser(basetype, &TInfo);
2916
2917 if (EllipsisLoc.isInvalid() &&
2918 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2920 return true;
2921
2922 // C++ [class.union.general]p4:
2923 // [...] A union shall not have base classes.
2924 if (Class->isUnion()) {
2925 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2926 << SpecifierRange;
2927 return true;
2928 }
2929
2930 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2931 Virtual, Access, TInfo,
2932 EllipsisLoc))
2933 return BaseSpec;
2934
2935 Class->setInvalidDecl();
2936 return true;
2937}
2938
2939/// Use small set to collect indirect bases. As this is only used
2940/// locally, there's no need to abstract the small size parameter.
2942
2943/// Recursively add the bases of Type. Don't add Type itself.
2944static void
2946 const QualType &Type)
2947{
2948 // Even though the incoming type is a base, it might not be
2949 // a class -- it could be a template parm, for instance.
2950 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2951 // Iterate over its bases.
2952 for (const auto &BaseSpec : Decl->bases()) {
2953 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2954 .getUnqualifiedType();
2955 if (Set.insert(Base).second)
2956 // If we've not already seen it, recurse.
2957 NoteIndirectBases(Context, Set, Base);
2958 }
2959 }
2960}
2961
2964 if (Bases.empty())
2965 return false;
2966
2967 // Used to keep track of which base types we have already seen, so
2968 // that we can properly diagnose redundant direct base types. Note
2969 // that the key is always the unqualified canonical type of the base
2970 // class.
2971 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2972
2973 // Used to track indirect bases so we can see if a direct base is
2974 // ambiguous.
2975 IndirectBaseSet IndirectBaseTypes;
2976
2977 // Copy non-redundant base specifiers into permanent storage.
2978 unsigned NumGoodBases = 0;
2979 bool Invalid = false;
2980 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2981 QualType NewBaseType
2982 = Context.getCanonicalType(Bases[idx]->getType());
2983 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2984
2985 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2986 if (KnownBase) {
2987 // C++ [class.mi]p3:
2988 // A class shall not be specified as a direct base class of a
2989 // derived class more than once.
2990 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2991 << KnownBase->getType() << Bases[idx]->getSourceRange();
2992
2993 // Delete the duplicate base class specifier; we're going to
2994 // overwrite its pointer later.
2995 Context.Deallocate(Bases[idx]);
2996
2997 Invalid = true;
2998 } else {
2999 // Okay, add this new base class.
3000 KnownBase = Bases[idx];
3001 Bases[NumGoodBases++] = Bases[idx];
3002
3003 if (NewBaseType->isDependentType())
3004 continue;
3005 // Note this base's direct & indirect bases, if there could be ambiguity.
3006 if (Bases.size() > 1)
3007 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3008
3009 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3010 if (Class->isInterface() &&
3011 (!RD->isInterfaceLike() ||
3012 KnownBase->getAccessSpecifier() != AS_public)) {
3013 // The Microsoft extension __interface does not permit bases that
3014 // are not themselves public interfaces.
3015 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3016 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3017 << RD->getSourceRange();
3018 Invalid = true;
3019 }
3020 if (RD->hasAttr<WeakAttr>())
3021 Class->addAttr(WeakAttr::CreateImplicit(Context));
3022 }
3023 }
3024 }
3025
3026 // Attach the remaining base class specifiers to the derived class.
3027 Class->setBases(Bases.data(), NumGoodBases);
3028
3029 // Check that the only base classes that are duplicate are virtual.
3030 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3031 // Check whether this direct base is inaccessible due to ambiguity.
3032 QualType BaseType = Bases[idx]->getType();
3033
3034 // Skip all dependent types in templates being used as base specifiers.
3035 // Checks below assume that the base specifier is a CXXRecord.
3036 if (BaseType->isDependentType())
3037 continue;
3038
3039 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3040 .getUnqualifiedType();
3041
3042 if (IndirectBaseTypes.count(CanonicalBase)) {
3043 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3044 /*DetectVirtual=*/true);
3045 bool found
3046 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3047 assert(found);
3048 (void)found;
3049
3050 if (Paths.isAmbiguous(CanonicalBase))
3051 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3052 << BaseType << getAmbiguousPathsDisplayString(Paths)
3053 << Bases[idx]->getSourceRange();
3054 else
3055 assert(Bases[idx]->isVirtual());
3056 }
3057
3058 // Delete the base class specifier, since its data has been copied
3059 // into the CXXRecordDecl.
3060 Context.Deallocate(Bases[idx]);
3061 }
3062
3063 return Invalid;
3064}
3065
3068 if (!ClassDecl || Bases.empty())
3069 return;
3070
3071 AdjustDeclIfTemplate(ClassDecl);
3072 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3073}
3074
3076 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3077 if (!getLangOpts().CPlusPlus)
3078 return false;
3079
3080 if (!Base || !Derived)
3081 return false;
3082
3083 // If either the base or the derived type is invalid, don't try to
3084 // check whether one is derived from the other.
3085 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3086 return false;
3087
3088 // FIXME: In a modules build, do we need the entire path to be visible for us
3089 // to be able to use the inheritance relationship?
3090 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3091 !Derived->isBeingDefined())
3092 return false;
3093
3094 return Derived->isDerivedFrom(Base, Paths);
3095}
3096
3099 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3100 /*DetectVirtual=*/false);
3101 return IsDerivedFrom(Loc, Derived, Base, Paths);
3102}
3103
3105 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3106 /*DetectVirtual=*/false);
3107 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3108 Base->getAsCXXRecordDecl(), Paths);
3109}
3110
3112 CXXBasePaths &Paths) {
3113 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3114 Base->getAsCXXRecordDecl(), Paths);
3115}
3116
3117static void BuildBasePathArray(const CXXBasePath &Path,
3118 CXXCastPath &BasePathArray) {
3119 // We first go backward and check if we have a virtual base.
3120 // FIXME: It would be better if CXXBasePath had the base specifier for
3121 // the nearest virtual base.
3122 unsigned Start = 0;
3123 for (unsigned I = Path.size(); I != 0; --I) {
3124 if (Path[I - 1].Base->isVirtual()) {
3125 Start = I - 1;
3126 break;
3127 }
3128 }
3129
3130 // Now add all bases.
3131 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3132 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3133}
3134
3135
3137 CXXCastPath &BasePathArray) {
3138 assert(BasePathArray.empty() && "Base path array must be empty!");
3139 assert(Paths.isRecordingPaths() && "Must record paths!");
3140 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3141}
3142
3143bool
3145 unsigned InaccessibleBaseID,
3146 unsigned AmbiguousBaseConvID,
3147 SourceLocation Loc, SourceRange Range,
3148 DeclarationName Name,
3149 CXXCastPath *BasePath,
3150 bool IgnoreAccess) {
3151 // First, determine whether the path from Derived to Base is
3152 // ambiguous. This is slightly more expensive than checking whether
3153 // the Derived to Base conversion exists, because here we need to
3154 // explore multiple paths to determine if there is an ambiguity.
3155 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3156 /*DetectVirtual=*/false);
3157 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3158 if (!DerivationOkay)
3159 return true;
3160
3161 const CXXBasePath *Path = nullptr;
3162 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3163 Path = &Paths.front();
3164
3165 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3166 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3167 // user to access such bases.
3168 if (!Path && getLangOpts().MSVCCompat) {
3169 for (const CXXBasePath &PossiblePath : Paths) {
3170 if (PossiblePath.size() == 1) {
3171 Path = &PossiblePath;
3172 if (AmbiguousBaseConvID)
3173 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3174 << Base << Derived << Range;
3175 break;
3176 }
3177 }
3178 }
3179
3180 if (Path) {
3181 if (!IgnoreAccess) {
3182 // Check that the base class can be accessed.
3183 switch (
3184 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3185 case AR_inaccessible:
3186 return true;
3187 case AR_accessible:
3188 case AR_dependent:
3189 case AR_delayed:
3190 break;
3191 }
3192 }
3193
3194 // Build a base path if necessary.
3195 if (BasePath)
3196 ::BuildBasePathArray(*Path, *BasePath);
3197 return false;
3198 }
3199
3200 if (AmbiguousBaseConvID) {
3201 // We know that the derived-to-base conversion is ambiguous, and
3202 // we're going to produce a diagnostic. Perform the derived-to-base
3203 // search just one more time to compute all of the possible paths so
3204 // that we can print them out. This is more expensive than any of
3205 // the previous derived-to-base checks we've done, but at this point
3206 // performance isn't as much of an issue.
3207 Paths.clear();
3208 Paths.setRecordingPaths(true);
3209 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3210 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3211 (void)StillOkay;
3212
3213 // Build up a textual representation of the ambiguous paths, e.g.,
3214 // D -> B -> A, that will be used to illustrate the ambiguous
3215 // conversions in the diagnostic. We only print one of the paths
3216 // to each base class subobject.
3217 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3218
3219 Diag(Loc, AmbiguousBaseConvID)
3220 << Derived << Base << PathDisplayStr << Range << Name;
3221 }
3222 return true;
3223}
3224
3225bool
3227 SourceLocation Loc, SourceRange Range,
3228 CXXCastPath *BasePath,
3229 bool IgnoreAccess) {
3231 Derived, Base, diag::err_upcast_to_inaccessible_base,
3232 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3233 BasePath, IgnoreAccess);
3234}
3235
3237 std::string PathDisplayStr;
3238 std::set<unsigned> DisplayedPaths;
3239 for (const CXXBasePath &Path : Paths) {
3240 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3241 // We haven't displayed a path to this particular base
3242 // class subobject yet.
3243 PathDisplayStr += "\n ";
3244 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3245 .getAsString();
3246 for (const CXXBasePathElement &Element : Path)
3247 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3248 }
3249 }
3250
3251 return PathDisplayStr;
3252}
3253
3254//===----------------------------------------------------------------------===//
3255// C++ class member Handling
3256//===----------------------------------------------------------------------===//
3257
3259 SourceLocation ColonLoc,
3260 const ParsedAttributesView &Attrs) {
3261 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3263 ASLoc, ColonLoc);
3264 CurContext->addHiddenDecl(ASDecl);
3265 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3266}
3267
3269 if (D->isInvalidDecl())
3270 return;
3271
3272 // We only care about "override" and "final" declarations.
3273 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3274 return;
3275
3276 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3277
3278 // We can't check dependent instance methods.
3279 if (MD && MD->isInstance() &&
3280 (MD->getParent()->hasAnyDependentBases() ||
3281 MD->getType()->isDependentType()))
3282 return;
3283
3284 if (MD && !MD->isVirtual()) {
3285 // If we have a non-virtual method, check if it hides a virtual method.
3286 // (In that case, it's most likely the method has the wrong type.)
3287 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3288 FindHiddenVirtualMethods(MD, OverloadedMethods);
3289
3290 if (!OverloadedMethods.empty()) {
3291 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3292 Diag(OA->getLocation(),
3293 diag::override_keyword_hides_virtual_member_function)
3294 << "override" << (OverloadedMethods.size() > 1);
3295 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3296 Diag(FA->getLocation(),
3297 diag::override_keyword_hides_virtual_member_function)
3298 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3299 << (OverloadedMethods.size() > 1);
3300 }
3301 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3302 MD->setInvalidDecl();
3303 return;
3304 }
3305 // Fall through into the general case diagnostic.
3306 // FIXME: We might want to attempt typo correction here.
3307 }
3308
3309 if (!MD || !MD->isVirtual()) {
3310 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3311 Diag(OA->getLocation(),
3312 diag::override_keyword_only_allowed_on_virtual_member_functions)
3313 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3314 D->dropAttr<OverrideAttr>();
3315 }
3316 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3317 Diag(FA->getLocation(),
3318 diag::override_keyword_only_allowed_on_virtual_member_functions)
3319 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3320 << FixItHint::CreateRemoval(FA->getLocation());
3321 D->dropAttr<FinalAttr>();
3322 }
3323 return;
3324 }
3325
3326 // C++11 [class.virtual]p5:
3327 // If a function is marked with the virt-specifier override and
3328 // does not override a member function of a base class, the program is
3329 // ill-formed.
3330 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3331 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3332 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3333 << MD->getDeclName();
3334}
3335
3337 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3338 return;
3339 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3340 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3341 return;
3342
3343 SourceLocation Loc = MD->getLocation();
3344 SourceLocation SpellingLoc = Loc;
3345 if (getSourceManager().isMacroArgExpansion(Loc))
3346 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3347 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3348 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3349 return;
3350
3351 if (MD->size_overridden_methods() > 0) {
3352 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3353 unsigned DiagID =
3354 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3355 ? DiagInconsistent
3356 : DiagSuggest;
3357 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3358 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3359 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3360 };
3361 if (isa<CXXDestructorDecl>(MD))
3362 EmitDiag(
3363 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3364 diag::warn_suggest_destructor_marked_not_override_overriding);
3365 else
3366 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3367 diag::warn_suggest_function_marked_not_override_overriding);
3368 }
3369}
3370
3372 const CXXMethodDecl *Old) {
3373 FinalAttr *FA = Old->getAttr<FinalAttr>();
3374 if (!FA)
3375 return false;
3376
3377 Diag(New->getLocation(), diag::err_final_function_overridden)
3378 << New->getDeclName()
3379 << FA->isSpelledAsSealed();
3380 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3381 return true;
3382}
3383
3385 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3386 // FIXME: Destruction of ObjC lifetime types has side-effects.
3387 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3388 return !RD->isCompleteDefinition() ||
3389 !RD->hasTrivialDefaultConstructor() ||
3390 !RD->hasTrivialDestructor();
3391 return false;
3392}
3393
3394void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3395 DeclarationName FieldName,
3396 const CXXRecordDecl *RD,
3397 bool DeclIsField) {
3398 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3399 return;
3400
3401 // To record a shadowed field in a base
3402 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3403 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3404 CXXBasePath &Path) {
3405 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3406 // Record an ambiguous path directly
3407 if (Bases.find(Base) != Bases.end())
3408 return true;
3409 for (const auto Field : Base->lookup(FieldName)) {
3410 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3411 Field->getAccess() != AS_private) {
3412 assert(Field->getAccess() != AS_none);
3413 assert(Bases.find(Base) == Bases.end());
3414 Bases[Base] = Field;
3415 return true;
3416 }
3417 }
3418 return false;
3419 };
3420
3421 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3422 /*DetectVirtual=*/true);
3423 if (!RD->lookupInBases(FieldShadowed, Paths))
3424 return;
3425
3426 for (const auto &P : Paths) {
3427 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3428 auto It = Bases.find(Base);
3429 // Skip duplicated bases
3430 if (It == Bases.end())
3431 continue;
3432 auto BaseField = It->second;
3433 assert(BaseField->getAccess() != AS_private);
3434 if (AS_none !=
3435 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3436 Diag(Loc, diag::warn_shadow_field)
3437 << FieldName << RD << Base << DeclIsField;
3438 Diag(BaseField->getLocation(), diag::note_shadow_field);
3439 Bases.erase(It);
3440 }
3441 }
3442}
3443
3444template <typename AttrType>
3445inline static bool HasAttribute(const QualType &T) {
3446 if (const TagDecl *TD = T->getAsTagDecl())
3447 return TD->hasAttr<AttrType>();
3448 if (const TypedefType *TDT = T->getAs<TypedefType>())
3449 return TDT->getDecl()->hasAttr<AttrType>();
3450 return false;
3451}
3452
3453static bool IsUnusedPrivateField(const FieldDecl *FD) {
3454 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3455 QualType FieldType = FD->getType();
3456 if (HasAttribute<WarnUnusedAttr>(FieldType))
3457 return true;
3458
3459 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3460 !FD->getParent()->isDependentContext() &&
3461 !HasAttribute<UnusedAttr>(FieldType) &&
3463 }
3464 return false;
3465}
3466
3467NamedDecl *
3469 MultiTemplateParamsArg TemplateParameterLists,
3470 Expr *BitWidth, const VirtSpecifiers &VS,
3471 InClassInitStyle InitStyle) {
3472 const DeclSpec &DS = D.getDeclSpec();
3474 DeclarationName Name = NameInfo.getName();
3475 SourceLocation Loc = NameInfo.getLoc();
3476
3477 // For anonymous bitfields, the location should point to the type.
3478 if (Loc.isInvalid())
3479 Loc = D.getBeginLoc();
3480
3482 assert(!DS.isFriendSpecified());
3483
3484 bool isFunc = D.isDeclarationOfFunction();
3485 const ParsedAttr *MSPropertyAttr =
3487
3488 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3489 // The Microsoft extension __interface only permits public member functions
3490 // and prohibits constructors, destructors, operators, non-public member
3491 // functions, static methods and data members.
3492 unsigned InvalidDecl;
3493 bool ShowDeclName = true;
3494 if (!isFunc &&
3495 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3496 InvalidDecl = 0;
3497 else if (!isFunc)
3498 InvalidDecl = 1;
3499 else if (AS != AS_public)
3500 InvalidDecl = 2;
3502 InvalidDecl = 3;
3503 else switch (Name.getNameKind()) {
3505 InvalidDecl = 4;
3506 ShowDeclName = false;
3507 break;
3508
3510 InvalidDecl = 5;
3511 ShowDeclName = false;
3512 break;
3513
3516 InvalidDecl = 6;
3517 break;
3518
3519 default:
3520 InvalidDecl = 0;
3521 break;
3522 }
3523
3524 if (InvalidDecl) {
3525 if (ShowDeclName)
3526 Diag(Loc, diag::err_invalid_member_in_interface)
3527 << (InvalidDecl-1) << Name;
3528 else
3529 Diag(Loc, diag::err_invalid_member_in_interface)
3530 << (InvalidDecl-1) << "";
3531 return nullptr;
3532 }
3533 }
3534
3535 // HLSL prohibits user defined constructors and destructors.
3536 if (getLangOpts().HLSL) {
3537 switch (Name.getNameKind()) {
3540 Diag(Loc, diag::err_hlsl_cstor_dstor);
3541 return nullptr;
3542 default:
3543 break;
3544 }
3545 }
3546
3547 // C++ 9.2p6: A member shall not be declared to have automatic storage
3548 // duration (auto, register) or with the extern storage-class-specifier.
3549 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3550 // data members and cannot be applied to names declared const or static,
3551 // and cannot be applied to reference members.
3552 switch (DS.getStorageClassSpec()) {
3556 break;
3558 if (isFunc) {
3559 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3560
3561 // FIXME: It would be nicer if the keyword was ignored only for this
3562 // declarator. Otherwise we could get follow-up errors.
3564 }
3565 break;
3566 default:
3568 diag::err_storageclass_invalid_for_member);
3570 break;
3571 }
3572
3573 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3575 !isFunc && TemplateParameterLists.empty();
3576
3577 if (DS.hasConstexprSpecifier() && isInstField) {
3579 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3580 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3581 if (InitStyle == ICIS_NoInit) {
3582 B << 0 << 0;
3584 B << FixItHint::CreateRemoval(ConstexprLoc);
3585 else {
3586 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3588 const char *PrevSpec;
3589 unsigned DiagID;
3590 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3591 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3592 (void)Failed;
3593 assert(!Failed && "Making a constexpr member const shouldn't fail");
3594 }
3595 } else {
3596 B << 1;
3597 const char *PrevSpec;
3598 unsigned DiagID;
3600 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3601 Context.getPrintingPolicy())) {
3603 "This is the only DeclSpec that should fail to be applied");
3604 B << 1;
3605 } else {
3606 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3607 isInstField = false;
3608 }
3609 }
3610 }
3611
3613 if (isInstField) {
3614 CXXScopeSpec &SS = D.getCXXScopeSpec();
3615
3616 // Data members must have identifiers for names.
3617 if (!Name.isIdentifier()) {
3618 Diag(Loc, diag::err_bad_variable_name)
3619 << Name;
3620 return nullptr;
3621 }
3622
3625 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3626 << II
3630 D.SetIdentifier(II, Loc);
3631 }
3632
3633 if (SS.isSet() && !SS.isInvalid()) {
3634 // The user provided a superfluous scope specifier inside a class
3635 // definition:
3636 //
3637 // class X {
3638 // int X::member;
3639 // };
3640 if (DeclContext *DC = computeDeclContext(SS, false)) {
3641 TemplateIdAnnotation *TemplateId =
3643 ? D.getName().TemplateId
3644 : nullptr;
3646 TemplateId,
3647 /*IsMemberSpecialization=*/false);
3648 } else {
3649 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3650 << Name << SS.getRange();
3651 }
3652 SS.clear();
3653 }
3654
3655 if (MSPropertyAttr) {
3657 BitWidth, InitStyle, AS, *MSPropertyAttr);
3658 if (!Member)
3659 return nullptr;
3660 isInstField = false;
3661 } else {
3663 BitWidth, InitStyle, AS);
3664 if (!Member)
3665 return nullptr;
3666 }
3667
3668 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3669 } else {
3670 Member = HandleDeclarator(S, D, TemplateParameterLists);
3671 if (!Member)
3672 return nullptr;
3673
3674 // Non-instance-fields can't have a bitfield.
3675 if (BitWidth) {
3676 if (Member->isInvalidDecl()) {
3677 // don't emit another diagnostic.
3679 // C++ 9.6p3: A bit-field shall not be a static member.
3680 // "static member 'A' cannot be a bit-field"
3681 Diag(Loc, diag::err_static_not_bitfield)
3682 << Name << BitWidth->getSourceRange();
3683 } else if (isa<TypedefDecl>(Member)) {
3684 // "typedef member 'x' cannot be a bit-field"
3685 Diag(Loc, diag::err_typedef_not_bitfield)
3686 << Name << BitWidth->getSourceRange();
3687 } else {
3688 // A function typedef ("typedef int f(); f a;").
3689 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3690 Diag(Loc, diag::err_not_integral_type_bitfield)
3691 << Name << cast<ValueDecl>(Member)->getType()
3692 << BitWidth->getSourceRange();
3693 }
3694
3695 BitWidth = nullptr;
3696 Member->setInvalidDecl();
3697 }
3698
3699 NamedDecl *NonTemplateMember = Member;
3700 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3701 NonTemplateMember = FunTmpl->getTemplatedDecl();
3702 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3703 NonTemplateMember = VarTmpl->getTemplatedDecl();
3704
3705 Member->setAccess(AS);
3706
3707 // If we have declared a member function template or static data member
3708 // template, set the access of the templated declaration as well.
3709 if (NonTemplateMember != Member)
3710 NonTemplateMember->setAccess(AS);
3711
3712 // C++ [temp.deduct.guide]p3:
3713 // A deduction guide [...] for a member class template [shall be
3714 // declared] with the same access [as the template].
3715 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3716 auto *TD = DG->getDeducedTemplate();
3717 // Access specifiers are only meaningful if both the template and the
3718 // deduction guide are from the same scope.
3719 if (AS != TD->getAccess() &&
3720 TD->getDeclContext()->getRedeclContext()->Equals(
3721 DG->getDeclContext()->getRedeclContext())) {
3722 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3723 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3724 << TD->getAccess();
3725 const AccessSpecDecl *LastAccessSpec = nullptr;
3726 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3727 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3728 LastAccessSpec = AccessSpec;
3729 }
3730 assert(LastAccessSpec && "differing access with no access specifier");
3731 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3732 << AS;
3733 }
3734 }
3735 }
3736
3737 if (VS.isOverrideSpecified())
3738 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3739 if (VS.isFinalSpecified())
3740 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3742 ? FinalAttr::Keyword_sealed
3743 : FinalAttr::Keyword_final));
3744
3745 if (VS.getLastLocation().isValid()) {
3746 // Update the end location of a method that has a virt-specifiers.
3747 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3748 MD->setRangeEnd(VS.getLastLocation());
3749 }
3750
3752
3753 assert((Name || isInstField) && "No identifier for non-field ?");
3754
3755 if (isInstField) {
3757 FieldCollector->Add(FD);
3758
3759 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3761 // Remember all explicit private FieldDecls that have a name, no side
3762 // effects and are not part of a dependent type declaration.
3763 UnusedPrivateFields.insert(FD);
3764 }
3765 }
3766
3767 return Member;
3768}
3769
3770namespace {
3771 class UninitializedFieldVisitor
3772 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3773 Sema &S;
3774 // List of Decls to generate a warning on. Also remove Decls that become
3775 // initialized.
3776 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3777 // List of base classes of the record. Classes are removed after their
3778 // initializers.
3779 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3780 // Vector of decls to be removed from the Decl set prior to visiting the
3781 // nodes. These Decls may have been initialized in the prior initializer.
3783 // If non-null, add a note to the warning pointing back to the constructor.
3785 // Variables to hold state when processing an initializer list. When
3786 // InitList is true, special case initialization of FieldDecls matching
3787 // InitListFieldDecl.
3788 bool InitList;
3789 FieldDecl *InitListFieldDecl;
3790 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3791
3792 public:
3794 UninitializedFieldVisitor(Sema &S,
3795 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3796 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3797 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3798 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3799
3800 // Returns true if the use of ME is not an uninitialized use.
3801 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3802 bool CheckReferenceOnly) {
3804 bool ReferenceField = false;
3805 while (ME) {
3806 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3807 if (!FD)
3808 return false;
3809 Fields.push_back(FD);
3810 if (FD->getType()->isReferenceType())
3811 ReferenceField = true;
3812 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3813 }
3814
3815 // Binding a reference to an uninitialized field is not an
3816 // uninitialized use.
3817 if (CheckReferenceOnly && !ReferenceField)
3818 return true;
3819
3820 // Discard the first field since it is the field decl that is being
3821 // initialized.
3822 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3823 auto UsedIter = UsedFields.begin();
3824 const auto UsedEnd = UsedFields.end();
3825
3826 for (const unsigned Orig : InitFieldIndex) {
3827 if (UsedIter == UsedEnd)
3828 break;
3829 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3830 if (UsedIndex < Orig)
3831 return true;
3832 if (UsedIndex > Orig)
3833 break;
3834 ++UsedIter;
3835 }
3836
3837 return false;
3838 }
3839
3840 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3841 bool AddressOf) {
3843 return;
3844
3845 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3846 // or union.
3847 MemberExpr *FieldME = ME;
3848
3849 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3850
3851 Expr *Base = ME;
3852 while (MemberExpr *SubME =
3853 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3854
3855 if (isa<VarDecl>(SubME->getMemberDecl()))
3856 return;
3857
3858 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3859 if (!FD->isAnonymousStructOrUnion())
3860 FieldME = SubME;
3861
3862 if (!FieldME->getType().isPODType(S.Context))
3863 AllPODFields = false;
3864
3865 Base = SubME->getBase();
3866 }
3867
3868 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3869 Visit(Base);
3870 return;
3871 }
3872
3873 if (AddressOf && AllPODFields)
3874 return;
3875
3876 ValueDecl* FoundVD = FieldME->getMemberDecl();
3877
3878 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3879 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3880 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3881 }
3882
3883 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3884 QualType T = BaseCast->getType();
3885 if (T->isPointerType() &&
3886 BaseClasses.count(T->getPointeeType())) {
3887 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3888 << T->getPointeeType() << FoundVD;
3889 }
3890 }
3891 }
3892
3893 if (!Decls.count(FoundVD))
3894 return;
3895
3896 const bool IsReference = FoundVD->getType()->isReferenceType();
3897
3898 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3899 // Special checking for initializer lists.
3900 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3901 return;
3902 }
3903 } else {
3904 // Prevent double warnings on use of unbounded references.
3905 if (CheckReferenceOnly && !IsReference)
3906 return;
3907 }
3908
3909 unsigned diag = IsReference
3910 ? diag::warn_reference_field_is_uninit
3911 : diag::warn_field_is_uninit;
3912 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3913 if (Constructor)
3914 S.Diag(Constructor->getLocation(),
3915 diag::note_uninit_in_this_constructor)
3916 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3917
3918 }
3919
3920 void HandleValue(Expr *E, bool AddressOf) {
3921 E = E->IgnoreParens();
3922
3923 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3924 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3925 AddressOf /*AddressOf*/);
3926 return;
3927 }
3928
3929 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3930 Visit(CO->getCond());
3931 HandleValue(CO->getTrueExpr(), AddressOf);
3932 HandleValue(CO->getFalseExpr(), AddressOf);
3933 return;
3934 }
3935
3936 if (BinaryConditionalOperator *BCO =
3937 dyn_cast<BinaryConditionalOperator>(E)) {
3938 Visit(BCO->getCond());
3939 HandleValue(BCO->getFalseExpr(), AddressOf);
3940 return;
3941 }
3942
3943 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3944 HandleValue(OVE->getSourceExpr(), AddressOf);
3945 return;
3946 }
3947
3948 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3949 switch (BO->getOpcode()) {
3950 default:
3951 break;
3952 case(BO_PtrMemD):
3953 case(BO_PtrMemI):
3954 HandleValue(BO->getLHS(), AddressOf);
3955 Visit(BO->getRHS());
3956 return;
3957 case(BO_Comma):
3958 Visit(BO->getLHS());
3959 HandleValue(BO->getRHS(), AddressOf);
3960 return;
3961 }
3962 }
3963
3964 Visit(E);
3965 }
3966
3967 void CheckInitListExpr(InitListExpr *ILE) {
3968 InitFieldIndex.push_back(0);
3969 for (auto *Child : ILE->children()) {
3970 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3971 CheckInitListExpr(SubList);
3972 } else {
3973 Visit(Child);
3974 }
3975 ++InitFieldIndex.back();
3976 }
3977 InitFieldIndex.pop_back();
3978 }
3979
3980 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3981 FieldDecl *Field, const Type *BaseClass) {
3982 // Remove Decls that may have been initialized in the previous
3983 // initializer.
3984 for (ValueDecl* VD : DeclsToRemove)
3985 Decls.erase(VD);
3986 DeclsToRemove.clear();
3987
3988 Constructor = FieldConstructor;
3989 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3990
3991 if (ILE && Field) {
3992 InitList = true;
3993 InitListFieldDecl = Field;
3994 InitFieldIndex.clear();
3995 CheckInitListExpr(ILE);
3996 } else {
3997 InitList = false;
3998 Visit(E);
3999 }
4000
4001 if (Field)
4002 Decls.erase(Field);
4003 if (BaseClass)
4004 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4005 }
4006
4007 void VisitMemberExpr(MemberExpr *ME) {
4008 // All uses of unbounded reference fields will warn.
4009 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4010 }
4011
4012 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4013 if (E->getCastKind() == CK_LValueToRValue) {
4014 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4015 return;
4016 }
4017
4018 Inherited::VisitImplicitCastExpr(E);
4019 }
4020
4021 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4022 if (E->getConstructor()->isCopyConstructor()) {
4023 Expr *ArgExpr = E->getArg(0);
4024 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4025 if (ILE->getNumInits() == 1)
4026 ArgExpr = ILE->getInit(0);
4027 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4028 if (ICE->getCastKind() == CK_NoOp)
4029 ArgExpr = ICE->getSubExpr();
4030 HandleValue(ArgExpr, false /*AddressOf*/);
4031 return;
4032 }
4033 Inherited::VisitCXXConstructExpr(E);
4034 }
4035
4036 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4037 Expr *Callee = E->getCallee();
4038 if (isa<MemberExpr>(Callee)) {
4039 HandleValue(Callee, false /*AddressOf*/);
4040 for (auto *Arg : E->arguments())
4041 Visit(Arg);
4042 return;
4043 }
4044
4045 Inherited::VisitCXXMemberCallExpr(E);
4046 }
4047
4048 void VisitCallExpr(CallExpr *E) {
4049 // Treat std::move as a use.
4050 if (E->isCallToStdMove()) {
4051 HandleValue(E->getArg(0), /*AddressOf=*/false);
4052 return;
4053 }
4054
4055 Inherited::VisitCallExpr(E);
4056 }
4057
4058 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4059 Expr *Callee = E->getCallee();
4060
4061 if (isa<UnresolvedLookupExpr>(Callee))
4062 return Inherited::VisitCXXOperatorCallExpr(E);
4063
4064 Visit(Callee);
4065 for (auto *Arg : E->arguments())
4066 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4067 }
4068
4069 void VisitBinaryOperator(BinaryOperator *E) {
4070 // If a field assignment is detected, remove the field from the
4071 // uninitiailized field set.
4072 if (E->getOpcode() == BO_Assign)
4073 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4074 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4075 if (!FD->getType()->isReferenceType())
4076 DeclsToRemove.push_back(FD);
4077
4078 if (E->isCompoundAssignmentOp()) {
4079 HandleValue(E->getLHS(), false /*AddressOf*/);
4080 Visit(E->getRHS());
4081 return;
4082 }
4083
4084 Inherited::VisitBinaryOperator(E);
4085 }
4086
4087 void VisitUnaryOperator(UnaryOperator *E) {
4088 if (E->isIncrementDecrementOp()) {
4089 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4090 return;
4091 }
4092 if (E->getOpcode() == UO_AddrOf) {
4093 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4094 HandleValue(ME->getBase(), true /*AddressOf*/);
4095 return;
4096 }
4097 }
4098
4099 Inherited::VisitUnaryOperator(E);
4100 }
4101 };
4102
4103 // Diagnose value-uses of fields to initialize themselves, e.g.
4104 // foo(foo)
4105 // where foo is not also a parameter to the constructor.
4106 // Also diagnose across field uninitialized use such as
4107 // x(y), y(x)
4108 // TODO: implement -Wuninitialized and fold this into that framework.
4109 static void DiagnoseUninitializedFields(
4110 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4111
4112 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4113 Constructor->getLocation())) {
4114 return;
4115 }
4116
4117 if (Constructor->isInvalidDecl())
4118 return;
4119
4120 const CXXRecordDecl *RD = Constructor->getParent();
4121
4122 if (RD->isDependentContext())
4123 return;
4124
4125 // Holds fields that are uninitialized.
4126 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4127
4128 // At the beginning, all fields are uninitialized.
4129 for (auto *I : RD->decls()) {
4130 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4131 UninitializedFields.insert(FD);
4132 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4133 UninitializedFields.insert(IFD->getAnonField());
4134 }
4135 }
4136
4137 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4138 for (const auto &I : RD->bases())
4139 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4140
4141 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4142 return;
4143
4144 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4145 UninitializedFields,
4146 UninitializedBaseClasses);
4147
4148 for (const auto *FieldInit : Constructor->inits()) {
4149 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4150 break;
4151
4152 Expr *InitExpr = FieldInit->getInit();
4153 if (!InitExpr)
4154 continue;
4155
4156 if (CXXDefaultInitExpr *Default =
4157 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4158 InitExpr = Default->getExpr();
4159 if (!InitExpr)
4160 continue;
4161 // In class initializers will point to the constructor.
4162 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4163 FieldInit->getAnyMember(),
4164 FieldInit->getBaseClass());
4165 } else {
4166 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4167 FieldInit->getAnyMember(),
4168 FieldInit->getBaseClass());
4169 }
4170 }
4171 }
4172} // namespace
4173
4175 // Create a synthetic function scope to represent the call to the constructor
4176 // that notionally surrounds a use of this initializer.
4178}
4179
4181 if (!D.isFunctionDeclarator())
4182 return;
4183 auto &FTI = D.getFunctionTypeInfo();
4184 if (!FTI.Params)
4185 return;
4186 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4187 FTI.NumParams)) {
4188 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4189 if (ParamDecl->getDeclName())
4190 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4191 }
4192}
4193
4195 return ActOnRequiresClause(ConstraintExpr);
4196}
4197
4199 if (ConstraintExpr.isInvalid())
4200 return ExprError();
4201
4202 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4204 return ExprError();
4205
4206 return ConstraintExpr;
4207}
4208
4210 Expr *InitExpr,
4211 SourceLocation InitLoc) {
4212 InitializedEntity Entity =
4214 InitializationKind Kind =
4217 InitExpr->getBeginLoc(),
4218 InitExpr->getEndLoc())
4219 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4220 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4221 return Seq.Perform(*this, Entity, Kind, InitExpr);
4222}
4223
4225 SourceLocation InitLoc,
4226 ExprResult InitExpr) {
4227 // Pop the notional constructor scope we created earlier.
4228 PopFunctionScopeInfo(nullptr, D);
4229
4230 // Microsoft C++'s property declaration cannot have a default member
4231 // initializer.
4232 if (isa<MSPropertyDecl>(D)) {
4233 D->setInvalidDecl();
4234 return;
4235 }
4236
4237 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4238 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4239 "must set init style when field is created");
4240
4241 if (!InitExpr.isUsable() ||
4243 FD->setInvalidDecl();
4244 ExprResult RecoveryInit =
4245 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4246 if (RecoveryInit.isUsable())
4247 FD->setInClassInitializer(RecoveryInit.get());
4248 return;
4249 }
4250
4251 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4252 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4253 // C++11 [class.base.init]p7:
4254 // The initialization of each base and member constitutes a
4255 // full-expression.
4256 if (!InitExpr.isInvalid())
4257 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4258 if (InitExpr.isInvalid()) {
4259 FD->setInvalidDecl();
4260 return;
4261 }
4262 }
4263
4264 FD->setInClassInitializer(InitExpr.get());
4265}
4266
4267/// Find the direct and/or virtual base specifiers that
4268/// correspond to the given base type, for use in base initialization
4269/// within a constructor.
4270static bool FindBaseInitializer(Sema &SemaRef,
4271 CXXRecordDecl *ClassDecl,
4272 QualType BaseType,
4273 const CXXBaseSpecifier *&DirectBaseSpec,
4274 const CXXBaseSpecifier *&VirtualBaseSpec) {
4275 // First, check for a direct base class.
4276 DirectBaseSpec = nullptr;
4277 for (const auto &Base : ClassDecl->bases()) {
4278 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4279 // We found a direct base of this type. That's what we're
4280 // initializing.
4281 DirectBaseSpec = &Base;
4282 break;
4283 }
4284 }
4285
4286 // Check for a virtual base class.
4287 // FIXME: We might be able to short-circuit this if we know in advance that
4288 // there are no virtual bases.
4289 VirtualBaseSpec = nullptr;
4290 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4291 // We haven't found a base yet; search the class hierarchy for a
4292 // virtual base class.
4293 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4294 /*DetectVirtual=*/false);
4295 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4296 SemaRef.Context.getCanonicalTagType(ClassDecl),
4297 BaseType, Paths)) {
4298 for (const CXXBasePath &Path : Paths) {
4299 if (Path.back().Base->isVirtual()) {
4300 VirtualBaseSpec = Path.back().Base;
4301 break;
4302 }
4303 }
4304 }
4305 }
4306
4307 return DirectBaseSpec || VirtualBaseSpec;
4308}
4309
4312 Scope *S,
4313 CXXScopeSpec &SS,
4314 IdentifierInfo *MemberOrBase,
4315 ParsedType TemplateTypeTy,
4316 const DeclSpec &DS,
4317 SourceLocation IdLoc,
4318 Expr *InitList,
4319 SourceLocation EllipsisLoc) {
4320 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4321 DS, IdLoc, InitList,
4322 EllipsisLoc);
4323}
4324
4327 Scope *S,
4328 CXXScopeSpec &SS,
4329 IdentifierInfo *MemberOrBase,
4330 ParsedType TemplateTypeTy,
4331 const DeclSpec &DS,
4332 SourceLocation IdLoc,
4333 SourceLocation LParenLoc,
4334 ArrayRef<Expr *> Args,
4335 SourceLocation RParenLoc,
4336 SourceLocation EllipsisLoc) {
4337 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4338 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4339 DS, IdLoc, List, EllipsisLoc);
4340}
4341
4342namespace {
4343
4344// Callback to only accept typo corrections that can be a valid C++ member
4345// initializer: either a non-static field member or a base class.
4346class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4347public:
4348 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4349 : ClassDecl(ClassDecl) {}
4350
4351 bool ValidateCandidate(const TypoCorrection &candidate) override {
4352 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4353 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4354 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4355 return isa<TypeDecl>(ND);
4356 }
4357 return false;
4358 }
4359
4360 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4361 return std::make_unique<MemInitializerValidatorCCC>(*this);
4362 }
4363
4364private:
4365 CXXRecordDecl *ClassDecl;
4366};
4367
4368}
4369
4371 RecordDecl *ClassDecl,
4372 const IdentifierInfo *Name) {
4373 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4375 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4376 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4378 });
4379 // We did not find a placeholder variable
4380 if (Found == Result.end())
4381 return false;
4382 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4383 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4384 const NamedDecl *ND = *It;
4385 if (ND->getDeclContext() != ND->getDeclContext())
4386 break;
4389 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4390 }
4391 return true;
4392}
4393
4394ValueDecl *
4396 const IdentifierInfo *MemberOrBase) {
4397 ValueDecl *ND = nullptr;
4398 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4400 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4401 if (ND) {
4402 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4403 return nullptr;
4404 break;
4405 }
4406 if (!IsPlaceholder)
4407 return cast<ValueDecl>(D);
4408 ND = cast<ValueDecl>(D);
4409 }
4410 }
4411 return ND;
4412}
4413
4415 CXXScopeSpec &SS,
4416 ParsedType TemplateTypeTy,
4417 IdentifierInfo *MemberOrBase) {
4418 if (SS.getScopeRep() || TemplateTypeTy)
4419 return nullptr;
4420 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4421}
4422
4425 Scope *S,
4426 CXXScopeSpec &SS,
4427 IdentifierInfo *MemberOrBase,
4428 ParsedType TemplateTypeTy,
4429 const DeclSpec &DS,
4430 SourceLocation IdLoc,
4431 Expr *Init,
4432 SourceLocation EllipsisLoc) {
4433 if (!ConstructorD || !Init)
4434 return true;
4435
4436 AdjustDeclIfTemplate(ConstructorD);
4437
4439 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4440 if (!Constructor) {
4441 // The user wrote a constructor initializer on a function that is
4442 // not a C++ constructor. Ignore the error for now, because we may
4443 // have more member initializers coming; we'll diagnose it just
4444 // once in ActOnMemInitializers.
4445 return true;
4446 }
4447
4448 CXXRecordDecl *ClassDecl = Constructor->getParent();
4449
4450 // C++ [class.base.init]p2:
4451 // Names in a mem-initializer-id are looked up in the scope of the
4452 // constructor's class and, if not found in that scope, are looked
4453 // up in the scope containing the constructor's definition.
4454 // [Note: if the constructor's class contains a member with the
4455 // same name as a direct or virtual base class of the class, a
4456 // mem-initializer-id naming the member or base class and composed
4457 // of a single identifier refers to the class member. A
4458 // mem-initializer-id for the hidden base class may be specified
4459 // using a qualified name. ]
4460
4461 // Look for a member, first.
4463 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4464 if (EllipsisLoc.isValid())
4465 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4466 << MemberOrBase
4467 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4468
4469 return BuildMemberInitializer(Member, Init, IdLoc);
4470 }
4471 // It didn't name a member, so see if it names a class.
4472 QualType BaseType;
4473 TypeSourceInfo *TInfo = nullptr;
4474
4475 if (TemplateTypeTy) {
4476 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4477 if (BaseType.isNull())
4478 return true;
4479 } else if (DS.getTypeSpecType() == TST_decltype) {
4480 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4481 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4482 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4483 return true;
4484 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4485 BaseType =
4487 DS.getBeginLoc(), DS.getEllipsisLoc());
4488 } else {
4489 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4490 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4491
4492 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4493 if (!TyD) {
4494 if (R.isAmbiguous()) return true;
4495
4496 // We don't want access-control diagnostics here.
4497 R.suppressDiagnostics();
4498
4499 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4500 bool NotUnknownSpecialization = false;
4501 DeclContext *DC = computeDeclContext(SS, false);
4502 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4503 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4504
4505 if (!NotUnknownSpecialization) {
4506 // When the scope specifier can refer to a member of an unknown
4507 // specialization, we take it as a type name.
4508 BaseType = CheckTypenameType(
4510 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4511 if (BaseType.isNull())
4512 return true;
4513
4514 TInfo = Context.CreateTypeSourceInfo(BaseType);
4517 if (!TL.isNull()) {
4518 TL.setNameLoc(IdLoc);
4521 }
4522
4523 R.clear();
4524 R.setLookupName(MemberOrBase);
4525 }
4526 }
4527
4528 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4529 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4530 auto *TempSpec = cast<TemplateSpecializationType>(
4531 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4532 TemplateName TN = TempSpec->getTemplateName();
4533 for (auto const &Base : ClassDecl->bases()) {
4534 auto BaseTemplate =
4535 Base.getType()->getAs<TemplateSpecializationType>();
4536 if (BaseTemplate &&
4537 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4538 /*IgnoreDeduced=*/true)) {
4539 Diag(IdLoc, diag::ext_unqualified_base_class)
4540 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4541 BaseType = Base.getType();
4542 break;
4543 }
4544 }
4545 }
4546 }
4547
4548 // If no results were found, try to correct typos.
4549 TypoCorrection Corr;
4550 MemInitializerValidatorCCC CCC(ClassDecl);
4551 if (R.empty() && BaseType.isNull() &&
4552 (Corr =
4553 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4554 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4556 // We have found a non-static data member with a similar
4557 // name to what was typed; complain and initialize that
4558 // member.
4559 diagnoseTypo(Corr,
4560 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4561 << MemberOrBase << true);
4562 return BuildMemberInitializer(Member, Init, IdLoc);
4563 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4564 const CXXBaseSpecifier *DirectBaseSpec;
4565 const CXXBaseSpecifier *VirtualBaseSpec;
4566 if (FindBaseInitializer(*this, ClassDecl,
4567 Context.getTypeDeclType(Type),
4568 DirectBaseSpec, VirtualBaseSpec)) {
4569 // We have found a direct or virtual base class with a
4570 // similar name to what was typed; complain and initialize
4571 // that base class.
4572 diagnoseTypo(Corr,
4573 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4574 << MemberOrBase << false,
4575 PDiag() /*Suppress note, we provide our own.*/);
4576
4577 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4578 : VirtualBaseSpec;
4579 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4580 << BaseSpec->getType() << BaseSpec->getSourceRange();
4581
4582 TyD = Type;
4583 }
4584 }
4585 }
4586
4587 if (!TyD && BaseType.isNull()) {
4588 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4589 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4590 return true;
4591 }
4592 }
4593
4594 if (BaseType.isNull()) {
4595 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4596
4597 TypeLocBuilder TLB;
4598 // FIXME: This is missing building the UsingType for TyD, if any.
4599 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4600 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4601 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4602 auto TL = TLB.push<TagTypeLoc>(BaseType);
4604 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4605 TL.setNameLoc(IdLoc);
4606 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4607 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4608 SS.getScopeRep(), TN);
4609 TLB.push<TypedefTypeLoc>(BaseType).set(
4610 /*ElaboratedKeywordLoc=*/SourceLocation(),
4611 SS.getWithLocInContext(Context), IdLoc);
4612 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4613 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4614 SS.getScopeRep(), UD);
4615 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4616 /*ElaboratedKeywordLoc=*/SourceLocation(),
4617 SS.getWithLocInContext(Context), IdLoc);
4618 } else {
4619 // FIXME: What else can appear here?
4620 assert(SS.isEmpty());
4621 BaseType = Context.getTypeDeclType(TyD);
4622 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4623 }
4624 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4625 }
4626 }
4627
4628 if (!TInfo)
4629 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4630
4631 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4632}
4633
4636 SourceLocation IdLoc) {
4637 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4638 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4639 assert((DirectMember || IndirectMember) &&
4640 "Member must be a FieldDecl or IndirectFieldDecl");
4641
4643 return true;
4644
4645 if (Member->isInvalidDecl())
4646 return true;
4647
4648 MultiExprArg Args;
4649 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4650 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4651 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4652 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4653 } else {
4654 // Template instantiation doesn't reconstruct ParenListExprs for us.
4655 Args = Init;
4656 }
4657
4658 SourceRange InitRange = Init->getSourceRange();
4659
4660 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4661 // Can't check initialization for a member of dependent type or when
4662 // any of the arguments are type-dependent expressions.
4664 } else {
4665 bool InitList = false;
4666 if (isa<InitListExpr>(Init)) {
4667 InitList = true;
4668 Args = Init;
4669 }
4670
4671 // Initialize the member.
4672 InitializedEntity MemberEntity =
4673 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4674 : InitializedEntity::InitializeMember(IndirectMember,
4675 nullptr);
4676 InitializationKind Kind =
4678 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4679 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4680 InitRange.getEnd());
4681
4682 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4683 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4684 nullptr);
4685 if (!MemberInit.isInvalid()) {
4686 // C++11 [class.base.init]p7:
4687 // The initialization of each base and member constitutes a
4688 // full-expression.
4689 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4690 /*DiscardedValue*/ false);
4691 }
4692
4693 if (MemberInit.isInvalid()) {
4694 // Args were sensible expressions but we couldn't initialize the member
4695 // from them. Preserve them in a RecoveryExpr instead.
4696 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4697 Member->getType())
4698 .get();
4699 if (!Init)
4700 return true;
4701 } else {
4702 Init = MemberInit.get();
4703 }
4704 }
4705
4706 if (DirectMember) {
4707 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4708 InitRange.getBegin(), Init,
4709 InitRange.getEnd());
4710 } else {
4711 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4712 InitRange.getBegin(), Init,
4713 InitRange.getEnd());
4714 }
4715}
4716
4719 CXXRecordDecl *ClassDecl) {
4720 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4721 if (!LangOpts.CPlusPlus11)
4722 return Diag(NameLoc, diag::err_delegating_ctor)
4723 << TInfo->getTypeLoc().getSourceRange();
4724 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4725
4726 bool InitList = true;
4727 MultiExprArg Args = Init;
4728 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4729 InitList = false;
4730 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4731 }
4732
4733 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4734
4735 SourceRange InitRange = Init->getSourceRange();
4736 // Initialize the object.
4737 InitializedEntity DelegationEntity =
4739 InitializationKind Kind =
4741 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4742 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4743 InitRange.getEnd());
4744 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4745 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4746 Args, nullptr);
4747 if (!DelegationInit.isInvalid()) {
4748 assert((DelegationInit.get()->containsErrors() ||
4749 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4750 "Delegating constructor with no target?");
4751
4752 // C++11 [class.base.init]p7:
4753 // The initialization of each base and member constitutes a
4754 // full-expression.
4755 DelegationInit = ActOnFinishFullExpr(
4756 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4757 }
4758
4759 if (DelegationInit.isInvalid()) {
4760 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4761 InitRange.getEnd(), Args, ClassType);
4762 if (DelegationInit.isInvalid())
4763 return true;
4764 } else {
4765 // If we are in a dependent context, template instantiation will
4766 // perform this type-checking again. Just save the arguments that we
4767 // received in a ParenListExpr.
4768 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4769 // of the information that we have about the base
4770 // initializer. However, deconstructing the ASTs is a dicey process,
4771 // and this approach is far more likely to get the corner cases right.
4772 if (CurContext->isDependentContext())
4773 DelegationInit = Init;
4774 }
4775
4776 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4777 DelegationInit.getAs<Expr>(),
4778 InitRange.getEnd());
4779}
4780
4783 Expr *Init, CXXRecordDecl *ClassDecl,
4784 SourceLocation EllipsisLoc) {
4785 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4786
4787 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4788 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4789 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4790
4791 // C++ [class.base.init]p2:
4792 // [...] Unless the mem-initializer-id names a nonstatic data
4793 // member of the constructor's class or a direct or virtual base
4794 // of that class, the mem-initializer is ill-formed. A
4795 // mem-initializer-list can initialize a base class using any
4796 // name that denotes that base class type.
4797
4798 // We can store the initializers in "as-written" form and delay analysis until
4799 // instantiation if the constructor is dependent. But not for dependent
4800 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4801 bool Dependent = CurContext->isDependentContext() &&
4802 (BaseType->isDependentType() || Init->isTypeDependent());
4803
4804 SourceRange InitRange = Init->getSourceRange();
4805 if (EllipsisLoc.isValid()) {
4806 // This is a pack expansion.
4807 if (!BaseType->containsUnexpandedParameterPack()) {
4808 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4809 << SourceRange(BaseLoc, InitRange.getEnd());
4810
4811 EllipsisLoc = SourceLocation();
4812 }
4813 } else {
4814 // Check for any unexpanded parameter packs.
4815 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4816 return true;
4817
4819 return true;
4820 }
4821
4822 // Check for direct and virtual base classes.
4823 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4824 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4825 if (!Dependent) {
4826 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4827 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4828
4829 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4830 VirtualBaseSpec);
4831
4832 // C++ [base.class.init]p2:
4833 // Unless the mem-initializer-id names a nonstatic data member of the
4834 // constructor's class or a direct or virtual base of that class, the
4835 // mem-initializer is ill-formed.
4836 if (!DirectBaseSpec && !VirtualBaseSpec) {
4837 // If the class has any dependent bases, then it's possible that
4838 // one of those types will resolve to the same type as
4839 // BaseType. Therefore, just treat this as a dependent base
4840 // class initialization. FIXME: Should we try to check the
4841 // initialization anyway? It seems odd.
4842 if (ClassDecl->hasAnyDependentBases())
4843 Dependent = true;
4844 else
4845 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4846 << BaseType << Context.getCanonicalTagType(ClassDecl)
4847 << BaseTInfo->getTypeLoc().getSourceRange();
4848 }
4849 }
4850
4851 if (Dependent) {
4853
4854 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4855 /*IsVirtual=*/false,
4856 InitRange.getBegin(), Init,
4857 InitRange.getEnd(), EllipsisLoc);
4858 }
4859
4860 // C++ [base.class.init]p2:
4861 // If a mem-initializer-id is ambiguous because it designates both
4862 // a direct non-virtual base class and an inherited virtual base
4863 // class, the mem-initializer is ill-formed.
4864 if (DirectBaseSpec && VirtualBaseSpec)
4865 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4866 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4867
4868 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4869 if (!BaseSpec)
4870 BaseSpec = VirtualBaseSpec;
4871
4872 // Initialize the base.
4873 bool InitList = true;
4874 MultiExprArg Args = Init;
4875 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4876 InitList = false;
4877 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4878 }
4879
4880 InitializedEntity BaseEntity =
4881 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4882 InitializationKind Kind =
4883 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4884 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4885 InitRange.getEnd());
4886 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4887 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4888 if (!BaseInit.isInvalid()) {
4889 // C++11 [class.base.init]p7:
4890 // The initialization of each base and member constitutes a
4891 // full-expression.
4892 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4893 /*DiscardedValue*/ false);
4894 }
4895
4896 if (BaseInit.isInvalid()) {
4897 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4898 Args, BaseType);
4899 if (BaseInit.isInvalid())
4900 return true;
4901 } else {
4902 // If we are in a dependent context, template instantiation will
4903 // perform this type-checking again. Just save the arguments that we
4904 // received in a ParenListExpr.
4905 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4906 // of the information that we have about the base
4907 // initializer. However, deconstructing the ASTs is a dicey process,
4908 // and this approach is far more likely to get the corner cases right.
4909 if (CurContext->isDependentContext())
4910 BaseInit = Init;
4911 }
4912
4913 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4914 BaseSpec->isVirtual(),
4915 InitRange.getBegin(),
4916 BaseInit.getAs<Expr>(),
4917 InitRange.getEnd(), EllipsisLoc);
4918}
4919
4920// Create a static_cast<T&&>(expr).
4921static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4922 QualType TargetType =
4923 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4925 SourceLocation ExprLoc = E->getBeginLoc();
4926 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4927 TargetType, ExprLoc);
4928
4929 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4930 SourceRange(ExprLoc, ExprLoc),
4931 E->getSourceRange()).get();
4932}
4933
4934/// ImplicitInitializerKind - How an implicit base or member initializer should
4935/// initialize its base or member.
4942
4943static bool
4945 ImplicitInitializerKind ImplicitInitKind,
4946 CXXBaseSpecifier *BaseSpec,
4947 bool IsInheritedVirtualBase,
4948 CXXCtorInitializer *&CXXBaseInit) {
4949 InitializedEntity InitEntity
4950 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4951 IsInheritedVirtualBase);
4952
4953 ExprResult BaseInit;
4954
4955 switch (ImplicitInitKind) {
4956 case IIK_Inherit:
4957 case IIK_Default: {
4958 InitializationKind InitKind
4960 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4961 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4962 break;
4963 }
4964
4965 case IIK_Move:
4966 case IIK_Copy: {
4967 bool Moving = ImplicitInitKind == IIK_Move;
4968 ParmVarDecl *Param = Constructor->getParamDecl(0);
4969 QualType ParamType = Param->getType().getNonReferenceType();
4970
4971 Expr *CopyCtorArg =
4973 SourceLocation(), Param, false,
4974 Constructor->getLocation(), ParamType,
4975 VK_LValue, nullptr);
4976
4977 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4978
4979 // Cast to the base class to avoid ambiguities.
4980 QualType ArgTy =
4981 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4982 ParamType.getQualifiers());
4983
4984 if (Moving) {
4985 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4986 }
4987
4988 CXXCastPath BasePath;
4989 BasePath.push_back(BaseSpec);
4990 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4991 CK_UncheckedDerivedToBase,
4992 Moving ? VK_XValue : VK_LValue,
4993 &BasePath).get();
4994
4995 InitializationKind InitKind
4998 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4999 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5000 break;
5001 }
5002 }
5003
5004 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5005 if (BaseInit.isInvalid())
5006 return true;
5007
5008 CXXBaseInit =
5009 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5010 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5011 SourceLocation()),
5012 BaseSpec->isVirtual(),
5014 BaseInit.getAs<Expr>(),
5016 SourceLocation());
5017
5018 return false;
5019}
5020
5021static bool RefersToRValueRef(Expr *MemRef) {
5022 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5023 return Referenced->getType()->isRValueReferenceType();
5024}
5025
5026static bool
5028 ImplicitInitializerKind ImplicitInitKind,
5029 FieldDecl *Field, IndirectFieldDecl *Indirect,
5030 CXXCtorInitializer *&CXXMemberInit) {
5031 if (Field->isInvalidDecl())
5032 return true;
5033
5034 SourceLocation Loc = Constructor->getLocation();
5035
5036 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5037 bool Moving = ImplicitInitKind == IIK_Move;
5038 ParmVarDecl *Param = Constructor->getParamDecl(0);
5039 QualType ParamType = Param->getType().getNonReferenceType();
5040
5041 // Suppress copying zero-width bitfields.
5042 if (Field->isZeroLengthBitField())
5043 return false;
5044
5045 Expr *MemberExprBase =
5047 SourceLocation(), Param, false,
5048 Loc, ParamType, VK_LValue, nullptr);
5049
5050 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5051
5052 if (Moving) {
5053 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5054 }
5055
5056 // Build a reference to this field within the parameter.
5057 CXXScopeSpec SS;
5058 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5060 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5061 : cast<ValueDecl>(Field), AS_public);
5062 MemberLookup.resolveKind();
5063 ExprResult CtorArg
5064 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5065 ParamType, Loc,
5066 /*IsArrow=*/false,
5067 SS,
5068 /*TemplateKWLoc=*/SourceLocation(),
5069 /*FirstQualifierInScope=*/nullptr,
5070 MemberLookup,
5071 /*TemplateArgs=*/nullptr,
5072 /*S*/nullptr);
5073 if (CtorArg.isInvalid())
5074 return true;
5075
5076 // C++11 [class.copy]p15:
5077 // - if a member m has rvalue reference type T&&, it is direct-initialized
5078 // with static_cast<T&&>(x.m);
5079 if (RefersToRValueRef(CtorArg.get())) {
5080 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5081 }
5082
5083 InitializedEntity Entity =
5086
5087 // Direct-initialize to use the copy constructor.
5088 InitializationKind InitKind =
5090
5091 Expr *CtorArgE = CtorArg.getAs<Expr>();
5092 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5093 ExprResult MemberInit =
5094 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5095 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5096 if (MemberInit.isInvalid())
5097 return true;
5098
5099 if (Indirect)
5100 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5101 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5102 else
5103 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5104 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5105 return false;
5106 }
5107
5108 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5109 "Unhandled implicit init kind!");
5110
5111 QualType FieldBaseElementType =
5112 SemaRef.Context.getBaseElementType(Field->getType());
5113
5114 if (FieldBaseElementType->isRecordType()) {
5115 InitializedEntity InitEntity =
5118 InitializationKind InitKind =
5120
5121 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5122 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5123
5124 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5125 if (MemberInit.isInvalid())
5126 return true;
5127
5128 if (Indirect)
5129 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5130 Indirect, Loc,
5131 Loc,
5132 MemberInit.get(),
5133 Loc);
5134 else
5135 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5136 Field, Loc, Loc,
5137 MemberInit.get(),
5138 Loc);
5139 return false;
5140 }
5141
5142 if (!Field->getParent()->isUnion()) {
5143 if (FieldBaseElementType->isReferenceType()) {
5144 SemaRef.Diag(Constructor->getLocation(),
5145 diag::err_uninitialized_member_in_ctor)
5146 << (int)Constructor->isImplicit()
5147 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5148 << Field->getDeclName();
5149 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5150 return true;
5151 }
5152
5153 if (FieldBaseElementType.isConstQualified()) {
5154 SemaRef.Diag(Constructor->getLocation(),
5155 diag::err_uninitialized_member_in_ctor)
5156 << (int)Constructor->isImplicit()
5157 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5158 << Field->getDeclName();
5159 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5160 return true;
5161 }
5162 }
5163
5164 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5165 // ARC and Weak:
5166 // Default-initialize Objective-C pointers to NULL.
5167 CXXMemberInit
5168 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5169 Loc, Loc,
5170 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5171 Loc);
5172 return false;
5173 }
5174
5175 // Nothing to initialize.
5176 CXXMemberInit = nullptr;
5177 return false;
5178}
5179
5180namespace {
5181struct BaseAndFieldInfo {
5182 Sema &S;
5183 CXXConstructorDecl *Ctor;
5184 bool AnyErrorsInInits;
5186 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5187 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5188 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5189
5190 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5191 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5192 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5193 if (Ctor->getInheritedConstructor())
5194 IIK = IIK_Inherit;
5195 else if (Generated && Ctor->isCopyConstructor())
5196 IIK = IIK_Copy;
5197 else if (Generated && Ctor->isMoveConstructor())
5198 IIK = IIK_Move;
5199 else
5200 IIK = IIK_Default;
5201 }
5202
5203 bool isImplicitCopyOrMove() const {
5204 switch (IIK) {
5205 case IIK_Copy:
5206 case IIK_Move:
5207 return true;
5208
5209 case IIK_Default:
5210 case IIK_Inherit:
5211 return false;
5212 }
5213
5214 llvm_unreachable("Invalid ImplicitInitializerKind!");
5215 }
5216
5217 bool addFieldInitializer(CXXCtorInitializer *Init) {
5218 AllToInit.push_back(Init);
5219
5220 // Check whether this initializer makes the field "used".
5221 if (Init->getInit()->HasSideEffects(S.Context))
5222 S.UnusedPrivateFields.remove(Init->getAnyMember());
5223
5224 return false;
5225 }
5226
5227 bool isInactiveUnionMember(FieldDecl *Field) {
5228 RecordDecl *Record = Field->getParent();
5229 if (!Record->isUnion())
5230 return false;
5231
5232 if (FieldDecl *Active =
5233 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5234 return Active != Field->getCanonicalDecl();
5235
5236 // In an implicit copy or move constructor, ignore any in-class initializer.
5237 if (isImplicitCopyOrMove())
5238 return true;
5239
5240 // If there's no explicit initialization, the field is active only if it
5241 // has an in-class initializer...
5242 if (Field->hasInClassInitializer())
5243 return false;
5244 // ... or it's an anonymous struct or union whose class has an in-class
5245 // initializer.
5246 if (!Field->isAnonymousStructOrUnion())
5247 return true;
5248 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5249 return !FieldRD->hasInClassInitializer();
5250 }
5251
5252 /// Determine whether the given field is, or is within, a union member
5253 /// that is inactive (because there was an initializer given for a different
5254 /// member of the union, or because the union was not initialized at all).
5255 bool isWithinInactiveUnionMember(FieldDecl *Field,
5256 IndirectFieldDecl *Indirect) {
5257 if (!Indirect)
5258 return isInactiveUnionMember(Field);
5259
5260 for (auto *C : Indirect->chain()) {
5261 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5262 if (Field && isInactiveUnionMember(Field))
5263 return true;
5264 }
5265 return false;
5266 }
5267};
5268}
5269
5270/// Determine whether the given type is an incomplete or zero-lenfgth
5271/// array type.
5273 if (T->isIncompleteArrayType())
5274 return true;
5275
5276 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5277 if (ArrayT->isZeroSize())
5278 return true;
5279
5280 T = ArrayT->getElementType();
5281 }
5282
5283 return false;
5284}
5285
5286static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5287 FieldDecl *Field,
5288 IndirectFieldDecl *Indirect = nullptr) {
5289 if (Field->isInvalidDecl())
5290 return false;
5291
5292 // Overwhelmingly common case: we have a direct initializer for this field.
5294 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5295 return Info.addFieldInitializer(Init);
5296
5297 // C++11 [class.base.init]p8:
5298 // if the entity is a non-static data member that has a
5299 // brace-or-equal-initializer and either
5300 // -- the constructor's class is a union and no other variant member of that
5301 // union is designated by a mem-initializer-id or
5302 // -- the constructor's class is not a union, and, if the entity is a member
5303 // of an anonymous union, no other member of that union is designated by
5304 // a mem-initializer-id,
5305 // the entity is initialized as specified in [dcl.init].
5306 //
5307 // We also apply the same rules to handle anonymous structs within anonymous
5308 // unions.
5309 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5310 return false;
5311
5312 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5313 ExprResult DIE =
5314 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5315 if (DIE.isInvalid())
5316 return true;
5317
5319 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5320
5322 if (Indirect)
5323 Init = new (SemaRef.Context)
5324 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5325 SourceLocation(), DIE.get(), SourceLocation());
5326 else
5327 Init = new (SemaRef.Context)
5328 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5329 SourceLocation(), DIE.get(), SourceLocation());
5330 return Info.addFieldInitializer(Init);
5331 }
5332
5333 // Don't initialize incomplete or zero-length arrays.
5334 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5335 return false;
5336
5337 // Don't try to build an implicit initializer if there were semantic
5338 // errors in any of the initializers (and therefore we might be
5339 // missing some that the user actually wrote).
5340 if (Info.AnyErrorsInInits)
5341 return false;
5342
5343 CXXCtorInitializer *Init = nullptr;
5344 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5345 Indirect, Init))
5346 return true;
5347
5348 if (!Init)
5349 return false;
5350
5351 return Info.addFieldInitializer(Init);
5352}
5353
5354bool
5357 assert(Initializer->isDelegatingInitializer());
5358 Constructor->setNumCtorInitializers(1);
5359 CXXCtorInitializer **initializer =
5360 new (Context) CXXCtorInitializer*[1];
5361 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5362 Constructor->setCtorInitializers(initializer);
5363
5364 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5365 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5366 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5367 }
5368
5370
5371 DiagnoseUninitializedFields(*this, Constructor);
5372
5373 return false;
5374}
5375
5377 CXXRecordDecl *Class) {
5378 if (Class->isInvalidDecl())
5379 return nullptr;
5380 if (Class->hasIrrelevantDestructor())
5381 return nullptr;
5382
5383 // Dtor might still be missing, e.g because it's invalid.
5384 return S.LookupDestructor(Class);
5385}
5386
5388 FieldDecl *Field) {
5389 if (Field->isInvalidDecl())
5390 return;
5391
5392 // Don't destroy incomplete or zero-length arrays.
5393 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5394 return;
5395
5396 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5397
5398 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5399 if (!FieldClassDecl)
5400 return;
5401
5402 // The destructor for an implicit anonymous union member is never invoked.
5403 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5404 return;
5405
5406 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5407 if (!Dtor)
5408 return;
5409
5410 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5411 S.PDiag(diag::err_access_dtor_field)
5412 << Field->getDeclName() << FieldType);
5413
5414 S.MarkFunctionReferenced(Location, Dtor);
5415 S.DiagnoseUseOfDecl(Dtor, Location);
5416}
5417
5419 CXXRecordDecl *ClassDecl) {
5420 if (ClassDecl->isDependentContext())
5421 return;
5422
5423 // We only potentially invoke the destructors of potentially constructed
5424 // subobjects.
5425 bool VisitVirtualBases = !ClassDecl->isAbstract();
5426
5427 // If the destructor exists and has already been marked used in the MS ABI,
5428 // then virtual base destructors have already been checked and marked used.
5429 // Skip checking them again to avoid duplicate diagnostics.
5431 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5432 if (Dtor && Dtor->isUsed())
5433 VisitVirtualBases = false;
5434 }
5435
5437
5438 // Bases.
5439 for (const auto &Base : ClassDecl->bases()) {
5440 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5441 if (!BaseClassDecl)
5442 continue;
5443
5444 // Remember direct virtual bases.
5445 if (Base.isVirtual()) {
5446 if (!VisitVirtualBases)
5447 continue;
5448 DirectVirtualBases.insert(BaseClassDecl);
5449 }
5450
5451 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5452 if (!Dtor)
5453 continue;
5454
5455 // FIXME: caret should be on the start of the class name
5456 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5457 S.PDiag(diag::err_access_dtor_base)
5458 << Base.getType() << Base.getSourceRange(),
5459 S.Context.getCanonicalTagType(ClassDecl));
5460
5461 S.MarkFunctionReferenced(Location, Dtor);
5462 S.DiagnoseUseOfDecl(Dtor, Location);
5463 }
5464
5465 if (VisitVirtualBases)
5466 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5467 &DirectVirtualBases);
5468}
5469
5471 ArrayRef<CXXCtorInitializer *> Initializers) {
5472 if (Constructor->isDependentContext()) {
5473 // Just store the initializers as written, they will be checked during
5474 // instantiation.
5475 if (!Initializers.empty()) {
5476 Constructor->setNumCtorInitializers(Initializers.size());
5477 CXXCtorInitializer **baseOrMemberInitializers =
5478 new (Context) CXXCtorInitializer*[Initializers.size()];
5479 memcpy(baseOrMemberInitializers, Initializers.data(),
5480 Initializers.size() * sizeof(CXXCtorInitializer*));
5481 Constructor->setCtorInitializers(baseOrMemberInitializers);
5482 }
5483
5484 // Let template instantiation know whether we had errors.
5485 if (AnyErrors)
5486 Constructor->setInvalidDecl();
5487
5488 return false;
5489 }
5490
5491 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5492
5493 // We need to build the initializer AST according to order of construction
5494 // and not what user specified in the Initializers list.
5495 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5496 if (!ClassDecl)
5497 return true;
5498
5499 bool HadError = false;
5500
5501 for (CXXCtorInitializer *Member : Initializers) {
5502 if (Member->isBaseInitializer())
5503 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5504 Member;
5505 else {
5506 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5507
5508 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5509 for (auto *C : F->chain()) {
5510 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5511 if (FD && FD->getParent()->isUnion())
5512 Info.ActiveUnionMember.insert(std::make_pair(
5514 }
5515 } else if (FieldDecl *FD = Member->getMember()) {
5516 if (FD->getParent()->isUnion())
5517 Info.ActiveUnionMember.insert(std::make_pair(
5519 }
5520 }
5521 }
5522
5523 // Keep track of the direct virtual bases.
5525 for (auto &I : ClassDecl->bases()) {
5526 if (I.isVirtual())
5527 DirectVBases.insert(&I);
5528 }
5529
5530 // Push virtual bases before others.
5531 for (auto &VBase : ClassDecl->vbases()) {
5532 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5533 VBase.getType()->getAsCanonical<RecordType>())) {
5534 // [class.base.init]p7, per DR257:
5535 // A mem-initializer where the mem-initializer-id names a virtual base
5536 // class is ignored during execution of a constructor of any class that
5537 // is not the most derived class.
5538 if (ClassDecl->isAbstract()) {
5539 // FIXME: Provide a fixit to remove the base specifier. This requires
5540 // tracking the location of the associated comma for a base specifier.
5541 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5542 << VBase.getType() << ClassDecl;
5543 DiagnoseAbstractType(ClassDecl);
5544 }
5545
5546 Info.AllToInit.push_back(Value);
5547 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5548 // [class.base.init]p8, per DR257:
5549 // If a given [...] base class is not named by a mem-initializer-id
5550 // [...] and the entity is not a virtual base class of an abstract
5551 // class, then [...] the entity is default-initialized.
5552 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5553 CXXCtorInitializer *CXXBaseInit;
5554 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5555 &VBase, IsInheritedVirtualBase,
5556 CXXBaseInit)) {
5557 HadError = true;
5558 continue;
5559 }
5560
5561 Info.AllToInit.push_back(CXXBaseInit);
5562 }
5563 }
5564
5565 // Non-virtual bases.
5566 for (auto &Base : ClassDecl->bases()) {
5567 // Virtuals are in the virtual base list and already constructed.
5568 if (Base.isVirtual())
5569 continue;
5570
5571 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5572 Base.getType()->getAsCanonical<RecordType>())) {
5573 Info.AllToInit.push_back(Value);
5574 } else if (!AnyErrors) {
5575 CXXCtorInitializer *CXXBaseInit;
5576 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5577 &Base, /*IsInheritedVirtualBase=*/false,
5578 CXXBaseInit)) {
5579 HadError = true;
5580 continue;
5581 }
5582
5583 Info.AllToInit.push_back(CXXBaseInit);
5584 }
5585 }
5586
5587 // Fields.
5588 for (auto *Mem : ClassDecl->decls()) {
5589 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5590 // C++ [class.bit]p2:
5591 // A declaration for a bit-field that omits the identifier declares an
5592 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5593 // initialized.
5594 if (F->isUnnamedBitField())
5595 continue;
5596
5597 // If we're not generating the implicit copy/move constructor, then we'll
5598 // handle anonymous struct/union fields based on their individual
5599 // indirect fields.
5600 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5601 continue;
5602
5603 if (CollectFieldInitializer(*this, Info, F))
5604 HadError = true;
5605 continue;
5606 }
5607
5608 // Beyond this point, we only consider default initialization.
5609 if (Info.isImplicitCopyOrMove())
5610 continue;
5611
5612 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5613 if (F->getType()->isIncompleteArrayType()) {
5614 assert(ClassDecl->hasFlexibleArrayMember() &&
5615 "Incomplete array type is not valid");
5616 continue;
5617 }
5618
5619 // Initialize each field of an anonymous struct individually.
5620 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5621 HadError = true;
5622
5623 continue;
5624 }
5625 }
5626
5627 unsigned NumInitializers = Info.AllToInit.size();
5628 if (NumInitializers > 0) {
5629 Constructor->setNumCtorInitializers(NumInitializers);
5630 CXXCtorInitializer **baseOrMemberInitializers =
5631 new (Context) CXXCtorInitializer*[NumInitializers];
5632 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5633 NumInitializers * sizeof(CXXCtorInitializer*));
5634 Constructor->setCtorInitializers(baseOrMemberInitializers);
5635
5636 SourceLocation Location = Constructor->getLocation();
5637
5638 // Constructors implicitly reference the base and member
5639 // destructors.
5640
5641 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5642 FieldDecl *Field = Initializer->getAnyMember();
5643 if (!Field)
5644 continue;
5645
5646 // C++ [class.base.init]p12:
5647 // In a non-delegating constructor, the destructor for each
5648 // potentially constructed subobject of class type is potentially
5649 // invoked.
5650 MarkFieldDestructorReferenced(*this, Location, Field);
5651 }
5652
5653 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5654 }
5655
5656 return HadError;
5657}
5658
5660 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5661 const RecordDecl *RD = RT->getDecl();
5662 if (RD->isAnonymousStructOrUnion()) {
5663 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5664 PopulateKeysForFields(Field, IdealInits);
5665 return;
5666 }
5667 }
5668 IdealInits.push_back(Field->getCanonicalDecl());
5669}
5670
5671static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5672 return Context.getCanonicalType(BaseType).getTypePtr();
5673}
5674
5675static const void *GetKeyForMember(ASTContext &Context,
5677 if (!Member->isAnyMemberInitializer())
5678 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5679
5680 return Member->getAnyMember()->getCanonicalDecl();
5681}
5682
5685 const CXXCtorInitializer *Current) {
5686 if (Previous->isAnyMemberInitializer())
5687 Diag << 0 << Previous->getAnyMember();
5688 else
5689 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5690
5691 if (Current->isAnyMemberInitializer())
5692 Diag << 0 << Current->getAnyMember();
5693 else
5694 Diag << 1 << Current->getTypeSourceInfo()->getType();
5695}
5696
5698 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5700 if (Constructor->getDeclContext()->isDependentContext())
5701 return;
5702
5703 // Don't check initializers order unless the warning is enabled at the
5704 // location of at least one initializer.
5705 bool ShouldCheckOrder = false;
5706 for (const CXXCtorInitializer *Init : Inits) {
5707 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5708 Init->getSourceLocation())) {
5709 ShouldCheckOrder = true;
5710 break;
5711 }
5712 }
5713 if (!ShouldCheckOrder)
5714 return;
5715
5716 // Build the list of bases and members in the order that they'll
5717 // actually be initialized. The explicit initializers should be in
5718 // this same order but may be missing things.
5719 SmallVector<const void*, 32> IdealInitKeys;
5720
5721 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5722
5723 // 1. Virtual bases.
5724 for (const auto &VBase : ClassDecl->vbases())
5725 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5726
5727 // 2. Non-virtual bases.
5728 for (const auto &Base : ClassDecl->bases()) {
5729 if (Base.isVirtual())
5730 continue;
5731 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5732 }
5733
5734 // 3. Direct fields.
5735 for (auto *Field : ClassDecl->fields()) {
5736 if (Field->isUnnamedBitField())
5737 continue;
5738
5739 PopulateKeysForFields(Field, IdealInitKeys);
5740 }
5741
5742 unsigned NumIdealInits = IdealInitKeys.size();
5743 unsigned IdealIndex = 0;
5744
5745 // Track initializers that are in an incorrect order for either a warning or
5746 // note if multiple ones occur.
5747 SmallVector<unsigned> WarnIndexes;
5748 // Correlates the index of an initializer in the init-list to the index of
5749 // the field/base in the class.
5750 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5751
5752 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5753 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5754
5755 // Scan forward to try to find this initializer in the idealized
5756 // initializers list.
5757 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5758 if (InitKey == IdealInitKeys[IdealIndex])
5759 break;
5760
5761 // If we didn't find this initializer, it must be because we
5762 // scanned past it on a previous iteration. That can only
5763 // happen if we're out of order; emit a warning.
5764 if (IdealIndex == NumIdealInits && InitIndex) {
5765 WarnIndexes.push_back(InitIndex);
5766
5767 // Move back to the initializer's location in the ideal list.
5768 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5769 if (InitKey == IdealInitKeys[IdealIndex])
5770 break;
5771
5772 assert(IdealIndex < NumIdealInits &&
5773 "initializer not found in initializer list");
5774 }
5775 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5776 }
5777
5778 if (WarnIndexes.empty())
5779 return;
5780
5781 // Sort based on the ideal order, first in the pair.
5782 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5783
5784 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5785 // emit the diagnostic before we can try adding notes.
5786 {
5788 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5789 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5790 : diag::warn_some_initializers_out_of_order);
5791
5792 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5793 if (CorrelatedInitOrder[I].second == I)
5794 continue;
5795 // Ideally we would be using InsertFromRange here, but clang doesn't
5796 // appear to handle InsertFromRange correctly when the source range is
5797 // modified by another fix-it.
5799 Inits[I]->getSourceRange(),
5802 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5803 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5804 }
5805
5806 // If there is only 1 item out of order, the warning expects the name and
5807 // type of each being added to it.
5808 if (WarnIndexes.size() == 1) {
5809 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5810 Inits[WarnIndexes.front()]);
5811 return;
5812 }
5813 }
5814 // More than 1 item to warn, create notes letting the user know which ones
5815 // are bad.
5816 for (unsigned WarnIndex : WarnIndexes) {
5817 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5818 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5819 diag::note_initializer_out_of_order);
5820 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5821 D << PrevInit->getSourceRange();
5822 }
5823}
5824
5825namespace {
5826bool CheckRedundantInit(Sema &S,
5827 CXXCtorInitializer *Init,
5828 CXXCtorInitializer *&PrevInit) {
5829 if (!PrevInit) {
5830 PrevInit = Init;
5831 return false;
5832 }
5833
5834 if (FieldDecl *Field = Init->getAnyMember())
5835 S.Diag(Init->getSourceLocation(),
5836 diag::err_multiple_mem_initialization)
5837 << Field->getDeclName()
5838 << Init->getSourceRange();
5839 else {
5840 const Type *BaseClass = Init->getBaseClass();
5841 assert(BaseClass && "neither field nor base");
5842 S.Diag(Init->getSourceLocation(),
5843 diag::err_multiple_base_initialization)
5844 << QualType(BaseClass, 0)
5845 << Init->getSourceRange();
5846 }
5847 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5848 << 0 << PrevInit->getSourceRange();
5849
5850 return true;
5851}
5852
5853typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5854typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5855
5856bool CheckRedundantUnionInit(Sema &S,
5857 CXXCtorInitializer *Init,
5858 RedundantUnionMap &Unions) {
5859 FieldDecl *Field = Init->getAnyMember();
5860 RecordDecl *Parent = Field->getParent();
5861 NamedDecl *Child = Field;
5862
5863 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5864 if (Parent->isUnion()) {
5865 UnionEntry &En = Unions[Parent];
5866 if (En.first && En.first != Child) {
5867 S.Diag(Init->getSourceLocation(),
5868 diag::err_multiple_mem_union_initialization)
5869 << Field->getDeclName()
5870 << Init->getSourceRange();
5871 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5872 << 0 << En.second->getSourceRange();
5873 return true;
5874 }
5875 if (!En.first) {
5876 En.first = Child;
5877 En.second = Init;
5878 }
5879 if (!Parent->isAnonymousStructOrUnion())
5880 return false;
5881 }
5882
5883 Child = Parent;
5884 Parent = cast<RecordDecl>(Parent->getDeclContext());
5885 }
5886
5887 return false;
5888}
5889} // namespace
5890
5891void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5892 SourceLocation ColonLoc,
5894 bool AnyErrors) {
5895 if (!ConstructorDecl)
5896 return;
5897
5898 AdjustDeclIfTemplate(ConstructorDecl);
5899
5901 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5902
5903 if (!Constructor) {
5904 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5905 return;
5906 }
5907
5908 // Mapping for the duplicate initializers check.
5909 // For member initializers, this is keyed with a FieldDecl*.
5910 // For base initializers, this is keyed with a Type*.
5911 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5912
5913 // Mapping for the inconsistent anonymous-union initializers check.
5914 RedundantUnionMap MemberUnions;
5915
5916 bool HadError = false;
5917 for (unsigned i = 0; i < MemInits.size(); i++) {
5918 CXXCtorInitializer *Init = MemInits[i];
5919
5920 // Set the source order index.
5921 Init->setSourceOrder(i);
5922
5923 if (Init->isAnyMemberInitializer()) {
5924 const void *Key = GetKeyForMember(Context, Init);
5925 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5926 CheckRedundantUnionInit(*this, Init, MemberUnions))
5927 HadError = true;
5928 } else if (Init->isBaseInitializer()) {
5929 const void *Key = GetKeyForMember(Context, Init);
5930 if (CheckRedundantInit(*this, Init, Members[Key]))
5931 HadError = true;
5932 } else {
5933 assert(Init->isDelegatingInitializer());
5934 // This must be the only initializer
5935 if (MemInits.size() != 1) {
5936 Diag(Init->getSourceLocation(),
5937 diag::err_delegating_initializer_alone)
5938 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5939 // We will treat this as being the only initializer.
5940 }
5942 // Return immediately as the initializer is set.
5943 return;
5944 }
5945 }
5946
5947 if (HadError)
5948 return;
5949
5951
5952 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5953
5954 DiagnoseUninitializedFields(*this, Constructor);
5955}
5956
5958 CXXRecordDecl *ClassDecl) {
5959 // Ignore dependent contexts. Also ignore unions, since their members never
5960 // have destructors implicitly called.
5961 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5962 return;
5963
5964 // FIXME: all the access-control diagnostics are positioned on the
5965 // field/base declaration. That's probably good; that said, the
5966 // user might reasonably want to know why the destructor is being
5967 // emitted, and we currently don't say.
5968
5969 // Non-static data members.
5970 for (auto *Field : ClassDecl->fields()) {
5971 MarkFieldDestructorReferenced(*this, Location, Field);
5972 }
5973
5974 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5975}
5976
5978 SourceLocation Location, CXXRecordDecl *ClassDecl,
5979 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5980 // Virtual bases.
5981 for (const auto &VBase : ClassDecl->vbases()) {
5982 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5983 if (!BaseClassDecl)
5984 continue;
5985
5986 // Ignore already visited direct virtual bases.
5987 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
5988 continue;
5989
5990 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
5991 if (!Dtor)
5992 continue;
5993
5994 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
5995 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
5996 PDiag(diag::err_access_dtor_vbase)
5997 << CT << VBase.getType(),
5998 CT) == AR_accessible) {
6000 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6001 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6002 }
6003
6004 MarkFunctionReferenced(Location, Dtor);
6005 DiagnoseUseOfDecl(Dtor, Location);
6006 }
6007}
6008
6010 if (!CDtorDecl)
6011 return;
6012
6014 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6015 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6016 !ClassDecl || ClassDecl->isInvalidDecl()) {
6017 return;
6018 }
6019 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6020 DiagnoseUninitializedFields(*this, Constructor);
6021 }
6022}
6023
6025 if (!getLangOpts().CPlusPlus)
6026 return false;
6027
6028 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6029 if (!RD)
6030 return false;
6031
6032 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6033 // class template specialization here, but doing so breaks a lot of code.
6034
6035 // We can't answer whether something is abstract until it has a
6036 // definition. If it's currently being defined, we'll walk back
6037 // over all the declarations when we have a full definition.
6038 const CXXRecordDecl *Def = RD->getDefinition();
6039 if (!Def || Def->isBeingDefined())
6040 return false;
6041
6042 return RD->isAbstract();
6043}
6044
6046 TypeDiagnoser &Diagnoser) {
6047 if (!isAbstractType(Loc, T))
6048 return false;
6049
6050 T = Context.getBaseElementType(T);
6051 Diagnoser.diagnose(*this, Loc, T);
6052 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6053 return true;
6054}
6055
6057 // Check if we've already emitted the list of pure virtual functions
6058 // for this class.
6060 return;
6061
6062 // If the diagnostic is suppressed, don't emit the notes. We're only
6063 // going to emit them once, so try to attach them to a diagnostic we're
6064 // actually going to show.
6065 if (Diags.isLastDiagnosticIgnored())
6066 return;
6067
6068 CXXFinalOverriderMap FinalOverriders;
6069 RD->getFinalOverriders(FinalOverriders);
6070
6071 // Keep a set of seen pure methods so we won't diagnose the same method
6072 // more than once.
6074
6075 for (const auto &M : FinalOverriders) {
6076 for (const auto &SO : M.second) {
6077 // C++ [class.abstract]p4:
6078 // A class is abstract if it contains or inherits at least one
6079 // pure virtual function for which the final overrider is pure
6080 // virtual.
6081
6082 if (SO.second.size() != 1)
6083 continue;
6084 const CXXMethodDecl *Method = SO.second.front().Method;
6085
6086 if (!Method->isPureVirtual())
6087 continue;
6088
6089 if (!SeenPureMethods.insert(Method).second)
6090 continue;
6091
6092 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6093 << Method->getDeclName() << RD->getDeclName();
6094 }
6095 }
6096
6099 PureVirtualClassDiagSet->insert(RD);
6100}
6101
6102namespace {
6103struct AbstractUsageInfo {
6104 Sema &S;
6106 CanQualType AbstractType;
6107 bool Invalid;
6108
6109 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6110 : S(S), Record(Record),
6111 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6112
6113 void DiagnoseAbstractType() {
6114 if (Invalid) return;
6116 Invalid = true;
6117 }
6118
6119 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6120};
6121
6122struct CheckAbstractUsage {
6123 AbstractUsageInfo &Info;
6124 const NamedDecl *Ctx;
6125
6126 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6127 : Info(Info), Ctx(Ctx) {}
6128
6129 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6130 switch (TL.getTypeLocClass()) {
6131#define ABSTRACT_TYPELOC(CLASS, PARENT)
6132#define TYPELOC(CLASS, PARENT) \
6133 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6134#include "clang/AST/TypeLocNodes.def"
6135 }
6136 }
6137
6138 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6140 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6141 if (!TL.getParam(I))
6142 continue;
6143
6144 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6145 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6146 }
6147 }
6148
6149 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6151 }
6152
6153 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6154 // Visit the type parameters from a permissive context.
6155 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6156 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6158 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6159 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6160 // TODO: other template argument types?
6161 }
6162 }
6163
6164 // Visit pointee types from a permissive context.
6165#define CheckPolymorphic(Type) \
6166 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6167 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6168 }
6174
6175 /// Handle all the types we haven't given a more specific
6176 /// implementation for above.
6177 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6178 // Every other kind of type that we haven't called out already
6179 // that has an inner type is either (1) sugar or (2) contains that
6180 // inner type in some way as a subobject.
6181 if (TypeLoc Next = TL.getNextTypeLoc())
6182 return Visit(Next, Sel);
6183
6184 // If there's no inner type and we're in a permissive context,
6185 // don't diagnose.
6186 if (Sel == Sema::AbstractNone) return;
6187
6188 // Check whether the type matches the abstract type.
6189 QualType T = TL.getType();
6190 if (T->isArrayType()) {
6192 T = Info.S.Context.getBaseElementType(T);
6193 }
6194 CanQualType CT = T->getCanonicalTypeUnqualified();
6195 if (CT != Info.AbstractType) return;
6196
6197 // It matched; do some magic.
6198 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6199 if (Sel == Sema::AbstractArrayType) {
6200 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6201 << T << TL.getSourceRange();
6202 } else {
6203 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6204 << Sel << T << TL.getSourceRange();
6205 }
6206 Info.DiagnoseAbstractType();
6207 }
6208};
6209
6210void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6212 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6213}
6214
6215}
6216
6217/// Check for invalid uses of an abstract type in a function declaration.
6218static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6219 FunctionDecl *FD) {
6220 // Only definitions are required to refer to complete and
6221 // non-abstract types.
6223 return;
6224
6225 // For safety's sake, just ignore it if we don't have type source
6226 // information. This should never happen for non-implicit methods,
6227 // but...
6228 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6229 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6230}
6231
6232/// Check for invalid uses of an abstract type in a variable0 declaration.
6233static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6234 VarDecl *VD) {
6235 // No need to do the check on definitions, which require that
6236 // the type is complete.
6238 return;
6239
6240 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6242}
6243
6244/// Check for invalid uses of an abstract type within a class definition.
6245static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6246 CXXRecordDecl *RD) {
6247 for (auto *D : RD->decls()) {
6248 if (D->isImplicit()) continue;
6249
6250 // Step through friends to the befriended declaration.
6251 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6252 D = FD->getFriendDecl();
6253 if (!D) continue;
6254 }
6255
6256 // Functions and function templates.
6257 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6258 CheckAbstractClassUsage(Info, FD);
6259 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6260 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6261
6262 // Fields and static variables.
6263 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6264 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6265 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6266 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6267 CheckAbstractClassUsage(Info, VD);
6268 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6269 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6270
6271 // Nested classes and class templates.
6272 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6273 CheckAbstractClassUsage(Info, RD);
6274 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6275 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6276 }
6277 }
6278}
6279
6281 Attr *ClassAttr = getDLLAttr(Class);
6282 if (!ClassAttr)
6283 return;
6284
6285 assert(ClassAttr->getKind() == attr::DLLExport);
6286
6287 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6288
6290 // Don't go any further if this is just an explicit instantiation
6291 // declaration.
6292 return;
6293
6294 // Add a context note to explain how we got to any diagnostics produced below.
6295 struct MarkingClassDllexported {
6296 Sema &S;
6297 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6298 SourceLocation AttrLoc)
6299 : S(S) {
6302 Ctx.PointOfInstantiation = AttrLoc;
6303 Ctx.Entity = Class;
6305 }
6306 ~MarkingClassDllexported() {
6308 }
6309 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6310
6311 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6312 S.MarkVTableUsed(Class->getLocation(), Class, true);
6313
6314 for (Decl *Member : Class->decls()) {
6315 // Skip members that were not marked exported.
6316 if (!Member->hasAttr<DLLExportAttr>())
6317 continue;
6318
6319 // Defined static variables that are members of an exported base
6320 // class must be marked export too.
6321 auto *VD = dyn_cast<VarDecl>(Member);
6322 if (VD && VD->getStorageClass() == SC_Static &&
6324 S.MarkVariableReferenced(VD->getLocation(), VD);
6325
6326 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6327 if (!MD)
6328 continue;
6329
6330 if (MD->isUserProvided()) {
6331 // Instantiate non-default class member functions ...
6332
6333 // .. except for certain kinds of template specializations.
6334 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6335 continue;
6336
6337 // If this is an MS ABI dllexport default constructor, instantiate any
6338 // default arguments.
6340 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6341 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6343 CD->getAttr<DLLExportAttr>()->getLocation(), CD);
6344 }
6345 }
6346
6347 S.MarkFunctionReferenced(Class->getLocation(), MD);
6348
6349 // The function will be passed to the consumer when its definition is
6350 // encountered.
6351 } else if (MD->isExplicitlyDefaulted()) {
6352 // Synthesize and instantiate explicitly defaulted methods.
6353 S.MarkFunctionReferenced(Class->getLocation(), MD);
6354
6356 // Except for explicit instantiation defs, we will not see the
6357 // definition again later, so pass it to the consumer now.
6359 }
6360 } else if (!MD->isTrivial() ||
6361 MD->isCopyAssignmentOperator() ||
6362 MD->isMoveAssignmentOperator()) {
6363 // Synthesize and instantiate non-trivial implicit methods, and the copy
6364 // and move assignment operators. The latter are exported even if they
6365 // are trivial, because the address of an operator can be taken and
6366 // should compare equal across libraries.
6367 S.MarkFunctionReferenced(Class->getLocation(), MD);
6368
6369 // There is no later point when we will see the definition of this
6370 // function, so pass it to the consumer now.
6372 }
6373 }
6374}
6375
6377 CXXRecordDecl *Class) {
6378 // Only the MS ABI has default constructor closures, so we don't need to do
6379 // this semantic checking anywhere else.
6381 return;
6382
6383 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6384 for (Decl *Member : Class->decls()) {
6385 // Look for exported default constructors.
6386 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6387 if (!CD || !CD->isDefaultConstructor())
6388 continue;
6389 auto *Attr = CD->getAttr<DLLExportAttr>();
6390 if (!Attr)
6391 continue;
6392
6393 // If the class is non-dependent, mark the default arguments as ODR-used so
6394 // that we can properly codegen the constructor closure.
6395 if (!Class->isDependentContext()) {
6398 }
6399
6400 if (LastExportedDefaultCtor) {
6401 S.Diag(LastExportedDefaultCtor->getLocation(),
6402 diag::err_attribute_dll_ambiguous_default_ctor)
6403 << Class;
6404 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6405 << CD->getDeclName();
6406 return;
6407 }
6408 LastExportedDefaultCtor = CD;
6409 }
6410}
6411
6413 CXXRecordDecl *Class) {
6414 bool ErrorReported = false;
6415 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6416 ClassTemplateDecl *TD) {
6417 if (ErrorReported)
6418 return;
6419 S.Diag(TD->getLocation(),
6420 diag::err_cuda_device_builtin_surftex_cls_template)
6421 << /*surface*/ 0 << TD;
6422 ErrorReported = true;
6423 };
6424
6425 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6426 if (!TD) {
6427 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6428 if (!SD) {
6429 S.Diag(Class->getLocation(),
6430 diag::err_cuda_device_builtin_surftex_ref_decl)
6431 << /*surface*/ 0 << Class;
6432 S.Diag(Class->getLocation(),
6433 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6434 << Class;
6435 return;
6436 }
6437 TD = SD->getSpecializedTemplate();
6438 }
6439
6441 unsigned N = Params->size();
6442
6443 if (N != 2) {
6444 reportIllegalClassTemplate(S, TD);
6445 S.Diag(TD->getLocation(),
6446 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6447 << TD << 2;
6448 }
6449 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6450 reportIllegalClassTemplate(S, TD);
6451 S.Diag(TD->getLocation(),
6452 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6453 << TD << /*1st*/ 0 << /*type*/ 0;
6454 }
6455 if (N > 1) {
6456 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6457 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6458 reportIllegalClassTemplate(S, TD);
6459 S.Diag(TD->getLocation(),
6460 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6461 << TD << /*2nd*/ 1 << /*integer*/ 1;
6462 }
6463 }
6464}
6465
6467 CXXRecordDecl *Class) {
6468 bool ErrorReported = false;
6469 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6470 ClassTemplateDecl *TD) {
6471 if (ErrorReported)
6472 return;
6473 S.Diag(TD->getLocation(),
6474 diag::err_cuda_device_builtin_surftex_cls_template)
6475 << /*texture*/ 1 << TD;
6476 ErrorReported = true;
6477 };
6478
6479 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6480 if (!TD) {
6481 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6482 if (!SD) {
6483 S.Diag(Class->getLocation(),
6484 diag::err_cuda_device_builtin_surftex_ref_decl)
6485 << /*texture*/ 1 << Class;
6486 S.Diag(Class->getLocation(),
6487 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6488 << Class;
6489 return;
6490 }
6491 TD = SD->getSpecializedTemplate();
6492 }
6493
6495 unsigned N = Params->size();
6496
6497 if (N != 3) {
6498 reportIllegalClassTemplate(S, TD);
6499 S.Diag(TD->getLocation(),
6500 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6501 << TD << 3;
6502 }
6503 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6504 reportIllegalClassTemplate(S, TD);
6505 S.Diag(TD->getLocation(),
6506 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6507 << TD << /*1st*/ 0 << /*type*/ 0;
6508 }
6509 if (N > 1) {
6510 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6511 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6512 reportIllegalClassTemplate(S, TD);
6513 S.Diag(TD->getLocation(),
6514 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6515 << TD << /*2nd*/ 1 << /*integer*/ 1;
6516 }
6517 }
6518 if (N > 2) {
6519 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6520 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6521 reportIllegalClassTemplate(S, TD);
6522 S.Diag(TD->getLocation(),
6523 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6524 << TD << /*3rd*/ 2 << /*integer*/ 1;
6525 }
6526 }
6527}
6528
6530 // Mark any compiler-generated routines with the implicit code_seg attribute.
6531 for (auto *Method : Class->methods()) {
6532 if (Method->isUserProvided())
6533 continue;
6534 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6535 Method->addAttr(A);
6536 }
6537}
6538
6540 Attr *ClassAttr = getDLLAttr(Class);
6541
6542 // MSVC inherits DLL attributes to partial class template specializations.
6543 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6544 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6545 if (Attr *TemplateAttr =
6546 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6547 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6548 A->setInherited(true);
6549 ClassAttr = A;
6550 }
6551 }
6552 }
6553
6554 if (!ClassAttr)
6555 return;
6556
6557 // MSVC allows imported or exported template classes that have UniqueExternal
6558 // linkage. This occurs when the template class has been instantiated with
6559 // a template parameter which itself has internal linkage.
6560 // We drop the attribute to avoid exporting or importing any members.
6561 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6562 Context.getTargetInfo().getTriple().isPS()) &&
6563 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6564 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6565 return;
6566 }
6567
6568 if (!Class->isExternallyVisible()) {
6569 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6570 << Class << ClassAttr;
6571 return;
6572 }
6573
6574 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6575 !ClassAttr->isInherited()) {
6576 // Diagnose dll attributes on members of class with dll attribute.
6577 for (Decl *Member : Class->decls()) {
6579 continue;
6580 InheritableAttr *MemberAttr = getDLLAttr(Member);
6581 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6582 continue;
6583
6584 Diag(MemberAttr->getLocation(),
6585 diag::err_attribute_dll_member_of_dll_class)
6586 << MemberAttr << ClassAttr;
6587 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6588 Member->setInvalidDecl();
6589 }
6590 }
6591
6592 if (Class->getDescribedClassTemplate())
6593 // Don't inherit dll attribute until the template is instantiated.
6594 return;
6595
6596 // The class is either imported or exported.
6597 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6598
6599 // Check if this was a dllimport attribute propagated from a derived class to
6600 // a base class template specialization. We don't apply these attributes to
6601 // static data members.
6602 const bool PropagatedImport =
6603 !ClassExported &&
6604 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6605
6606 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6607
6608 // Ignore explicit dllexport on explicit class template instantiation
6609 // declarations, except in MinGW mode.
6610 if (ClassExported && !ClassAttr->isInherited() &&
6612 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6613 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6614 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6615 Class->dropAttr<DLLExportAttr>();
6616 }
6617 return;
6618 }
6619
6620 // Force declaration of implicit members so they can inherit the attribute.
6622
6623 // Inherited constructors are created lazily; force their creation now so the
6624 // loop below can propagate the DLL attribute to them.
6625 if (ClassExported && getLangOpts().DllExportInlines) {
6627 for (Decl *D : Class->decls())
6628 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6629 Shadows.push_back(S);
6630 for (ConstructorUsingShadowDecl *S : Shadows) {
6631 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6632 if (!BC || BC->isDeleted())
6633 continue;
6634 // Skip constructors whose requires clause is not satisfied.
6635 // Normally overload resolution filters these, but we are bypassing
6636 // it to eagerly create inherited constructors for dllexport.
6637 if (BC->getTrailingRequiresClause()) {
6638 ConstraintSatisfaction Satisfaction;
6639 if (CheckFunctionConstraints(BC, Satisfaction) ||
6640 !Satisfaction.IsSatisfied)
6641 continue;
6642 }
6643 findInheritingConstructor(Class->getLocation(), BC, S);
6644 }
6645 }
6646
6647 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6648 // seem to be true in practice?
6649
6650 for (Decl *Member : Class->decls()) {
6651 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6652 continue;
6653
6654 VarDecl *VD = dyn_cast<VarDecl>(Member);
6655 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6656
6657 // Only methods and static fields inherit the attributes.
6658 if (!VD && !MD)
6659 continue;
6660
6661 if (MD) {
6662 // Don't process deleted methods.
6663 if (MD->isDeleted())
6664 continue;
6665
6666 if (ClassExported && getLangOpts().DllExportInlines) {
6667 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6668 if (CD && CD->getInheritedConstructor()) {
6669 // Inherited constructors already had their base constructor's
6670 // constraints checked before creation via
6671 // findInheritingConstructor, so only ABI-compatibility checks
6672 // are needed here.
6673 //
6674 // Don't export inherited constructors whose parameters prevent
6675 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6676 // CodeGen) returns false, Clang inlines the constructor body
6677 // instead of emitting a forwarding thunk, producing code that
6678 // is not ABI-compatible with MSVC. Suppress the export and warn
6679 // so the user gets a linker error rather than a silent runtime
6680 // mismatch.
6681 if (CD->isVariadic()) {
6682 Diag(CD->getLocation(),
6683 diag::warn_dllexport_inherited_ctor_unsupported)
6684 << /*variadic=*/0;
6685 continue;
6686 }
6687 if (Context.getTargetInfo()
6688 .getCXXABI()
6689 .areArgsDestroyedLeftToRightInCallee()) {
6690 bool HasCalleeCleanupParam = false;
6691 for (const ParmVarDecl *P : CD->parameters())
6692 if (P->needsDestruction(Context)) {
6693 HasCalleeCleanupParam = true;
6694 break;
6695 }
6696 if (HasCalleeCleanupParam) {
6697 Diag(CD->getLocation(),
6698 diag::warn_dllexport_inherited_ctor_unsupported)
6699 << /*callee-cleanup=*/1;
6700 continue;
6701 }
6702 }
6703 } else if (MD->getTrailingRequiresClause()) {
6704 // Don't export methods whose requires clause is not satisfied.
6705 // For class template specializations, member constraints may
6706 // depend on template arguments and an unsatisfied constraint
6707 // means the member should not be available in this
6708 // specialization.
6709 ConstraintSatisfaction Satisfaction;
6710 if (CheckFunctionConstraints(MD, Satisfaction) ||
6711 !Satisfaction.IsSatisfied)
6712 continue;
6713 }
6714 }
6715
6716 if (MD->isInlined()) {
6717 // MinGW does not import or export inline methods. But do it for
6718 // template instantiations and inherited constructors (which are
6719 // marked inline but must be exported to match MSVC behavior).
6720 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6723 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6724 !CD || !CD->getInheritedConstructor())
6725 continue;
6726 }
6727
6728 // MSVC versions before 2015 don't export the move assignment operators
6729 // and move constructor, so don't attempt to import/export them if
6730 // we have a definition.
6731 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6732 if ((MD->isMoveAssignmentOperator() ||
6733 (Ctor && Ctor->isMoveConstructor())) &&
6734 getLangOpts().isCompatibleWithMSVC() &&
6735 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6736 continue;
6737
6738 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6739 // operator is exported anyway.
6740 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6741 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6742 continue;
6743 }
6744 }
6745
6746 // Don't apply dllimport attributes to static data members of class template
6747 // instantiations when the attribute is propagated from a derived class.
6748 if (VD && PropagatedImport)
6749 continue;
6750
6752 continue;
6753
6754 if (!getDLLAttr(Member)) {
6755 InheritableAttr *NewAttr = nullptr;
6756
6757 // Do not export/import inline function when -fno-dllexport-inlines is
6758 // passed. But add attribute for later local static var check.
6759 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6762 if (ClassExported) {
6763 NewAttr = ::new (getASTContext())
6764 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6765 } else {
6766 NewAttr = ::new (getASTContext())
6767 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6768 }
6769 } else {
6770 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6771 }
6772
6773 NewAttr->setInherited(true);
6774 Member->addAttr(NewAttr);
6775
6776 if (MD) {
6777 // Propagate DLLAttr to friend re-declarations of MD that have already
6778 // been constructed.
6779 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6780 FD = FD->getPreviousDecl()) {
6782 continue;
6783 assert(!getDLLAttr(FD) &&
6784 "friend re-decl should not already have a DLLAttr");
6785 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6786 NewAttr->setInherited(true);
6787 FD->addAttr(NewAttr);
6788 }
6789 }
6790 }
6791 }
6792
6793 if (ClassExported)
6794 DelayedDllExportClasses.push_back(Class);
6795}
6796
6798 CXXRecordDecl *Class, Attr *ClassAttr,
6799 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6800 if (getDLLAttr(
6801 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6802 // If the base class template has a DLL attribute, don't try to change it.
6803 return;
6804 }
6805
6806 auto TSK = BaseTemplateSpec->getSpecializationKind();
6807 if (!getDLLAttr(BaseTemplateSpec) &&
6809 TSK == TSK_ImplicitInstantiation)) {
6810 // The template hasn't been instantiated yet (or it has, but only as an
6811 // explicit instantiation declaration or implicit instantiation, which means
6812 // we haven't codegenned any members yet), so propagate the attribute.
6813 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6814 NewAttr->setInherited(true);
6815 BaseTemplateSpec->addAttr(NewAttr);
6816
6817 // If this was an import, mark that we propagated it from a derived class to
6818 // a base class template specialization.
6819 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6820 ImportAttr->setPropagatedToBaseTemplate();
6821
6822 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6823 // needs to be run again to work see the new attribute. Otherwise this will
6824 // get run whenever the template is instantiated.
6825 if (TSK != TSK_Undeclared)
6826 checkClassLevelDLLAttribute(BaseTemplateSpec);
6827
6828 return;
6829 }
6830
6831 if (getDLLAttr(BaseTemplateSpec)) {
6832 // The template has already been specialized or instantiated with an
6833 // attribute, explicitly or through propagation. We should not try to change
6834 // it.
6835 return;
6836 }
6837
6838 // The template was previously instantiated or explicitly specialized without
6839 // a dll attribute, It's too late for us to add an attribute, so warn that
6840 // this is unsupported.
6841 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6842 << BaseTemplateSpec->isExplicitSpecialization();
6843 Diag(ClassAttr->getLocation(), diag::note_attribute);
6844 if (BaseTemplateSpec->isExplicitSpecialization()) {
6845 Diag(BaseTemplateSpec->getLocation(),
6846 diag::note_template_class_explicit_specialization_was_here)
6847 << BaseTemplateSpec;
6848 } else {
6849 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6850 diag::note_template_class_instantiation_was_here)
6851 << BaseTemplateSpec;
6852 }
6853}
6854
6857 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6858 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6859 if (Ctor->isDefaultConstructor())
6861
6862 if (Ctor->isCopyConstructor())
6864
6865 if (Ctor->isMoveConstructor())
6867 }
6868
6869 if (MD->isCopyAssignmentOperator())
6871
6872 if (MD->isMoveAssignmentOperator())
6874
6875 if (isa<CXXDestructorDecl>(FD))
6877 }
6878
6879 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6880 case OO_EqualEqual:
6882
6883 case OO_ExclaimEqual:
6885
6886 case OO_Spaceship:
6887 // No point allowing this if <=> doesn't exist in the current language mode.
6888 if (!getLangOpts().CPlusPlus20)
6889 break;
6891
6892 case OO_Less:
6893 case OO_LessEqual:
6894 case OO_Greater:
6895 case OO_GreaterEqual:
6896 // No point allowing this if <=> doesn't exist in the current language mode.
6897 if (!getLangOpts().CPlusPlus20)
6898 break;
6900
6901 default:
6902 break;
6903 }
6904
6905 // Not defaultable.
6906 return DefaultedFunctionKind();
6907}
6908
6910 SourceLocation DefaultLoc) {
6912 if (DFK.isComparison())
6913 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6914
6915 switch (DFK.asSpecialMember()) {
6919 break;
6922 break;
6925 break;
6928 break;
6931 break;
6934 break;
6936 llvm_unreachable("Invalid special member.");
6937 }
6938}
6939
6940/// Determine whether a type is permitted to be passed or returned in
6941/// registers, per C++ [class.temporary]p3.
6944 if (D->isDependentType() || D->isInvalidDecl())
6945 return false;
6946
6947 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6948 // The PS4 platform ABI follows the behavior of Clang 3.2.
6950 return !D->hasNonTrivialDestructorForCall() &&
6952
6953 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6954 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6955 bool DtorIsTrivialForCall = false;
6956
6957 // If a class has at least one eligible, trivial copy constructor, it
6958 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6959 //
6960 // Note: This permits classes with non-trivial copy or move ctors to be
6961 // passed in registers, so long as they *also* have a trivial copy ctor,
6962 // which is non-conforming.
6966 CopyCtorIsTrivial = true;
6968 CopyCtorIsTrivialForCall = true;
6969 }
6970 } else {
6971 for (const CXXConstructorDecl *CD : D->ctors()) {
6972 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6973 !CD->isIneligibleOrNotSelected()) {
6974 if (CD->isTrivial())
6975 CopyCtorIsTrivial = true;
6976 if (CD->isTrivialForCall())
6977 CopyCtorIsTrivialForCall = true;
6978 }
6979 }
6980 }
6981
6982 if (D->needsImplicitDestructor()) {
6983 if (!D->defaultedDestructorIsDeleted() &&
6985 DtorIsTrivialForCall = true;
6986 } else if (const auto *DD = D->getDestructor()) {
6987 if (!DD->isDeleted() && DD->isTrivialForCall())
6988 DtorIsTrivialForCall = true;
6989 }
6990
6991 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6992 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6993 return true;
6994
6995 // If a class has a destructor, we'd really like to pass it indirectly
6996 // because it allows us to elide copies. Unfortunately, MSVC makes that
6997 // impossible for small types, which it will pass in a single register or
6998 // stack slot. Most objects with dtors are large-ish, so handle that early.
6999 // We can't call out all large objects as being indirect because there are
7000 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7001 // how we pass large POD types.
7002
7003 // Note: This permits small classes with nontrivial destructors to be
7004 // passed in registers, which is non-conforming.
7005 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7006 uint64_t TypeSize = isAArch64 ? 128 : 64;
7007
7008 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7009 S.Context.getCanonicalTagType(D)) <= TypeSize)
7010 return true;
7011 return false;
7012 }
7013
7014 // Per C++ [class.temporary]p3, the relevant condition is:
7015 // each copy constructor, move constructor, and destructor of X is
7016 // either trivial or deleted, and X has at least one non-deleted copy
7017 // or move constructor
7018 bool HasNonDeletedCopyOrMove = false;
7019
7023 return false;
7024 HasNonDeletedCopyOrMove = true;
7025 }
7026
7027 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7030 return false;
7031 HasNonDeletedCopyOrMove = true;
7032 }
7033
7036 return false;
7037
7038 for (const CXXMethodDecl *MD : D->methods()) {
7039 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7040 continue;
7041
7042 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7043 if (CD && CD->isCopyOrMoveConstructor())
7044 HasNonDeletedCopyOrMove = true;
7045 else if (!isa<CXXDestructorDecl>(MD))
7046 continue;
7047
7048 if (!MD->isTrivialForCall())
7049 return false;
7050 }
7051
7052 return HasNonDeletedCopyOrMove;
7053}
7054
7055/// Report an error regarding overriding, along with any relevant
7056/// overridden methods.
7057///
7058/// \param DiagID the primary error to report.
7059/// \param MD the overriding method.
7060static bool
7061ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7062 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7063 bool IssuedDiagnostic = false;
7064 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7065 if (Report(O)) {
7066 if (!IssuedDiagnostic) {
7067 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7068 IssuedDiagnostic = true;
7069 }
7070 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7071 }
7072 }
7073 return IssuedDiagnostic;
7074}
7075
7077 if (!Record)
7078 return;
7079
7080 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7081 AbstractUsageInfo Info(*this, Record);
7083 }
7084
7085 // If this is not an aggregate type and has no user-declared constructor,
7086 // complain about any non-static data members of reference or const scalar
7087 // type, since they will never get initializers.
7088 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7089 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7090 !Record->isLambda()) {
7091 bool Complained = false;
7092 for (const auto *F : Record->fields()) {
7093 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7094 continue;
7095
7096 if (F->getType()->isReferenceType() ||
7097 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7098 if (!Complained) {
7099 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7100 << Record->getTagKind() << Record;
7101 Complained = true;
7102 }
7103
7104 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7105 << F->getType()->isReferenceType()
7106 << F->getDeclName();
7107 }
7108 }
7109 }
7110
7111 if (Record->getIdentifier()) {
7112 // C++ [class.mem]p13:
7113 // If T is the name of a class, then each of the following shall have a
7114 // name different from T:
7115 // - every member of every anonymous union that is a member of class T.
7116 //
7117 // C++ [class.mem]p14:
7118 // In addition, if class T has a user-declared constructor (12.1), every
7119 // non-static data member of class T shall have a name different from T.
7120 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7121 const NamedDecl *D = Element->getUnderlyingDecl();
7122 // Invalid IndirectFieldDecls have already been diagnosed with
7123 // err_anonymous_record_member_redecl in
7124 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7126 Record->hasUserDeclaredConstructor()) ||
7127 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7128 Diag(Element->getLocation(), diag::err_member_name_of_class)
7129 << D->getDeclName();
7130 break;
7131 }
7132 }
7133 }
7134
7135 // Warn if the class has virtual methods but non-virtual public destructor.
7136 if (Record->isPolymorphic() && !Record->isDependentType()) {
7137 CXXDestructorDecl *dtor = Record->getDestructor();
7138 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7139 !Record->hasAttr<FinalAttr>())
7140 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7141 diag::warn_non_virtual_dtor)
7142 << Context.getCanonicalTagType(Record);
7143 }
7144
7145 if (Record->isAbstract()) {
7146 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7147 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7148 << FA->isSpelledAsSealed();
7150 }
7151 }
7152
7153 // Warn if the class has a final destructor but is not itself marked final.
7154 if (!Record->hasAttr<FinalAttr>()) {
7155 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7156 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7157 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7158 << FA->isSpelledAsSealed()
7160 getLocForEndOfToken(Record->getLocation()),
7161 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7162 Diag(Record->getLocation(),
7163 diag::note_final_dtor_non_final_class_silence)
7164 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7165 }
7166 }
7167 }
7168
7169 // See if trivial_abi has to be dropped.
7170 if (Record->hasAttr<TrivialABIAttr>())
7172
7173 // Set HasTrivialSpecialMemberForCall if the record has attribute
7174 // "trivial_abi".
7175 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7176
7177 if (HasTrivialABI)
7178 Record->setHasTrivialSpecialMemberForCall();
7179
7180 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7181 // We check these last because they can depend on the properties of the
7182 // primary comparison functions (==, <=>).
7183 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7184
7185 // Perform checks that can't be done until we know all the properties of a
7186 // member function (whether it's defaulted, deleted, virtual, overriding,
7187 // ...).
7188 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7189 // A static function cannot override anything.
7190 if (MD->getStorageClass() == SC_Static) {
7191 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7192 [](const CXXMethodDecl *) { return true; }))
7193 return;
7194 }
7195
7196 // A deleted function cannot override a non-deleted function and vice
7197 // versa.
7198 if (ReportOverrides(*this,
7199 MD->isDeleted() ? diag::err_deleted_override
7200 : diag::err_non_deleted_override,
7201 MD, [&](const CXXMethodDecl *V) {
7202 return MD->isDeleted() != V->isDeleted();
7203 })) {
7204 if (MD->isDefaulted() && MD->isDeleted())
7205 // Explain why this defaulted function was deleted.
7207 return;
7208 }
7209
7210 // A consteval function cannot override a non-consteval function and vice
7211 // versa.
7212 if (ReportOverrides(*this,
7213 MD->isConsteval() ? diag::err_consteval_override
7214 : diag::err_non_consteval_override,
7215 MD, [&](const CXXMethodDecl *V) {
7216 return MD->isConsteval() != V->isConsteval();
7217 })) {
7218 if (MD->isDefaulted() && MD->isDeleted())
7219 // Explain why this defaulted function was deleted.
7221 return;
7222 }
7223 };
7224
7225 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7226 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7227 return false;
7228
7232 DefaultedSecondaryComparisons.push_back(FD);
7233 return true;
7234 }
7235
7237 return false;
7238 };
7239
7240 if (!Record->isInvalidDecl() &&
7241 Record->hasAttr<VTablePointerAuthenticationAttr>())
7243
7244 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7245 // Check whether the explicitly-defaulted members are valid.
7246 bool Incomplete = CheckForDefaultedFunction(M);
7247
7248 // Skip the rest of the checks for a member of a dependent class.
7249 if (Record->isDependentType())
7250 return;
7251
7252 // For an explicitly defaulted or deleted special member, we defer
7253 // determining triviality until the class is complete. That time is now!
7255 if (!M->isImplicit() && !M->isUserProvided()) {
7256 if (CSM != CXXSpecialMemberKind::Invalid) {
7257 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7258 // Inform the class that we've finished declaring this member.
7259 Record->finishedDefaultedOrDeletedMember(M);
7260 M->setTrivialForCall(
7261 HasTrivialABI ||
7264 Record->setTrivialForCallFlags(M);
7265 }
7266 }
7267
7268 // Set triviality for the purpose of calls if this is a user-provided
7269 // copy/move constructor or destructor.
7273 M->isUserProvided()) {
7274 M->setTrivialForCall(HasTrivialABI);
7275 Record->setTrivialForCallFlags(M);
7276 }
7277
7278 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7279 M->hasAttr<DLLExportAttr>()) {
7280 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7281 M->isTrivial() &&
7285 M->dropAttr<DLLExportAttr>();
7286
7287 if (M->hasAttr<DLLExportAttr>()) {
7288 // Define after any fields with in-class initializers have been parsed.
7290 }
7291 }
7292
7293 bool EffectivelyConstexprDestructor = true;
7294 // Avoid triggering vtable instantiation due to a dtor that is not
7295 // "effectively constexpr" for better compatibility.
7296 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7297 if (isa<CXXDestructorDecl>(M)) {
7298 llvm::SmallDenseSet<QualType> Visited;
7299 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7300 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7301 return false;
7302 const CXXRecordDecl *RD =
7303 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7304 if (!RD || !RD->isCompleteDefinition())
7305 return true;
7306
7307 if (!RD->hasConstexprDestructor())
7308 return false;
7309
7310 for (const CXXBaseSpecifier &B : RD->bases())
7311 if (!Check(B.getType(), Check))
7312 return false;
7313 for (const FieldDecl *FD : RD->fields())
7314 if (!Check(FD->getType(), Check))
7315 return false;
7316 return true;
7317 };
7318 EffectivelyConstexprDestructor =
7319 Check(Context.getCanonicalTagType(Record), Check);
7320 }
7321
7322 // Define defaulted constexpr virtual functions that override a base class
7323 // function right away.
7324 // FIXME: We can defer doing this until the vtable is marked as used.
7325 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7326 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7327 EffectivelyConstexprDestructor)
7328 DefineDefaultedFunction(*this, M, M->getLocation());
7329
7330 if (!Incomplete)
7331 CheckCompletedMemberFunction(M);
7332 };
7333
7334 // Check the destructor before any other member function. We need to
7335 // determine whether it's trivial in order to determine whether the claas
7336 // type is a literal type, which is a prerequisite for determining whether
7337 // other special member functions are valid and whether they're implicitly
7338 // 'constexpr'.
7339 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7340 CompleteMemberFunction(Dtor);
7341
7342 bool HasMethodWithOverrideControl = false,
7343 HasOverridingMethodWithoutOverrideControl = false;
7344 for (auto *D : Record->decls()) {
7345 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7346 // FIXME: We could do this check for dependent types with non-dependent
7347 // bases.
7348 if (!Record->isDependentType()) {
7349 // See if a method overloads virtual methods in a base
7350 // class without overriding any.
7351 if (!M->isStatic())
7353
7354 if (M->hasAttr<OverrideAttr>()) {
7355 HasMethodWithOverrideControl = true;
7356 } else if (M->size_overridden_methods() > 0) {
7357 HasOverridingMethodWithoutOverrideControl = true;
7358 } else {
7359 // Warn on newly-declared virtual methods in `final` classes
7360 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7361 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7362 << M;
7363 }
7364 }
7365 }
7366
7367 if (!isa<CXXDestructorDecl>(M))
7368 CompleteMemberFunction(M);
7369 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7370 CheckForDefaultedFunction(
7371 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7372 }
7373 }
7374
7375 if (HasOverridingMethodWithoutOverrideControl) {
7376 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7377 for (auto *M : Record->methods())
7378 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7379 }
7380
7381 // Check the defaulted secondary comparisons after any other member functions.
7382 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7384
7385 // If this is a member function, we deferred checking it until now.
7386 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7387 CheckCompletedMemberFunction(MD);
7388 }
7389
7390 // {ms,gcc}_struct is a request to change ABI rules to either follow
7391 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7392 // present, we do not layout classes following foreign ABI rules, but
7393 // instead enter a special "compatibility mode", which only changes
7394 // alignments of fundamental types and layout of bit fields.
7395 // Check whether this class uses any C++ features that are implemented
7396 // completely differently in the requested ABI, and if so, emit a
7397 // diagnostic. That diagnostic defaults to an error, but we allow
7398 // projects to map it down to a warning (or ignore it). It's a fairly
7399 // common practice among users of the ms_struct pragma to
7400 // mass-annotate headers, sweeping up a bunch of types that the
7401 // project doesn't really rely on MSVC-compatible layout for. We must
7402 // therefore support "ms_struct except for C++ stuff" as a secondary
7403 // ABI.
7404 // Don't emit this diagnostic if the feature was enabled as a
7405 // language option (as opposed to via a pragma or attribute), as
7406 // the option -mms-bitfields otherwise essentially makes it impossible
7407 // to build C++ code, unless this diagnostic is turned off.
7408 if (Context.getLangOpts().getLayoutCompatibility() ==
7410 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7411 (Record->isPolymorphic() || Record->getNumBases())) {
7412 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7413 }
7414
7417
7418 bool ClangABICompat4 =
7419 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7421 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7422 bool CanPass = canPassInRegisters(*this, Record, CCK);
7423
7424 // Do not change ArgPassingRestrictions if it has already been set to
7425 // RecordArgPassingKind::CanNeverPassInRegs.
7426 if (Record->getArgPassingRestrictions() !=
7428 Record->setArgPassingRestrictions(
7431
7432 // If canPassInRegisters returns true despite the record having a non-trivial
7433 // destructor, the record is destructed in the callee. This happens only when
7434 // the record or one of its subobjects has a field annotated with trivial_abi
7435 // or a field qualified with ObjC __strong/__weak.
7436 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7437 Record->setParamDestroyedInCallee(true);
7438 else if (Record->hasNonTrivialDestructor())
7439 Record->setParamDestroyedInCallee(CanPass);
7440
7441 if (getLangOpts().ForceEmitVTables) {
7442 // If we want to emit all the vtables, we need to mark it as used. This
7443 // is especially required for cases like vtable assumption loads.
7444 MarkVTableUsed(Record->getInnerLocStart(), Record);
7445 }
7446
7447 if (getLangOpts().CUDA) {
7448 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7450 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7452 }
7453
7454 llvm::SmallDenseMap<OverloadedOperatorKind,
7456 TypeAwareDecls{{OO_New, {}},
7457 {OO_Array_New, {}},
7458 {OO_Delete, {}},
7459 {OO_Array_New, {}}};
7460 for (auto *D : Record->decls()) {
7461 const FunctionDecl *FnDecl = D->getAsFunction();
7462 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7463 continue;
7464 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7465 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7466 }
7467 auto CheckMismatchedTypeAwareAllocators =
7468 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7469 OverloadedOperatorKind DeleteKind) {
7470 auto &NewDecls = TypeAwareDecls[NewKind];
7471 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7472 if (NewDecls.empty() == DeleteDecls.empty())
7473 return;
7474 DeclarationName FoundOperator =
7475 Context.DeclarationNames.getCXXOperatorName(
7476 NewDecls.empty() ? DeleteKind : NewKind);
7477 DeclarationName MissingOperator =
7478 Context.DeclarationNames.getCXXOperatorName(
7479 NewDecls.empty() ? NewKind : DeleteKind);
7480 Diag(Record->getLocation(),
7481 diag::err_type_aware_allocator_missing_matching_operator)
7482 << FoundOperator << Context.getCanonicalTagType(Record)
7483 << MissingOperator;
7484 for (auto MD : NewDecls)
7485 Diag(MD->getLocation(),
7486 diag::note_unmatched_type_aware_allocator_declared)
7487 << MD;
7488 for (auto MD : DeleteDecls)
7489 Diag(MD->getLocation(),
7490 diag::note_unmatched_type_aware_allocator_declared)
7491 << MD;
7492 };
7493 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7494 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7495}
7496
7497/// Look up the special member function that would be called by a special
7498/// member function for a subobject of class type.
7499///
7500/// \param Class The class type of the subobject.
7501/// \param CSM The kind of special member function.
7502/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7503/// \param ConstRHS True if this is a copy operation with a const object
7504/// on its RHS, that is, if the argument to the outer special member
7505/// function is 'const' and this is not a field marked 'mutable'.
7508 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7509 bool ConstRHS) {
7510 unsigned LHSQuals = 0;
7513 LHSQuals = FieldQuals;
7514
7515 unsigned RHSQuals = FieldQuals;
7518 RHSQuals = 0;
7519 else if (ConstRHS)
7520 RHSQuals |= Qualifiers::Const;
7521
7522 return S.LookupSpecialMember(Class, CSM,
7523 RHSQuals & Qualifiers::Const,
7524 RHSQuals & Qualifiers::Volatile,
7525 false,
7526 LHSQuals & Qualifiers::Const,
7527 LHSQuals & Qualifiers::Volatile);
7528}
7529
7531 Sema &S;
7532 SourceLocation UseLoc;
7533
7534 /// A mapping from the base classes through which the constructor was
7535 /// inherited to the using shadow declaration in that base class (or a null
7536 /// pointer if the constructor was declared in that base class).
7537 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7538 InheritedFromBases;
7539
7540public:
7543 : S(S), UseLoc(UseLoc) {
7544 bool DiagnosedMultipleConstructedBases = false;
7545 CXXRecordDecl *ConstructedBase = nullptr;
7546 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7547
7548 // Find the set of such base class subobjects and check that there's a
7549 // unique constructed subobject.
7550 for (auto *D : Shadow->redecls()) {
7551 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7552 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7553 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7554
7555 InheritedFromBases.insert(
7556 std::make_pair(DNominatedBase->getCanonicalDecl(),
7557 DShadow->getNominatedBaseClassShadowDecl()));
7558 if (DShadow->constructsVirtualBase())
7559 InheritedFromBases.insert(
7560 std::make_pair(DConstructedBase->getCanonicalDecl(),
7561 DShadow->getConstructedBaseClassShadowDecl()));
7562 else
7563 assert(DNominatedBase == DConstructedBase);
7564
7565 // [class.inhctor.init]p2:
7566 // If the constructor was inherited from multiple base class subobjects
7567 // of type B, the program is ill-formed.
7568 if (!ConstructedBase) {
7569 ConstructedBase = DConstructedBase;
7570 ConstructedBaseIntroducer = D->getIntroducer();
7571 } else if (ConstructedBase != DConstructedBase &&
7572 !Shadow->isInvalidDecl()) {
7573 if (!DiagnosedMultipleConstructedBases) {
7574 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7575 << Shadow->getTargetDecl();
7576 S.Diag(ConstructedBaseIntroducer->getLocation(),
7577 diag::note_ambiguous_inherited_constructor_using)
7578 << ConstructedBase;
7579 DiagnosedMultipleConstructedBases = true;
7580 }
7581 S.Diag(D->getIntroducer()->getLocation(),
7582 diag::note_ambiguous_inherited_constructor_using)
7583 << DConstructedBase;
7584 }
7585 }
7586
7587 if (DiagnosedMultipleConstructedBases)
7588 Shadow->setInvalidDecl();
7589 }
7590
7591 /// Find the constructor to use for inherited construction of a base class,
7592 /// and whether that base class constructor inherits the constructor from a
7593 /// virtual base class (in which case it won't actually invoke it).
7594 std::pair<CXXConstructorDecl *, bool>
7596 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7597 if (It == InheritedFromBases.end())
7598 return std::make_pair(nullptr, false);
7599
7600 // This is an intermediary class.
7601 if (It->second)
7602 return std::make_pair(
7603 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7604 It->second->constructsVirtualBase());
7605
7606 // This is the base class from which the constructor was inherited.
7607 return std::make_pair(Ctor, false);
7608 }
7609};
7610
7611/// Is the special member function which would be selected to perform the
7612/// specified operation on the specified class type a constexpr constructor?
7614 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7615 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7616 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7617 // Suppress duplicate constraint checking here, in case a constraint check
7618 // caused us to decide to do this. Any truely recursive checks will get
7619 // caught during these checks anyway.
7621
7622 // If we're inheriting a constructor, see if we need to call it for this base
7623 // class.
7624 if (InheritedCtor) {
7626 auto BaseCtor =
7627 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7628 if (BaseCtor)
7629 return BaseCtor->isConstexpr();
7630 }
7631
7633 return ClassDecl->hasConstexprDefaultConstructor();
7635 return ClassDecl->hasConstexprDestructor();
7636
7638 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7639 if (!SMOR.getMethod())
7640 // A constructor we wouldn't select can't be "involved in initializing"
7641 // anything.
7642 return true;
7643 return SMOR.getMethod()->isConstexpr();
7644}
7645
7646/// Determine whether the specified special member function would be constexpr
7647/// if it were implicitly defined.
7649 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7650 CXXConstructorDecl *InheritedCtor = nullptr,
7651 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7652 if (!S.getLangOpts().CPlusPlus11)
7653 return false;
7654
7655 // C++11 [dcl.constexpr]p4:
7656 // In the definition of a constexpr constructor [...]
7657 bool Ctor = true;
7658 switch (CSM) {
7660 if (Inherited)
7661 break;
7662 // Since default constructor lookup is essentially trivial (and cannot
7663 // involve, for instance, template instantiation), we compute whether a
7664 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7665 //
7666 // This is important for performance; we need to know whether the default
7667 // constructor is constexpr to determine whether the type is a literal type.
7668 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7669
7672 // For copy or move constructors, we need to perform overload resolution.
7673 break;
7674
7677 if (!S.getLangOpts().CPlusPlus14)
7678 return false;
7679 // In C++1y, we need to perform overload resolution.
7680 Ctor = false;
7681 break;
7682
7684 return ClassDecl->defaultedDestructorIsConstexpr();
7685
7687 return false;
7688 }
7689
7690 // -- if the class is a non-empty union, or for each non-empty anonymous
7691 // union member of a non-union class, exactly one non-static data member
7692 // shall be initialized; [DR1359]
7693 //
7694 // If we squint, this is guaranteed, since exactly one non-static data member
7695 // will be initialized (if the constructor isn't deleted), we just don't know
7696 // which one.
7697 if (Ctor && ClassDecl->isUnion())
7699 ? ClassDecl->hasInClassInitializer() ||
7700 !ClassDecl->hasVariantMembers()
7701 : true;
7702
7703 // -- the class shall not have any virtual base classes;
7704 if (Ctor && ClassDecl->getNumVBases())
7705 return false;
7706
7707 // C++1y [class.copy]p26:
7708 // -- [the class] is a literal type, and
7709 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7710 return false;
7711
7712 // -- every constructor involved in initializing [...] base class
7713 // sub-objects shall be a constexpr constructor;
7714 // -- the assignment operator selected to copy/move each direct base
7715 // class is a constexpr function, and
7716 if (!S.getLangOpts().CPlusPlus23) {
7717 for (const auto &B : ClassDecl->bases()) {
7718 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7719 if (!BaseClassDecl)
7720 continue;
7721 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7722 InheritedCtor, Inherited))
7723 return false;
7724 }
7725 }
7726
7727 // -- every constructor involved in initializing non-static data members
7728 // [...] shall be a constexpr constructor;
7729 // -- every non-static data member and base class sub-object shall be
7730 // initialized
7731 // -- for each non-static data member of X that is of class type (or array
7732 // thereof), the assignment operator selected to copy/move that member is
7733 // a constexpr function
7734 if (!S.getLangOpts().CPlusPlus23) {
7735 for (const auto *F : ClassDecl->fields()) {
7736 if (F->isInvalidDecl())
7737 continue;
7739 F->hasInClassInitializer())
7740 continue;
7741 QualType BaseType = S.Context.getBaseElementType(F->getType());
7742 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7743 auto *FieldRecDecl =
7744 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7745 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7746 BaseType.getCVRQualifiers(),
7747 ConstArg && !F->isMutable()))
7748 return false;
7749 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7750 return false;
7751 }
7752 }
7753 }
7754
7755 // All OK, it's constexpr!
7756 return true;
7757}
7758
7759namespace {
7760/// RAII object to register a defaulted function as having its exception
7761/// specification computed.
7762struct ComputingExceptionSpec {
7763 Sema &S;
7764
7765 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7766 : S(S) {
7767 Sema::CodeSynthesisContext Ctx;
7769 Ctx.PointOfInstantiation = Loc;
7770 Ctx.Entity = FD;
7772 }
7773 ~ComputingExceptionSpec() {
7775 }
7776};
7777}
7778
7779static Sema::ImplicitExceptionSpecification
7780ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7781 CXXMethodDecl *MD,
7783 Sema::InheritedConstructorInfo *ICI);
7784
7785static Sema::ImplicitExceptionSpecification
7786ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7787 FunctionDecl *FD,
7789
7790static Sema::ImplicitExceptionSpecification
7792 auto DFK = S.getDefaultedFunctionKind(FD);
7793 if (DFK.isSpecialMember())
7795 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7796 if (DFK.isComparison())
7798 DFK.asComparison());
7799
7800 auto *CD = cast<CXXConstructorDecl>(FD);
7801 assert(CD->getInheritedConstructor() &&
7802 "only defaulted functions and inherited constructors have implicit "
7803 "exception specs");
7805 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7808}
7809
7811 CXXMethodDecl *MD) {
7813
7814 // Build an exception specification pointing back at this member.
7816 EPI.ExceptionSpec.SourceDecl = MD;
7817
7818 // Set the calling convention to the default for C++ instance methods.
7820 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7821 /*IsCXXMethod=*/true));
7822 return EPI;
7823}
7824
7826 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7828 return;
7829
7830 // Evaluate the exception specification.
7831 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7832 auto ESI = IES.getExceptionSpec();
7833
7834 // Update the type of the special member to use it.
7835 UpdateExceptionSpec(FD, ESI);
7836}
7837
7839 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7840
7842 if (!DefKind) {
7843 assert(FD->getDeclContext()->isDependentContext());
7844 return;
7845 }
7846
7847 if (DefKind.isComparison()) {
7848 auto PT = FD->getParamDecl(0)->getType();
7849 if (const CXXRecordDecl *RD =
7850 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7851 for (FieldDecl *Field : RD->fields()) {
7852 UnusedPrivateFields.remove(Field);
7853 }
7854 }
7855 }
7856
7857 if (DefKind.isSpecialMember()
7859 DefKind.asSpecialMember(),
7860 FD->getDefaultLoc())
7862 FD->setInvalidDecl();
7863}
7864
7867 SourceLocation DefaultLoc) {
7868 CXXRecordDecl *RD = MD->getParent();
7869
7871 "not an explicitly-defaulted special member");
7872
7873 // Defer all checking for special members of a dependent type.
7874 if (RD->isDependentType())
7875 return false;
7876
7877 // Whether this was the first-declared instance of the constructor.
7878 // This affects whether we implicitly add an exception spec and constexpr.
7879 bool First = MD == MD->getCanonicalDecl();
7880
7881 bool HadError = false;
7882
7883 // C++11 [dcl.fct.def.default]p1:
7884 // A function that is explicitly defaulted shall
7885 // -- be a special member function [...] (checked elsewhere),
7886 // -- have the same type (except for ref-qualifiers, and except that a
7887 // copy operation can take a non-const reference) as an implicit
7888 // declaration, and
7889 // -- not have default arguments.
7890 // C++2a changes the second bullet to instead delete the function if it's
7891 // defaulted on its first declaration, unless it's "an assignment operator,
7892 // and its return type differs or its parameter type is not a reference".
7893 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7894 bool ShouldDeleteForTypeMismatch = false;
7895 unsigned ExpectedParams = 1;
7898 ExpectedParams = 0;
7899 if (MD->getNumExplicitParams() != ExpectedParams) {
7900 // This checks for default arguments: a copy or move constructor with a
7901 // default argument is classified as a default constructor, and assignment
7902 // operations and destructors can't have default arguments.
7903 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7904 << CSM << MD->getSourceRange();
7905 HadError = true;
7906 } else if (MD->isVariadic()) {
7907 if (DeleteOnTypeMismatch)
7908 ShouldDeleteForTypeMismatch = true;
7909 else {
7910 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7911 << CSM << MD->getSourceRange();
7912 HadError = true;
7913 }
7914 }
7915
7917
7918 bool CanHaveConstParam = false;
7920 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7922 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7923
7924 QualType ReturnType = Context.VoidTy;
7927 // Check for return type matching.
7928 ReturnType = Type->getReturnType();
7930
7931 QualType DeclType =
7933 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7934 DeclType = Context.getAddrSpaceQualType(
7935 DeclType, ThisType.getQualifiers().getAddressSpace());
7936 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7937
7938 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7939 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7941 << ExpectedReturnType;
7942 HadError = true;
7943 }
7944
7945 // A defaulted special member cannot have cv-qualifiers.
7946 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7947 if (DeleteOnTypeMismatch)
7948 ShouldDeleteForTypeMismatch = true;
7949 else {
7950 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7952 << getLangOpts().CPlusPlus14;
7953 HadError = true;
7954 }
7955 }
7956 // [C++23][dcl.fct.def.default]/p2.2
7957 // if F2 has an implicit object parameter of type “reference to C”,
7958 // F1 may be an explicit object member function whose explicit object
7959 // parameter is of (possibly different) type “reference to C”,
7960 // in which case the type of F1 would differ from the type of F2
7961 // in that the type of F1 has an additional parameter;
7962 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7963 ? MD->getParamDecl(0)->getType()
7964 : QualType();
7965 if (!ExplicitObjectParameter.isNull() &&
7966 (!ExplicitObjectParameter->isReferenceType() ||
7967 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7968 Context.getCanonicalTagType(RD)))) {
7969 if (DeleteOnTypeMismatch)
7970 ShouldDeleteForTypeMismatch = true;
7971 else {
7972 Diag(MD->getLocation(),
7973 diag::err_defaulted_special_member_explicit_object_mismatch)
7974 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7975 << MD->getSourceRange();
7976 HadError = true;
7977 }
7978 }
7979 }
7980
7981 // Check for parameter type matching.
7983 ExpectedParams
7984 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7985 : QualType();
7986 bool HasConstParam = false;
7987 if (ExpectedParams && ArgType->isReferenceType()) {
7988 // Argument must be reference to possibly-const T.
7989 QualType ReferentType = ArgType->getPointeeType();
7990 HasConstParam = ReferentType.isConstQualified();
7991
7992 if (ReferentType.isVolatileQualified()) {
7993 if (DeleteOnTypeMismatch)
7994 ShouldDeleteForTypeMismatch = true;
7995 else {
7996 Diag(MD->getLocation(),
7997 diag::err_defaulted_special_member_volatile_param)
7998 << CSM;
7999 HadError = true;
8000 }
8001 }
8002
8003 if (HasConstParam && !CanHaveConstParam) {
8004 if (DeleteOnTypeMismatch)
8005 ShouldDeleteForTypeMismatch = true;
8006 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8008 Diag(MD->getLocation(),
8009 diag::err_defaulted_special_member_copy_const_param)
8011 // FIXME: Explain why this special member can't be const.
8012 HadError = true;
8013 } else {
8014 Diag(MD->getLocation(),
8015 diag::err_defaulted_special_member_move_const_param)
8017 HadError = true;
8018 }
8019 }
8020 } else if (ExpectedParams) {
8021 // A copy assignment operator can take its argument by value, but a
8022 // defaulted one cannot.
8024 "unexpected non-ref argument");
8025 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8026 HadError = true;
8027 }
8028
8029 // C++11 [dcl.fct.def.default]p2:
8030 // An explicitly-defaulted function may be declared constexpr only if it
8031 // would have been implicitly declared as constexpr,
8032 // Do not apply this rule to members of class templates, since core issue 1358
8033 // makes such functions always instantiate to constexpr functions. For
8034 // functions which cannot be constexpr (for non-constructors in C++11 and for
8035 // destructors in C++14 and C++17), this is checked elsewhere.
8036 //
8037 // FIXME: This should not apply if the member is deleted.
8038 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8039 HasConstParam);
8040
8041 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8042 // If the instantiated template specialization of a constexpr function
8043 // template or member function of a class template would fail to satisfy
8044 // the requirements for a constexpr function or constexpr constructor, that
8045 // specialization is still a constexpr function or constexpr constructor,
8046 // even though a call to such a function cannot appear in a constant
8047 // expression.
8048 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8049 Constexpr = true;
8050
8051 if ((getLangOpts().CPlusPlus20 ||
8053 : isa<CXXConstructorDecl>(MD))) &&
8054 MD->isConstexpr() && !Constexpr &&
8056 if (!MD->isConsteval() && RD->getNumVBases()) {
8057 Diag(MD->getBeginLoc(),
8058 diag::err_incorrect_defaulted_constexpr_with_vb)
8059 << CSM;
8060 for (const auto &I : RD->vbases())
8061 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8062 } else {
8063 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8064 << CSM << MD->isConsteval();
8065 }
8066 HadError = true;
8067 // FIXME: Explain why the special member can't be constexpr.
8068 }
8069
8070 if (First) {
8071 // C++2a [dcl.fct.def.default]p3:
8072 // If a function is explicitly defaulted on its first declaration, it is
8073 // implicitly considered to be constexpr if the implicit declaration
8074 // would be.
8079
8080 if (!Type->hasExceptionSpec()) {
8081 // C++2a [except.spec]p3:
8082 // If a declaration of a function does not have a noexcept-specifier
8083 // [and] is defaulted on its first declaration, [...] the exception
8084 // specification is as specified below
8085 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8087 EPI.ExceptionSpec.SourceDecl = MD;
8088 MD->setType(
8089 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8090 }
8091 }
8092
8093 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8094 if (First) {
8095 SetDeclDeleted(MD, MD->getLocation());
8096 if (!inTemplateInstantiation() && !HadError) {
8097 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8098 if (ShouldDeleteForTypeMismatch) {
8099 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8100 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8101 /*Diagnose*/ true) &&
8102 DefaultLoc.isValid()) {
8103 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8104 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8105 }
8106 }
8107 if (ShouldDeleteForTypeMismatch && !HadError) {
8108 Diag(MD->getLocation(),
8109 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8110 << CSM;
8111 }
8112 } else {
8113 // C++11 [dcl.fct.def.default]p4:
8114 // [For a] user-provided explicitly-defaulted function [...] if such a
8115 // function is implicitly defined as deleted, the program is ill-formed.
8116 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8117 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8118 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8119 HadError = true;
8120 }
8121 }
8122
8123 return HadError;
8124}
8125
8126namespace {
8127/// Helper class for building and checking a defaulted comparison.
8128///
8129/// Defaulted functions are built in two phases:
8130///
8131/// * First, the set of operations that the function will perform are
8132/// identified, and some of them are checked. If any of the checked
8133/// operations is invalid in certain ways, the comparison function is
8134/// defined as deleted and no body is built.
8135/// * Then, if the function is not defined as deleted, the body is built.
8136///
8137/// This is accomplished by performing two visitation steps over the eventual
8138/// body of the function.
8139template<typename Derived, typename ResultList, typename Result,
8140 typename Subobject>
8141class DefaultedComparisonVisitor {
8142public:
8143 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8144
8145 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8146 DefaultedComparisonKind DCK)
8147 : S(S), RD(RD), FD(FD), DCK(DCK) {
8148 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8149 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8150 // UnresolvedSet to avoid this copy.
8151 Fns.assign(Info->getUnqualifiedLookups().begin(),
8152 Info->getUnqualifiedLookups().end());
8153 }
8154 }
8155
8156 ResultList visit() {
8157 // The type of an lvalue naming a parameter of this function.
8158 QualType ParamLvalType =
8160
8161 ResultList Results;
8162
8163 switch (DCK) {
8164 case DefaultedComparisonKind::None:
8165 llvm_unreachable("not a defaulted comparison");
8166
8167 case DefaultedComparisonKind::Equal:
8168 case DefaultedComparisonKind::ThreeWay:
8169 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8170 return Results;
8171
8172 case DefaultedComparisonKind::NotEqual:
8173 case DefaultedComparisonKind::Relational:
8174 Results.add(getDerived().visitExpandedSubobject(
8175 ParamLvalType, getDerived().getCompleteObject()));
8176 return Results;
8177 }
8178 llvm_unreachable("");
8179 }
8180
8181protected:
8182 Derived &getDerived() { return static_cast<Derived&>(*this); }
8183
8184 /// Visit the expanded list of subobjects of the given type, as specified in
8185 /// C++2a [class.compare.default].
8186 ///
8187 /// \return \c true if the ResultList object said we're done, \c false if not.
8188 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8189 Qualifiers Quals) {
8190 // C++2a [class.compare.default]p4:
8191 // The direct base class subobjects of C
8192 for (CXXBaseSpecifier &Base : Record->bases())
8193 if (Results.add(getDerived().visitSubobject(
8194 S.Context.getQualifiedType(Base.getType(), Quals),
8195 getDerived().getBase(&Base))))
8196 return true;
8197
8198 // followed by the non-static data members of C
8199 for (FieldDecl *Field : Record->fields()) {
8200 // C++23 [class.bit]p2:
8201 // Unnamed bit-fields are not members ...
8202 if (Field->isUnnamedBitField())
8203 continue;
8204 // Recursively expand anonymous structs.
8205 if (Field->isAnonymousStructOrUnion()) {
8206 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8207 Quals))
8208 return true;
8209 continue;
8210 }
8211
8212 // Figure out the type of an lvalue denoting this field.
8213 Qualifiers FieldQuals = Quals;
8214 if (Field->isMutable())
8215 FieldQuals.removeConst();
8216 QualType FieldType =
8217 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8218
8219 if (Results.add(getDerived().visitSubobject(
8220 FieldType, getDerived().getField(Field))))
8221 return true;
8222 }
8223
8224 // form a list of subobjects.
8225 return false;
8226 }
8227
8228 Result visitSubobject(QualType Type, Subobject Subobj) {
8229 // In that list, any subobject of array type is recursively expanded
8230 const ArrayType *AT = S.Context.getAsArrayType(Type);
8231 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8232 return getDerived().visitSubobjectArray(CAT->getElementType(),
8233 CAT->getSize(), Subobj);
8234 return getDerived().visitExpandedSubobject(Type, Subobj);
8235 }
8236
8237 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8238 Subobject Subobj) {
8239 return getDerived().visitSubobject(Type, Subobj);
8240 }
8241
8242protected:
8243 Sema &S;
8244 CXXRecordDecl *RD;
8245 FunctionDecl *FD;
8246 DefaultedComparisonKind DCK;
8247 UnresolvedSet<16> Fns;
8248};
8249
8250/// Information about a defaulted comparison, as determined by
8251/// DefaultedComparisonAnalyzer.
8252struct DefaultedComparisonInfo {
8253 bool Deleted = false;
8254 bool Constexpr = true;
8255 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8256
8257 static DefaultedComparisonInfo deleted() {
8258 DefaultedComparisonInfo Deleted;
8259 Deleted.Deleted = true;
8260 return Deleted;
8261 }
8262
8263 bool add(const DefaultedComparisonInfo &R) {
8264 Deleted |= R.Deleted;
8265 Constexpr &= R.Constexpr;
8266 Category = commonComparisonType(Category, R.Category);
8267 return Deleted;
8268 }
8269};
8270
8271/// An element in the expanded list of subobjects of a defaulted comparison, as
8272/// specified in C++2a [class.compare.default]p4.
8273struct DefaultedComparisonSubobject {
8274 enum { CompleteObject, Member, Base } Kind;
8275 NamedDecl *Decl;
8276 SourceLocation Loc;
8277};
8278
8279/// A visitor over the notional body of a defaulted comparison that determines
8280/// whether that body would be deleted or constexpr.
8281class DefaultedComparisonAnalyzer
8282 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8283 DefaultedComparisonInfo,
8284 DefaultedComparisonInfo,
8285 DefaultedComparisonSubobject> {
8286public:
8287 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8288
8289private:
8290 DiagnosticKind Diagnose;
8291
8292public:
8293 using Base = DefaultedComparisonVisitor;
8294 using Result = DefaultedComparisonInfo;
8295 using Subobject = DefaultedComparisonSubobject;
8296
8297 friend Base;
8298
8299 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8300 DefaultedComparisonKind DCK,
8301 DiagnosticKind Diagnose = NoDiagnostics)
8302 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8303
8304 Result visit() {
8305 if ((DCK == DefaultedComparisonKind::Equal ||
8306 DCK == DefaultedComparisonKind::ThreeWay) &&
8307 RD->hasVariantMembers()) {
8308 // C++2a [class.compare.default]p2 [P2002R0]:
8309 // A defaulted comparison operator function for class C is defined as
8310 // deleted if [...] C has variant members.
8311 if (Diagnose == ExplainDeleted) {
8312 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8313 << FD << RD->isUnion() << RD;
8314 }
8315 return Result::deleted();
8316 }
8317
8318 return Base::visit();
8319 }
8320
8321private:
8322 Subobject getCompleteObject() {
8323 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8324 }
8325
8326 Subobject getBase(CXXBaseSpecifier *Base) {
8327 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8328 Base->getBaseTypeLoc()};
8329 }
8330
8331 Subobject getField(FieldDecl *Field) {
8332 return Subobject{Subobject::Member, Field, Field->getLocation()};
8333 }
8334
8335 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8336 // C++2a [class.compare.default]p2 [P2002R0]:
8337 // A defaulted <=> or == operator function for class C is defined as
8338 // deleted if any non-static data member of C is of reference type
8339 if (Type->isReferenceType()) {
8340 if (Diagnose == ExplainDeleted) {
8341 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8342 << FD << RD;
8343 }
8344 return Result::deleted();
8345 }
8346
8347 // [...] Let xi be an lvalue denoting the ith element [...]
8348 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8349 Expr *Args[] = {&Xi, &Xi};
8350
8351 // All operators start by trying to apply that same operator recursively.
8353 assert(OO != OO_None && "not an overloaded operator!");
8354 return visitBinaryOperator(OO, Args, Subobj);
8355 }
8356
8357 Result
8358 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8359 Subobject Subobj,
8360 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8361 // Note that there is no need to consider rewritten candidates here if
8362 // we've already found there is no viable 'operator<=>' candidate (and are
8363 // considering synthesizing a '<=>' from '==' and '<').
8364 OverloadCandidateSet CandidateSet(
8366 OverloadCandidateSet::OperatorRewriteInfo(
8367 OO, FD->getLocation(),
8368 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8369
8370 /// C++2a [class.compare.default]p1 [P2002R0]:
8371 /// [...] the defaulted function itself is never a candidate for overload
8372 /// resolution [...]
8373 CandidateSet.exclude(FD);
8374
8375 if (Args[0]->getType()->isOverloadableType())
8376 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8377 else
8378 // FIXME: We determine whether this is a valid expression by checking to
8379 // see if there's a viable builtin operator candidate for it. That isn't
8380 // really what the rules ask us to do, but should give the right results.
8381 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8382
8383 Result R;
8384
8386 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8387 case OR_Success: {
8388 // C++2a [class.compare.secondary]p2 [P2002R0]:
8389 // The operator function [...] is defined as deleted if [...] the
8390 // candidate selected by overload resolution is not a rewritten
8391 // candidate.
8392 if ((DCK == DefaultedComparisonKind::NotEqual ||
8393 DCK == DefaultedComparisonKind::Relational) &&
8394 !Best->RewriteKind) {
8395 if (Diagnose == ExplainDeleted) {
8396 if (Best->Function) {
8397 S.Diag(Best->Function->getLocation(),
8398 diag::note_defaulted_comparison_not_rewritten_callee)
8399 << FD;
8400 } else {
8401 assert(Best->Conversions.size() == 2 &&
8402 Best->Conversions[0].isUserDefined() &&
8403 "non-user-defined conversion from class to built-in "
8404 "comparison");
8405 S.Diag(Best->Conversions[0]
8406 .UserDefined.FoundConversionFunction.getDecl()
8407 ->getLocation(),
8408 diag::note_defaulted_comparison_not_rewritten_conversion)
8409 << FD;
8410 }
8411 }
8412 return Result::deleted();
8413 }
8414
8415 // Throughout C++2a [class.compare]: if overload resolution does not
8416 // result in a usable function, the candidate function is defined as
8417 // deleted. This requires that we selected an accessible function.
8418 //
8419 // Note that this only considers the access of the function when named
8420 // within the type of the subobject, and not the access path for any
8421 // derived-to-base conversion.
8422 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8423 if (ArgClass && Best->FoundDecl.getDecl() &&
8424 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8425 QualType ObjectType = Subobj.Kind == Subobject::Member
8426 ? Args[0]->getType()
8429 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8430 Diagnose == ExplainDeleted
8431 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8432 << FD << Subobj.Kind << Subobj.Decl
8433 : S.PDiag()))
8434 return Result::deleted();
8435 }
8436
8437 bool NeedsDeducing =
8438 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8439
8440 if (FunctionDecl *BestFD = Best->Function) {
8441 // C++2a [class.compare.default]p3 [P2002R0]:
8442 // A defaulted comparison function is constexpr-compatible if
8443 // [...] no overlod resolution performed [...] results in a
8444 // non-constexpr function.
8445 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8446 // If it's not constexpr, explain why not.
8447 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8448 if (Subobj.Kind != Subobject::CompleteObject)
8449 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8450 << Subobj.Kind << Subobj.Decl;
8451 S.Diag(BestFD->getLocation(),
8452 diag::note_defaulted_comparison_not_constexpr_here);
8453 // Bail out after explaining; we don't want any more notes.
8454 return Result::deleted();
8455 }
8456 R.Constexpr &= BestFD->isConstexpr();
8457
8458 if (NeedsDeducing) {
8459 // If any callee has an undeduced return type, deduce it now.
8460 // FIXME: It's not clear how a failure here should be handled. For
8461 // now, we produce an eager diagnostic, because that is forward
8462 // compatible with most (all?) other reasonable options.
8463 if (BestFD->getReturnType()->isUndeducedType() &&
8464 S.DeduceReturnType(BestFD, FD->getLocation(),
8465 /*Diagnose=*/false)) {
8466 // Don't produce a duplicate error when asked to explain why the
8467 // comparison is deleted: we diagnosed that when initially checking
8468 // the defaulted operator.
8469 if (Diagnose == NoDiagnostics) {
8470 S.Diag(
8471 FD->getLocation(),
8472 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8473 << Subobj.Kind << Subobj.Decl;
8474 S.Diag(
8475 Subobj.Loc,
8476 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8477 << Subobj.Kind << Subobj.Decl;
8478 S.Diag(BestFD->getLocation(),
8479 diag::note_defaulted_comparison_cannot_deduce_callee)
8480 << Subobj.Kind << Subobj.Decl;
8481 }
8482 return Result::deleted();
8483 }
8485 BestFD->getCallResultType());
8486 if (!Info) {
8487 if (Diagnose == ExplainDeleted) {
8488 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8489 << Subobj.Kind << Subobj.Decl
8490 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8491 S.Diag(BestFD->getLocation(),
8492 diag::note_defaulted_comparison_cannot_deduce_callee)
8493 << Subobj.Kind << Subobj.Decl;
8494 }
8495 return Result::deleted();
8496 }
8497 R.Category = Info->Kind;
8498 }
8499 } else {
8500 QualType T = Best->BuiltinParamTypes[0];
8501 assert(T == Best->BuiltinParamTypes[1] &&
8502 "builtin comparison for different types?");
8503 assert(Best->BuiltinParamTypes[2].isNull() &&
8504 "invalid builtin comparison");
8505
8506 // FIXME: If the type we deduced is a vector type, we mark the
8507 // comparison as deleted because we don't yet support this.
8508 if (isa<VectorType>(T)) {
8509 if (Diagnose == ExplainDeleted) {
8510 S.Diag(FD->getLocation(),
8511 diag::note_defaulted_comparison_vector_types)
8512 << FD;
8513 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8514 }
8515 return Result::deleted();
8516 }
8517
8518 if (NeedsDeducing) {
8519 std::optional<ComparisonCategoryType> Cat =
8521 assert(Cat && "no category for builtin comparison?");
8522 R.Category = *Cat;
8523 }
8524 }
8525
8526 // Note that we might be rewriting to a different operator. That call is
8527 // not considered until we come to actually build the comparison function.
8528 break;
8529 }
8530
8531 case OR_Ambiguous:
8532 if (Diagnose == ExplainDeleted) {
8533 unsigned Kind = 0;
8534 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8535 Kind = OO == OO_EqualEqual ? 1 : 2;
8536 CandidateSet.NoteCandidates(
8538 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8539 << FD << Kind << Subobj.Kind << Subobj.Decl),
8540 S, OCD_AmbiguousCandidates, Args);
8541 }
8542 R = Result::deleted();
8543 break;
8544
8545 case OR_Deleted:
8546 if (Diagnose == ExplainDeleted) {
8547 if ((DCK == DefaultedComparisonKind::NotEqual ||
8548 DCK == DefaultedComparisonKind::Relational) &&
8549 !Best->RewriteKind) {
8550 S.Diag(Best->Function->getLocation(),
8551 diag::note_defaulted_comparison_not_rewritten_callee)
8552 << FD;
8553 } else {
8554 S.Diag(Subobj.Loc,
8555 diag::note_defaulted_comparison_calls_deleted)
8556 << FD << Subobj.Kind << Subobj.Decl;
8557 S.NoteDeletedFunction(Best->Function);
8558 }
8559 }
8560 R = Result::deleted();
8561 break;
8562
8564 // If there's no usable candidate, we're done unless we can rewrite a
8565 // '<=>' in terms of '==' and '<'.
8566 if (OO == OO_Spaceship &&
8568 // For any kind of comparison category return type, we need a usable
8569 // '==' and a usable '<'.
8570 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8571 &CandidateSet)))
8572 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8573 break;
8574 }
8575
8576 if (Diagnose == ExplainDeleted) {
8577 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8578 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8579 << Subobj.Kind << Subobj.Decl;
8580
8581 // For a three-way comparison, list both the candidates for the
8582 // original operator and the candidates for the synthesized operator.
8583 if (SpaceshipCandidates) {
8584 SpaceshipCandidates->NoteCandidates(
8585 S, Args,
8586 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8587 Args, FD->getLocation()));
8588 S.Diag(Subobj.Loc,
8589 diag::note_defaulted_comparison_no_viable_function_synthesized)
8590 << (OO == OO_EqualEqual ? 0 : 1);
8591 }
8592
8593 CandidateSet.NoteCandidates(
8594 S, Args,
8595 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8596 FD->getLocation()));
8597 }
8598 R = Result::deleted();
8599 break;
8600 }
8601
8602 return R;
8603 }
8604};
8605
8606/// A list of statements.
8607struct StmtListResult {
8608 bool IsInvalid = false;
8609 llvm::SmallVector<Stmt*, 16> Stmts;
8610
8611 bool add(const StmtResult &S) {
8612 IsInvalid |= S.isInvalid();
8613 if (IsInvalid)
8614 return true;
8615 Stmts.push_back(S.get());
8616 return false;
8617 }
8618};
8619
8620/// A visitor over the notional body of a defaulted comparison that synthesizes
8621/// the actual body.
8622class DefaultedComparisonSynthesizer
8623 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8624 StmtListResult, StmtResult,
8625 std::pair<ExprResult, ExprResult>> {
8626 SourceLocation Loc;
8627 unsigned ArrayDepth = 0;
8628
8629public:
8630 using Base = DefaultedComparisonVisitor;
8631 using ExprPair = std::pair<ExprResult, ExprResult>;
8632
8633 friend Base;
8634
8635 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8636 DefaultedComparisonKind DCK,
8637 SourceLocation BodyLoc)
8638 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8639
8640 /// Build a suitable function body for this defaulted comparison operator.
8641 StmtResult build() {
8642 Sema::CompoundScopeRAII CompoundScope(S);
8643
8644 StmtListResult Stmts = visit();
8645 if (Stmts.IsInvalid)
8646 return StmtError();
8647
8648 ExprResult RetVal;
8649 switch (DCK) {
8650 case DefaultedComparisonKind::None:
8651 llvm_unreachable("not a defaulted comparison");
8652
8653 case DefaultedComparisonKind::Equal: {
8654 // C++2a [class.eq]p3:
8655 // [...] compar[e] the corresponding elements [...] until the first
8656 // index i where xi == yi yields [...] false. If no such index exists,
8657 // V is true. Otherwise, V is false.
8658 //
8659 // Join the comparisons with '&&'s and return the result. Use a right
8660 // fold (traversing the conditions right-to-left), because that
8661 // short-circuits more naturally.
8662 auto OldStmts = std::move(Stmts.Stmts);
8663 Stmts.Stmts.clear();
8664 ExprResult CmpSoFar;
8665 // Finish a particular comparison chain.
8666 auto FinishCmp = [&] {
8667 if (Expr *Prior = CmpSoFar.get()) {
8668 // Convert the last expression to 'return ...;'
8669 if (RetVal.isUnset() && Stmts.Stmts.empty())
8670 RetVal = CmpSoFar;
8671 // Convert any prior comparison to 'if (!(...)) return false;'
8672 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8673 return true;
8674 CmpSoFar = ExprResult();
8675 }
8676 return false;
8677 };
8678 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8679 Expr *E = dyn_cast<Expr>(EAsStmt);
8680 if (!E) {
8681 // Found an array comparison.
8682 if (FinishCmp() || Stmts.add(EAsStmt))
8683 return StmtError();
8684 continue;
8685 }
8686
8687 if (CmpSoFar.isUnset()) {
8688 CmpSoFar = E;
8689 continue;
8690 }
8691 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8692 if (CmpSoFar.isInvalid())
8693 return StmtError();
8694 }
8695 if (FinishCmp())
8696 return StmtError();
8697 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8698 // If no such index exists, V is true.
8699 if (RetVal.isUnset())
8700 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8701 break;
8702 }
8703
8704 case DefaultedComparisonKind::ThreeWay: {
8705 // Per C++2a [class.spaceship]p3, as a fallback add:
8706 // return static_cast<R>(std::strong_ordering::equal);
8707 QualType StrongOrdering = S.CheckComparisonCategoryType(
8708 ComparisonCategoryType::StrongOrdering, Loc,
8709 Sema::ComparisonCategoryUsage::DefaultedOperator);
8710 if (StrongOrdering.isNull())
8711 return StmtError();
8712 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8713 .getValueInfo(ComparisonCategoryResult::Equal)
8714 ->VD;
8715 RetVal = getDecl(EqualVD);
8716 if (RetVal.isInvalid())
8717 return StmtError();
8718 RetVal = buildStaticCastToR(RetVal.get());
8719 break;
8720 }
8721
8722 case DefaultedComparisonKind::NotEqual:
8723 case DefaultedComparisonKind::Relational:
8724 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8725 break;
8726 }
8727
8728 // Build the final return statement.
8729 if (RetVal.isInvalid())
8730 return StmtError();
8731 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8732 if (ReturnStmt.isInvalid())
8733 return StmtError();
8734 Stmts.Stmts.push_back(ReturnStmt.get());
8735
8736 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8737 }
8738
8739private:
8740 ExprResult getDecl(ValueDecl *VD) {
8741 return S.BuildDeclarationNameExpr(
8742 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8743 }
8744
8745 ExprResult getParam(unsigned I) {
8746 ParmVarDecl *PD = FD->getParamDecl(I);
8747 return getDecl(PD);
8748 }
8749
8750 ExprPair getCompleteObject() {
8751 unsigned Param = 0;
8752 ExprResult LHS;
8753 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8754 MD && MD->isImplicitObjectMemberFunction()) {
8755 // LHS is '*this'.
8756 LHS = S.ActOnCXXThis(Loc);
8757 if (!LHS.isInvalid())
8758 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8759 } else {
8760 LHS = getParam(Param++);
8761 }
8762 ExprResult RHS = getParam(Param++);
8763 assert(Param == FD->getNumParams());
8764 return {LHS, RHS};
8765 }
8766
8767 ExprPair getBase(CXXBaseSpecifier *Base) {
8768 ExprPair Obj = getCompleteObject();
8769 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8770 return {ExprError(), ExprError()};
8771 CXXCastPath Path = {Base};
8772 const auto CastToBase = [&](Expr *E) {
8773 QualType ToType = S.Context.getQualifiedType(
8774 Base->getType(), E->getType().getQualifiers());
8775 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8776 };
8777 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8778 }
8779
8780 ExprPair getField(FieldDecl *Field) {
8781 ExprPair Obj = getCompleteObject();
8782 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8783 return {ExprError(), ExprError()};
8784
8785 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8786 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8787 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8788 CXXScopeSpec(), Field, Found, NameInfo),
8789 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8790 CXXScopeSpec(), Field, Found, NameInfo)};
8791 }
8792
8793 // FIXME: When expanding a subobject, register a note in the code synthesis
8794 // stack to say which subobject we're comparing.
8795
8796 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8797 if (Cond.isInvalid())
8798 return StmtError();
8799
8800 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8801 if (NotCond.isInvalid())
8802 return StmtError();
8803
8804 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8805 assert(!False.isInvalid() && "should never fail");
8806 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8807 if (ReturnFalse.isInvalid())
8808 return StmtError();
8809
8810 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8811 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8812 Sema::ConditionKind::Boolean),
8813 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8814 }
8815
8816 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8817 ExprPair Subobj) {
8818 QualType SizeType = S.Context.getSizeType();
8819 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8820
8821 // Build 'size_t i$n = 0'.
8822 IdentifierInfo *IterationVarName = nullptr;
8823 {
8824 SmallString<8> Str;
8825 llvm::raw_svector_ostream OS(Str);
8826 OS << "i" << ArrayDepth;
8827 IterationVarName = &S.Context.Idents.get(OS.str());
8828 }
8829 VarDecl *IterationVar = VarDecl::Create(
8830 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8831 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8832 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8833 IterationVar->setInit(
8834 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8835 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8836
8837 auto IterRef = [&] {
8838 ExprResult Ref = S.BuildDeclarationNameExpr(
8839 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8840 IterationVar);
8841 assert(!Ref.isInvalid() && "can't reference our own variable?");
8842 return Ref.get();
8843 };
8844
8845 // Build 'i$n != Size'.
8846 ExprResult Cond = S.CreateBuiltinBinOp(
8847 Loc, BO_NE, IterRef(),
8848 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8849 assert(!Cond.isInvalid() && "should never fail");
8850
8851 // Build '++i$n'.
8852 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8853 assert(!Inc.isInvalid() && "should never fail");
8854
8855 // Build 'a[i$n]' and 'b[i$n]'.
8856 auto Index = [&](ExprResult E) {
8857 if (E.isInvalid())
8858 return ExprError();
8859 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8860 };
8861 Subobj.first = Index(Subobj.first);
8862 Subobj.second = Index(Subobj.second);
8863
8864 // Compare the array elements.
8865 ++ArrayDepth;
8866 StmtResult Substmt = visitSubobject(Type, Subobj);
8867 --ArrayDepth;
8868
8869 if (Substmt.isInvalid())
8870 return StmtError();
8871
8872 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8873 // For outer levels or for an 'operator<=>' we already have a suitable
8874 // statement that returns as necessary.
8875 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8876 assert(DCK == DefaultedComparisonKind::Equal &&
8877 "should have non-expression statement");
8878 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8879 if (Substmt.isInvalid())
8880 return StmtError();
8881 }
8882
8883 // Build 'for (...) ...'
8884 return S.ActOnForStmt(Loc, Loc, Init,
8885 S.ActOnCondition(nullptr, Loc, Cond.get(),
8886 Sema::ConditionKind::Boolean),
8887 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8888 Substmt.get());
8889 }
8890
8891 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8892 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8893 return StmtError();
8894
8897 ExprResult Op;
8898 if (Type->isOverloadableType())
8899 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8900 Obj.second.get(), /*PerformADL=*/true,
8901 /*AllowRewrittenCandidates=*/true, FD);
8902 else
8903 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8904 if (Op.isInvalid())
8905 return StmtError();
8906
8907 switch (DCK) {
8908 case DefaultedComparisonKind::None:
8909 llvm_unreachable("not a defaulted comparison");
8910
8911 case DefaultedComparisonKind::Equal:
8912 // Per C++2a [class.eq]p2, each comparison is individually contextually
8913 // converted to bool.
8914 Op = S.PerformContextuallyConvertToBool(Op.get());
8915 if (Op.isInvalid())
8916 return StmtError();
8917 return Op.get();
8918
8919 case DefaultedComparisonKind::ThreeWay: {
8920 // Per C++2a [class.spaceship]p3, form:
8921 // if (R cmp = static_cast<R>(op); cmp != 0)
8922 // return cmp;
8923 QualType R = FD->getReturnType();
8924 Op = buildStaticCastToR(Op.get());
8925 if (Op.isInvalid())
8926 return StmtError();
8927
8928 // R cmp = ...;
8929 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8930 VarDecl *VD =
8931 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8932 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8933 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8934 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8935
8936 // cmp != 0
8937 ExprResult VDRef = getDecl(VD);
8938 if (VDRef.isInvalid())
8939 return StmtError();
8940 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8941 Expr *Zero =
8942 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8944 if (VDRef.get()->getType()->isOverloadableType())
8945 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8946 true, FD);
8947 else
8948 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8949 if (Comp.isInvalid())
8950 return StmtError();
8951 Sema::ConditionResult Cond = S.ActOnCondition(
8952 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8953 if (Cond.isInvalid())
8954 return StmtError();
8955
8956 // return cmp;
8957 VDRef = getDecl(VD);
8958 if (VDRef.isInvalid())
8959 return StmtError();
8960 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8961 if (ReturnStmt.isInvalid())
8962 return StmtError();
8963
8964 // if (...)
8965 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8966 Loc, ReturnStmt.get(),
8967 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8968 }
8969
8970 case DefaultedComparisonKind::NotEqual:
8971 case DefaultedComparisonKind::Relational:
8972 // C++2a [class.compare.secondary]p2:
8973 // Otherwise, the operator function yields x @ y.
8974 return Op.get();
8975 }
8976 llvm_unreachable("");
8977 }
8978
8979 /// Build "static_cast<R>(E)".
8980 ExprResult buildStaticCastToR(Expr *E) {
8981 QualType R = FD->getReturnType();
8982 assert(!R->isUndeducedType() && "type should have been deduced already");
8983
8984 // Don't bother forming a no-op cast in the common case.
8985 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8986 return E;
8987 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8988 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8989 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8990 }
8991};
8992}
8993
8994/// Perform the unqualified lookups that might be needed to form a defaulted
8995/// comparison function for the given operator.
8997 UnresolvedSetImpl &Operators,
8999 auto Lookup = [&](OverloadedOperatorKind OO) {
9000 Self.LookupOverloadedOperatorName(OO, S, Operators);
9001 };
9002
9003 // Every defaulted operator looks up itself.
9004 Lookup(Op);
9005 // ... and the rewritten form of itself, if any.
9007 Lookup(ExtraOp);
9008
9009 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9010 // synthesize a three-way comparison from '<' and '=='. In a dependent
9011 // context, we also need to look up '==' in case we implicitly declare a
9012 // defaulted 'operator=='.
9013 if (Op == OO_Spaceship) {
9014 Lookup(OO_ExclaimEqual);
9015 Lookup(OO_Less);
9016 Lookup(OO_EqualEqual);
9017 }
9018}
9019
9022 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9023
9024 // Perform any unqualified lookups we're going to need to default this
9025 // function.
9026 if (S) {
9027 UnresolvedSet<32> Operators;
9028 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9029 FD->getOverloadedOperator());
9032 Context, Operators.pairs()));
9033 }
9034
9035 // C++2a [class.compare.default]p1:
9036 // A defaulted comparison operator function for some class C shall be a
9037 // non-template function declared in the member-specification of C that is
9038 // -- a non-static const non-volatile member of C having one parameter of
9039 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9040 // -- a friend of C having two parameters of type const C& or two
9041 // parameters of type C.
9042
9043 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9044 bool IsMethod = isa<CXXMethodDecl>(FD);
9045 if (IsMethod) {
9046 auto *MD = cast<CXXMethodDecl>(FD);
9047 assert(!MD->isStatic() && "comparison function cannot be a static member");
9048
9049 if (MD->getRefQualifier() == RQ_RValue) {
9050 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9051
9052 // Remove the ref qualifier to recover.
9053 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9054 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9055 EPI.RefQualifier = RQ_None;
9056 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9057 FPT->getParamTypes(), EPI));
9058 }
9059
9060 // If we're out-of-class, this is the class we're comparing.
9061 if (!RD)
9062 RD = MD->getParent();
9063 QualType T = MD->getFunctionObjectParameterReferenceType();
9064 if (!T.getNonReferenceType().isConstQualified() &&
9065 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9066 SourceLocation Loc, InsertLoc;
9067 if (MD->isExplicitObjectMemberFunction()) {
9068 Loc = MD->getParamDecl(0)->getBeginLoc();
9069 InsertLoc = getLocForEndOfToken(
9070 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9071 } else {
9072 Loc = MD->getLocation();
9073 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9074 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9075 }
9076 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9077 // corresponding defaulted 'operator<=>' already.
9078 if (!MD->isImplicit()) {
9079 Diag(Loc, diag::err_defaulted_comparison_non_const)
9080 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9081 }
9082
9083 // Add the 'const' to the type to recover.
9084 if (MD->isExplicitObjectMemberFunction()) {
9085 assert(T->isLValueReferenceType());
9086 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9087 T.getNonReferenceType().withConst()));
9088 } else {
9089 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9090 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9091 EPI.TypeQuals.addConst();
9092 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9093 FPT->getParamTypes(), EPI));
9094 }
9095 }
9096
9097 if (MD->isVolatile()) {
9098 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9099
9100 // Remove the 'volatile' from the type to recover.
9101 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9104 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9105 FPT->getParamTypes(), EPI));
9106 }
9107 }
9108
9109 if ((FD->getNumParams() -
9110 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9111 (IsMethod ? 1 : 2)) {
9112 // Let's not worry about using a variadic template pack here -- who would do
9113 // such a thing?
9114 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9115 << int(IsMethod) << int(DCK);
9116 return true;
9117 }
9118
9119 const ParmVarDecl *KnownParm = nullptr;
9120 for (const ParmVarDecl *Param : FD->parameters()) {
9121 QualType ParmTy = Param->getType();
9122 if (!KnownParm) {
9123 auto CTy = ParmTy;
9124 // Is it `T const &`?
9125 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9126 QualType ExpectedTy;
9127 if (RD)
9128 ExpectedTy = Context.getCanonicalTagType(RD);
9129 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9130 CTy = Ref->getPointeeType();
9131 if (RD)
9132 ExpectedTy.addConst();
9133 Ok = true;
9134 }
9135
9136 // Is T a class?
9137 if (RD) {
9138 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9139 } else {
9140 RD = CTy->getAsCXXRecordDecl();
9141 Ok &= RD != nullptr;
9142 }
9143
9144 if (Ok) {
9145 KnownParm = Param;
9146 } else {
9147 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9148 // corresponding defaulted 'operator<=>' already.
9149 if (!FD->isImplicit()) {
9150 if (RD) {
9151 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9152 QualType RefTy =
9153 Context.getLValueReferenceType(PlainTy.withConst());
9154 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9155 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9156 << Param->getSourceRange();
9157 } else {
9158 assert(!IsMethod && "should know expected type for method");
9159 Diag(FD->getLocation(),
9160 diag::err_defaulted_comparison_param_unknown)
9161 << int(DCK) << ParmTy << Param->getSourceRange();
9162 }
9163 }
9164 return true;
9165 }
9166 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9167 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9168 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9169 << ParmTy << Param->getSourceRange();
9170 return true;
9171 }
9172 }
9173
9174 assert(RD && "must have determined class");
9175 if (IsMethod) {
9176 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9177 // In-class, must be a friend decl.
9178 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9179 } else {
9180 // Out of class, require the defaulted comparison to be a friend (of a
9181 // complete type, per CWG2547).
9182 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9183 diag::err_defaulted_comparison_not_friend, int(DCK),
9184 int(1)))
9185 return true;
9186
9187 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9188 return declaresSameEntity(F->getFriendDecl(), FD);
9189 })) {
9190 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9191 << int(DCK) << int(0) << RD;
9192 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9193 return true;
9194 }
9195 }
9196
9197 // C++2a [class.eq]p1, [class.rel]p1:
9198 // A [defaulted comparison other than <=>] shall have a declared return
9199 // type bool.
9202 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9203 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9204 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9205 << FD->getReturnTypeSourceRange();
9206 return true;
9207 }
9208 // C++2a [class.spaceship]p2 [P2002R0]:
9209 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9210 // R shall not contain a placeholder type.
9211 if (QualType RT = FD->getDeclaredReturnType();
9213 RT->getContainedDeducedType() &&
9214 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9215 RT->getContainedAutoType()->isConstrained())) {
9216 Diag(FD->getLocation(),
9217 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9218 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9219 << FD->getReturnTypeSourceRange();
9220 return true;
9221 }
9222
9223 // For a defaulted function in a dependent class, defer all remaining checks
9224 // until instantiation.
9225 if (RD->isDependentType())
9226 return false;
9227
9228 // Determine whether the function should be defined as deleted.
9229 DefaultedComparisonInfo Info =
9230 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9231
9232 bool First = FD == FD->getCanonicalDecl();
9233
9234 if (!First) {
9235 if (Info.Deleted) {
9236 // C++11 [dcl.fct.def.default]p4:
9237 // [For a] user-provided explicitly-defaulted function [...] if such a
9238 // function is implicitly defined as deleted, the program is ill-formed.
9239 //
9240 // This is really just a consequence of the general rule that you can
9241 // only delete a function on its first declaration.
9242 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9243 << FD->isImplicit() << (int)DCK;
9244 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9245 DefaultedComparisonAnalyzer::ExplainDeleted)
9246 .visit();
9247 return true;
9248 }
9250 // C++20 [class.compare.default]p1:
9251 // [...] A definition of a comparison operator as defaulted that appears
9252 // in a class shall be the first declaration of that function.
9253 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9254 << (int)DCK;
9256 diag::note_previous_declaration);
9257 return true;
9258 }
9259 }
9260
9261 // If we want to delete the function, then do so; there's nothing else to
9262 // check in that case.
9263 if (Info.Deleted) {
9264 SetDeclDeleted(FD, FD->getLocation());
9265 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9266 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9267 << (int)DCK;
9268 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9269 DefaultedComparisonAnalyzer::ExplainDeleted)
9270 .visit();
9271 if (FD->getDefaultLoc().isValid())
9272 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9273 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9274 }
9275 return false;
9276 }
9277
9278 // C++2a [class.spaceship]p2:
9279 // The return type is deduced as the common comparison type of R0, R1, ...
9283 if (RetLoc.isInvalid())
9284 RetLoc = FD->getBeginLoc();
9285 // FIXME: Should we really care whether we have the complete type and the
9286 // 'enumerator' constants here? A forward declaration seems sufficient.
9288 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9289 if (Cat.isNull())
9290 return true;
9291 Context.adjustDeducedFunctionResultType(
9292 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9293 }
9294
9295 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9296 // An explicitly-defaulted function that is not defined as deleted may be
9297 // declared constexpr or consteval only if it is constexpr-compatible.
9298 // C++2a [class.compare.default]p3 [P2002R0]:
9299 // A defaulted comparison function is constexpr-compatible if it satisfies
9300 // the requirements for a constexpr function [...]
9301 // The only relevant requirements are that the parameter and return types are
9302 // literal types. The remaining conditions are checked by the analyzer.
9303 //
9304 // We support P2448R2 in language modes earlier than C++23 as an extension.
9305 // The concept of constexpr-compatible was removed.
9306 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9307 // A function explicitly defaulted on its first declaration is implicitly
9308 // inline, and is implicitly constexpr if it is constexpr-suitable.
9309 // C++23 [dcl.constexpr]p3
9310 // A function is constexpr-suitable if
9311 // - it is not a coroutine, and
9312 // - if the function is a constructor or destructor, its class does not
9313 // have any virtual base classes.
9314 if (FD->isConstexpr()) {
9315 if (!getLangOpts().CPlusPlus23 &&
9318 !Info.Constexpr) {
9319 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9320 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9321 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9322 DefaultedComparisonAnalyzer::ExplainConstexpr)
9323 .visit();
9324 }
9325 }
9326
9327 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9328 // If a constexpr-compatible function is explicitly defaulted on its first
9329 // declaration, it is implicitly considered to be constexpr.
9330 // FIXME: Only applying this to the first declaration seems problematic, as
9331 // simple reorderings can affect the meaning of the program.
9332 if (First && !FD->isConstexpr() && Info.Constexpr)
9334
9335 // C++2a [except.spec]p3:
9336 // If a declaration of a function does not have a noexcept-specifier
9337 // [and] is defaulted on its first declaration, [...] the exception
9338 // specification is as specified below
9339 if (FD->getExceptionSpecType() == EST_None) {
9340 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9341 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9343 EPI.ExceptionSpec.SourceDecl = FD;
9344 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9345 FPT->getParamTypes(), EPI));
9346 }
9347
9348 return false;
9349}
9350
9352 FunctionDecl *Spaceship) {
9355 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9356 Ctx.Entity = Spaceship;
9358
9359 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9360 EqualEqual->setImplicit();
9361
9363}
9364
9367 assert(FD->isDefaulted() && !FD->isDeleted() &&
9369 if (FD->willHaveBody() || FD->isInvalidDecl())
9370 return;
9371
9373
9374 // Add a context note for diagnostics produced after this point.
9375 Scope.addContextNote(UseLoc);
9376
9377 {
9378 // Build and set up the function body.
9379 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9380 // the type of the class being compared.
9381 auto PT = FD->getParamDecl(0)->getType();
9382 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9383 SourceLocation BodyLoc =
9384 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9385 StmtResult Body =
9386 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9387 if (Body.isInvalid()) {
9388 FD->setInvalidDecl();
9389 return;
9390 }
9391 FD->setBody(Body.get());
9392 FD->markUsed(Context);
9393 }
9394
9395 // The exception specification is needed because we are defining the
9396 // function. Note that this will reuse the body we just built.
9398
9400 L->CompletedImplicitDefinition(FD);
9401}
9402
9405 FunctionDecl *FD,
9407 ComputingExceptionSpec CES(S, FD, Loc);
9409
9410 if (FD->isInvalidDecl())
9411 return ExceptSpec;
9412
9413 // The common case is that we just defined the comparison function. In that
9414 // case, just look at whether the body can throw.
9415 if (FD->hasBody()) {
9416 ExceptSpec.CalledStmt(FD->getBody());
9417 } else {
9418 // Otherwise, build a body so we can check it. This should ideally only
9419 // happen when we're not actually marking the function referenced. (This is
9420 // only really important for efficiency: we don't want to build and throw
9421 // away bodies for comparison functions more than we strictly need to.)
9422
9423 // Pretend to synthesize the function body in an unevaluated context.
9424 // Note that we can't actually just go ahead and define the function here:
9425 // we are not permitted to mark its callees as referenced.
9429
9430 CXXRecordDecl *RD =
9432 ? FD->getDeclContext()
9433 : FD->getLexicalDeclContext());
9434 SourceLocation BodyLoc =
9435 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9436 StmtResult Body =
9437 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9438 if (!Body.isInvalid())
9439 ExceptSpec.CalledStmt(Body.get());
9440
9441 // FIXME: Can we hold onto this body and just transform it to potentially
9442 // evaluated when we're asked to define the function rather than rebuilding
9443 // it? Either that, or we should only build the bits of the body that we
9444 // need (the expressions, not the statements).
9445 }
9446
9447 return ExceptSpec;
9448}
9449
9451 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9453
9454 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9456
9457 // Perform any deferred checking of exception specifications for virtual
9458 // destructors.
9459 for (auto &Check : Overriding)
9460 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9461
9462 // Perform any deferred checking of exception specifications for befriended
9463 // special members.
9464 for (auto &Check : Equivalent)
9465 CheckEquivalentExceptionSpec(Check.second, Check.first);
9466}
9467
9468namespace {
9469/// CRTP base class for visiting operations performed by a special member
9470/// function (or inherited constructor).
9471template<typename Derived>
9472struct SpecialMemberVisitor {
9473 Sema &S;
9474 CXXMethodDecl *MD;
9477
9478 // Properties of the special member, computed for convenience.
9479 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9480
9481 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9483 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9484 switch (CSM) {
9488 IsConstructor = true;
9489 break;
9492 IsAssignment = true;
9493 break;
9495 break;
9497 llvm_unreachable("invalid special member kind");
9498 }
9499
9500 if (MD->getNumExplicitParams()) {
9501 if (const ReferenceType *RT =
9502 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9503 ConstArg = RT->getPointeeType().isConstQualified();
9504 }
9505 }
9506
9507 Derived &getDerived() { return static_cast<Derived&>(*this); }
9508
9509 /// Is this a "move" special member?
9510 bool isMove() const {
9511 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9512 CSM == CXXSpecialMemberKind::MoveAssignment;
9513 }
9514
9515 /// Look up the corresponding special member in the given class.
9516 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9517 unsigned Quals, bool IsMutable) {
9518 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9519 ConstArg && !IsMutable);
9520 }
9521
9522 /// Look up the constructor for the specified base class to see if it's
9523 /// overridden due to this being an inherited constructor.
9524 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9525 if (!ICI)
9526 return {};
9527 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9528 auto *BaseCtor =
9529 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9530 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9531 return MD;
9532 return {};
9533 }
9534
9535 /// A base or member subobject.
9536 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9537
9538 /// Get the location to use for a subobject in diagnostics.
9539 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9540 // FIXME: For an indirect virtual base, the direct base leading to
9541 // the indirect virtual base would be a more useful choice.
9542 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9543 return B->getBaseTypeLoc();
9544 else
9545 return cast<FieldDecl *>(Subobj)->getLocation();
9546 }
9547
9548 enum BasesToVisit {
9549 /// Visit all non-virtual (direct) bases.
9550 VisitNonVirtualBases,
9551 /// Visit all direct bases, virtual or not.
9552 VisitDirectBases,
9553 /// Visit all non-virtual bases, and all virtual bases if the class
9554 /// is not abstract.
9555 VisitPotentiallyConstructedBases,
9556 /// Visit all direct or virtual bases.
9557 VisitAllBases
9558 };
9559
9560 // Visit the bases and members of the class.
9561 bool visit(BasesToVisit Bases) {
9562 CXXRecordDecl *RD = MD->getParent();
9563
9564 if (Bases == VisitPotentiallyConstructedBases)
9565 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9566
9567 for (auto &B : RD->bases())
9568 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9569 getDerived().visitBase(&B))
9570 return true;
9571
9572 if (Bases == VisitAllBases)
9573 for (auto &B : RD->vbases())
9574 if (getDerived().visitBase(&B))
9575 return true;
9576
9577 for (auto *F : RD->fields())
9578 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9579 getDerived().visitField(F))
9580 return true;
9581
9582 return false;
9583 }
9584};
9585}
9586
9587namespace {
9588struct SpecialMemberDeletionInfo
9589 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9590 bool Diagnose;
9591
9592 SourceLocation Loc;
9593
9594 bool AllFieldsAreConst;
9595
9596 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9598 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9599 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9600 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9601
9602 bool inUnion() const { return MD->getParent()->isUnion(); }
9603
9604 CXXSpecialMemberKind getEffectiveCSM() {
9605 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9606 }
9607
9608 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9609
9610 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9611
9612 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9613 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9614
9615 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9616 bool shouldDeleteForField(FieldDecl *FD);
9617 bool shouldDeleteForAllConstMembers();
9618
9619 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9620 unsigned Quals);
9621 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9622 Sema::SpecialMemberOverloadResult SMOR,
9623 bool IsDtorCallInCtor);
9624
9625 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9626};
9627}
9628
9629/// Is the given special member inaccessible when used on the given
9630/// sub-object.
9631bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9632 CXXMethodDecl *target) {
9633 /// If we're operating on a base class, the object type is the
9634 /// type of this special member.
9635 CanQualType objectTy;
9636 AccessSpecifier access = target->getAccess();
9637 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9638 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9639 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9640
9641 // If we're operating on a field, the object type is the type of the field.
9642 } else {
9643 objectTy = S.Context.getCanonicalTagType(target->getParent());
9644 }
9645
9647 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9648}
9649
9650/// Check whether we should delete a special member due to the implicit
9651/// definition containing a call to a special member of a subobject.
9652bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9653 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9654 bool IsDtorCallInCtor) {
9655 CXXMethodDecl *Decl = SMOR.getMethod();
9656 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9657
9658 enum {
9659 NotSet = -1,
9660 NoDecl,
9661 DeletedDecl,
9662 MultipleDecl,
9663 InaccessibleDecl,
9664 NonTrivialDecl
9665 } DiagKind = NotSet;
9666
9668 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9669 Field->getParent()->isUnion()) {
9670 // [class.default.ctor]p2:
9671 // A defaulted default constructor for class X is defined as deleted if
9672 // - X is a union that has a variant member with a non-trivial default
9673 // constructor and no variant member of X has a default member
9674 // initializer
9675 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9676 if (RD->hasInClassInitializer())
9677 return false;
9678 }
9679 DiagKind = !Decl ? NoDecl : DeletedDecl;
9681 DiagKind = MultipleDecl;
9682 else if (!isAccessible(Subobj, Decl))
9683 DiagKind = InaccessibleDecl;
9684 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9685 !Decl->isTrivial()) {
9686 // A member of a union must have a trivial corresponding special member.
9687 // As a weird special case, a destructor call from a union's constructor
9688 // must be accessible and non-deleted, but need not be trivial. Such a
9689 // destructor is never actually called, but is semantically checked as
9690 // if it were.
9691 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9692 // [class.default.ctor]p2:
9693 // A defaulted default constructor for class X is defined as deleted if
9694 // - X is a union that has a variant member with a non-trivial default
9695 // constructor and no variant member of X has a default member
9696 // initializer
9697 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9698 if (!RD->hasInClassInitializer())
9699 DiagKind = NonTrivialDecl;
9700 } else {
9701 DiagKind = NonTrivialDecl;
9702 }
9703 }
9704
9705 if (DiagKind == NotSet)
9706 return false;
9707
9708 if (Diagnose) {
9709 if (Field) {
9710 S.Diag(Field->getLocation(),
9711 diag::note_deleted_special_member_class_subobject)
9712 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9713 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9714 } else {
9715 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9716 S.Diag(Base->getBeginLoc(),
9717 diag::note_deleted_special_member_class_subobject)
9718 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9719 << Base->getType() << DiagKind << IsDtorCallInCtor
9720 << /*IsObjCPtr*/ false;
9721 }
9722
9723 if (DiagKind == DeletedDecl)
9724 S.NoteDeletedFunction(Decl);
9725 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9726 }
9727
9728 return true;
9729}
9730
9731/// Check whether we should delete a special member function due to having a
9732/// direct or virtual base class or non-static data member of class type M.
9733bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9734 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9735 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9736 bool IsMutable = Field && Field->isMutable();
9737
9738 // C++11 [class.ctor]p5:
9739 // -- any direct or virtual base class, or non-static data member with no
9740 // brace-or-equal-initializer, has class type M (or array thereof) and
9741 // either M has no default constructor or overload resolution as applied
9742 // to M's default constructor results in an ambiguity or in a function
9743 // that is deleted or inaccessible
9744 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9745 // -- a direct or virtual base class B that cannot be copied/moved because
9746 // overload resolution, as applied to B's corresponding special member,
9747 // results in an ambiguity or a function that is deleted or inaccessible
9748 // from the defaulted special member
9749 // C++11 [class.dtor]p5:
9750 // -- any direct or virtual base class [...] has a type with a destructor
9751 // that is deleted or inaccessible
9752 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9753 Field->hasInClassInitializer()) &&
9754 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9755 false))
9756 return true;
9757
9758 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9759 // -- any direct or virtual base class or non-static data member has a
9760 // type with a destructor that is deleted or inaccessible
9761 if (IsConstructor) {
9762 Sema::SpecialMemberOverloadResult SMOR =
9763 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9764 false, false, false, false);
9765 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9766 return true;
9767 }
9768
9769 return false;
9770}
9771
9772bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9773 FieldDecl *FD, QualType FieldType) {
9774 // The defaulted special functions are defined as deleted if this is a variant
9775 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9776 // type under ARC.
9777 if (!FieldType.hasNonTrivialObjCLifetime())
9778 return false;
9779
9780 // Don't make the defaulted default constructor defined as deleted if the
9781 // member has an in-class initializer.
9782 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9784 return false;
9785
9786 if (Diagnose) {
9787 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9788 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9789 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9790 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9791 }
9792
9793 return true;
9794}
9795
9796bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9797 const FieldDecl *FD) {
9798 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9799 // Copy/move constructors/assignment operators are deleted if the field has an
9800 // address-discriminated ptrauth qualifier.
9801 PointerAuthQualifier Q = FieldType.getPointerAuth();
9802
9803 if (!Q || !Q.isAddressDiscriminated())
9804 return false;
9805
9806 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9807 CSM == CXXSpecialMemberKind::Destructor)
9808 return false;
9809
9810 if (Diagnose) {
9811 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9812 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9813 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9814 << /*IsDtorCallInCtor*/ false << 2;
9815 }
9816
9817 return true;
9818}
9819
9820/// Check whether we should delete a special member function due to the class
9821/// having a particular direct or virtual base class.
9822bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9823 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9824 // If program is correct, BaseClass cannot be null, but if it is, the error
9825 // must be reported elsewhere.
9826 if (!BaseClass)
9827 return false;
9828 // If we have an inheriting constructor, check whether we're calling an
9829 // inherited constructor instead of a default constructor.
9830 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9831 if (auto *BaseCtor = SMOR.getMethod()) {
9832 // Note that we do not check access along this path; other than that,
9833 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9834 // FIXME: Check that the base has a usable destructor! Sink this into
9835 // shouldDeleteForClassSubobject.
9836 if (BaseCtor->isDeleted() && Diagnose) {
9837 S.Diag(Base->getBeginLoc(),
9838 diag::note_deleted_special_member_class_subobject)
9839 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9840 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9841 << /*IsObjCPtr*/ false;
9842 S.NoteDeletedFunction(BaseCtor);
9843 }
9844 return BaseCtor->isDeleted();
9845 }
9846 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9847}
9848
9849/// Check whether we should delete a special member function due to the class
9850/// having a particular non-static data member.
9851bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9852 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9853 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9854
9855 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9856 return true;
9857
9858 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9859 return true;
9860
9861 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9862 // For a default constructor, all references must be initialized in-class
9863 // and, if a union, it must have a non-const member.
9864 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9865 if (Diagnose)
9866 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9867 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9868 return true;
9869 }
9870 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9871 // data member of const-qualified type (or array thereof) with no
9872 // brace-or-equal-initializer is not const-default-constructible.
9873 if (!inUnion() && FieldType.isConstQualified() &&
9874 !FD->hasInClassInitializer() &&
9875 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9876 if (Diagnose)
9877 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9878 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9879 return true;
9880 }
9881
9882 if (inUnion() && !FieldType.isConstQualified())
9883 AllFieldsAreConst = false;
9884 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9885 // For a copy constructor, data members must not be of rvalue reference
9886 // type.
9887 if (FieldType->isRValueReferenceType()) {
9888 if (Diagnose)
9889 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9890 << MD->getParent() << FD << FieldType;
9891 return true;
9892 }
9893 } else if (IsAssignment) {
9894 // For an assignment operator, data members must not be of reference type.
9895 if (FieldType->isReferenceType()) {
9896 if (Diagnose)
9897 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9898 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9899 return true;
9900 }
9901 if (!FieldRecord && FieldType.isConstQualified()) {
9902 // C++11 [class.copy]p23:
9903 // -- a non-static data member of const non-class type (or array thereof)
9904 if (Diagnose)
9905 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9906 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9907 return true;
9908 }
9909 }
9910
9911 if (FieldRecord) {
9912 // Some additional restrictions exist on the variant members.
9913 if (!inUnion() && FieldRecord->isUnion() &&
9914 FieldRecord->isAnonymousStructOrUnion()) {
9915 bool AllVariantFieldsAreConst = true;
9916
9917 // FIXME: Handle anonymous unions declared within anonymous unions.
9918 for (auto *UI : FieldRecord->fields()) {
9919 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9920
9921 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9922 return true;
9923
9924 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9925 return true;
9926
9927 if (!UnionFieldType.isConstQualified())
9928 AllVariantFieldsAreConst = false;
9929
9930 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9931 if (UnionFieldRecord &&
9932 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9933 UnionFieldType.getCVRQualifiers()))
9934 return true;
9935 }
9936
9937 // At least one member in each anonymous union must be non-const
9938 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9939 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9940 if (Diagnose)
9941 S.Diag(FieldRecord->getLocation(),
9942 diag::note_deleted_default_ctor_all_const)
9943 << !!ICI << MD->getParent() << /*anonymous union*/1;
9944 return true;
9945 }
9946
9947 // Don't check the implicit member of the anonymous union type.
9948 // This is technically non-conformant but supported, and we have a
9949 // diagnostic for this elsewhere.
9950 return false;
9951 }
9952
9953 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9954 FieldType.getCVRQualifiers()))
9955 return true;
9956 }
9957
9958 return false;
9959}
9960
9961/// C++11 [class.ctor] p5:
9962/// A defaulted default constructor for a class X is defined as deleted if
9963/// X is a union and all of its variant members are of const-qualified type.
9964bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9965 // This is a silly definition, because it gives an empty union a deleted
9966 // default constructor. Don't do that.
9967 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9968 AllFieldsAreConst) {
9969 bool AnyFields = false;
9970 for (auto *F : MD->getParent()->fields())
9971 if ((AnyFields = !F->isUnnamedBitField()))
9972 break;
9973 if (!AnyFields)
9974 return false;
9975 if (Diagnose)
9976 S.Diag(MD->getParent()->getLocation(),
9977 diag::note_deleted_default_ctor_all_const)
9978 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9979 return true;
9980 }
9981 return false;
9982}
9983
9984/// Determine whether a defaulted special member function should be defined as
9985/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9986/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9990 bool Diagnose) {
9991 if (MD->isInvalidDecl())
9992 return false;
9993 CXXRecordDecl *RD = MD->getParent();
9994 assert(!RD->isDependentType() && "do deletion after instantiation");
9995 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9996 RD->isInvalidDecl())
9997 return false;
9998
9999 // C++11 [expr.lambda.prim]p19:
10000 // The closure type associated with a lambda-expression has a
10001 // deleted (8.4.3) default constructor and a deleted copy
10002 // assignment operator.
10003 // C++2a adds back these operators if the lambda has no lambda-capture.
10007 if (Diagnose)
10008 Diag(RD->getLocation(), diag::note_lambda_decl);
10009 return true;
10010 }
10011
10012 // C++11 [class.copy]p7, p18:
10013 // If the class definition declares a move constructor or move assignment
10014 // operator, an implicitly declared copy constructor or copy assignment
10015 // operator is defined as deleted.
10018 CXXMethodDecl *UserDeclaredMove = nullptr;
10019
10020 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10021 // deletion of the corresponding copy operation, not both copy operations.
10022 // MSVC 2015 has adopted the standards conforming behavior.
10023 bool DeletesOnlyMatchingCopy =
10024 getLangOpts().MSVCCompat &&
10025 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10026
10028 (!DeletesOnlyMatchingCopy ||
10030 if (!Diagnose) return true;
10031
10032 // Find any user-declared move constructor.
10033 for (auto *I : RD->ctors()) {
10034 if (I->isMoveConstructor()) {
10035 UserDeclaredMove = I;
10036 break;
10037 }
10038 }
10039 assert(UserDeclaredMove);
10040 } else if (RD->hasUserDeclaredMoveAssignment() &&
10041 (!DeletesOnlyMatchingCopy ||
10043 if (!Diagnose) return true;
10044
10045 // Find any user-declared move assignment operator.
10046 for (auto *I : RD->methods()) {
10047 if (I->isMoveAssignmentOperator()) {
10048 UserDeclaredMove = I;
10049 break;
10050 }
10051 }
10052 assert(UserDeclaredMove);
10053 }
10054
10055 if (UserDeclaredMove) {
10056 Diag(UserDeclaredMove->getLocation(),
10057 diag::note_deleted_copy_user_declared_move)
10058 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10059 << UserDeclaredMove->isMoveAssignmentOperator();
10060 return true;
10061 }
10062 }
10063
10064 // Do access control from the special member function
10065 ContextRAII MethodContext(*this, MD);
10066
10067 // C++11 [class.dtor]p5:
10068 // -- for a virtual destructor, lookup of the non-array deallocation function
10069 // results in an ambiguity or in a function that is deleted or inaccessible
10070 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10071 FunctionDecl *OperatorDelete = nullptr;
10072 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10073 DeclarationName Name =
10074 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10078 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10079 OperatorDelete, IDP,
10080 /*Diagnose=*/false)) {
10081 if (Diagnose)
10082 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10083 return true;
10084 }
10085 }
10086
10087 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10088
10089 // Per DR1611, do not consider virtual bases of constructors of abstract
10090 // classes, since we are not going to construct them.
10091 // Per DR1658, do not consider virtual bases of destructors of abstract
10092 // classes either.
10093 // Per DR2180, for assignment operators we only assign (and thus only
10094 // consider) direct bases.
10095 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10096 : SMI.VisitPotentiallyConstructedBases))
10097 return true;
10098
10099 if (SMI.shouldDeleteForAllConstMembers())
10100 return true;
10101
10102 if (getLangOpts().CUDA) {
10103 // We should delete the special member in CUDA mode if target inference
10104 // failed.
10105 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10106 // is treated as certain special member, which may not reflect what special
10107 // member MD really is. However inferTargetForImplicitSpecialMember
10108 // expects CSM to match MD, therefore recalculate CSM.
10109 assert(ICI || CSM == getSpecialMember(MD));
10110 auto RealCSM = CSM;
10111 if (ICI)
10112 RealCSM = getSpecialMember(MD);
10113
10114 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10115 SMI.ConstArg, Diagnose);
10116 }
10117
10118 return false;
10119}
10120
10123 assert(DFK && "not a defaultable function");
10124 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10125
10126 if (DFK.isSpecialMember()) {
10128 nullptr, /*Diagnose=*/true);
10129 } else {
10130 DefaultedComparisonAnalyzer(
10132 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10133 .visit();
10134 }
10135}
10136
10137/// Perform lookup for a special member of the specified kind, and determine
10138/// whether it is trivial. If the triviality can be determined without the
10139/// lookup, skip it. This is intended for use when determining whether a
10140/// special member of a containing object is trivial, and thus does not ever
10141/// perform overload resolution for default constructors.
10142///
10143/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10144/// member that was most likely to be intended to be trivial, if any.
10145///
10146/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10147/// determine whether the special member is trivial.
10149 CXXSpecialMemberKind CSM, unsigned Quals,
10150 bool ConstRHS, TrivialABIHandling TAH,
10151 CXXMethodDecl **Selected) {
10152 if (Selected)
10153 *Selected = nullptr;
10154
10155 switch (CSM) {
10157 llvm_unreachable("not a special member");
10158
10160 // C++11 [class.ctor]p5:
10161 // A default constructor is trivial if:
10162 // - all the [direct subobjects] have trivial default constructors
10163 //
10164 // Note, no overload resolution is performed in this case.
10166 return true;
10167
10168 if (Selected) {
10169 // If there's a default constructor which could have been trivial, dig it
10170 // out. Otherwise, if there's any user-provided default constructor, point
10171 // to that as an example of why there's not a trivial one.
10172 CXXConstructorDecl *DefCtor = nullptr;
10175 for (auto *CI : RD->ctors()) {
10176 if (!CI->isDefaultConstructor())
10177 continue;
10178 DefCtor = CI;
10179 if (!DefCtor->isUserProvided())
10180 break;
10181 }
10182
10183 *Selected = DefCtor;
10184 }
10185
10186 return false;
10187
10189 // C++11 [class.dtor]p5:
10190 // A destructor is trivial if:
10191 // - all the direct [subobjects] have trivial destructors
10192 if (RD->hasTrivialDestructor() ||
10195 return true;
10196
10197 if (Selected) {
10198 if (RD->needsImplicitDestructor())
10200 *Selected = RD->getDestructor();
10201 }
10202
10203 return false;
10204
10206 // C++11 [class.copy]p12:
10207 // A copy constructor is trivial if:
10208 // - the constructor selected to copy each direct [subobject] is trivial
10209 if (RD->hasTrivialCopyConstructor() ||
10212 if (Quals == Qualifiers::Const)
10213 // We must either select the trivial copy constructor or reach an
10214 // ambiguity; no need to actually perform overload resolution.
10215 return true;
10216 } else if (!Selected) {
10217 return false;
10218 }
10219 // In C++98, we are not supposed to perform overload resolution here, but we
10220 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10221 // cases like B as having a non-trivial copy constructor:
10222 // struct A { template<typename T> A(T&); };
10223 // struct B { mutable A a; };
10224 goto NeedOverloadResolution;
10225
10227 // C++11 [class.copy]p25:
10228 // A copy assignment operator is trivial if:
10229 // - the assignment operator selected to copy each direct [subobject] is
10230 // trivial
10231 if (RD->hasTrivialCopyAssignment()) {
10232 if (Quals == Qualifiers::Const)
10233 return true;
10234 } else if (!Selected) {
10235 return false;
10236 }
10237 // In C++98, we are not supposed to perform overload resolution here, but we
10238 // treat that as a language defect.
10239 goto NeedOverloadResolution;
10240
10243 NeedOverloadResolution:
10245 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10246
10247 // The standard doesn't describe how to behave if the lookup is ambiguous.
10248 // We treat it as not making the member non-trivial, just like the standard
10249 // mandates for the default constructor. This should rarely matter, because
10250 // the member will also be deleted.
10252 return true;
10253
10254 if (!SMOR.getMethod()) {
10255 assert(SMOR.getKind() ==
10257 return false;
10258 }
10259
10260 // We deliberately don't check if we found a deleted special member. We're
10261 // not supposed to!
10262 if (Selected)
10263 *Selected = SMOR.getMethod();
10264
10268 return SMOR.getMethod()->isTrivialForCall();
10269 return SMOR.getMethod()->isTrivial();
10270 }
10271
10272 llvm_unreachable("unknown special method kind");
10273}
10274
10276 for (auto *CI : RD->ctors())
10277 if (!CI->isImplicit())
10278 return CI;
10279
10280 // Look for constructor templates.
10282 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10283 if (CXXConstructorDecl *CD =
10284 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10285 return CD;
10286 }
10287
10288 return nullptr;
10289}
10290
10291/// The kind of subobject we are checking for triviality. The values of this
10292/// enumeration are used in diagnostics.
10294 /// The subobject is a base class.
10296 /// The subobject is a non-static data member.
10298 /// The object is actually the complete object.
10300};
10301
10302/// Check whether the special member selected for a given type would be trivial.
10304 QualType SubType, bool ConstRHS,
10307 TrivialABIHandling TAH, bool Diagnose) {
10308 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10309 if (!SubRD)
10310 return true;
10311
10312 CXXMethodDecl *Selected;
10313 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10314 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10315 return true;
10316
10317 if (Diagnose) {
10318 if (ConstRHS)
10319 SubType.addConst();
10320
10321 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10322 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10323 << Kind << SubType.getUnqualifiedType();
10325 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10326 } else if (!Selected)
10327 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10328 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10329 else if (Selected->isUserProvided()) {
10330 if (Kind == TSK_CompleteObject)
10331 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10332 << Kind << SubType.getUnqualifiedType() << CSM;
10333 else {
10334 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10335 << Kind << SubType.getUnqualifiedType() << CSM;
10336 S.Diag(Selected->getLocation(), diag::note_declared_at);
10337 }
10338 } else {
10339 if (Kind != TSK_CompleteObject)
10340 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10341 << Kind << SubType.getUnqualifiedType() << CSM;
10342
10343 // Explain why the defaulted or deleted special member isn't trivial.
10344 S.SpecialMemberIsTrivial(Selected, CSM,
10346 }
10347 }
10348
10349 return false;
10350}
10351
10352/// Check whether the members of a class type allow a special member to be
10353/// trivial.
10355 CXXSpecialMemberKind CSM, bool ConstArg,
10356 TrivialABIHandling TAH, bool Diagnose) {
10357 for (const auto *FI : RD->fields()) {
10358 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10359 continue;
10360
10361 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10362
10363 // Pretend anonymous struct or union members are members of this class.
10364 if (FI->isAnonymousStructOrUnion()) {
10365 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10366 CSM, ConstArg, TAH, Diagnose))
10367 return false;
10368 continue;
10369 }
10370
10371 // C++11 [class.ctor]p5:
10372 // A default constructor is trivial if [...]
10373 // -- no non-static data member of its class has a
10374 // brace-or-equal-initializer
10376 FI->hasInClassInitializer()) {
10377 if (Diagnose)
10378 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10379 << FI;
10380 return false;
10381 }
10382
10383 // Objective C ARC 4.3.5:
10384 // [...] nontrivally ownership-qualified types are [...] not trivially
10385 // default constructible, copy constructible, move constructible, copy
10386 // assignable, move assignable, or destructible [...]
10387 if (FieldType.hasNonTrivialObjCLifetime()) {
10388 if (Diagnose)
10389 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10390 << RD << FieldType.getObjCLifetime();
10391 return false;
10392 }
10393
10394 bool ConstRHS = ConstArg && !FI->isMutable();
10395 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10396 CSM, TSK_Field, TAH, Diagnose))
10397 return false;
10398 }
10399
10400 return true;
10401}
10402
10405 CanQualType Ty = Context.getCanonicalTagType(RD);
10406
10407 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10409 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10412 /*Diagnose*/ true);
10413}
10414
10416 TrivialABIHandling TAH, bool Diagnose) {
10417 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10418 "not special enough");
10419
10420 CXXRecordDecl *RD = MD->getParent();
10421
10422 bool ConstArg = false;
10423
10424 // C++11 [class.copy]p12, p25: [DR1593]
10425 // A [special member] is trivial if [...] its parameter-type-list is
10426 // equivalent to the parameter-type-list of an implicit declaration [...]
10427 switch (CSM) {
10430 // Trivial default constructors and destructors cannot have parameters.
10431 break;
10432
10435 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10436 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10437
10438 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10439 // if they are not user-provided and their parameter-type-list is equivalent
10440 // to the parameter-type-list of an implicit declaration. This maintains the
10441 // behavior before dr2171 was implemented.
10442 //
10443 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10444 // trivial, if they are not user-provided, regardless of the qualifiers on
10445 // the reference type.
10446 const bool ClangABICompat14 =
10447 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
10448 if (!RT ||
10450 ClangABICompat14)) {
10451 if (Diagnose)
10452 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10453 << Param0->getSourceRange() << Param0->getType()
10454 << Context.getLValueReferenceType(
10455 Context.getCanonicalTagType(RD).withConst());
10456 return false;
10457 }
10458
10459 ConstArg = RT->getPointeeType().isConstQualified();
10460 break;
10461 }
10462
10465 // Trivial move operations always have non-cv-qualified parameters.
10466 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10467 const RValueReferenceType *RT =
10468 Param0->getType()->getAs<RValueReferenceType>();
10469 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10470 if (Diagnose)
10471 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10472 << Param0->getSourceRange() << Param0->getType()
10473 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10474 return false;
10475 }
10476 break;
10477 }
10478
10480 llvm_unreachable("not a special member");
10481 }
10482
10483 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10484 if (Diagnose)
10486 diag::note_nontrivial_default_arg)
10488 return false;
10489 }
10490 if (MD->isVariadic()) {
10491 if (Diagnose)
10492 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10493 return false;
10494 }
10495
10496 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10497 // A copy/move [constructor or assignment operator] is trivial if
10498 // -- the [member] selected to copy/move each direct base class subobject
10499 // is trivial
10500 //
10501 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10502 // A [default constructor or destructor] is trivial if
10503 // -- all the direct base classes have trivial [default constructors or
10504 // destructors]
10505 for (const auto &BI : RD->bases())
10506 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10507 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10508 return false;
10509
10510 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10511 // A copy/move [constructor or assignment operator] for a class X is
10512 // trivial if
10513 // -- for each non-static data member of X that is of class type (or array
10514 // thereof), the constructor selected to copy/move that member is
10515 // trivial
10516 //
10517 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10518 // A [default constructor or destructor] is trivial if
10519 // -- for all of the non-static data members of its class that are of class
10520 // type (or array thereof), each such class has a trivial [default
10521 // constructor or destructor]
10522 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10523 return false;
10524
10525 // C++11 [class.dtor]p5:
10526 // A destructor is trivial if [...]
10527 // -- the destructor is not virtual
10528 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10529 if (Diagnose)
10530 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10531 return false;
10532 }
10533
10534 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10535 // A [special member] for class X is trivial if [...]
10536 // -- class X has no virtual functions and no virtual base classes
10538 MD->getParent()->isDynamicClass()) {
10539 if (!Diagnose)
10540 return false;
10541
10542 if (RD->getNumVBases()) {
10543 // Check for virtual bases. We already know that the corresponding
10544 // member in all bases is trivial, so vbases must all be direct.
10545 CXXBaseSpecifier &BS = *RD->vbases_begin();
10546 assert(BS.isVirtual());
10547 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10548 return false;
10549 }
10550
10551 // Must have a virtual method.
10552 for (const auto *MI : RD->methods()) {
10553 if (MI->isVirtual()) {
10554 SourceLocation MLoc = MI->getBeginLoc();
10555 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10556 return false;
10557 }
10558 }
10559
10560 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10561 }
10562
10563 // Looks like it's trivial!
10564 return true;
10565}
10566
10567namespace {
10568struct FindHiddenVirtualMethod {
10569 Sema *S;
10571 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10572 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10573
10574private:
10575 /// Check whether any most overridden method from MD in Methods
10576 static bool CheckMostOverridenMethods(
10577 const CXXMethodDecl *MD,
10578 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10579 if (MD->size_overridden_methods() == 0)
10580 return Methods.count(MD->getCanonicalDecl());
10581 for (const CXXMethodDecl *O : MD->overridden_methods())
10582 if (CheckMostOverridenMethods(O, Methods))
10583 return true;
10584 return false;
10585 }
10586
10587public:
10588 /// Member lookup function that determines whether a given C++
10589 /// method overloads virtual methods in a base class without overriding any,
10590 /// to be used with CXXRecordDecl::lookupInBases().
10591 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10592 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10593 DeclarationName Name = Method->getDeclName();
10594 assert(Name.getNameKind() == DeclarationName::Identifier);
10595
10596 bool foundSameNameMethod = false;
10597 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10598 for (Path.Decls = BaseRecord->lookup(Name).begin();
10599 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10600 NamedDecl *D = *Path.Decls;
10601 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10602 MD = MD->getCanonicalDecl();
10603 foundSameNameMethod = true;
10604 // Interested only in hidden virtual methods.
10605 if (!MD->isVirtual())
10606 continue;
10607 // If the method we are checking overrides a method from its base
10608 // don't warn about the other overloaded methods. Clang deviates from
10609 // GCC by only diagnosing overloads of inherited virtual functions that
10610 // do not override any other virtual functions in the base. GCC's
10611 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10612 // function from a base class. These cases may be better served by a
10613 // warning (not specific to virtual functions) on call sites when the
10614 // call would select a different function from the base class, were it
10615 // visible.
10616 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10617 if (!S->IsOverload(Method, MD, false))
10618 return true;
10619 // Collect the overload only if its hidden.
10620 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10621 overloadedMethods.push_back(MD);
10622 }
10623 }
10624
10625 if (foundSameNameMethod)
10626 OverloadedMethods.append(overloadedMethods.begin(),
10627 overloadedMethods.end());
10628 return foundSameNameMethod;
10629 }
10630};
10631} // end anonymous namespace
10632
10633/// Add the most overridden methods from MD to Methods
10635 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10636 if (MD->size_overridden_methods() == 0)
10637 Methods.insert(MD->getCanonicalDecl());
10638 else
10639 for (const CXXMethodDecl *O : MD->overridden_methods())
10640 AddMostOverridenMethods(O, Methods);
10641}
10642
10644 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10645 if (!MD->getDeclName().isIdentifier())
10646 return;
10647
10648 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10649 /*bool RecordPaths=*/false,
10650 /*bool DetectVirtual=*/false);
10651 FindHiddenVirtualMethod FHVM;
10652 FHVM.Method = MD;
10653 FHVM.S = this;
10654
10655 // Keep the base methods that were overridden or introduced in the subclass
10656 // by 'using' in a set. A base method not in this set is hidden.
10657 CXXRecordDecl *DC = MD->getParent();
10658 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10659 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10660 ND = shad->getTargetDecl();
10661 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10662 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10663 }
10664
10665 if (DC->lookupInBases(FHVM, Paths))
10666 OverloadedMethods = FHVM.OverloadedMethods;
10667}
10668
10670 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10671 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10673 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10674 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10675 Diag(overloadedMD->getLocation(), PD);
10676 }
10677}
10678
10680 if (MD->isInvalidDecl())
10681 return;
10682
10683 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10684 return;
10685
10686 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10687 FindHiddenVirtualMethods(MD, OverloadedMethods);
10688 if (!OverloadedMethods.empty()) {
10689 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10690 << MD << (OverloadedMethods.size() > 1);
10691
10692 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10693 }
10694}
10695
10697 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10698 // No diagnostics if this is a template instantiation.
10700 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10701 diag::ext_cannot_use_trivial_abi) << &RD;
10702 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10703 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10704 }
10705 RD.dropAttr<TrivialABIAttr>();
10706 };
10707
10708 // Ill-formed if the struct has virtual functions.
10709 if (RD.isPolymorphic()) {
10710 PrintDiagAndRemoveAttr(1);
10711 return;
10712 }
10713
10714 for (const auto &B : RD.bases()) {
10715 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10716 // virtual base.
10717 if (!B.getType()->isDependentType() &&
10718 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10719 PrintDiagAndRemoveAttr(2);
10720 return;
10721 }
10722
10723 if (B.isVirtual()) {
10724 PrintDiagAndRemoveAttr(3);
10725 return;
10726 }
10727 }
10728
10729 for (const auto *FD : RD.fields()) {
10730 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10731 // non-trivial for the purpose of calls.
10732 QualType FT = FD->getType();
10734 PrintDiagAndRemoveAttr(4);
10735 return;
10736 }
10737
10738 // Ill-formed if the field is an address-discriminated value.
10740 PrintDiagAndRemoveAttr(6);
10741 return;
10742 }
10743
10744 if (const auto *RT =
10745 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10746 if (!RT->isDependentType() &&
10747 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10748 ->canPassInRegisters()) {
10749 PrintDiagAndRemoveAttr(5);
10750 return;
10751 }
10752 }
10753
10755 return;
10756
10757 // Ill-formed if the copy and move constructors are deleted.
10758 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10759 // If the type is dependent, then assume it might have
10760 // implicit copy or move ctor because we won't know yet at this point.
10761 if (RD.isDependentType())
10762 return true;
10765 return true;
10768 return true;
10769 for (const CXXConstructorDecl *CD : RD.ctors())
10770 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10771 return true;
10772 return false;
10773 };
10774
10775 if (!HasNonDeletedCopyOrMoveConstructor()) {
10776 PrintDiagAndRemoveAttr(0);
10777 return;
10778 }
10779}
10780
10782 CXXRecordDecl &RD) {
10783 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10784 diag::err_incomplete_type_vtable_pointer_auth))
10785 return;
10786
10787 const CXXRecordDecl *PrimaryBase = &RD;
10788 if (PrimaryBase->hasAnyDependentBases())
10789 return;
10790
10791 while (1) {
10792 assert(PrimaryBase);
10793 const CXXRecordDecl *Base = nullptr;
10794 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10795 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10796 continue;
10797 Base = BasePtr.getType()->getAsCXXRecordDecl();
10798 break;
10799 }
10800 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10801 break;
10802 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10803 diag::err_non_top_level_vtable_pointer_auth)
10804 << &RD << Base;
10805 PrimaryBase = Base;
10806 }
10807
10808 if (!RD.isPolymorphic())
10809 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10810 diag::err_non_polymorphic_vtable_pointer_auth)
10811 << &RD;
10812}
10813
10816 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10817 if (!TagDecl)
10818 return;
10819
10821
10822 for (const ParsedAttr &AL : AttrList) {
10823 if (AL.getKind() != ParsedAttr::AT_Visibility)
10824 continue;
10825 AL.setInvalid();
10826 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10827 }
10828
10829 ActOnFields(S, RLoc, TagDecl,
10831 // strict aliasing violation!
10832 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10833 FieldCollector->getCurNumFields()),
10834 LBrac, RBrac, AttrList);
10835
10837}
10838
10839/// Find the equality comparison functions that should be implicitly declared
10840/// in a given class definition, per C++2a [class.compare.default]p3.
10842 ASTContext &Ctx, CXXRecordDecl *RD,
10844 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10845 if (!RD->lookup(EqEq).empty())
10846 // Member operator== explicitly declared: no implicit operator==s.
10847 return;
10848
10849 // Traverse friends looking for an '==' or a '<=>'.
10850 for (FriendDecl *Friend : RD->friends()) {
10851 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10852 if (!FD) continue;
10853
10854 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10855 // Friend operator== explicitly declared: no implicit operator==s.
10856 Spaceships.clear();
10857 return;
10858 }
10859
10860 if (FD->getOverloadedOperator() == OO_Spaceship &&
10862 Spaceships.push_back(FD);
10863 }
10864
10865 // Look for members named 'operator<=>'.
10867 for (NamedDecl *ND : RD->lookup(Cmp)) {
10868 // Note that we could find a non-function here (either a function template
10869 // or a using-declaration). Neither case results in an implicit
10870 // 'operator=='.
10871 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10872 if (FD->isExplicitlyDefaulted())
10873 Spaceships.push_back(FD);
10874 }
10875}
10876
10878 // Don't add implicit special members to templated classes.
10879 // FIXME: This means unqualified lookups for 'operator=' within a class
10880 // template don't work properly.
10881 if (!ClassDecl->isDependentType()) {
10882 if (ClassDecl->needsImplicitDefaultConstructor()) {
10883 ++getASTContext().NumImplicitDefaultConstructors;
10884
10885 if (ClassDecl->hasInheritedConstructor())
10887 }
10888
10889 if (ClassDecl->needsImplicitCopyConstructor()) {
10890 ++getASTContext().NumImplicitCopyConstructors;
10891
10892 // If the properties or semantics of the copy constructor couldn't be
10893 // determined while the class was being declared, force a declaration
10894 // of it now.
10896 ClassDecl->hasInheritedConstructor())
10898 // For the MS ABI we need to know whether the copy ctor is deleted. A
10899 // prerequisite for deleting the implicit copy ctor is that the class has
10900 // a move ctor or move assignment that is either user-declared or whose
10901 // semantics are inherited from a subobject. FIXME: We should provide a
10902 // more direct way for CodeGen to ask whether the constructor was deleted.
10903 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10904 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10906 ClassDecl->hasUserDeclaredMoveAssignment() ||
10909 }
10910
10911 if (getLangOpts().CPlusPlus11 &&
10912 ClassDecl->needsImplicitMoveConstructor()) {
10913 ++getASTContext().NumImplicitMoveConstructors;
10914
10916 ClassDecl->hasInheritedConstructor())
10918 }
10919
10920 if (ClassDecl->needsImplicitCopyAssignment()) {
10921 ++getASTContext().NumImplicitCopyAssignmentOperators;
10922
10923 // If we have a dynamic class, then the copy assignment operator may be
10924 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10925 // it shows up in the right place in the vtable and that we diagnose
10926 // problems with the implicit exception specification.
10927 if (ClassDecl->isDynamicClass() ||
10929 ClassDecl->hasInheritedAssignment())
10931 }
10932
10933 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10934 ++getASTContext().NumImplicitMoveAssignmentOperators;
10935
10936 // Likewise for the move assignment operator.
10937 if (ClassDecl->isDynamicClass() ||
10939 ClassDecl->hasInheritedAssignment())
10941 }
10942
10943 if (ClassDecl->needsImplicitDestructor()) {
10944 ++getASTContext().NumImplicitDestructors;
10945
10946 // If we have a dynamic class, then the destructor may be virtual, so we
10947 // have to declare the destructor immediately. This ensures that, e.g., it
10948 // shows up in the right place in the vtable and that we diagnose problems
10949 // with the implicit exception specification.
10950 if (ClassDecl->isDynamicClass() ||
10952 DeclareImplicitDestructor(ClassDecl);
10953 }
10954 }
10955
10956 // C++2a [class.compare.default]p3:
10957 // If the member-specification does not explicitly declare any member or
10958 // friend named operator==, an == operator function is declared implicitly
10959 // for each defaulted three-way comparison operator function defined in
10960 // the member-specification
10961 // FIXME: Consider doing this lazily.
10962 // We do this during the initial parse for a class template, not during
10963 // instantiation, so that we can handle unqualified lookups for 'operator=='
10964 // when parsing the template.
10966 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10968 DefaultedSpaceships);
10969 for (auto *FD : DefaultedSpaceships)
10970 DeclareImplicitEqualityComparison(ClassDecl, FD);
10971 }
10972}
10973
10974unsigned
10976 llvm::function_ref<Scope *()> EnterScope) {
10977 if (!D)
10978 return 0;
10980
10981 // In order to get name lookup right, reenter template scopes in order from
10982 // outermost to innermost.
10984 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10985
10986 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10987 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
10988 ParameterLists.push_back(TPL);
10989
10990 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10991 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10992 ParameterLists.push_back(FTD->getTemplateParameters());
10993 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10994 LookupDC = VD->getDeclContext();
10995
10997 ParameterLists.push_back(VTD->getTemplateParameters());
10998 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10999 ParameterLists.push_back(PSD->getTemplateParameters());
11000 }
11001 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11002 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11003 ParameterLists.push_back(TPL);
11004
11005 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11007 ParameterLists.push_back(CTD->getTemplateParameters());
11008 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11009 ParameterLists.push_back(PSD->getTemplateParameters());
11010 }
11011 }
11012 // FIXME: Alias declarations and concepts.
11013
11014 unsigned Count = 0;
11015 Scope *InnermostTemplateScope = nullptr;
11016 for (TemplateParameterList *Params : ParameterLists) {
11017 // Ignore explicit specializations; they don't contribute to the template
11018 // depth.
11019 if (Params->size() == 0)
11020 continue;
11021
11022 InnermostTemplateScope = EnterScope();
11023 for (NamedDecl *Param : *Params) {
11024 if (Param->getDeclName()) {
11025 InnermostTemplateScope->AddDecl(Param);
11026 IdResolver.AddDecl(Param);
11027 }
11028 }
11029 ++Count;
11030 }
11031
11032 // Associate the new template scopes with the corresponding entities.
11033 if (InnermostTemplateScope) {
11034 assert(LookupDC && "no enclosing DeclContext for template lookup");
11035 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11036 }
11037
11038 return Count;
11039}
11040
11042 if (!RecordD) return;
11043 AdjustDeclIfTemplate(RecordD);
11046}
11047
11049 if (!RecordD) return;
11051}
11052
11054 if (!Param)
11055 return;
11056
11057 S->AddDecl(Param);
11058 if (Param->getDeclName())
11059 IdResolver.AddDecl(Param);
11060}
11061
11064
11065/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11066/// C++ method declaration. We're (re-)introducing the given
11067/// function parameter into scope for use in parsing later parts of
11068/// the method declaration. For example, we could see an
11069/// ActOnParamDefaultArgument event for this parameter.
11071 if (!ParamD)
11072 return;
11073
11074 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11075
11076 S->AddDecl(Param);
11077 if (Param->getDeclName())
11078 IdResolver.AddDecl(Param);
11079}
11080
11082 if (!MethodD)
11083 return;
11084
11085 AdjustDeclIfTemplate(MethodD);
11086
11088
11089 // Now that we have our default arguments, check the constructor
11090 // again. It could produce additional diagnostics or affect whether
11091 // the class has implicitly-declared destructors, among other
11092 // things.
11093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11095
11096 // Check the default arguments, which we may have added.
11097 if (!Method->isInvalidDecl())
11099}
11100
11101// Emit the given diagnostic for each non-address-space qualifier.
11102// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11103static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11105 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11106 bool DiagOccurred = false;
11108 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11109 SourceLocation SL) {
11110 // This diagnostic should be emitted on any qualifier except an addr
11111 // space qualifier. However, forEachQualifier currently doesn't visit
11112 // addr space qualifiers, so there's no way to write this condition
11113 // right now; we just diagnose on everything.
11114 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11115 DiagOccurred = true;
11116 });
11117 if (DiagOccurred)
11118 D.setInvalidType();
11119 }
11120}
11121
11123 unsigned Kind) {
11124 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11125 return;
11126
11128 if (Chunk.Kind == DeclaratorChunk::Paren ||
11130 return;
11131
11132 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11133 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11134 << Kind << Chunk.getSourceRange();
11135 D.setInvalidType();
11136}
11137
11139 StorageClass &SC) {
11140 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11141
11142 // C++ [class.ctor]p3:
11143 // A constructor shall not be virtual (10.3) or static (9.4). A
11144 // constructor can be invoked for a const, volatile or const
11145 // volatile object. A constructor shall not be declared const,
11146 // volatile, or const volatile (9.3.2).
11147 if (isVirtual) {
11148 if (!D.isInvalidType())
11149 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11150 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11152 D.setInvalidType();
11153 }
11154 if (SC == SC_Static) {
11155 if (!D.isInvalidType())
11156 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11157 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11159 D.setInvalidType();
11160 SC = SC_None;
11161 }
11162
11163 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11165 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11169 D.setInvalidType();
11170 }
11171
11172 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11173 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11174
11175 // C++0x [class.ctor]p4:
11176 // A constructor shall not be declared with a ref-qualifier.
11178 if (FTI.hasRefQualifier()) {
11179 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11182 D.setInvalidType();
11183 }
11184
11185 // Rebuild the function type "R" without any type qualifiers (in
11186 // case any of the errors above fired) and with "void" as the
11187 // return type, since constructors don't have return types.
11188 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11189 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11190 return R;
11191
11193 EPI.TypeQuals = Qualifiers();
11194 EPI.RefQualifier = RQ_None;
11195
11196 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11197}
11198
11200 CXXRecordDecl *ClassDecl
11201 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11202 if (!ClassDecl)
11203 return Constructor->setInvalidDecl();
11204
11205 // C++ [class.copy]p3:
11206 // A declaration of a constructor for a class X is ill-formed if
11207 // its first parameter is of type (optionally cv-qualified) X and
11208 // either there are no other parameters or else all other
11209 // parameters have default arguments.
11210 if (!Constructor->isInvalidDecl() &&
11211 Constructor->hasOneParamOrDefaultArgs() &&
11212 !Constructor->isFunctionTemplateSpecialization()) {
11213 CanQualType ParamType =
11214 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11215 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11216 if (ParamType == ClassTy) {
11217 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11218 const char *ConstRef
11219 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11220 : " const &";
11221 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11222 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11223
11224 // FIXME: Rather that making the constructor invalid, we should endeavor
11225 // to fix the type.
11226 Constructor->setInvalidDecl();
11227 }
11228 }
11229}
11230
11232 CXXRecordDecl *RD = Destructor->getParent();
11233
11234 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11235 SourceLocation Loc;
11236
11237 if (!Destructor->isImplicit())
11238 Loc = Destructor->getLocation();
11239 else
11240 Loc = RD->getLocation();
11241
11242 DeclarationName Name =
11243 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11244 // If we have a virtual destructor, look up the deallocation function
11246 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11247 Expr *ThisArg = nullptr;
11248
11249 // If the notional 'delete this' expression requires a non-trivial
11250 // conversion from 'this' to the type of a destroying operator delete's
11251 // first parameter, perform that conversion now.
11252 if (OperatorDelete->isDestroyingOperatorDelete()) {
11253 unsigned AddressParamIndex = 0;
11254 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11255 ++AddressParamIndex;
11256 QualType ParamType =
11257 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11258 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11259 // C++ [class.dtor]p13:
11260 // ... as if for the expression 'delete this' appearing in a
11261 // non-virtual destructor of the destructor's class.
11262 ContextRAII SwitchContext(*this, Destructor);
11264 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11265 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11266 This = PerformImplicitConversion(This.get(), ParamType,
11268 if (This.isInvalid()) {
11269 // FIXME: Register this as a context note so that it comes out
11270 // in the right order.
11271 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11272 return true;
11273 }
11274 ThisArg = This.get();
11275 }
11276 }
11277
11278 DiagnoseUseOfDecl(OperatorDelete, Loc);
11279 MarkFunctionReferenced(Loc, OperatorDelete);
11280 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11281
11282 if (isa<CXXMethodDecl>(OperatorDelete) &&
11283 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11284 Context.getLangOpts())) {
11285 // In Microsoft ABI whenever a class has a defined operator delete,
11286 // scalar deleting destructors check the 3rd bit of the implicit
11287 // parameter and if it is set, then, global operator delete must be
11288 // called instead of the class-specific one. Find and save the global
11289 // operator delete for that case. Do not diagnose at this point because
11290 // the lack of a global operator delete is not an error if there are no
11291 // delete calls that require it.
11292 FunctionDecl *GlobalOperatorDelete =
11293 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11294 /*LookForGlobal*/ true, Name);
11295 if (GlobalOperatorDelete) {
11296 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11297 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11298 }
11299 }
11300
11301 if (Context.getTargetInfo().emitVectorDeletingDtors(
11302 Context.getLangOpts())) {
11303 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11304 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11305 DeclarationName VDeleteName =
11306 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11308 Loc, RD, /*Diagnose*/ false,
11309 /*LookForGlobal*/ false, VDeleteName);
11310 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11311 FunctionDecl *GlobalArrOperatorDelete =
11312 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11313 /*LookForGlobal*/ true,
11314 VDeleteName);
11315 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11316 if (GlobalArrOperatorDelete &&
11317 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11318 DestructorIsExported))
11319 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11320 } else if (!ArrOperatorDelete) {
11321 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11322 Loc, RD, /*Diagnose*/ false,
11323 /*LookForGlobal*/ true, VDeleteName);
11324 }
11325 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11326 if (ArrOperatorDelete &&
11327 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11328 DestructorIsExported))
11329 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11330 }
11331 }
11332 }
11333
11334 return false;
11335}
11336
11338 StorageClass& SC) {
11339 // C++ [class.dtor]p1:
11340 // [...] A typedef-name that names a class is a class-name
11341 // (7.1.3); however, a typedef-name that names a class shall not
11342 // be used as the identifier in the declarator for a destructor
11343 // declaration.
11344 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11345 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11346 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11347 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11348 else if (const TemplateSpecializationType *TST =
11349 DeclaratorType->getAs<TemplateSpecializationType>())
11350 if (TST->isTypeAlias())
11351 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11352 << DeclaratorType << 1;
11353
11354 // C++ [class.dtor]p2:
11355 // A destructor is used to destroy objects of its class type. A
11356 // destructor takes no parameters, and no return type can be
11357 // specified for it (not even void). The address of a destructor
11358 // shall not be taken. A destructor shall not be static. A
11359 // destructor can be invoked for a const, volatile or const
11360 // volatile object. A destructor shall not be declared const,
11361 // volatile or const volatile (9.3.2).
11362 if (SC == SC_Static) {
11363 if (!D.isInvalidType())
11364 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11365 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11368
11369 SC = SC_None;
11370 }
11371 if (!D.isInvalidType()) {
11372 // Destructors don't have return types, but the parser will
11373 // happily parse something like:
11374 //
11375 // class X {
11376 // float ~X();
11377 // };
11378 //
11379 // The return type will be eliminated later.
11380 if (D.getDeclSpec().hasTypeSpecifier())
11381 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11384 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11385 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11391 D.setInvalidType();
11392 }
11393 }
11394
11395 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11396 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11397
11398 // C++0x [class.dtor]p2:
11399 // A destructor shall not be declared with a ref-qualifier.
11401 if (FTI.hasRefQualifier()) {
11402 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11405 D.setInvalidType();
11406 }
11407
11408 // Make sure we don't have any parameters.
11409 if (FTIHasNonVoidParameters(FTI)) {
11410 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11411
11412 // Delete the parameters.
11413 FTI.freeParams();
11414 D.setInvalidType();
11415 }
11416
11417 // Make sure the destructor isn't variadic.
11418 if (FTI.isVariadic) {
11419 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11420 D.setInvalidType();
11421 }
11422
11423 // Rebuild the function type "R" without any type qualifiers or
11424 // parameters (in case any of the errors above fired) and with
11425 // "void" as the return type, since destructors don't have return
11426 // types.
11427 if (!D.isInvalidType())
11428 return R;
11429
11430 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11432 EPI.Variadic = false;
11433 EPI.TypeQuals = Qualifiers();
11434 EPI.RefQualifier = RQ_None;
11435 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11436}
11437
11438static void extendLeft(SourceRange &R, SourceRange Before) {
11439 if (Before.isInvalid())
11440 return;
11441 R.setBegin(Before.getBegin());
11442 if (R.getEnd().isInvalid())
11443 R.setEnd(Before.getEnd());
11444}
11445
11446static void extendRight(SourceRange &R, SourceRange After) {
11447 if (After.isInvalid())
11448 return;
11449 if (R.getBegin().isInvalid())
11450 R.setBegin(After.getBegin());
11451 R.setEnd(After.getEnd());
11452}
11453
11455 StorageClass& SC) {
11456 // C++ [class.conv.fct]p1:
11457 // Neither parameter types nor return type can be specified. The
11458 // type of a conversion function (8.3.5) is "function taking no
11459 // parameter returning conversion-type-id."
11460 if (SC == SC_Static) {
11461 if (!D.isInvalidType())
11462 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11464 << D.getName().getSourceRange();
11465 D.setInvalidType();
11466 SC = SC_None;
11467 }
11468
11469 TypeSourceInfo *ConvTSI = nullptr;
11470 QualType ConvType =
11472
11473 const DeclSpec &DS = D.getDeclSpec();
11474 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11475 // Conversion functions don't have return types, but the parser will
11476 // happily parse something like:
11477 //
11478 // class X {
11479 // float operator bool();
11480 // };
11481 //
11482 // The return type will be changed later anyway.
11483 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11486 D.setInvalidType();
11487 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11488 // It's also plausible that the user writes type qualifiers in the wrong
11489 // place, such as:
11490 // struct S { const operator int(); };
11491 // FIXME: we could provide a fixit to move the qualifiers onto the
11492 // conversion type.
11493 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11494 << SourceRange(D.getIdentifierLoc()) << 0;
11495 D.setInvalidType();
11496 }
11497 const auto *Proto = R->castAs<FunctionProtoType>();
11498 // Make sure we don't have any parameters.
11500 unsigned NumParam = Proto->getNumParams();
11501
11502 // [C++2b]
11503 // A conversion function shall have no non-object parameters.
11504 if (NumParam == 1) {
11506 if (const auto *First =
11507 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11508 First && First->isExplicitObjectParameter())
11509 NumParam--;
11510 }
11511
11512 if (NumParam != 0) {
11513 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11514 // Delete the parameters.
11515 FTI.freeParams();
11516 D.setInvalidType();
11517 } else if (Proto->isVariadic()) {
11518 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11519 D.setInvalidType();
11520 }
11521
11522 // Diagnose "&operator bool()" and other such nonsense. This
11523 // is actually a gcc extension which we don't support.
11524 if (Proto->getReturnType() != ConvType) {
11525 bool NeedsTypedef = false;
11526 SourceRange Before, After;
11527
11528 // Walk the chunks and extract information on them for our diagnostic.
11529 bool PastFunctionChunk = false;
11530 for (auto &Chunk : D.type_objects()) {
11531 switch (Chunk.Kind) {
11533 if (!PastFunctionChunk) {
11534 if (Chunk.Fun.HasTrailingReturnType) {
11535 TypeSourceInfo *TRT = nullptr;
11536 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11537 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11538 }
11539 PastFunctionChunk = true;
11540 break;
11541 }
11542 [[fallthrough]];
11544 NeedsTypedef = true;
11545 extendRight(After, Chunk.getSourceRange());
11546 break;
11547
11553 extendLeft(Before, Chunk.getSourceRange());
11554 break;
11555
11557 extendLeft(Before, Chunk.Loc);
11558 extendRight(After, Chunk.EndLoc);
11559 break;
11560 }
11561 }
11562
11563 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11564 After.isValid() ? After.getBegin() :
11565 D.getIdentifierLoc();
11566 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11567 DB << Before << After;
11568
11569 if (!NeedsTypedef) {
11570 DB << /*don't need a typedef*/0;
11571
11572 // If we can provide a correct fix-it hint, do so.
11573 if (After.isInvalid() && ConvTSI) {
11574 SourceLocation InsertLoc =
11576 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11578 InsertLoc, CharSourceRange::getTokenRange(Before))
11579 << FixItHint::CreateRemoval(Before);
11580 }
11581 } else if (!Proto->getReturnType()->isDependentType()) {
11582 DB << /*typedef*/1 << Proto->getReturnType();
11583 } else if (getLangOpts().CPlusPlus11) {
11584 DB << /*alias template*/2 << Proto->getReturnType();
11585 } else {
11586 DB << /*might not be fixable*/3;
11587 }
11588
11589 // Recover by incorporating the other type chunks into the result type.
11590 // Note, this does *not* change the name of the function. This is compatible
11591 // with the GCC extension:
11592 // struct S { &operator int(); } s;
11593 // int &r = s.operator int(); // ok in GCC
11594 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11595 ConvType = Proto->getReturnType();
11596 }
11597
11598 // C++ [class.conv.fct]p4:
11599 // The conversion-type-id shall not represent a function type nor
11600 // an array type.
11601 if (ConvType->isArrayType()) {
11602 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11603 ConvType = Context.getPointerType(ConvType);
11604 D.setInvalidType();
11605 } else if (ConvType->isFunctionType()) {
11606 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11607 ConvType = Context.getPointerType(ConvType);
11608 D.setInvalidType();
11609 }
11610
11611 // Rebuild the function type "R" without any parameters (in case any
11612 // of the errors above fired) and with the conversion type as the
11613 // return type.
11614 if (D.isInvalidType())
11615 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11616
11617 // C++0x explicit conversion operators.
11621 ? diag::warn_cxx98_compat_explicit_conversion_functions
11622 : diag::ext_explicit_conversion_functions)
11624}
11625
11627 assert(Conversion && "Expected to receive a conversion function declaration");
11628
11629 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11630
11631 // Make sure we aren't redeclaring the conversion function.
11632 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11633 // C++ [class.conv.fct]p1:
11634 // [...] A conversion function is never used to convert a
11635 // (possibly cv-qualified) object to the (possibly cv-qualified)
11636 // same object type (or a reference to it), to a (possibly
11637 // cv-qualified) base class of that type (or a reference to it),
11638 // or to (possibly cv-qualified) void.
11639 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11640 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11641 ConvType = ConvTypeRef->getPointeeType();
11642 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11644 /* Suppress diagnostics for instantiations. */;
11645 else if (Conversion->size_overridden_methods() != 0)
11646 /* Suppress diagnostics for overriding virtual function in a base class. */;
11647 else if (ConvType->isRecordType()) {
11648 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11649 if (ConvType == ClassType)
11650 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11651 << ClassType;
11652 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11653 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11654 << ClassType << ConvType;
11655 } else if (ConvType->isVoidType()) {
11656 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11657 << ClassType << ConvType;
11658 }
11659
11660 if (FunctionTemplateDecl *ConversionTemplate =
11661 Conversion->getDescribedFunctionTemplate()) {
11662 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11663 ConvType = ConvTypePtr->getPointeeType();
11664 }
11665 if (ConvType->isUndeducedAutoType()) {
11666 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11667 << getReturnTypeLoc(Conversion).getSourceRange()
11668 << ConvType->castAs<AutoType>()->getKeyword()
11669 << /* in declaration of conversion function template= */ 24;
11670 }
11671
11672 return ConversionTemplate;
11673 }
11674
11675 return Conversion;
11676}
11677
11682
11686
11688 DeclarationName Name, QualType R,
11689 bool IsLambda, DeclContext *DC) {
11690 if (!D.isFunctionDeclarator())
11691 return;
11692
11694 if (FTI.NumParams == 0)
11695 return;
11696 ParmVarDecl *ExplicitObjectParam = nullptr;
11697 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11698 const auto &ParamInfo = FTI.Params[Idx];
11699 if (!ParamInfo.Param)
11700 continue;
11701 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11702 if (!Param->isExplicitObjectParameter())
11703 continue;
11704 if (Idx == 0) {
11705 ExplicitObjectParam = Param;
11706 continue;
11707 } else {
11708 Diag(Param->getLocation(),
11709 diag::err_explicit_object_parameter_must_be_first)
11710 << IsLambda << Param->getSourceRange();
11711 }
11712 }
11713 if (!ExplicitObjectParam)
11714 return;
11715
11716 if (ExplicitObjectParam->hasDefaultArg()) {
11717 Diag(ExplicitObjectParam->getLocation(),
11718 diag::err_explicit_object_default_arg)
11719 << ExplicitObjectParam->getSourceRange();
11720 D.setInvalidType();
11721 }
11722
11725 D.isStaticMember())) {
11726 Diag(ExplicitObjectParam->getBeginLoc(),
11727 diag::err_explicit_object_parameter_nonmember)
11728 << D.getSourceRange() << /*static=*/0 << IsLambda;
11729 D.setInvalidType();
11730 }
11731
11732 if (D.getDeclSpec().isVirtualSpecified()) {
11733 Diag(ExplicitObjectParam->getBeginLoc(),
11734 diag::err_explicit_object_parameter_nonmember)
11735 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11736 D.setInvalidType();
11737 }
11738
11739 // Friend declarations require some care. Consider:
11740 //
11741 // namespace N {
11742 // struct A{};
11743 // int f(A);
11744 // }
11745 //
11746 // struct S {
11747 // struct T {
11748 // int f(this T);
11749 // };
11750 //
11751 // friend int T::f(this T); // Allow this.
11752 // friend int f(this S); // But disallow this.
11753 // friend int N::f(this A); // And disallow this.
11754 // };
11755 //
11756 // Here, it seems to suffice to check whether the scope
11757 // specifier designates a class type.
11758 if (D.getDeclSpec().isFriendSpecified() &&
11759 !isa_and_present<CXXRecordDecl>(
11761 Diag(ExplicitObjectParam->getBeginLoc(),
11762 diag::err_explicit_object_parameter_nonmember)
11763 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11764 D.setInvalidType();
11765 }
11766
11767 if (IsLambda && FTI.hasMutableQualifier()) {
11768 Diag(ExplicitObjectParam->getBeginLoc(),
11769 diag::err_explicit_object_parameter_mutable)
11770 << D.getSourceRange();
11771 }
11772
11773 if (IsLambda)
11774 return;
11775
11776 if (!DC || !DC->isRecord()) {
11777 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11778 "should have been diagnosed already");
11779 return;
11780 }
11781
11782 // CWG2674: constructors and destructors cannot have explicit parameters.
11785 Diag(ExplicitObjectParam->getBeginLoc(),
11786 diag::err_explicit_object_parameter_constructor)
11788 << D.getSourceRange();
11789 D.setInvalidType();
11790 }
11791}
11792
11793namespace {
11794/// Utility class to accumulate and print a diagnostic listing the invalid
11795/// specifier(s) on a declaration.
11796struct BadSpecifierDiagnoser {
11797 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11798 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11799 ~BadSpecifierDiagnoser() {
11800 Diagnostic << Specifiers;
11801 }
11802
11803 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11804 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11805 }
11806 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11807 return check(SpecLoc,
11809 }
11810 void check(SourceLocation SpecLoc, const char *Spec) {
11811 if (SpecLoc.isInvalid()) return;
11812 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11813 if (!Specifiers.empty()) Specifiers += " ";
11814 Specifiers += Spec;
11815 }
11816
11817 Sema &S;
11818 Sema::SemaDiagnosticBuilder Diagnostic;
11819 std::string Specifiers;
11820};
11821}
11822
11824 StorageClass &SC) {
11825 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11826 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11827 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11828
11829 // C++ [temp.deduct.guide]p3:
11830 // A deduction-gide shall be declared in the same scope as the
11831 // corresponding class template.
11832 if (!CurContext->getRedeclContext()->Equals(
11833 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11834 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11835 << GuidedTemplateDecl;
11836 NoteTemplateLocation(*GuidedTemplateDecl);
11837 }
11838
11839 auto &DS = D.getMutableDeclSpec();
11840 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11841 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11842 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11843 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11844 BadSpecifierDiagnoser Diagnoser(
11845 *this, D.getIdentifierLoc(),
11846 diag::err_deduction_guide_invalid_specifier);
11847
11848 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11849 DS.ClearStorageClassSpecs();
11850 SC = SC_None;
11851
11852 // 'explicit' is permitted.
11853 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11854 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11855 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11856 DS.ClearConstexprSpec();
11857
11858 Diagnoser.check(DS.getConstSpecLoc(), "const");
11859 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11860 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11861 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11862 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11863 DS.ClearTypeQualifiers();
11864
11865 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11866 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11867 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11868 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11869 DS.ClearTypeSpecType();
11870 }
11871
11872 if (D.isInvalidType())
11873 return true;
11874
11875 // Check the declarator is simple enough.
11876 bool FoundFunction = false;
11877 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11878 if (Chunk.Kind == DeclaratorChunk::Paren)
11879 continue;
11880 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11882 diag::err_deduction_guide_with_complex_decl)
11883 << D.getSourceRange();
11884 break;
11885 }
11886 if (!Chunk.Fun.hasTrailingReturnType())
11887 return Diag(D.getName().getBeginLoc(),
11888 diag::err_deduction_guide_no_trailing_return_type);
11889
11890 // Check that the return type is written as a specialization of
11891 // the template specified as the deduction-guide's name.
11892 // The template name may not be qualified. [temp.deduct.guide]
11893 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11894 TypeSourceInfo *TSI = nullptr;
11895 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11896 assert(TSI && "deduction guide has valid type but invalid return type?");
11897 bool AcceptableReturnType = false;
11898 bool MightInstantiateToSpecialization = false;
11899 if (auto RetTST =
11901 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11902 bool TemplateMatches = Context.hasSameTemplateName(
11903 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11904
11906 SpecifiedName.getAsQualifiedTemplateName();
11907 // A Template template parameter is never wrapped in a
11908 // QualifiedTemplateName, but it's always simply-written.
11909 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11910 !Qualifiers->getQualifier());
11911 if (SimplyWritten && TemplateMatches)
11912 AcceptableReturnType = true;
11913 else {
11914 // This could still instantiate to the right type, unless we know it
11915 // names the wrong class template.
11916 auto *TD = SpecifiedName.getAsTemplateDecl();
11917 MightInstantiateToSpecialization =
11918 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11919 }
11920 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11921 MightInstantiateToSpecialization = true;
11922 }
11923
11924 if (!AcceptableReturnType)
11925 return Diag(TSI->getTypeLoc().getBeginLoc(),
11926 diag::err_deduction_guide_bad_trailing_return_type)
11927 << GuidedTemplate << TSI->getType()
11928 << MightInstantiateToSpecialization
11929 << TSI->getTypeLoc().getSourceRange();
11930
11931 // Keep going to check that we don't have any inner declarator pieces (we
11932 // could still have a function returning a pointer to a function).
11933 FoundFunction = true;
11934 }
11935
11936 if (D.isFunctionDefinition())
11937 // we can still create a valid deduction guide here.
11938 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11939 return false;
11940}
11941
11942//===----------------------------------------------------------------------===//
11943// Namespace Handling
11944//===----------------------------------------------------------------------===//
11945
11946/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11947/// reopened.
11949 SourceLocation Loc,
11950 IdentifierInfo *II, bool *IsInline,
11951 NamespaceDecl *PrevNS) {
11952 assert(*IsInline != PrevNS->isInline());
11953
11954 // 'inline' must appear on the original definition, but not necessarily
11955 // on all extension definitions, so the note should point to the first
11956 // definition to avoid confusion.
11957 PrevNS = PrevNS->getFirstDecl();
11958
11959 if (PrevNS->isInline())
11960 // The user probably just forgot the 'inline', so suggest that it
11961 // be added back.
11962 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11963 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11964 else
11965 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11966
11967 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11968 *IsInline = PrevNS->isInline();
11969}
11970
11971/// ActOnStartNamespaceDef - This is called at the start of a namespace
11972/// definition.
11974 SourceLocation InlineLoc,
11975 SourceLocation NamespaceLoc,
11976 SourceLocation IdentLoc, IdentifierInfo *II,
11977 SourceLocation LBrace,
11978 const ParsedAttributesView &AttrList,
11979 UsingDirectiveDecl *&UD, bool IsNested) {
11980 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11981 // For anonymous namespace, take the location of the left brace.
11982 SourceLocation Loc = II ? IdentLoc : LBrace;
11983 bool IsInline = InlineLoc.isValid();
11984 bool IsInvalid = false;
11985 bool IsStd = false;
11986 bool AddToKnown = false;
11987 Scope *DeclRegionScope = NamespcScope->getParent();
11988
11989 NamespaceDecl *PrevNS = nullptr;
11990 if (II) {
11991 // C++ [namespace.std]p7:
11992 // A translation unit shall not declare namespace std to be an inline
11993 // namespace (9.8.2).
11994 //
11995 // Precondition: the std namespace is in the file scope and is declared to
11996 // be inline
11997 auto DiagnoseInlineStdNS = [&]() {
11998 assert(IsInline && II->isStr("std") &&
11999 CurContext->getRedeclContext()->isTranslationUnit() &&
12000 "Precondition of DiagnoseInlineStdNS not met");
12001 Diag(InlineLoc, diag::err_inline_namespace_std)
12002 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12003 IsInline = false;
12004 };
12005 // C++ [namespace.def]p2:
12006 // The identifier in an original-namespace-definition shall not
12007 // have been previously defined in the declarative region in
12008 // which the original-namespace-definition appears. The
12009 // identifier in an original-namespace-definition is the name of
12010 // the namespace. Subsequently in that declarative region, it is
12011 // treated as an original-namespace-name.
12012 //
12013 // Since namespace names are unique in their scope, and we don't
12014 // look through using directives, just look for any ordinary names
12015 // as if by qualified name lookup.
12016 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12018 LookupQualifiedName(R, CurContext->getRedeclContext());
12019 NamedDecl *PrevDecl =
12020 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12021 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12022
12023 if (PrevNS) {
12024 // This is an extended namespace definition.
12025 if (IsInline && II->isStr("std") &&
12026 CurContext->getRedeclContext()->isTranslationUnit())
12027 DiagnoseInlineStdNS();
12028 else if (IsInline != PrevNS->isInline())
12029 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12030 &IsInline, PrevNS);
12031 } else if (PrevDecl) {
12032 // This is an invalid name redefinition.
12033 Diag(Loc, diag::err_redefinition_different_kind)
12034 << II;
12035 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12036 IsInvalid = true;
12037 // Continue on to push Namespc as current DeclContext and return it.
12038 } else if (II->isStr("std") &&
12039 CurContext->getRedeclContext()->isTranslationUnit()) {
12040 if (IsInline)
12041 DiagnoseInlineStdNS();
12042 // This is the first "real" definition of the namespace "std", so update
12043 // our cache of the "std" namespace to point at this definition.
12044 PrevNS = getStdNamespace();
12045 IsStd = true;
12046 AddToKnown = !IsInline;
12047 } else {
12048 // We've seen this namespace for the first time.
12049 AddToKnown = !IsInline;
12050 }
12051 } else {
12052 // Anonymous namespaces.
12053
12054 // Determine whether the parent already has an anonymous namespace.
12055 DeclContext *Parent = CurContext->getRedeclContext();
12056 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12057 PrevNS = TU->getAnonymousNamespace();
12058 } else {
12059 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12060 PrevNS = ND->getAnonymousNamespace();
12061 }
12062
12063 if (PrevNS && IsInline != PrevNS->isInline())
12064 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12065 &IsInline, PrevNS);
12066 }
12067
12069 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12070 if (IsInvalid)
12071 Namespc->setInvalidDecl();
12072
12073 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12074 AddPragmaAttributes(DeclRegionScope, Namespc);
12075 ProcessAPINotes(Namespc);
12076
12077 // FIXME: Should we be merging attributes?
12078 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12080
12081 if (IsStd)
12082 StdNamespace = Namespc;
12083 if (AddToKnown)
12084 KnownNamespaces[Namespc] = false;
12085
12086 if (II) {
12087 PushOnScopeChains(Namespc, DeclRegionScope);
12088 } else {
12089 // Link the anonymous namespace into its parent.
12090 DeclContext *Parent = CurContext->getRedeclContext();
12091 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12092 TU->setAnonymousNamespace(Namespc);
12093 } else {
12094 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12095 }
12096
12097 CurContext->addDecl(Namespc);
12098
12099 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12100 // behaves as if it were replaced by
12101 // namespace unique { /* empty body */ }
12102 // using namespace unique;
12103 // namespace unique { namespace-body }
12104 // where all occurrences of 'unique' in a translation unit are
12105 // replaced by the same identifier and this identifier differs
12106 // from all other identifiers in the entire program.
12107
12108 // We just create the namespace with an empty name and then add an
12109 // implicit using declaration, just like the standard suggests.
12110 //
12111 // CodeGen enforces the "universally unique" aspect by giving all
12112 // declarations semantically contained within an anonymous
12113 // namespace internal linkage.
12114
12115 if (!PrevNS) {
12117 /* 'using' */ LBrace,
12118 /* 'namespace' */ SourceLocation(),
12119 /* qualifier */ NestedNameSpecifierLoc(),
12120 /* identifier */ SourceLocation(),
12121 Namespc,
12122 /* Ancestor */ Parent);
12123 UD->setImplicit();
12124 Parent->addDecl(UD);
12125 }
12126 }
12127
12128 ActOnDocumentableDecl(Namespc);
12129
12130 // Although we could have an invalid decl (i.e. the namespace name is a
12131 // redefinition), push it as current DeclContext and try to continue parsing.
12132 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12133 // for the namespace has the declarations that showed up in that particular
12134 // namespace definition.
12135 PushDeclContext(NamespcScope, Namespc);
12136 return Namespc;
12137}
12138
12139/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12140/// is a namespace alias, returns the namespace it points to.
12142 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12143 return AD->getNamespace();
12144 return dyn_cast_or_null<NamespaceDecl>(D);
12145}
12146
12148 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12149 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12150 Namespc->setRBraceLoc(RBrace);
12152 if (Namespc->hasAttr<VisibilityAttr>())
12153 PopPragmaVisibility(true, RBrace);
12154 // If this namespace contains an export-declaration, export it now.
12155 if (DeferredExportedNamespaces.erase(Namespc))
12157}
12158
12160 return cast_or_null<CXXRecordDecl>(
12161 StdBadAlloc.get(Context.getExternalSource()));
12162}
12163
12165 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12166}
12167
12169 return cast_or_null<NamespaceDecl>(
12170 StdNamespace.get(Context.getExternalSource()));
12171}
12172
12173namespace {
12174
12175enum UnsupportedSTLSelect {
12176 USS_InvalidMember,
12177 USS_MissingMember,
12178 USS_NonTrivial,
12179 USS_Other
12180};
12181
12182struct InvalidSTLDiagnoser {
12183 Sema &S;
12184 SourceLocation Loc;
12185 QualType TyForDiags;
12186
12187 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12188 const VarDecl *VD = nullptr) {
12189 {
12190 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12191 << TyForDiags << ((int)Sel);
12192 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12193 assert(!Name.empty());
12194 D << Name;
12195 }
12196 }
12197 if (Sel == USS_InvalidMember) {
12198 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12199 << VD << VD->getSourceRange();
12200 }
12201 return QualType();
12202 }
12203};
12204} // namespace
12205
12207 SourceLocation Loc,
12209 assert(getLangOpts().CPlusPlus &&
12210 "Looking for comparison category type outside of C++.");
12211
12212 // Use an elaborated type for diagnostics which has a name containing the
12213 // prepended 'std' namespace but not any inline namespace names.
12214 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12216 /*Prefix=*/std::nullopt);
12217 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12218 Info->Record,
12219 /*OwnsTag=*/false);
12220 };
12221
12222 // Check if we've already successfully checked the comparison category type
12223 // before. If so, skip checking it again.
12224 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12225 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12226 // The only thing we need to check is that the type has a reachable
12227 // definition in the current context.
12228 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12229 return QualType();
12230
12231 return Info->getType();
12232 }
12233
12234 // If lookup failed
12235 if (!Info) {
12236 std::string NameForDiags = "std::";
12237 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12238 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12239 << NameForDiags << (int)Usage;
12240 return QualType();
12241 }
12242
12243 assert(Info->Kind == Kind);
12244 assert(Info->Record);
12245
12246 // Update the Record decl in case we encountered a forward declaration on our
12247 // first pass. FIXME: This is a bit of a hack.
12248 if (Info->Record->hasDefinition())
12249 Info->Record = Info->Record->getDefinition();
12250
12251 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12252 return QualType();
12253
12254 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12255
12256 if (!Info->Record->isTriviallyCopyable())
12257 return UnsupportedSTLError(USS_NonTrivial);
12258
12259 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12260 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12261 // Tolerate empty base classes.
12262 if (Base->isEmpty())
12263 continue;
12264 // Reject STL implementations which have at least one non-empty base.
12265 return UnsupportedSTLError();
12266 }
12267
12268 // Check that the STL has implemented the types using a single integer field.
12269 // This expectation allows better codegen for builtin operators. We require:
12270 // (1) The class has exactly one field.
12271 // (2) The field is an integral or enumeration type.
12272 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12273 if (std::distance(FIt, FEnd) != 1 ||
12274 !FIt->getType()->isIntegralOrEnumerationType()) {
12275 return UnsupportedSTLError();
12276 }
12277
12278 // Build each of the require values and store them in Info.
12279 for (ComparisonCategoryResult CCR :
12281 StringRef MemName = ComparisonCategories::getResultString(CCR);
12282 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12283
12284 if (!ValInfo)
12285 return UnsupportedSTLError(USS_MissingMember, MemName);
12286
12287 VarDecl *VD = ValInfo->VD;
12288 assert(VD && "should not be null!");
12289
12290 // Attempt to diagnose reasons why the STL definition of this type
12291 // might be foobar, including it failing to be a constant expression.
12292 // TODO Handle more ways the lookup or result can be invalid.
12293 if (!VD->isStaticDataMember() ||
12295 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12296
12297 // Attempt to evaluate the var decl as a constant expression and extract
12298 // the value of its first field as a ICE. If this fails, the STL
12299 // implementation is not supported.
12300 if (!ValInfo->hasValidIntValue())
12301 return UnsupportedSTLError();
12302
12303 MarkVariableReferenced(Loc, VD);
12304 }
12305
12306 // We've successfully built the required types and expressions. Update
12307 // the cache and return the newly cached value.
12308 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12309 return Info->getType();
12310}
12311
12313 if (!StdNamespace) {
12314 // The "std" namespace has not yet been defined, so build one implicitly.
12316 Context, Context.getTranslationUnitDecl(),
12317 /*Inline=*/false, SourceLocation(), SourceLocation(),
12318 &PP.getIdentifierTable().get("std"),
12319 /*PrevDecl=*/nullptr, /*Nested=*/false);
12320 getStdNamespace()->setImplicit(true);
12321 // We want the created NamespaceDecl to be available for redeclaration
12322 // lookups, but not for regular name lookups.
12323 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12324 getStdNamespace()->clearIdentifierNamespace();
12325 }
12326
12327 return getStdNamespace();
12328}
12329
12330static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12331 const char *ClassName,
12332 ClassTemplateDecl **CachedDecl,
12333 const Decl **MalformedDecl) {
12334 // We're looking for implicit instantiations of
12335 // template <typename U> class std::{ClassName}.
12336
12337 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12338 // it.
12339 return false;
12340
12341 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12342 if (!MalformedDecl)
12343 return;
12344 if (!D)
12345 D = SugaredType->getAsTagDecl();
12346 if (!D || !D->isInStdNamespace())
12347 return;
12348 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12349 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12350 *MalformedDecl = D;
12351 };
12352
12353 ClassTemplateDecl *Template = nullptr;
12355 if (const TemplateSpecializationType *TST =
12357 Template = dyn_cast_or_null<ClassTemplateDecl>(
12358 TST->getTemplateName().getAsTemplateDecl());
12359 Arguments = TST->template_arguments();
12360 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12361 Template = TT->getTemplateDecl();
12362 Arguments = TT->getTemplateArgs(S.Context);
12363 }
12364
12365 if (!Template) {
12366 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12367 return false;
12368 }
12369
12370 if (!*CachedDecl) {
12371 // Haven't recognized std::{ClassName} yet, maybe this is it.
12372 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12373 // semantics of this are slightly different, most notably the existing
12374 // "lookup" semantics explicitly diagnose an invalid definition as an
12375 // error.
12376 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12377 if (TemplateClass->getIdentifier() !=
12378 &S.PP.getIdentifierTable().get(ClassName) ||
12380 TemplateClass->getNonTransparentDeclContext()))
12381 return false;
12382 // This is a template called std::{ClassName}, but is it the right
12383 // template?
12384 TemplateParameterList *Params = Template->getTemplateParameters();
12385 if (Params->getMinRequiredArguments() != 1 ||
12386 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12387 Params->getParam(0)->isTemplateParameterPack()) {
12388 if (MalformedDecl)
12389 *MalformedDecl = TemplateClass;
12390 return false;
12391 }
12392
12393 // It's the right template.
12394 *CachedDecl = Template;
12395 }
12396
12397 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12398 return false;
12399
12400 // This is an instance of std::{ClassName}. Find the argument type.
12401 if (TypeArg) {
12402 QualType ArgType = Arguments[0].getAsType();
12403 // FIXME: Since TST only has as-written arguments, we have to perform the
12404 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12405 // - If an explicitly-specified template argument type is a lifetime type
12406 // with no lifetime qualifier, the __strong lifetime qualifier is
12407 // inferred.
12408 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12409 !ArgType.getObjCLifetime()) {
12410 Qualifiers Qs;
12412 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12413 }
12414 *TypeArg = ArgType;
12415 }
12416
12417 return true;
12418}
12419
12421 assert(getLangOpts().CPlusPlus &&
12422 "Looking for std::initializer_list outside of C++.");
12423
12424 // We're looking for implicit instantiations of
12425 // template <typename E> class std::initializer_list.
12426
12427 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12428 &StdInitializerList, /*MalformedDecl=*/nullptr);
12429}
12430
12432 const Decl **MalformedDecl) {
12433 assert(getLangOpts().CPlusPlus &&
12434 "Looking for std::type_identity outside of C++.");
12435
12436 // We're looking for implicit instantiations of
12437 // template <typename T> struct std::type_identity.
12438
12439 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12440 &StdTypeIdentity, MalformedDecl);
12441}
12442
12444 const char *ClassName,
12445 bool *WasMalformed) {
12446 if (!S.StdNamespace)
12447 return nullptr;
12448
12449 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12452 return nullptr;
12453
12455 if (!Template) {
12456 Result.suppressDiagnostics();
12457 // We found something weird. Complain about the first thing we found.
12458 NamedDecl *Found = *Result.begin();
12459 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12460 << ClassName;
12461 if (WasMalformed)
12462 *WasMalformed = true;
12463 return nullptr;
12464 }
12465
12466 // We found some template with the correct name. Now verify that it's
12467 // correct.
12468 TemplateParameterList *Params = Template->getTemplateParameters();
12469 if (Params->getMinRequiredArguments() != 1 ||
12470 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12471 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12472 << ClassName;
12473 if (WasMalformed)
12474 *WasMalformed = true;
12475 return nullptr;
12476 }
12477
12478 return Template;
12479}
12480
12482 QualType TypeParam, SourceLocation Loc) {
12483 assert(S.getStdNamespace());
12484 TemplateArgumentListInfo Args(Loc, Loc);
12485 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12486 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12487
12489 Loc, Args, /*Scope=*/nullptr,
12490 /*ForNestedNameSpecifier=*/false);
12491}
12492
12494 if (!StdInitializerList) {
12495 bool WasMalformed = false;
12497 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12498 if (!StdInitializerList) {
12499 if (!WasMalformed)
12500 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12501 return QualType();
12502 }
12503 }
12504 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12505}
12506
12508 if (!StdTypeIdentity) {
12509 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12510 /*WasMalformed=*/nullptr);
12511 if (!StdTypeIdentity)
12512 return QualType();
12513 }
12514 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12515}
12516
12518 // C++ [dcl.init.list]p2:
12519 // A constructor is an initializer-list constructor if its first parameter
12520 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12521 // std::initializer_list<E> for some type E, and either there are no other
12522 // parameters or else all other parameters have default arguments.
12523 if (!Ctor->hasOneParamOrDefaultArgs())
12524 return false;
12525
12526 QualType ArgType = Ctor->getParamDecl(0)->getType();
12527 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12528 ArgType = RT->getPointeeType().getUnqualifiedType();
12529
12530 return isStdInitializerList(ArgType, nullptr);
12531}
12532
12533/// Determine whether a using statement is in a context where it will be
12534/// apply in all contexts.
12536 switch (CurContext->getDeclKind()) {
12537 case Decl::TranslationUnit:
12538 return true;
12539 case Decl::LinkageSpec:
12540 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12541 default:
12542 return false;
12543 }
12544}
12545
12546namespace {
12547
12548// Callback to only accept typo corrections that are namespaces.
12549class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12550public:
12551 bool ValidateCandidate(const TypoCorrection &candidate) override {
12552 if (NamedDecl *ND = candidate.getCorrectionDecl())
12554 return false;
12555 }
12556
12557 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12558 return std::make_unique<NamespaceValidatorCCC>(*this);
12559 }
12560};
12561
12562}
12563
12564static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12565 Sema &S) {
12566 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12567 Module *M = ND->getOwningModule();
12568 assert(M && "hidden namespace definition not in a module?");
12569
12570 if (M->isExplicitGlobalModule())
12571 S.Diag(Corrected.getCorrectionRange().getBegin(),
12572 diag::err_module_unimported_use_header)
12574 << /*Header Name*/ false;
12575 else
12576 S.Diag(Corrected.getCorrectionRange().getBegin(),
12577 diag::err_module_unimported_use)
12579 << M->getTopLevelModuleName();
12580}
12581
12583 CXXScopeSpec &SS,
12584 SourceLocation IdentLoc,
12585 IdentifierInfo *Ident) {
12586 R.clear();
12587 NamespaceValidatorCCC CCC{};
12588 if (TypoCorrection Corrected =
12589 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12591 // Generally we find it is confusing more than helpful to diagnose the
12592 // invisible namespace.
12593 // See https://github.com/llvm/llvm-project/issues/73893.
12594 //
12595 // However, we should diagnose when the users are trying to using an
12596 // invisible namespace. So we handle the case specially here.
12597 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12598 Corrected.requiresImport()) {
12599 DiagnoseInvisibleNamespace(Corrected, S);
12600 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12601 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12602 bool DroppedSpecifier =
12603 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12604 S.diagnoseTypo(Corrected,
12605 S.PDiag(diag::err_using_directive_member_suggest)
12606 << Ident << DC << DroppedSpecifier << SS.getRange(),
12607 S.PDiag(diag::note_namespace_defined_here));
12608 } else {
12609 S.diagnoseTypo(Corrected,
12610 S.PDiag(diag::err_using_directive_suggest) << Ident,
12611 S.PDiag(diag::note_namespace_defined_here));
12612 }
12613 R.addDecl(Corrected.getFoundDecl());
12614 return true;
12615 }
12616 return false;
12617}
12618
12620 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12621 SourceLocation IdentLoc,
12622 IdentifierInfo *NamespcName,
12623 const ParsedAttributesView &AttrList) {
12624 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12625 assert(NamespcName && "Invalid NamespcName.");
12626 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12627
12628 // Get the innermost enclosing declaration scope.
12629 S = S->getDeclParent();
12630
12631 UsingDirectiveDecl *UDir = nullptr;
12632 NestedNameSpecifier Qualifier = SS.getScopeRep();
12633
12634 // Lookup namespace name.
12635 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12636 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12637 if (R.isAmbiguous())
12638 return nullptr;
12639
12640 if (R.empty()) {
12641 R.clear();
12642 // Allow "using namespace std;" or "using namespace ::std;" even if
12643 // "std" hasn't been defined yet, for GCC compatibility.
12644 if ((!Qualifier ||
12645 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12646 NamespcName->isStr("std")) {
12647 Diag(IdentLoc, diag::ext_using_undefined_std);
12648 R.addDecl(getOrCreateStdNamespace());
12649 R.resolveKind();
12650 }
12651 // Otherwise, attempt typo correction.
12652 else
12653 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12654 }
12655
12656 if (!R.empty()) {
12657 NamedDecl *Named = R.getRepresentativeDecl();
12658 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12659 assert(NS && "expected namespace decl");
12660
12661 // The use of a nested name specifier may trigger deprecation warnings.
12662 DiagnoseUseOfDecl(Named, IdentLoc);
12663
12664 // C++ [namespace.udir]p1:
12665 // A using-directive specifies that the names in the nominated
12666 // namespace can be used in the scope in which the
12667 // using-directive appears after the using-directive. During
12668 // unqualified name lookup (3.4.1), the names appear as if they
12669 // were declared in the nearest enclosing namespace which
12670 // contains both the using-directive and the nominated
12671 // namespace. [Note: in this context, "contains" means "contains
12672 // directly or indirectly". ]
12673
12674 // Find enclosing context containing both using-directive and
12675 // nominated namespace.
12676 DeclContext *CommonAncestor = NS;
12677 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12678 CommonAncestor = CommonAncestor->getParent();
12679
12680 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12682 IdentLoc, Named, CommonAncestor);
12683
12685 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12686 Diag(IdentLoc, diag::warn_using_directive_in_header);
12687 }
12688
12689 PushUsingDirective(S, UDir);
12690 } else {
12691 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12692 }
12693
12694 if (UDir) {
12695 ProcessDeclAttributeList(S, UDir, AttrList);
12696 ProcessAPINotes(UDir);
12697 }
12698
12699 return UDir;
12700}
12701
12703 // If the scope has an associated entity and the using directive is at
12704 // namespace or translation unit scope, add the UsingDirectiveDecl into
12705 // its lookup structure so qualified name lookup can find it.
12706 DeclContext *Ctx = S->getEntity();
12707 if (Ctx && !Ctx->isFunctionOrMethod())
12708 Ctx->addDecl(UDir);
12709 else
12710 // Otherwise, it is at block scope. The using-directives will affect lookup
12711 // only to the end of the scope.
12712 S->PushUsingDirective(UDir);
12713}
12714
12716 SourceLocation UsingLoc,
12717 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12718 UnqualifiedId &Name,
12719 SourceLocation EllipsisLoc,
12720 const ParsedAttributesView &AttrList) {
12721 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12722
12723 if (SS.isEmpty()) {
12724 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12725 return nullptr;
12726 }
12727
12728 switch (Name.getKind()) {
12734 break;
12735
12738 // C++11 inheriting constructors.
12739 Diag(Name.getBeginLoc(),
12741 ? diag::warn_cxx98_compat_using_decl_constructor
12742 : diag::err_using_decl_constructor)
12743 << SS.getRange();
12744
12745 if (getLangOpts().CPlusPlus11) break;
12746
12747 return nullptr;
12748
12750 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12751 return nullptr;
12752
12754 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12756 return nullptr;
12757
12759 llvm_unreachable("cannot parse qualified deduction guide name");
12760 }
12761
12762 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12763 DeclarationName TargetName = TargetNameInfo.getName();
12764 if (!TargetName)
12765 return nullptr;
12766
12767 // Warn about access declarations.
12768 if (UsingLoc.isInvalid()) {
12770 ? diag::err_access_decl
12771 : diag::warn_access_decl_deprecated)
12772 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12773 }
12774
12775 if (EllipsisLoc.isInvalid()) {
12778 return nullptr;
12779 } else {
12781 !TargetNameInfo.containsUnexpandedParameterPack()) {
12782 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12783 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12784 EllipsisLoc = SourceLocation();
12785 }
12786 }
12787
12788 NamedDecl *UD =
12789 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12790 SS, TargetNameInfo, EllipsisLoc, AttrList,
12791 /*IsInstantiation*/ false,
12792 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12793 if (UD)
12794 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12795
12796 return UD;
12797}
12798
12800 SourceLocation UsingLoc,
12801 SourceLocation EnumLoc, SourceRange TyLoc,
12802 const IdentifierInfo &II, ParsedType Ty,
12803 const CXXScopeSpec &SS) {
12804 TypeSourceInfo *TSI = nullptr;
12805 SourceLocation IdentLoc = TyLoc.getBegin();
12806 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12807 if (EnumTy.isNull()) {
12808 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12809 ? diag::err_using_enum_is_dependent
12810 : diag::err_unknown_typename)
12811 << II.getName()
12812 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12813 TyLoc.getEnd());
12814 return nullptr;
12815 }
12816
12817 if (EnumTy->isDependentType()) {
12818 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12819 return nullptr;
12820 }
12821
12822 auto *Enum = EnumTy->getAsEnumDecl();
12823 if (!Enum) {
12824 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12825 return nullptr;
12826 }
12827
12828 if (TSI == nullptr)
12829 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12830
12831 auto *UD =
12832 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12833
12834 if (UD)
12835 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12836
12837 return UD;
12838}
12839
12840/// Determine whether a using declaration considers the given
12841/// declarations as "equivalent", e.g., if they are redeclarations of
12842/// the same entity or are both typedefs of the same type.
12843static bool
12845 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12846 return true;
12847
12848 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12849 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12850 return Context.hasSameType(TD1->getUnderlyingType(),
12851 TD2->getUnderlyingType());
12852
12853 // Two using_if_exists using-declarations are equivalent if both are
12854 // unresolved.
12857 return true;
12858
12859 return false;
12860}
12861
12863 const LookupResult &Previous,
12864 UsingShadowDecl *&PrevShadow) {
12865 // Diagnose finding a decl which is not from a base class of the
12866 // current class. We do this now because there are cases where this
12867 // function will silently decide not to build a shadow decl, which
12868 // will pre-empt further diagnostics.
12869 //
12870 // We don't need to do this in C++11 because we do the check once on
12871 // the qualifier.
12872 //
12873 // FIXME: diagnose the following if we care enough:
12874 // struct A { int foo; };
12875 // struct B : A { using A::foo; };
12876 // template <class T> struct C : A {};
12877 // template <class T> struct D : C<T> { using B::foo; } // <---
12878 // This is invalid (during instantiation) in C++03 because B::foo
12879 // resolves to the using decl in B, which is not a base class of D<T>.
12880 // We can't diagnose it immediately because C<T> is an unknown
12881 // specialization. The UsingShadowDecl in D<T> then points directly
12882 // to A::foo, which will look well-formed when we instantiate.
12883 // The right solution is to not collapse the shadow-decl chain.
12884 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12885 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12886 DeclContext *OrigDC = Orig->getDeclContext();
12887
12888 // Handle enums and anonymous structs.
12889 if (isa<EnumDecl>(OrigDC))
12890 OrigDC = OrigDC->getParent();
12891 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12892 while (OrigRec->isAnonymousStructOrUnion())
12893 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12894
12896 if (OrigDC == CurContext) {
12897 Diag(Using->getLocation(),
12898 diag::err_using_decl_nested_name_specifier_is_current_class)
12899 << Using->getQualifierLoc().getSourceRange();
12900 Diag(Orig->getLocation(), diag::note_using_decl_target);
12901 Using->setInvalidDecl();
12902 return true;
12903 }
12904
12905 Diag(Using->getQualifierLoc().getBeginLoc(),
12906 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12907 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12908 << Using->getQualifierLoc().getSourceRange();
12909 Diag(Orig->getLocation(), diag::note_using_decl_target);
12910 Using->setInvalidDecl();
12911 return true;
12912 }
12913 }
12914
12915 if (Previous.empty()) return false;
12916
12917 NamedDecl *Target = Orig;
12919 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12920
12921 // If the target happens to be one of the previous declarations, we
12922 // don't have a conflict.
12923 //
12924 // FIXME: but we might be increasing its access, in which case we
12925 // should redeclare it.
12926 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12927 bool FoundEquivalentDecl = false;
12928 for (NamedDecl *Element : Previous) {
12929 NamedDecl *D = Element->getUnderlyingDecl();
12930 // We can have UsingDecls in our Previous results because we use the same
12931 // LookupResult for checking whether the UsingDecl itself is a valid
12932 // redeclaration.
12934 continue;
12935
12936 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12937 // C++ [class.mem]p19:
12938 // If T is the name of a class, then [every named member other than
12939 // a non-static data member] shall have a name different from T
12940 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12944 CurContext,
12946 return true;
12947 }
12948
12950 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12951 PrevShadow = Shadow;
12952 FoundEquivalentDecl = true;
12954 // We don't conflict with an existing using shadow decl of an equivalent
12955 // declaration, but we're not a redeclaration of it.
12956 FoundEquivalentDecl = true;
12957 }
12958
12959 if (isVisible(D))
12960 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12961 }
12962
12963 if (FoundEquivalentDecl)
12964 return false;
12965
12966 // Always emit a diagnostic for a mismatch between an unresolved
12967 // using_if_exists and a resolved using declaration in either direction.
12969 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12970 if (!NonTag && !Tag)
12971 return false;
12972 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12973 Diag(Target->getLocation(), diag::note_using_decl_target);
12974 Diag((NonTag ? NonTag : Tag)->getLocation(),
12975 diag::note_using_decl_conflict);
12976 BUD->setInvalidDecl();
12977 return true;
12978 }
12979
12980 if (FunctionDecl *FD = Target->getAsFunction()) {
12981 NamedDecl *OldDecl = nullptr;
12982 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12983 /*IsForUsingDecl*/ true)) {
12985 return false;
12986
12988 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12989 break;
12990
12991 // We found a decl with the exact signature.
12993 // If we're in a record, we want to hide the target, so we
12994 // return true (without a diagnostic) to tell the caller not to
12995 // build a shadow decl.
12996 if (CurContext->isRecord())
12997 return true;
12998
12999 // If we're not in a record, this is an error.
13000 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13001 break;
13002 }
13003
13004 Diag(Target->getLocation(), diag::note_using_decl_target);
13005 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13006 BUD->setInvalidDecl();
13007 return true;
13008 }
13009
13010 // Target is not a function.
13011
13012 if (isa<TagDecl>(Target)) {
13013 // No conflict between a tag and a non-tag.
13014 if (!Tag) return false;
13015
13016 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13017 Diag(Target->getLocation(), diag::note_using_decl_target);
13018 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13019 BUD->setInvalidDecl();
13020 return true;
13021 }
13022
13023 // No conflict between a tag and a non-tag.
13024 if (!NonTag) return false;
13025
13026 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13027 Diag(Target->getLocation(), diag::note_using_decl_target);
13028 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13029 BUD->setInvalidDecl();
13030 return true;
13031}
13032
13033/// Determine whether a direct base class is a virtual base class.
13035 if (!Derived->getNumVBases())
13036 return false;
13037 for (auto &B : Derived->bases())
13038 if (B.getType()->getAsCXXRecordDecl() == Base)
13039 return B.isVirtual();
13040 llvm_unreachable("not a direct base class");
13041}
13042
13044 NamedDecl *Orig,
13045 UsingShadowDecl *PrevDecl) {
13046 // If we resolved to another shadow declaration, just coalesce them.
13047 NamedDecl *Target = Orig;
13049 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13050 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13051 }
13052
13053 NamedDecl *NonTemplateTarget = Target;
13054 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13055 NonTemplateTarget = TargetTD->getTemplatedDecl();
13056
13057 UsingShadowDecl *Shadow;
13058 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13059 UsingDecl *Using = cast<UsingDecl>(BUD);
13060 bool IsVirtualBase =
13062 Using->getQualifier().getAsRecordDecl());
13064 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13065 } else {
13067 Target->getDeclName(), BUD, Target);
13068 }
13069 BUD->addShadowDecl(Shadow);
13070
13071 Shadow->setAccess(BUD->getAccess());
13072 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13073 Shadow->setInvalidDecl();
13074
13075 Shadow->setPreviousDecl(PrevDecl);
13076
13077 if (S)
13078 PushOnScopeChains(Shadow, S);
13079 else
13080 CurContext->addDecl(Shadow);
13081
13082
13083 return Shadow;
13084}
13085
13087 if (Shadow->getDeclName().getNameKind() ==
13089 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13090
13091 // Remove it from the DeclContext...
13092 Shadow->getDeclContext()->removeDecl(Shadow);
13093
13094 // ...and the scope, if applicable...
13095 if (S) {
13096 S->RemoveDecl(Shadow);
13097 IdResolver.RemoveDecl(Shadow);
13098 }
13099
13100 // ...and the using decl.
13101 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13102
13103 // TODO: complain somehow if Shadow was used. It shouldn't
13104 // be possible for this to happen, because...?
13105}
13106
13107/// Find the base specifier for a base class with the given type.
13109 QualType DesiredBase,
13110 bool &AnyDependentBases) {
13111 // Check whether the named type is a direct base class.
13112 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13113 for (auto &Base : Derived->bases()) {
13114 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13115 if (CanonicalDesiredBase == BaseType)
13116 return &Base;
13117 if (BaseType->isDependentType())
13118 AnyDependentBases = true;
13119 }
13120 return nullptr;
13121}
13122
13123namespace {
13124class UsingValidatorCCC final : public CorrectionCandidateCallback {
13125public:
13126 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13127 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13128 : HasTypenameKeyword(HasTypenameKeyword),
13129 IsInstantiation(IsInstantiation), OldNNS(NNS),
13130 RequireMemberOf(RequireMemberOf) {}
13131
13132 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13133 NamedDecl *ND = Candidate.getCorrectionDecl();
13134
13135 // Keywords are not valid here.
13136 if (!ND || isa<NamespaceDecl>(ND))
13137 return false;
13138
13139 // Completely unqualified names are invalid for a 'using' declaration.
13140 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13141 return false;
13142
13143 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13144 // reject.
13145
13146 if (RequireMemberOf) {
13147 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13148 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13149 // No-one ever wants a using-declaration to name an injected-class-name
13150 // of a base class, unless they're declaring an inheriting constructor.
13151 ASTContext &Ctx = ND->getASTContext();
13152 if (!Ctx.getLangOpts().CPlusPlus11)
13153 return false;
13154 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13155
13156 // Check that the injected-class-name is named as a member of its own
13157 // type; we don't want to suggest 'using Derived::Base;', since that
13158 // means something else.
13159 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13160 ? Candidate.getCorrectionSpecifier()
13161 : OldNNS;
13162 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13163 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13164 return false;
13165
13166 // Check that this inheriting constructor declaration actually names a
13167 // direct base class of the current class.
13168 bool AnyDependentBases = false;
13169 if (!findDirectBaseWithType(RequireMemberOf,
13170 Ctx.getCanonicalTagType(FoundRecord),
13171 AnyDependentBases) &&
13172 !AnyDependentBases)
13173 return false;
13174 } else {
13175 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13176 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13177 return false;
13178
13179 // FIXME: Check that the base class member is accessible?
13180 }
13181 } else {
13182 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13183 if (FoundRecord && FoundRecord->isInjectedClassName())
13184 return false;
13185 }
13186
13187 if (isa<TypeDecl>(ND))
13188 return HasTypenameKeyword || !IsInstantiation;
13189
13190 return !HasTypenameKeyword;
13191 }
13192
13193 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13194 return std::make_unique<UsingValidatorCCC>(*this);
13195 }
13196
13197private:
13198 bool HasTypenameKeyword;
13199 bool IsInstantiation;
13200 NestedNameSpecifier OldNNS;
13201 CXXRecordDecl *RequireMemberOf;
13202};
13203} // end anonymous namespace
13204
13206 // It is really dumb that we have to do this.
13207 LookupResult::Filter F = Previous.makeFilter();
13208 while (F.hasNext()) {
13209 NamedDecl *D = F.next();
13210 if (!isDeclInScope(D, CurContext, S))
13211 F.erase();
13212 // If we found a local extern declaration that's not ordinarily visible,
13213 // and this declaration is being added to a non-block scope, ignore it.
13214 // We're only checking for scope conflicts here, not also for violations
13215 // of the linkage rules.
13216 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13218 F.erase();
13219 }
13220 F.done();
13221}
13222
13224 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13225 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13226 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13227 const ParsedAttributesView &AttrList, bool IsInstantiation,
13228 bool IsUsingIfExists) {
13229 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13230 SourceLocation IdentLoc = NameInfo.getLoc();
13231 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13232
13233 // FIXME: We ignore attributes for now.
13234
13235 // For an inheriting constructor declaration, the name of the using
13236 // declaration is the name of a constructor in this class, not in the
13237 // base class.
13238 DeclarationNameInfo UsingName = NameInfo;
13240 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13241 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13242 Context.getCanonicalTagType(RD)));
13243
13244 // Do the redeclaration lookup in the current scope.
13245 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13247 Previous.setHideTags(false);
13248 if (S) {
13249 LookupName(Previous, S);
13250
13252 } else {
13253 assert(IsInstantiation && "no scope in non-instantiation");
13254 if (CurContext->isRecord())
13256 else {
13257 // No redeclaration check is needed here; in non-member contexts we
13258 // diagnosed all possible conflicts with other using-declarations when
13259 // building the template:
13260 //
13261 // For a dependent non-type using declaration, the only valid case is
13262 // if we instantiate to a single enumerator. We check for conflicts
13263 // between shadow declarations we introduce, and we check in the template
13264 // definition for conflicts between a non-type using declaration and any
13265 // other declaration, which together covers all cases.
13266 //
13267 // A dependent typename using declaration will never successfully
13268 // instantiate, since it will always name a class member, so we reject
13269 // that in the template definition.
13270 }
13271 }
13272
13273 // Check for invalid redeclarations.
13274 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13275 SS, IdentLoc, Previous))
13276 return nullptr;
13277
13278 // 'using_if_exists' doesn't make sense on an inherited constructor.
13279 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13281 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13282 return nullptr;
13283 }
13284
13285 DeclContext *LookupContext = computeDeclContext(SS);
13287 if (!LookupContext || EllipsisLoc.isValid()) {
13288 NamedDecl *D;
13289 // Dependent scope, or an unexpanded pack
13290 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13291 SS, NameInfo, IdentLoc))
13292 return nullptr;
13293
13294 if (Previous.isSingleResult() &&
13295 Previous.getFoundDecl()->isTemplateParameter())
13296 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13297
13298 if (HasTypenameKeyword) {
13299 // FIXME: not all declaration name kinds are legal here
13301 UsingLoc, TypenameLoc,
13302 QualifierLoc,
13303 IdentLoc, NameInfo.getName(),
13304 EllipsisLoc);
13305 } else {
13307 QualifierLoc, NameInfo, EllipsisLoc);
13308 }
13309 D->setAccess(AS);
13310 CurContext->addDecl(D);
13311 ProcessDeclAttributeList(S, D, AttrList);
13312 return D;
13313 }
13314
13315 auto Build = [&](bool Invalid) {
13316 UsingDecl *UD =
13317 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13318 UsingName, HasTypenameKeyword);
13319 UD->setAccess(AS);
13320 CurContext->addDecl(UD);
13321 ProcessDeclAttributeList(S, UD, AttrList);
13323 return UD;
13324 };
13325 auto BuildInvalid = [&]{ return Build(true); };
13326 auto BuildValid = [&]{ return Build(false); };
13327
13328 if (RequireCompleteDeclContext(SS, LookupContext))
13329 return BuildInvalid();
13330
13331 // Look up the target name.
13332 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13333
13334 // Unlike most lookups, we don't always want to hide tag
13335 // declarations: tag names are visible through the using declaration
13336 // even if hidden by ordinary names, *except* in a dependent context
13337 // where they may be used by two-phase lookup.
13338 if (!IsInstantiation)
13339 R.setHideTags(false);
13340
13341 // For the purposes of this lookup, we have a base object type
13342 // equal to that of the current context.
13343 if (CurContext->isRecord()) {
13344 R.setBaseObjectType(
13345 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13346 }
13347
13348 LookupQualifiedName(R, LookupContext);
13349
13350 // Validate the context, now we have a lookup
13351 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13352 IdentLoc, &R))
13353 return nullptr;
13354
13355 if (R.empty() && IsUsingIfExists)
13357 UsingName.getName()),
13358 AS_public);
13359
13360 // Try to correct typos if possible. If constructor name lookup finds no
13361 // results, that means the named class has no explicit constructors, and we
13362 // suppressed declaring implicit ones (probably because it's dependent or
13363 // invalid).
13364 if (R.empty() &&
13366 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13367 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13368 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13369 auto *II = NameInfo.getName().getAsIdentifierInfo();
13370 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13371 CurContext->isStdNamespace() &&
13372 isa<TranslationUnitDecl>(LookupContext) &&
13373 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13374 getSourceManager().isInSystemHeader(UsingLoc))
13375 return nullptr;
13376 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13377 dyn_cast<CXXRecordDecl>(CurContext));
13378 if (TypoCorrection Corrected =
13379 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13381 // We reject candidates where DroppedSpecifier == true, hence the
13382 // literal '0' below.
13383 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13384 << NameInfo.getName() << LookupContext << 0
13385 << SS.getRange());
13386
13387 // If we picked a correction with no attached Decl we can't do anything
13388 // useful with it, bail out.
13389 NamedDecl *ND = Corrected.getCorrectionDecl();
13390 if (!ND)
13391 return BuildInvalid();
13392
13393 // If we corrected to an inheriting constructor, handle it as one.
13394 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13395 if (RD && RD->isInjectedClassName()) {
13396 // The parent of the injected class name is the class itself.
13397 RD = cast<CXXRecordDecl>(RD->getParent());
13398
13399 // Fix up the information we'll use to build the using declaration.
13400 if (Corrected.WillReplaceSpecifier()) {
13402 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13403 QualifierLoc.getSourceRange());
13404 QualifierLoc = Builder.getWithLocInContext(Context);
13405 }
13406
13407 // In this case, the name we introduce is the name of a derived class
13408 // constructor.
13409 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13410 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13411 Context.getCanonicalTagType(CurClass)));
13412 UsingName.setNamedTypeInfo(nullptr);
13413 for (auto *Ctor : LookupConstructors(RD))
13414 R.addDecl(Ctor);
13415 R.resolveKind();
13416 } else {
13417 // FIXME: Pick up all the declarations if we found an overloaded
13418 // function.
13419 UsingName.setName(ND->getDeclName());
13420 R.addDecl(ND);
13421 }
13422 } else {
13423 Diag(IdentLoc, diag::err_no_member)
13424 << NameInfo.getName() << LookupContext << SS.getRange();
13425 return BuildInvalid();
13426 }
13427 }
13428
13429 if (R.isAmbiguous())
13430 return BuildInvalid();
13431
13432 if (HasTypenameKeyword) {
13433 // If we asked for a typename and got a non-type decl, error out.
13434 if (!R.getAsSingle<TypeDecl>() &&
13435 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13436 Diag(IdentLoc, diag::err_using_typename_non_type);
13437 for (const NamedDecl *D : R)
13438 Diag(D->getUnderlyingDecl()->getLocation(),
13439 diag::note_using_decl_target);
13440 return BuildInvalid();
13441 }
13442 } else {
13443 // If we asked for a non-typename and we got a type, error out,
13444 // but only if this is an instantiation of an unresolved using
13445 // decl. Otherwise just silently find the type name.
13446 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13447 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13448 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13449 return BuildInvalid();
13450 }
13451 }
13452
13453 // C++14 [namespace.udecl]p6:
13454 // A using-declaration shall not name a namespace.
13455 if (R.getAsSingle<NamespaceDecl>()) {
13456 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13457 << SS.getRange();
13458 // Suggest using 'using namespace ...' instead.
13459 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13460 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13461 return BuildInvalid();
13462 }
13463
13464 UsingDecl *UD = BuildValid();
13465
13466 // Some additional rules apply to inheriting constructors.
13467 if (UsingName.getName().getNameKind() ==
13469 // Suppress access diagnostics; the access check is instead performed at the
13470 // point of use for an inheriting constructor.
13471 R.suppressDiagnostics();
13473 return UD;
13474 }
13475
13476 for (NamedDecl *D : R) {
13477 UsingShadowDecl *PrevDecl = nullptr;
13478 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13479 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13480 }
13481
13482 return UD;
13483}
13484
13486 SourceLocation UsingLoc,
13487 SourceLocation EnumLoc,
13488 SourceLocation NameLoc,
13489 TypeSourceInfo *EnumType,
13490 EnumDecl *ED) {
13491 bool Invalid = false;
13492
13493 if (CurContext->getRedeclContext()->isRecord()) {
13494 /// In class scope, check if this is a duplicate, for better a diagnostic.
13495 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13496 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13498
13500
13501 for (NamedDecl *D : Previous)
13502 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13503 if (UED->getEnumDecl() == ED) {
13504 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13505 << SourceRange(EnumLoc, NameLoc);
13506 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13507 Invalid = true;
13508 break;
13509 }
13510 }
13511
13512 if (RequireCompleteEnumDecl(ED, NameLoc))
13513 Invalid = true;
13514
13516 EnumLoc, NameLoc, EnumType);
13517 UD->setAccess(AS);
13518 CurContext->addDecl(UD);
13519
13520 if (Invalid) {
13521 UD->setInvalidDecl();
13522 return UD;
13523 }
13524
13525 // Create the shadow decls for each enumerator
13526 for (EnumConstantDecl *EC : ED->enumerators()) {
13527 UsingShadowDecl *PrevDecl = nullptr;
13528 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13531 LookupName(Previous, S);
13533
13534 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13535 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13536 }
13537
13538 return UD;
13539}
13540
13542 ArrayRef<NamedDecl *> Expansions) {
13543 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13544 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13545 isa<UsingPackDecl>(InstantiatedFrom));
13546
13547 auto *UPD =
13548 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13549 UPD->setAccess(InstantiatedFrom->getAccess());
13550 CurContext->addDecl(UPD);
13551 return UPD;
13552}
13553
13555 assert(!UD->hasTypename() && "expecting a constructor name");
13556
13557 QualType SourceType(UD->getQualifier().getAsType(), 0);
13559
13560 // Check whether the named type is a direct base class.
13561 bool AnyDependentBases = false;
13562 auto *Base =
13563 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13564 if (!Base && !AnyDependentBases) {
13565 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13566 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13567 UD->setInvalidDecl();
13568 return true;
13569 }
13570
13571 if (Base)
13572 Base->setInheritConstructors();
13573
13574 return false;
13575}
13576
13578 bool HasTypenameKeyword,
13579 const CXXScopeSpec &SS,
13580 SourceLocation NameLoc,
13581 const LookupResult &Prev) {
13582 NestedNameSpecifier Qual = SS.getScopeRep();
13583
13584 // C++03 [namespace.udecl]p8:
13585 // C++0x [namespace.udecl]p10:
13586 // A using-declaration is a declaration and can therefore be used
13587 // repeatedly where (and only where) multiple declarations are
13588 // allowed.
13589 //
13590 // That's in non-member contexts.
13591 if (!CurContext->getRedeclContext()->isRecord()) {
13592 // A dependent qualifier outside a class can only ever resolve to an
13593 // enumeration type. Therefore it conflicts with any other non-type
13594 // declaration in the same scope.
13595 // FIXME: How should we check for dependent type-type conflicts at block
13596 // scope?
13597 if (Qual.isDependent() && !HasTypenameKeyword) {
13598 for (auto *D : Prev) {
13599 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13600 bool OldCouldBeEnumerator =
13602 Diag(NameLoc,
13603 OldCouldBeEnumerator ? diag::err_redefinition
13604 : diag::err_redefinition_different_kind)
13605 << Prev.getLookupName();
13606 Diag(D->getLocation(), diag::note_previous_definition);
13607 return true;
13608 }
13609 }
13610 }
13611 return false;
13612 }
13613
13614 NestedNameSpecifier CNNS = Qual.getCanonical();
13615 for (const NamedDecl *D : Prev) {
13616 bool DTypename;
13617 NestedNameSpecifier DQual = std::nullopt;
13618 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13619 DTypename = UD->hasTypename();
13620 DQual = UD->getQualifier();
13621 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13622 DTypename = false;
13623 DQual = UD->getQualifier();
13624 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13625 DTypename = true;
13626 DQual = UD->getQualifier();
13627 } else
13628 continue;
13629
13630 // using decls differ if one says 'typename' and the other doesn't.
13631 // FIXME: non-dependent using decls?
13632 if (HasTypenameKeyword != DTypename) continue;
13633
13634 // using decls differ if they name different scopes (but note that
13635 // template instantiation can cause this check to trigger when it
13636 // didn't before instantiation).
13637 if (CNNS != DQual.getCanonical())
13638 continue;
13639
13640 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13641 Diag(D->getLocation(), diag::note_using_decl) << 1;
13642 return true;
13643 }
13644
13645 return false;
13646}
13647
13648bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13649 const CXXScopeSpec &SS,
13650 const DeclarationNameInfo &NameInfo,
13651 SourceLocation NameLoc,
13652 const LookupResult *R, const UsingDecl *UD) {
13653 DeclContext *NamedContext = computeDeclContext(SS);
13654 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13655 "resolvable context must have exactly one set of decls");
13656
13657 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13658 // relationship.
13659 bool Cxx20Enumerator = false;
13660 if (NamedContext) {
13661 EnumConstantDecl *EC = nullptr;
13662 if (R)
13663 EC = R->getAsSingle<EnumConstantDecl>();
13664 else if (UD && UD->shadow_size() == 1)
13665 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13666 if (EC)
13667 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13668
13669 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13670 // C++14 [namespace.udecl]p7:
13671 // A using-declaration shall not name a scoped enumerator.
13672 // C++20 p1099 permits enumerators.
13673 if (EC && R && ED->isScoped())
13674 Diag(SS.getBeginLoc(),
13676 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13677 : diag::ext_using_decl_scoped_enumerator)
13678 << SS.getRange();
13679
13680 // We want to consider the scope of the enumerator
13681 NamedContext = ED->getDeclContext();
13682 }
13683 }
13684
13685 if (!CurContext->isRecord()) {
13686 // C++03 [namespace.udecl]p3:
13687 // C++0x [namespace.udecl]p8:
13688 // A using-declaration for a class member shall be a member-declaration.
13689 // C++20 [namespace.udecl]p7
13690 // ... other than an enumerator ...
13691
13692 // If we weren't able to compute a valid scope, it might validly be a
13693 // dependent class or enumeration scope. If we have a 'typename' keyword,
13694 // the scope must resolve to a class type.
13695 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13696 : !HasTypename)
13697 return false; // OK
13698
13699 Diag(NameLoc,
13700 Cxx20Enumerator
13701 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13702 : diag::err_using_decl_can_not_refer_to_class_member)
13703 << SS.getRange();
13704
13705 if (Cxx20Enumerator)
13706 return false; // OK
13707
13708 auto *RD = NamedContext
13709 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13710 : nullptr;
13711 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13712 // See if there's a helpful fixit
13713
13714 if (!R) {
13715 // We will have already diagnosed the problem on the template
13716 // definition, Maybe we should do so again?
13717 } else if (R->getAsSingle<TypeDecl>()) {
13718 if (getLangOpts().CPlusPlus11) {
13719 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13720 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13721 << diag::MemClassWorkaround::AliasDecl
13723 NameInfo.getName().getAsString() +
13724 " = ");
13725 } else {
13726 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13727 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13728 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13729 << diag::MemClassWorkaround::TypedefDecl
13730 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13732 InsertLoc, " " + NameInfo.getName().getAsString());
13733 }
13734 } else if (R->getAsSingle<VarDecl>()) {
13735 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13736 // repeating the type of the static data member here.
13737 FixItHint FixIt;
13738 if (getLangOpts().CPlusPlus11) {
13739 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13741 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13742 }
13743
13744 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13745 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13746 } else if (R->getAsSingle<EnumConstantDecl>()) {
13747 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13748 // repeating the type of the enumeration here, and we can't do so if
13749 // the type is anonymous.
13750 FixItHint FixIt;
13751 if (getLangOpts().CPlusPlus11) {
13752 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13754 UsingLoc,
13755 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13756 }
13757
13758 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13759 << (getLangOpts().CPlusPlus11
13760 ? diag::MemClassWorkaround::ConstexprVar
13761 : diag::MemClassWorkaround::ConstVar)
13762 << FixIt;
13763 }
13764 }
13765
13766 return true; // Fail
13767 }
13768
13769 // If the named context is dependent, we can't decide much.
13770 if (!NamedContext) {
13771 // FIXME: in C++0x, we can diagnose if we can prove that the
13772 // nested-name-specifier does not refer to a base class, which is
13773 // still possible in some cases.
13774
13775 // Otherwise we have to conservatively report that things might be
13776 // okay.
13777 return false;
13778 }
13779
13780 // The current scope is a record.
13781 if (!NamedContext->isRecord()) {
13782 // Ideally this would point at the last name in the specifier,
13783 // but we don't have that level of source info.
13784 Diag(SS.getBeginLoc(),
13785 Cxx20Enumerator
13786 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13787 : diag::err_using_decl_nested_name_specifier_is_not_class)
13788 << SS.getScopeRep() << SS.getRange();
13789
13790 if (Cxx20Enumerator)
13791 return false; // OK
13792
13793 return true;
13794 }
13795
13796 if (!NamedContext->isDependentContext() &&
13797 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13798 return true;
13799
13800 // C++26 [namespace.udecl]p3:
13801 // In a using-declaration used as a member-declaration, each
13802 // using-declarator shall either name an enumerator or have a
13803 // nested-name-specifier naming a base class of the current class
13804 // ([expr.prim.this]). ...
13805 // "have a nested-name-specifier naming a base class of the current class"
13806 // was introduced by CWG400.
13807
13810
13811 if (Cxx20Enumerator) {
13812 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13813 << SS.getScopeRep() << SS.getRange();
13814 return false;
13815 }
13816
13817 if (CurContext == NamedContext) {
13818 Diag(SS.getBeginLoc(),
13819 diag::err_using_decl_nested_name_specifier_is_current_class)
13820 << SS.getRange();
13821 return true;
13822 }
13823
13824 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13825 Diag(SS.getBeginLoc(),
13826 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13828 << SS.getRange();
13829 }
13830 return true;
13831 }
13832
13833 return false;
13834}
13835
13837 MultiTemplateParamsArg TemplateParamLists,
13838 SourceLocation UsingLoc, UnqualifiedId &Name,
13839 const ParsedAttributesView &AttrList,
13840 TypeResult Type, Decl *DeclFromDeclSpec) {
13841
13842 if (Type.isInvalid())
13843 return nullptr;
13844
13845 bool Invalid = false;
13847 TypeSourceInfo *TInfo = nullptr;
13848 GetTypeFromParser(Type.get(), &TInfo);
13849
13850 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13851 return nullptr;
13852
13855 Invalid = true;
13856 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13857 TInfo->getTypeLoc().getBeginLoc());
13858 }
13859
13860 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13861 TemplateParamLists.size()
13864 LookupName(Previous, S);
13865
13866 // Warn about shadowing the name of a template parameter.
13867 if (Previous.isSingleResult() &&
13868 Previous.getFoundDecl()->isTemplateParameter()) {
13870 Previous.clear();
13871 }
13872
13873 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13874 "name in alias declaration must be an identifier");
13876 Name.StartLocation,
13877 Name.Identifier, TInfo);
13878
13879 NewTD->setAccess(AS);
13880
13881 if (Invalid)
13882 NewTD->setInvalidDecl();
13883
13884 ProcessDeclAttributeList(S, NewTD, AttrList);
13885 AddPragmaAttributes(S, NewTD);
13886 ProcessAPINotes(NewTD);
13887
13889 Invalid |= NewTD->isInvalidDecl();
13890
13891 // Get the innermost enclosing declaration scope.
13892 S = S->getDeclParent();
13893
13894 bool Redeclaration = false;
13895
13896 NamedDecl *NewND;
13897 if (TemplateParamLists.size()) {
13898 TypeAliasTemplateDecl *OldDecl = nullptr;
13899 TemplateParameterList *OldTemplateParams = nullptr;
13900
13901 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13902 if (TemplateParamLists.size() != 1) {
13903 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13904 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13905 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13906 Invalid = true;
13907
13908 // Recover by picking the last non-empty template parameter list.
13909 auto It = llvm::find_if(
13910 llvm::reverse(TemplateParamLists),
13911 [](TemplateParameterList *TPL) { return !TPL->empty(); });
13912 assert(It != TemplateParamLists.rend() &&
13913 "if all template parameter lists were empty, this should have "
13914 "been rejected as an explicit specialization");
13915 TemplateParams = *It;
13916 }
13917
13918 // Check that we can declare a template here.
13919 if (CheckTemplateDeclScope(S, TemplateParams))
13920 return nullptr;
13921
13922 // Only consider previous declarations in the same scope.
13923 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13924 /*ExplicitInstantiationOrSpecialization*/false);
13925 if (!Previous.empty()) {
13926 Redeclaration = true;
13927
13928 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13929 if (!OldDecl && !Invalid) {
13930 Diag(UsingLoc, diag::err_redefinition_different_kind)
13931 << Name.Identifier;
13932
13933 NamedDecl *OldD = Previous.getRepresentativeDecl();
13934 if (OldD->getLocation().isValid())
13935 Diag(OldD->getLocation(), diag::note_previous_definition);
13936
13937 Invalid = true;
13938 }
13939
13940 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13941 if (TemplateParameterListsAreEqual(TemplateParams,
13942 OldDecl->getTemplateParameters(),
13943 /*Complain=*/true,
13945 OldTemplateParams =
13947 else
13948 Invalid = true;
13949
13950 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13951 if (!Invalid &&
13952 !Context.hasSameType(OldTD->getUnderlyingType(),
13953 NewTD->getUnderlyingType())) {
13954 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13955 // but we can't reasonably accept it.
13956 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13957 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13958 if (OldTD->getLocation().isValid())
13959 Diag(OldTD->getLocation(), diag::note_previous_definition);
13960 Invalid = true;
13961 }
13962 }
13963 }
13964
13965 // Merge any previous default template arguments into our parameters,
13966 // and check the parameter list.
13967 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13968 TPC_Other))
13969 return nullptr;
13970
13971 TypeAliasTemplateDecl *NewDecl =
13973 Name.Identifier, TemplateParams,
13974 NewTD);
13975 NewTD->setDescribedAliasTemplate(NewDecl);
13976
13977 NewDecl->setAccess(AS);
13978
13979 if (Invalid)
13980 NewDecl->setInvalidDecl();
13981 else if (OldDecl) {
13982 NewDecl->setPreviousDecl(OldDecl);
13983 CheckRedeclarationInModule(NewDecl, OldDecl);
13984 }
13985
13986 NewND = NewDecl;
13987 } else {
13988 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13990 handleTagNumbering(TD, S);
13991 }
13993 NewND = NewTD;
13994 }
13995
13996 PushOnScopeChains(NewND, S);
13997 ActOnDocumentableDecl(NewND);
13998 return NewND;
13999}
14000
14002 SourceLocation AliasLoc,
14003 IdentifierInfo *Alias, CXXScopeSpec &SS,
14004 SourceLocation IdentLoc,
14005 IdentifierInfo *Ident) {
14006
14007 // Lookup the namespace name.
14008 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14009 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14010
14011 if (R.isAmbiguous())
14012 return nullptr;
14013
14014 if (R.empty()) {
14015 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14016 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14017 return nullptr;
14018 }
14019 }
14020 assert(!R.isAmbiguous() && !R.empty());
14021 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14022
14023 // Check if we have a previous declaration with the same name.
14024 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14026 LookupName(PrevR, S);
14027
14028 // Check we're not shadowing a template parameter.
14029 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14031 PrevR.clear();
14032 }
14033
14034 // Filter out any other lookup result from an enclosing scope.
14035 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14036 /*AllowInlineNamespace*/false);
14037
14038 // Find the previous declaration and check that we can redeclare it.
14039 NamespaceAliasDecl *Prev = nullptr;
14040 if (PrevR.isSingleResult()) {
14041 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14042 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14043 // We already have an alias with the same name that points to the same
14044 // namespace; check that it matches.
14045 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14046 Prev = AD;
14047 } else if (isVisible(PrevDecl)) {
14048 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14049 << Alias;
14050 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14051 << AD->getNamespace();
14052 return nullptr;
14053 }
14054 } else if (isVisible(PrevDecl)) {
14055 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14056 ? diag::err_redefinition
14057 : diag::err_redefinition_different_kind;
14058 Diag(AliasLoc, DiagID) << Alias;
14059 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14060 return nullptr;
14061 }
14062 }
14063
14064 // The use of a nested name specifier may trigger deprecation warnings.
14065 DiagnoseUseOfDecl(ND, IdentLoc);
14066
14068 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14069 Alias, SS.getWithLocInContext(Context),
14070 IdentLoc, ND);
14071 if (Prev)
14072 AliasDecl->setPreviousDecl(Prev);
14073
14075 return AliasDecl;
14076}
14077
14078namespace {
14079struct SpecialMemberExceptionSpecInfo
14080 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14081 SourceLocation Loc;
14083
14084 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14087 SourceLocation Loc)
14088 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14089
14090 bool visitBase(CXXBaseSpecifier *Base);
14091 bool visitField(FieldDecl *FD);
14092
14093 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14094 unsigned Quals);
14095
14096 void visitSubobjectCall(Subobject Subobj,
14098};
14099}
14100
14101bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14102 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14103 if (!BaseClass)
14104 return false;
14105
14106 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14107 if (auto *BaseCtor = SMOR.getMethod()) {
14108 visitSubobjectCall(Base, BaseCtor);
14109 return false;
14110 }
14111
14112 visitClassSubobject(BaseClass, Base, 0);
14113 return false;
14114}
14115
14116bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14117 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14118 FD->hasInClassInitializer()) {
14119 Expr *E = FD->getInClassInitializer();
14120 if (!E)
14121 // FIXME: It's a little wasteful to build and throw away a
14122 // CXXDefaultInitExpr here.
14123 // FIXME: We should have a single context note pointing at Loc, and
14124 // this location should be MD->getLocation() instead, since that's
14125 // the location where we actually use the default init expression.
14126 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
14127 if (E)
14128 ExceptSpec.CalledExpr(E);
14129 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14130 ->getAsCXXRecordDecl()) {
14131 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14132 }
14133 return false;
14134}
14135
14136void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14137 Subobject Subobj,
14138 unsigned Quals) {
14139 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14140 bool IsMutable = Field && Field->isMutable();
14141 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14142}
14143
14144void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14145 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14146 // Note, if lookup fails, it doesn't matter what exception specification we
14147 // choose because the special member will be deleted.
14148 if (CXXMethodDecl *MD = SMOR.getMethod())
14149 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14150}
14151
14153 llvm::APSInt Result;
14155 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14156 ExplicitSpec.setExpr(Converted.get());
14157 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14158 ExplicitSpec.setKind(Result.getBoolValue()
14161 return true;
14162 }
14164 return false;
14165}
14166
14169 if (!ExplicitExpr->isTypeDependent())
14171 return ES;
14172}
14173
14178 ComputingExceptionSpec CES(S, MD, Loc);
14179
14180 CXXRecordDecl *ClassDecl = MD->getParent();
14181
14182 // C++ [except.spec]p14:
14183 // An implicitly declared special member function (Clause 12) shall have an
14184 // exception-specification. [...]
14185 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14186 if (ClassDecl->isInvalidDecl())
14187 return Info.ExceptSpec;
14188
14189 // FIXME: If this diagnostic fires, we're probably missing a check for
14190 // attempting to resolve an exception specification before it's known
14191 // at a higher level.
14192 if (S.RequireCompleteType(MD->getLocation(),
14193 S.Context.getCanonicalTagType(ClassDecl),
14194 diag::err_exception_spec_incomplete_type))
14195 return Info.ExceptSpec;
14196
14197 // C++1z [except.spec]p7:
14198 // [Look for exceptions thrown by] a constructor selected [...] to
14199 // initialize a potentially constructed subobject,
14200 // C++1z [except.spec]p8:
14201 // The exception specification for an implicitly-declared destructor, or a
14202 // destructor without a noexcept-specifier, is potentially-throwing if and
14203 // only if any of the destructors for any of its potentially constructed
14204 // subojects is potentially throwing.
14205 // FIXME: We respect the first rule but ignore the "potentially constructed"
14206 // in the second rule to resolve a core issue (no number yet) that would have
14207 // us reject:
14208 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14209 // struct B : A {};
14210 // struct C : B { void f(); };
14211 // ... due to giving B::~B() a non-throwing exception specification.
14212 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14213 : Info.VisitAllBases);
14214
14215 return Info.ExceptSpec;
14216}
14217
14218namespace {
14219/// RAII object to register a special member as being currently declared.
14220struct DeclaringSpecialMember {
14221 Sema &S;
14223 Sema::ContextRAII SavedContext;
14224 bool WasAlreadyBeingDeclared;
14225
14226 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14227 : S(S), D(RD, CSM), SavedContext(S, RD) {
14228 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14229 if (WasAlreadyBeingDeclared)
14230 // This almost never happens, but if it does, ensure that our cache
14231 // doesn't contain a stale result.
14232 S.SpecialMemberCache.clear();
14233 else {
14234 // Register a note to be produced if we encounter an error while
14235 // declaring the special member.
14236 Sema::CodeSynthesisContext Ctx;
14237 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14238 // FIXME: We don't have a location to use here. Using the class's
14239 // location maintains the fiction that we declare all special members
14240 // with the class, but (1) it's not clear that lying about that helps our
14241 // users understand what's going on, and (2) there may be outer contexts
14242 // on the stack (some of which are relevant) and printing them exposes
14243 // our lies.
14244 Ctx.PointOfInstantiation = RD->getLocation();
14245 Ctx.Entity = RD;
14246 Ctx.SpecialMember = CSM;
14247 S.pushCodeSynthesisContext(Ctx);
14248 }
14249 }
14250 ~DeclaringSpecialMember() {
14251 if (!WasAlreadyBeingDeclared) {
14252 S.SpecialMembersBeingDeclared.erase(D);
14254 }
14255 }
14256
14257 /// Are we already trying to declare this special member?
14258 bool isAlreadyBeingDeclared() const {
14259 return WasAlreadyBeingDeclared;
14260 }
14261};
14262}
14263
14265 // Look up any existing declarations, but don't trigger declaration of all
14266 // implicit special members with this name.
14267 DeclarationName Name = FD->getDeclName();
14270 for (auto *D : FD->getParent()->lookup(Name))
14271 if (auto *Acceptable = R.getAcceptableDecl(D))
14272 R.addDecl(Acceptable);
14273 R.resolveKind();
14274 R.suppressDiagnostics();
14275
14276 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14278}
14279
14280void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14281 QualType ResultTy,
14282 ArrayRef<QualType> Args) {
14283 // Build an exception specification pointing back at this constructor.
14285
14286 LangAS AS = getDefaultCXXMethodAddrSpace();
14287 if (AS != LangAS::Default) {
14288 EPI.TypeQuals.addAddressSpace(AS);
14289 }
14290
14291 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14292 SpecialMem->setType(QT);
14293
14294 // During template instantiation of implicit special member functions we need
14295 // a reliable TypeSourceInfo for the function prototype in order to allow
14296 // functions to be substituted.
14297 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14298 TypeSourceInfo *TSI =
14299 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14300 SpecialMem->setTypeSourceInfo(TSI);
14301 }
14302}
14303
14305 CXXRecordDecl *ClassDecl) {
14306 // C++ [class.ctor]p5:
14307 // A default constructor for a class X is a constructor of class X
14308 // that can be called without an argument. If there is no
14309 // user-declared constructor for class X, a default constructor is
14310 // implicitly declared. An implicitly-declared default constructor
14311 // is an inline public member of its class.
14312 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14313 "Should not build implicit default constructor!");
14314
14315 DeclaringSpecialMember DSM(*this, ClassDecl,
14317 if (DSM.isAlreadyBeingDeclared())
14318 return nullptr;
14319
14321 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14322
14323 // Create the actual constructor declaration.
14324 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14325 SourceLocation ClassLoc = ClassDecl->getLocation();
14326 DeclarationName Name
14327 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14328 DeclarationNameInfo NameInfo(Name, ClassLoc);
14330 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14331 /*TInfo=*/nullptr, ExplicitSpecifier(),
14332 getCurFPFeatures().isFPConstrained(),
14333 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14336 DefaultCon->setAccess(AS_public);
14337 DefaultCon->setDefaulted();
14338
14339 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14340
14341 if (getLangOpts().CUDA)
14342 CUDA().inferTargetForImplicitSpecialMember(
14343 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14344 /* ConstRHS */ false,
14345 /* Diagnose */ false);
14346
14347 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14348 // constructors is easy to compute.
14349 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14350
14351 // Note that we have declared this constructor.
14352 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14353
14354 Scope *S = getScopeForContext(ClassDecl);
14356
14357 if (ShouldDeleteSpecialMember(DefaultCon,
14359 SetDeclDeleted(DefaultCon, ClassLoc);
14360
14361 if (S)
14362 PushOnScopeChains(DefaultCon, S, false);
14363 ClassDecl->addDecl(DefaultCon);
14364
14365 return DefaultCon;
14366}
14367
14370 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14371 !Constructor->doesThisDeclarationHaveABody() &&
14372 !Constructor->isDeleted()) &&
14373 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14374 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14375 return;
14376
14377 CXXRecordDecl *ClassDecl = Constructor->getParent();
14378 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14379 if (ClassDecl->isInvalidDecl()) {
14380 return;
14381 }
14382
14384
14385 // The exception specification is needed because we are defining the
14386 // function.
14387 ResolveExceptionSpec(CurrentLocation,
14388 Constructor->getType()->castAs<FunctionProtoType>());
14389 MarkVTableUsed(CurrentLocation, ClassDecl);
14390
14391 // Add a context note for diagnostics produced after this point.
14392 Scope.addContextNote(CurrentLocation);
14393
14394 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14395 Constructor->setInvalidDecl();
14396 return;
14397 }
14398
14399 SourceLocation Loc = Constructor->getEndLoc().isValid()
14400 ? Constructor->getEndLoc()
14401 : Constructor->getLocation();
14402 Constructor->setBody(new (Context) CompoundStmt(Loc));
14403 Constructor->markUsed(Context);
14404
14406 L->CompletedImplicitDefinition(Constructor);
14407 }
14408
14409 DiagnoseUninitializedFields(*this, Constructor);
14410
14411 // The synthesized body applies the class's NSDMIs and never reaches the
14412 // normal IssueWarnings path, so run lifetime safety on it here.
14413 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14414}
14415
14417 // Perform any delayed checks on exception specifications.
14419}
14420
14421/// Find or create the fake constructor we synthesize to model constructing an
14422/// object of a derived class via a constructor of a base class.
14425 CXXConstructorDecl *BaseCtor,
14427 CXXRecordDecl *Derived = Shadow->getParent();
14428 SourceLocation UsingLoc = Shadow->getLocation();
14429
14430 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14431 // For now we use the name of the base class constructor as a member of the
14432 // derived class to indicate a (fake) inherited constructor name.
14433 DeclarationName Name = BaseCtor->getDeclName();
14434
14435 // Check to see if we already have a fake constructor for this inherited
14436 // constructor call.
14437 for (NamedDecl *Ctor : Derived->lookup(Name))
14439 ->getInheritedConstructor()
14440 .getConstructor(),
14441 BaseCtor))
14442 return cast<CXXConstructorDecl>(Ctor);
14443
14444 DeclarationNameInfo NameInfo(Name, UsingLoc);
14445 TypeSourceInfo *TInfo =
14446 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14447 FunctionProtoTypeLoc ProtoLoc =
14449
14450 // Check the inherited constructor is valid and find the list of base classes
14451 // from which it was inherited.
14452 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14453
14454 bool Constexpr = BaseCtor->isConstexpr() &&
14457 false, BaseCtor, &ICI);
14458
14460 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14461 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14462 /*isInline=*/true,
14463 /*isImplicitlyDeclared=*/true,
14465 InheritedConstructor(Shadow, BaseCtor),
14466 BaseCtor->getTrailingRequiresClause());
14467 if (Shadow->isInvalidDecl())
14468 DerivedCtor->setInvalidDecl();
14469
14470 // Build an unevaluated exception specification for this fake constructor.
14471 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14474 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14475 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14476 FPT->getParamTypes(), EPI));
14477
14478 // Build the parameter declarations.
14480 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14481 TypeSourceInfo *TInfo =
14482 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14484 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14485 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14486 PD->setScopeInfo(0, I);
14487 PD->setImplicit();
14488 // Ensure attributes are propagated onto parameters (this matters for
14489 // format, pass_object_size, ...).
14490 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14491 ParamDecls.push_back(PD);
14492 ProtoLoc.setParam(I, PD);
14493 }
14494
14495 // Set up the new constructor.
14496 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14497 DerivedCtor->setAccess(BaseCtor->getAccess());
14498 DerivedCtor->setParams(ParamDecls);
14499 Derived->addDecl(DerivedCtor);
14500
14501 if (ShouldDeleteSpecialMember(DerivedCtor,
14503 SetDeclDeleted(DerivedCtor, UsingLoc);
14504
14505 return DerivedCtor;
14506}
14507
14515
14518 CXXRecordDecl *ClassDecl = Constructor->getParent();
14519 assert(Constructor->getInheritedConstructor() &&
14520 !Constructor->doesThisDeclarationHaveABody() &&
14521 !Constructor->isDeleted());
14522 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14523 return;
14524
14525 // Initializations are performed "as if by a defaulted default constructor",
14526 // so enter the appropriate scope.
14528
14529 // The exception specification is needed because we are defining the
14530 // function.
14531 ResolveExceptionSpec(CurrentLocation,
14532 Constructor->getType()->castAs<FunctionProtoType>());
14533 MarkVTableUsed(CurrentLocation, ClassDecl);
14534
14535 // Add a context note for diagnostics produced after this point.
14536 Scope.addContextNote(CurrentLocation);
14537
14539 Constructor->getInheritedConstructor().getShadowDecl();
14540 CXXConstructorDecl *InheritedCtor =
14541 Constructor->getInheritedConstructor().getConstructor();
14542
14543 // [class.inhctor.init]p1:
14544 // initialization proceeds as if a defaulted default constructor is used to
14545 // initialize the D object and each base class subobject from which the
14546 // constructor was inherited
14547
14548 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14549 CXXRecordDecl *RD = Shadow->getParent();
14550 SourceLocation InitLoc = Shadow->getLocation();
14551
14552 // Build explicit initializers for all base classes from which the
14553 // constructor was inherited.
14555 for (bool VBase : {false, true}) {
14556 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14557 if (B.isVirtual() != VBase)
14558 continue;
14559
14560 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14561 if (!BaseRD)
14562 continue;
14563
14564 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14565 if (!BaseCtor.first)
14566 continue;
14567
14568 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14570 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14571
14572 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14573 Inits.push_back(new (Context) CXXCtorInitializer(
14574 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14575 SourceLocation()));
14576 }
14577 }
14578
14579 // We now proceed as if for a defaulted default constructor, with the relevant
14580 // initializers replaced.
14581
14582 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14583 Constructor->setInvalidDecl();
14584 return;
14585 }
14586
14587 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14588 Constructor->markUsed(Context);
14589
14591 L->CompletedImplicitDefinition(Constructor);
14592 }
14593
14594 DiagnoseUninitializedFields(*this, Constructor);
14595
14596 // The synthesized body applies the class's NSDMIs and never reaches the
14597 // normal IssueWarnings path, so run lifetime safety on it here.
14598 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14599}
14600
14602 // C++ [class.dtor]p2:
14603 // If a class has no user-declared destructor, a destructor is
14604 // declared implicitly. An implicitly-declared destructor is an
14605 // inline public member of its class.
14606 assert(ClassDecl->needsImplicitDestructor());
14607
14608 DeclaringSpecialMember DSM(*this, ClassDecl,
14610 if (DSM.isAlreadyBeingDeclared())
14611 return nullptr;
14612
14614 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14615
14616 // Create the actual destructor declaration.
14617 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14618 SourceLocation ClassLoc = ClassDecl->getLocation();
14619 DeclarationName Name
14620 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14621 DeclarationNameInfo NameInfo(Name, ClassLoc);
14623 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14624 getCurFPFeatures().isFPConstrained(),
14625 /*isInline=*/true,
14626 /*isImplicitlyDeclared=*/true,
14629 Destructor->setAccess(AS_public);
14630 Destructor->setDefaulted();
14631
14632 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14633
14634 if (getLangOpts().CUDA)
14635 CUDA().inferTargetForImplicitSpecialMember(
14637 /* ConstRHS */ false,
14638 /* Diagnose */ false);
14639
14640 // We don't need to use SpecialMemberIsTrivial here; triviality for
14641 // destructors is easy to compute.
14642 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14643 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14644 ClassDecl->hasTrivialDestructorForCall());
14645
14646 // Note that we have declared this destructor.
14647 ++getASTContext().NumImplicitDestructorsDeclared;
14648
14649 Scope *S = getScopeForContext(ClassDecl);
14651
14652 // We can't check whether an implicit destructor is deleted before we complete
14653 // the definition of the class, because its validity depends on the alignment
14654 // of the class. We'll check this from ActOnFields once the class is complete.
14655 if (ClassDecl->isCompleteDefinition() &&
14657 SetDeclDeleted(Destructor, ClassLoc);
14658
14659 // Introduce this destructor into its scope.
14660 if (S)
14661 PushOnScopeChains(Destructor, S, false);
14662 ClassDecl->addDecl(Destructor);
14663
14664 return Destructor;
14665}
14666
14669 assert((Destructor->isDefaulted() &&
14670 !Destructor->doesThisDeclarationHaveABody() &&
14671 !Destructor->isDeleted()) &&
14672 "DefineImplicitDestructor - call it for implicit default dtor");
14673 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14674 return;
14675
14676 CXXRecordDecl *ClassDecl = Destructor->getParent();
14677 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14678
14680
14681 // The exception specification is needed because we are defining the
14682 // function.
14683 ResolveExceptionSpec(CurrentLocation,
14684 Destructor->getType()->castAs<FunctionProtoType>());
14685 MarkVTableUsed(CurrentLocation, ClassDecl);
14686
14687 // Add a context note for diagnostics produced after this point.
14688 Scope.addContextNote(CurrentLocation);
14689
14691 Destructor->getParent());
14692
14694 Destructor->setInvalidDecl();
14695 return;
14696 }
14697
14698 SourceLocation Loc = Destructor->getEndLoc().isValid()
14699 ? Destructor->getEndLoc()
14700 : Destructor->getLocation();
14701 Destructor->setBody(new (Context) CompoundStmt(Loc));
14702 Destructor->markUsed(Context);
14703
14705 L->CompletedImplicitDefinition(Destructor);
14706 }
14707}
14708
14711 if (Destructor->isInvalidDecl())
14712 return;
14713
14714 CXXRecordDecl *ClassDecl = Destructor->getParent();
14715 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14716 "implicit complete dtors unneeded outside MS ABI");
14717 assert(ClassDecl->getNumVBases() > 0 &&
14718 "complete dtor only exists for classes with vbases");
14719
14721
14722 // Add a context note for diagnostics produced after this point.
14723 Scope.addContextNote(CurrentLocation);
14724
14725 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14726}
14727
14729 // If the context is an invalid C++ class, just suppress these checks.
14730 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14731 if (Record->isInvalidDecl()) {
14734 return;
14735 }
14737 }
14738}
14739
14742
14743 if (!DelayedDllExportMemberFunctions.empty()) {
14745 std::swap(DelayedDllExportMemberFunctions, WorkList);
14746 for (CXXMethodDecl *M : WorkList) {
14747 DefineDefaultedFunction(*this, M, M->getLocation());
14748
14749 // Pass the method to the consumer to get emitted. This is not necessary
14750 // for explicit instantiation definitions, as they will get emitted
14751 // anyway.
14752 if (M->getParent()->getTemplateSpecializationKind() !=
14755 }
14756 }
14757}
14758
14760 if (!DelayedDllExportClasses.empty()) {
14761 // Calling ReferenceDllExportedMembers might cause the current function to
14762 // be called again, so use a local copy of DelayedDllExportClasses.
14764 std::swap(DelayedDllExportClasses, WorkList);
14765 for (CXXRecordDecl *Class : WorkList)
14767 }
14768}
14769
14771 assert(getLangOpts().CPlusPlus11 &&
14772 "adjusting dtor exception specs was introduced in c++11");
14773
14774 if (Destructor->isDependentContext())
14775 return;
14776
14777 // C++11 [class.dtor]p3:
14778 // A declaration of a destructor that does not have an exception-
14779 // specification is implicitly considered to have the same exception-
14780 // specification as an implicit declaration.
14781 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14782 if (DtorType->hasExceptionSpec())
14783 return;
14784
14785 // Replace the destructor's type, building off the existing one. Fortunately,
14786 // the only thing of interest in the destructor type is its extended info.
14787 // The return and arguments are fixed.
14788 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14791 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14792
14793 // FIXME: If the destructor has a body that could throw, and the newly created
14794 // spec doesn't allow exceptions, we should emit a warning, because this
14795 // change in behavior can break conforming C++03 programs at runtime.
14796 // However, we don't have a body or an exception specification yet, so it
14797 // needs to be done somewhere else.
14798}
14799
14800namespace {
14801/// An abstract base class for all helper classes used in building the
14802// copy/move operators. These classes serve as factory functions and help us
14803// avoid using the same Expr* in the AST twice.
14804class ExprBuilder {
14805 ExprBuilder(const ExprBuilder&) = delete;
14806 ExprBuilder &operator=(const ExprBuilder&) = delete;
14807
14808protected:
14809 static Expr *assertNotNull(Expr *E) {
14810 assert(E && "Expression construction must not fail.");
14811 return E;
14812 }
14813
14814public:
14815 ExprBuilder() {}
14816 virtual ~ExprBuilder() {}
14817
14818 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14819};
14820
14821class RefBuilder: public ExprBuilder {
14822 VarDecl *Var;
14823 QualType VarType;
14824
14825public:
14826 Expr *build(Sema &S, SourceLocation Loc) const override {
14827 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14828 }
14829
14830 RefBuilder(VarDecl *Var, QualType VarType)
14831 : Var(Var), VarType(VarType) {}
14832};
14833
14834class ThisBuilder: public ExprBuilder {
14835public:
14836 Expr *build(Sema &S, SourceLocation Loc) const override {
14837 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14838 }
14839};
14840
14841class CastBuilder: public ExprBuilder {
14842 const ExprBuilder &Builder;
14843 QualType Type;
14845 const CXXCastPath &Path;
14846
14847public:
14848 Expr *build(Sema &S, SourceLocation Loc) const override {
14849 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14850 CK_UncheckedDerivedToBase, Kind,
14851 &Path).get());
14852 }
14853
14854 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14855 const CXXCastPath &Path)
14856 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14857};
14858
14859class DerefBuilder: public ExprBuilder {
14860 const ExprBuilder &Builder;
14861
14862public:
14863 Expr *build(Sema &S, SourceLocation Loc) const override {
14864 return assertNotNull(
14865 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14866 }
14867
14868 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14869};
14870
14871class MemberBuilder: public ExprBuilder {
14872 const ExprBuilder &Builder;
14873 QualType Type;
14874 CXXScopeSpec SS;
14875 bool IsArrow;
14876 LookupResult &MemberLookup;
14877
14878public:
14879 Expr *build(Sema &S, SourceLocation Loc) const override {
14880 return assertNotNull(S.BuildMemberReferenceExpr(
14881 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14882 nullptr, MemberLookup, nullptr, nullptr).get());
14883 }
14884
14885 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14886 LookupResult &MemberLookup)
14887 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14888 MemberLookup(MemberLookup) {}
14889};
14890
14891class MoveCastBuilder: public ExprBuilder {
14892 const ExprBuilder &Builder;
14893
14894public:
14895 Expr *build(Sema &S, SourceLocation Loc) const override {
14896 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14897 }
14898
14899 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14900};
14901
14902class LvalueConvBuilder: public ExprBuilder {
14903 const ExprBuilder &Builder;
14904
14905public:
14906 Expr *build(Sema &S, SourceLocation Loc) const override {
14907 return assertNotNull(
14908 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14909 }
14910
14911 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14912};
14913
14914class SubscriptBuilder: public ExprBuilder {
14915 const ExprBuilder &Base;
14916 const ExprBuilder &Index;
14917
14918public:
14919 Expr *build(Sema &S, SourceLocation Loc) const override {
14920 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14921 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14922 }
14923
14924 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14925 : Base(Base), Index(Index) {}
14926};
14927
14928} // end anonymous namespace
14929
14930/// When generating a defaulted copy or move assignment operator, if a field
14931/// should be copied with __builtin_memcpy rather than via explicit assignments,
14932/// do so. This optimization only applies for arrays of scalars, and for arrays
14933/// of class type where the selected copy/move-assignment operator is trivial.
14934static StmtResult
14936 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14937 // Compute the size of the memory buffer to be copied.
14938 QualType SizeType = S.Context.getSizeType();
14939 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14941
14942 // Take the address of the field references for "from" and "to". We
14943 // directly construct UnaryOperators here because semantic analysis
14944 // does not permit us to take the address of an xvalue.
14945 Expr *From = FromB.build(S, Loc);
14946 From = UnaryOperator::Create(
14947 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14948 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14949 Expr *To = ToB.build(S, Loc);
14951 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14952 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14953
14954 bool NeedsCollectableMemCpy = false;
14955 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14956 NeedsCollectableMemCpy = RD->hasObjectMember();
14957
14958 // Create a reference to the __builtin_objc_memmove_collectable function
14959 StringRef MemCpyName = NeedsCollectableMemCpy ?
14960 "__builtin_objc_memmove_collectable" :
14961 "__builtin_memcpy";
14962 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14964 S.LookupName(R, S.TUScope, true);
14965
14966 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14967 if (!MemCpy)
14968 // Something went horribly wrong earlier, and we will have complained
14969 // about it.
14970 return StmtError();
14971
14972 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14973 VK_PRValue, Loc, nullptr);
14974 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14975
14976 Expr *CallArgs[] = {
14977 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14978 };
14979 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14980 Loc, CallArgs, Loc);
14981
14982 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14983 return Call.getAs<Stmt>();
14984}
14985
14986/// Builds a statement that copies/moves the given entity from \p From to
14987/// \c To.
14988///
14989/// This routine is used to copy/move the members of a class with an
14990/// implicitly-declared copy/move assignment operator. When the entities being
14991/// copied are arrays, this routine builds for loops to copy them.
14992///
14993/// \param S The Sema object used for type-checking.
14994///
14995/// \param Loc The location where the implicit copy/move is being generated.
14996///
14997/// \param T The type of the expressions being copied/moved. Both expressions
14998/// must have this type.
14999///
15000/// \param To The expression we are copying/moving to.
15001///
15002/// \param From The expression we are copying/moving from.
15003///
15004/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15005/// Otherwise, it's a non-static member subobject.
15006///
15007/// \param Copying Whether we're copying or moving.
15008///
15009/// \param Depth Internal parameter recording the depth of the recursion.
15010///
15011/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15012/// if a memcpy should be used instead.
15013static StmtResult
15015 const ExprBuilder &To, const ExprBuilder &From,
15016 bool CopyingBaseSubobject, bool Copying,
15017 unsigned Depth = 0) {
15018 // C++11 [class.copy]p28:
15019 // Each subobject is assigned in the manner appropriate to its type:
15020 //
15021 // - if the subobject is of class type, as if by a call to operator= with
15022 // the subobject as the object expression and the corresponding
15023 // subobject of x as a single function argument (as if by explicit
15024 // qualification; that is, ignoring any possible virtual overriding
15025 // functions in more derived classes);
15026 //
15027 // C++03 [class.copy]p13:
15028 // - if the subobject is of class type, the copy assignment operator for
15029 // the class is used (as if by explicit qualification; that is,
15030 // ignoring any possible virtual overriding functions in more derived
15031 // classes);
15032 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15033 // Look for operator=.
15034 DeclarationName Name
15036 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15037 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15038
15039 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15040 // operator.
15041 if (!S.getLangOpts().CPlusPlus11) {
15042 LookupResult::Filter F = OpLookup.makeFilter();
15043 while (F.hasNext()) {
15044 NamedDecl *D = F.next();
15045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15046 if (Method->isCopyAssignmentOperator() ||
15047 (!Copying && Method->isMoveAssignmentOperator()))
15048 continue;
15049
15050 F.erase();
15051 }
15052 F.done();
15053 }
15054
15055 // Suppress the protected check (C++ [class.protected]) for each of the
15056 // assignment operators we found. This strange dance is required when
15057 // we're assigning via a base classes's copy-assignment operator. To
15058 // ensure that we're getting the right base class subobject (without
15059 // ambiguities), we need to cast "this" to that subobject type; to
15060 // ensure that we don't go through the virtual call mechanism, we need
15061 // to qualify the operator= name with the base class (see below). However,
15062 // this means that if the base class has a protected copy assignment
15063 // operator, the protected member access check will fail. So, we
15064 // rewrite "protected" access to "public" access in this case, since we
15065 // know by construction that we're calling from a derived class.
15066 if (CopyingBaseSubobject) {
15067 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15068 L != LEnd; ++L) {
15069 if (L.getAccess() == AS_protected)
15070 L.setAccess(AS_public);
15071 }
15072 }
15073
15074 // Create the nested-name-specifier that will be used to qualify the
15075 // reference to operator=; this is required to suppress the virtual
15076 // call mechanism.
15077 CXXScopeSpec SS;
15078 // FIXME: Don't canonicalize this.
15079 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15080 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15081
15082 // Create the reference to operator=.
15083 ExprResult OpEqualRef
15084 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15085 SS, /*TemplateKWLoc=*/SourceLocation(),
15086 /*FirstQualifierInScope=*/nullptr,
15087 OpLookup,
15088 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15089 /*SuppressQualifierCheck=*/true);
15090 if (OpEqualRef.isInvalid())
15091 return StmtError();
15092
15093 // Build the call to the assignment operator.
15094
15095 Expr *FromInst = From.build(S, Loc);
15096 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15097 OpEqualRef.getAs<Expr>(),
15098 Loc, FromInst, Loc);
15099 if (Call.isInvalid())
15100 return StmtError();
15101
15102 // If we built a call to a trivial 'operator=' while copying an array,
15103 // bail out. We'll replace the whole shebang with a memcpy.
15104 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15105 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15106 return StmtResult((Stmt*)nullptr);
15107
15108 // Convert to an expression-statement, and clean up any produced
15109 // temporaries.
15110 return S.ActOnExprStmt(Call);
15111 }
15112
15113 // - if the subobject is of scalar type, the built-in assignment
15114 // operator is used.
15115 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15116 if (!ArrayTy) {
15118 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15119 if (Assignment.isInvalid())
15120 return StmtError();
15121 return S.ActOnExprStmt(Assignment);
15122 }
15123
15124 // - if the subobject is an array, each element is assigned, in the
15125 // manner appropriate to the element type;
15126
15127 // Construct a loop over the array bounds, e.g.,
15128 //
15129 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15130 //
15131 // that will copy each of the array elements.
15132 QualType SizeType = S.Context.getSizeType();
15133
15134 // Create the iteration variable.
15135 IdentifierInfo *IterationVarName = nullptr;
15136 {
15137 SmallString<8> Str;
15138 llvm::raw_svector_ostream OS(Str);
15139 OS << "__i" << Depth;
15140 IterationVarName = &S.Context.Idents.get(OS.str());
15141 }
15142 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15143 IterationVarName, SizeType,
15144 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15145 SC_None);
15146
15147 // Initialize the iteration variable to zero.
15148 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15149 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15150
15151 // Creates a reference to the iteration variable.
15152 RefBuilder IterationVarRef(IterationVar, SizeType);
15153 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15154
15155 // Create the DeclStmt that holds the iteration variable.
15156 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15157
15158 // Subscript the "from" and "to" expressions with the iteration variable.
15159 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15160 MoveCastBuilder FromIndexMove(FromIndexCopy);
15161 const ExprBuilder *FromIndex;
15162 if (Copying)
15163 FromIndex = &FromIndexCopy;
15164 else
15165 FromIndex = &FromIndexMove;
15166
15167 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15168
15169 // Build the copy/move for an individual element of the array.
15170 StmtResult Copy =
15172 ToIndex, *FromIndex, CopyingBaseSubobject,
15173 Copying, Depth + 1);
15174 // Bail out if copying fails or if we determined that we should use memcpy.
15175 if (Copy.isInvalid() || !Copy.get())
15176 return Copy;
15177
15178 // Create the comparison against the array bound.
15179 llvm::APInt Upper
15180 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15182 S.Context, IterationVarRefRVal.build(S, Loc),
15183 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15186
15187 // Create the pre-increment of the iteration variable. We can determine
15188 // whether the increment will overflow based on the value of the array
15189 // bound.
15190 Expr *Increment = UnaryOperator::Create(
15191 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15192 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15193
15194 // Construct the loop that copies all elements of this array.
15195 return S.ActOnForStmt(
15196 Loc, Loc, InitStmt,
15198 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15199}
15200
15201static StmtResult
15203 const ExprBuilder &To, const ExprBuilder &From,
15204 bool CopyingBaseSubobject, bool Copying) {
15205 // Maybe we should use a memcpy?
15206 if (T->isArrayType() && !T.hasQualifiers() &&
15207 T.isTriviallyCopyableType(S.Context))
15208 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15209
15210 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15211 CopyingBaseSubobject,
15212 Copying, 0));
15213
15214 // If we ended up picking a trivial assignment operator for an array of a
15215 // non-trivially-copyable class type, just emit a memcpy.
15216 if (!Result.isInvalid() && !Result.get())
15217 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15218
15219 return Result;
15220}
15221
15223 // Note: The following rules are largely analoguous to the copy
15224 // constructor rules. Note that virtual bases are not taken into account
15225 // for determining the argument type of the operator. Note also that
15226 // operators taking an object instead of a reference are allowed.
15227 assert(ClassDecl->needsImplicitCopyAssignment());
15228
15229 DeclaringSpecialMember DSM(*this, ClassDecl,
15231 if (DSM.isAlreadyBeingDeclared())
15232 return nullptr;
15233
15235 /*Qualifier=*/std::nullopt, ClassDecl,
15236 /*OwnsTag=*/false);
15238 if (AS != LangAS::Default)
15239 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15240 QualType RetType = Context.getLValueReferenceType(ArgType);
15241 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15242 if (Const)
15243 ArgType = ArgType.withConst();
15244
15245 ArgType = Context.getLValueReferenceType(ArgType);
15246
15248 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15249
15250 // An implicitly-declared copy assignment operator is an inline public
15251 // member of its class.
15252 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15253 SourceLocation ClassLoc = ClassDecl->getLocation();
15254 DeclarationNameInfo NameInfo(Name, ClassLoc);
15256 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15257 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15258 getCurFPFeatures().isFPConstrained(),
15259 /*isInline=*/true,
15261 SourceLocation());
15262 CopyAssignment->setAccess(AS_public);
15263 CopyAssignment->setDefaulted();
15264 CopyAssignment->setImplicit();
15265
15266 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15267
15268 if (getLangOpts().CUDA)
15269 CUDA().inferTargetForImplicitSpecialMember(
15271 /* ConstRHS */ Const,
15272 /* Diagnose */ false);
15273
15274 // Add the parameter to the operator.
15276 ClassLoc, ClassLoc,
15277 /*Id=*/nullptr, ArgType,
15278 /*TInfo=*/nullptr, SC_None,
15279 nullptr);
15280 CopyAssignment->setParams(FromParam);
15281
15282 CopyAssignment->setTrivial(
15286 : ClassDecl->hasTrivialCopyAssignment());
15287
15288 // Note that we have added this copy-assignment operator.
15289 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15290
15291 Scope *S = getScopeForContext(ClassDecl);
15293
15297 SetDeclDeleted(CopyAssignment, ClassLoc);
15298 }
15299
15300 if (S)
15302 ClassDecl->addDecl(CopyAssignment);
15303
15304 return CopyAssignment;
15305}
15306
15307/// Diagnose an implicit copy operation for a class which is odr-used, but
15308/// which is deprecated because the class has a user-declared copy constructor,
15309/// copy assignment operator, or destructor.
15311 assert(CopyOp->isImplicit());
15312
15313 CXXRecordDecl *RD = CopyOp->getParent();
15314 CXXMethodDecl *UserDeclaredOperation = nullptr;
15315
15316 if (RD->hasUserDeclaredDestructor()) {
15317 UserDeclaredOperation = RD->getDestructor();
15318 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15320 // Find any user-declared copy constructor.
15321 for (auto *I : RD->ctors()) {
15322 if (I->isCopyConstructor()) {
15323 UserDeclaredOperation = I;
15324 break;
15325 }
15326 }
15327 assert(UserDeclaredOperation);
15328 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15330 // Find any user-declared move assignment operator.
15331 for (auto *I : RD->methods()) {
15332 if (I->isCopyAssignmentOperator()) {
15333 UserDeclaredOperation = I;
15334 break;
15335 }
15336 }
15337 assert(UserDeclaredOperation);
15338 }
15339
15340 if (UserDeclaredOperation) {
15341 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15342 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15343 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15344 unsigned DiagID =
15345 (UDOIsUserProvided && UDOIsDestructor)
15346 ? diag::warn_deprecated_copy_with_user_provided_dtor
15347 : (UDOIsUserProvided && !UDOIsDestructor)
15348 ? diag::warn_deprecated_copy_with_user_provided_copy
15349 : (!UDOIsUserProvided && UDOIsDestructor)
15350 ? diag::warn_deprecated_copy_with_dtor
15351 : diag::warn_deprecated_copy;
15352 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15353 << RD << IsCopyAssignment;
15354 }
15355}
15356
15358 CXXMethodDecl *CopyAssignOperator) {
15359 assert((CopyAssignOperator->isDefaulted() &&
15360 CopyAssignOperator->isOverloadedOperator() &&
15361 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15362 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15363 !CopyAssignOperator->isDeleted()) &&
15364 "DefineImplicitCopyAssignment called for wrong function");
15365 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15366 return;
15367
15368 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15369 if (ClassDecl->isInvalidDecl()) {
15370 CopyAssignOperator->setInvalidDecl();
15371 return;
15372 }
15373
15374 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15375
15376 // The exception specification is needed because we are defining the
15377 // function.
15378 ResolveExceptionSpec(CurrentLocation,
15379 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15380
15381 // Add a context note for diagnostics produced after this point.
15382 Scope.addContextNote(CurrentLocation);
15383
15384 // C++11 [class.copy]p18:
15385 // The [definition of an implicitly declared copy assignment operator] is
15386 // deprecated if the class has a user-declared copy constructor or a
15387 // user-declared destructor.
15388 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15389 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15390
15391 // C++0x [class.copy]p30:
15392 // The implicitly-defined or explicitly-defaulted copy assignment operator
15393 // for a non-union class X performs memberwise copy assignment of its
15394 // subobjects. The direct base classes of X are assigned first, in the
15395 // order of their declaration in the base-specifier-list, and then the
15396 // immediate non-static data members of X are assigned, in the order in
15397 // which they were declared in the class definition.
15398
15399 // The statements that form the synthesized function body.
15400 SmallVector<Stmt*, 8> Statements;
15401
15402 // The parameter for the "other" object, which we are copying from.
15403 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15404 Qualifiers OtherQuals = Other->getType().getQualifiers();
15405 QualType OtherRefType = Other->getType();
15406 if (OtherRefType->isLValueReferenceType()) {
15407 OtherRefType = OtherRefType->getPointeeType();
15408 OtherQuals = OtherRefType.getQualifiers();
15409 }
15410
15411 // Our location for everything implicitly-generated.
15412 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15413 ? CopyAssignOperator->getEndLoc()
15414 : CopyAssignOperator->getLocation();
15415
15416 // Builds a DeclRefExpr for the "other" object.
15417 RefBuilder OtherRef(Other, OtherRefType);
15418
15419 // Builds the function object parameter.
15420 std::optional<ThisBuilder> This;
15421 std::optional<DerefBuilder> DerefThis;
15422 std::optional<RefBuilder> ExplicitObject;
15423 bool IsArrow = false;
15424 QualType ObjectType;
15425 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15426 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15427 if (ObjectType->isReferenceType())
15428 ObjectType = ObjectType->getPointeeType();
15429 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15430 } else {
15431 ObjectType = getCurrentThisType();
15432 This.emplace();
15433 DerefThis.emplace(*This);
15434 IsArrow = !LangOpts.HLSL;
15435 }
15436 ExprBuilder &ObjectParameter =
15437 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15438 : static_cast<ExprBuilder &>(*This);
15439
15440 // Assign base classes.
15441 bool Invalid = false;
15442 for (auto &Base : ClassDecl->bases()) {
15443 // Form the assignment:
15444 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15445 QualType BaseType = Base.getType().getUnqualifiedType();
15446 if (!BaseType->isRecordType()) {
15447 Invalid = true;
15448 continue;
15449 }
15450
15451 CXXCastPath BasePath;
15452 BasePath.push_back(&Base);
15453
15454 // Construct the "from" expression, which is an implicit cast to the
15455 // appropriately-qualified base type.
15456 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15457 VK_LValue, BasePath);
15458
15459 // Dereference "this".
15460 CastBuilder To(
15461 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15462 : static_cast<ExprBuilder &>(*DerefThis),
15463 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15464 VK_LValue, BasePath);
15465
15466 // Build the copy.
15467 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15468 To, From,
15469 /*CopyingBaseSubobject=*/true,
15470 /*Copying=*/true);
15471 if (Copy.isInvalid()) {
15472 CopyAssignOperator->setInvalidDecl();
15473 return;
15474 }
15475
15476 // Success! Record the copy.
15477 Statements.push_back(Copy.getAs<Expr>());
15478 }
15479
15480 // Assign non-static members.
15481 for (auto *Field : ClassDecl->fields()) {
15482 // FIXME: We should form some kind of AST representation for the implied
15483 // memcpy in a union copy operation.
15484 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15485 continue;
15486
15487 if (Field->isInvalidDecl()) {
15488 Invalid = true;
15489 continue;
15490 }
15491
15492 // Check for members of reference type; we can't copy those.
15493 if (Field->getType()->isReferenceType()) {
15494 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15495 << Context.getCanonicalTagType(ClassDecl) << 0
15496 << Field->getDeclName();
15497 Diag(Field->getLocation(), diag::note_declared_at);
15498 Invalid = true;
15499 continue;
15500 }
15501
15502 // Check for members of const-qualified, non-class type.
15503 QualType BaseType = Context.getBaseElementType(Field->getType());
15504 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15505 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15506 << Context.getCanonicalTagType(ClassDecl) << 1
15507 << Field->getDeclName();
15508 Diag(Field->getLocation(), diag::note_declared_at);
15509 Invalid = true;
15510 continue;
15511 }
15512
15513 // Suppress assigning zero-width bitfields.
15514 if (Field->isZeroLengthBitField())
15515 continue;
15516
15517 QualType FieldType = Field->getType().getNonReferenceType();
15518 if (FieldType->isIncompleteArrayType()) {
15519 assert(ClassDecl->hasFlexibleArrayMember() &&
15520 "Incomplete array type is not valid");
15521 continue;
15522 }
15523
15524 // Build references to the field in the object we're copying from and to.
15525 CXXScopeSpec SS; // Intentionally empty
15526 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15528 MemberLookup.addDecl(Field);
15529 MemberLookup.resolveKind();
15530
15531 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15532 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15533 // Build the copy of this field.
15534 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15535 To, From,
15536 /*CopyingBaseSubobject=*/false,
15537 /*Copying=*/true);
15538 if (Copy.isInvalid()) {
15539 CopyAssignOperator->setInvalidDecl();
15540 return;
15541 }
15542
15543 // Success! Record the copy.
15544 Statements.push_back(Copy.getAs<Stmt>());
15545 }
15546
15547 if (!Invalid) {
15548 // Add a "return *this;"
15549 Expr *ThisExpr =
15550 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15551 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15552 : static_cast<ExprBuilder &>(*DerefThis))
15553 .build(*this, Loc);
15554 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15555 if (Return.isInvalid())
15556 Invalid = true;
15557 else
15558 Statements.push_back(Return.getAs<Stmt>());
15559 }
15560
15561 if (Invalid) {
15562 CopyAssignOperator->setInvalidDecl();
15563 return;
15564 }
15565
15566 StmtResult Body;
15567 {
15568 CompoundScopeRAII CompoundScope(*this);
15569 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15570 /*isStmtExpr=*/false);
15571 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15572 }
15573 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15574 CopyAssignOperator->markUsed(Context);
15575
15577 L->CompletedImplicitDefinition(CopyAssignOperator);
15578 }
15579}
15580
15582 assert(ClassDecl->needsImplicitMoveAssignment());
15583
15584 DeclaringSpecialMember DSM(*this, ClassDecl,
15586 if (DSM.isAlreadyBeingDeclared())
15587 return nullptr;
15588
15589 // Note: The following rules are largely analoguous to the move
15590 // constructor rules.
15591
15593 /*Qualifier=*/std::nullopt, ClassDecl,
15594 /*OwnsTag=*/false);
15596 if (AS != LangAS::Default)
15597 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15598 QualType RetType = Context.getLValueReferenceType(ArgType);
15599 ArgType = Context.getRValueReferenceType(ArgType);
15600
15602 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15603
15604 // An implicitly-declared move assignment operator is an inline public
15605 // member of its class.
15606 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15607 SourceLocation ClassLoc = ClassDecl->getLocation();
15608 DeclarationNameInfo NameInfo(Name, ClassLoc);
15610 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15611 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15612 getCurFPFeatures().isFPConstrained(),
15613 /*isInline=*/true,
15615 SourceLocation());
15616 MoveAssignment->setAccess(AS_public);
15617 MoveAssignment->setDefaulted();
15618 MoveAssignment->setImplicit();
15619
15620 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15621
15622 if (getLangOpts().CUDA)
15623 CUDA().inferTargetForImplicitSpecialMember(
15625 /* ConstRHS */ false,
15626 /* Diagnose */ false);
15627
15628 // Add the parameter to the operator.
15630 ClassLoc, ClassLoc,
15631 /*Id=*/nullptr, ArgType,
15632 /*TInfo=*/nullptr, SC_None,
15633 nullptr);
15634 MoveAssignment->setParams(FromParam);
15635
15636 MoveAssignment->setTrivial(
15640 : ClassDecl->hasTrivialMoveAssignment());
15641
15642 // Note that we have added this copy-assignment operator.
15643 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15644
15645 Scope *S = getScopeForContext(ClassDecl);
15647
15651 SetDeclDeleted(MoveAssignment, ClassLoc);
15652 }
15653
15654 if (S)
15656 ClassDecl->addDecl(MoveAssignment);
15657
15658 return MoveAssignment;
15659}
15660
15661/// Check if we're implicitly defining a move assignment operator for a class
15662/// with virtual bases. Such a move assignment might move-assign the virtual
15663/// base multiple times.
15665 SourceLocation CurrentLocation) {
15666 assert(!Class->isDependentContext() && "should not define dependent move");
15667
15668 // Only a virtual base could get implicitly move-assigned multiple times.
15669 // Only a non-trivial move assignment can observe this. We only want to
15670 // diagnose if we implicitly define an assignment operator that assigns
15671 // two base classes, both of which move-assign the same virtual base.
15672 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15673 Class->getNumBases() < 2)
15674 return;
15675
15677 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15678 VBaseMap VBases;
15679
15680 for (auto &BI : Class->bases()) {
15681 Worklist.push_back(&BI);
15682 while (!Worklist.empty()) {
15683 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15684 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15685
15686 // If the base has no non-trivial move assignment operators,
15687 // we don't care about moves from it.
15688 if (!Base->hasNonTrivialMoveAssignment())
15689 continue;
15690
15691 // If there's nothing virtual here, skip it.
15692 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15693 continue;
15694
15695 // If we're not actually going to call a move assignment for this base,
15696 // or the selected move assignment is trivial, skip it.
15699 /*ConstArg*/ false, /*VolatileArg*/ false,
15700 /*RValueThis*/ true, /*ConstThis*/ false,
15701 /*VolatileThis*/ false);
15702 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15704 continue;
15705
15706 if (BaseSpec->isVirtual()) {
15707 // We're going to move-assign this virtual base, and its move
15708 // assignment operator is not trivial. If this can happen for
15709 // multiple distinct direct bases of Class, diagnose it. (If it
15710 // only happens in one base, we'll diagnose it when synthesizing
15711 // that base class's move assignment operator.)
15712 CXXBaseSpecifier *&Existing =
15713 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15714 .first->second;
15715 if (Existing && Existing != &BI) {
15716 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15717 << Class << Base;
15718 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15719 << (Base->getCanonicalDecl() ==
15721 << Base << Existing->getType() << Existing->getSourceRange();
15722 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15723 << (Base->getCanonicalDecl() ==
15724 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15725 << Base << BI.getType() << BaseSpec->getSourceRange();
15726
15727 // Only diagnose each vbase once.
15728 Existing = nullptr;
15729 }
15730 } else {
15731 // Only walk over bases that have defaulted move assignment operators.
15732 // We assume that any user-provided move assignment operator handles
15733 // the multiple-moves-of-vbase case itself somehow.
15734 if (!SMOR.getMethod()->isDefaulted())
15735 continue;
15736
15737 // We're going to move the base classes of Base. Add them to the list.
15738 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15739 }
15740 }
15741 }
15742}
15743
15745 CXXMethodDecl *MoveAssignOperator) {
15746 assert((MoveAssignOperator->isDefaulted() &&
15747 MoveAssignOperator->isOverloadedOperator() &&
15748 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15749 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15750 !MoveAssignOperator->isDeleted()) &&
15751 "DefineImplicitMoveAssignment called for wrong function");
15752 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15753 return;
15754
15755 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15756 if (ClassDecl->isInvalidDecl()) {
15757 MoveAssignOperator->setInvalidDecl();
15758 return;
15759 }
15760
15761 // C++0x [class.copy]p28:
15762 // The implicitly-defined or move assignment operator for a non-union class
15763 // X performs memberwise move assignment of its subobjects. The direct base
15764 // classes of X are assigned first, in the order of their declaration in the
15765 // base-specifier-list, and then the immediate non-static data members of X
15766 // are assigned, in the order in which they were declared in the class
15767 // definition.
15768
15769 // Issue a warning if our implicit move assignment operator will move
15770 // from a virtual base more than once.
15771 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15772
15773 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15774
15775 // The exception specification is needed because we are defining the
15776 // function.
15777 ResolveExceptionSpec(CurrentLocation,
15778 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15779
15780 // Add a context note for diagnostics produced after this point.
15781 Scope.addContextNote(CurrentLocation);
15782
15783 // The statements that form the synthesized function body.
15784 SmallVector<Stmt*, 8> Statements;
15785
15786 // The parameter for the "other" object, which we are move from.
15787 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15788 QualType OtherRefType =
15789 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15790
15791 // Our location for everything implicitly-generated.
15792 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15793 ? MoveAssignOperator->getEndLoc()
15794 : MoveAssignOperator->getLocation();
15795
15796 // Builds a reference to the "other" object.
15797 RefBuilder OtherRef(Other, OtherRefType);
15798 // Cast to rvalue.
15799 MoveCastBuilder MoveOther(OtherRef);
15800
15801 // Builds the function object parameter.
15802 std::optional<ThisBuilder> This;
15803 std::optional<DerefBuilder> DerefThis;
15804 std::optional<RefBuilder> ExplicitObject;
15805 QualType ObjectType;
15806 bool IsArrow = false;
15807 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15808 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15809 if (ObjectType->isReferenceType())
15810 ObjectType = ObjectType->getPointeeType();
15811 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15812 } else {
15813 ObjectType = getCurrentThisType();
15814 This.emplace();
15815 DerefThis.emplace(*This);
15816 IsArrow = !getLangOpts().HLSL;
15817 }
15818 ExprBuilder &ObjectParameter =
15819 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15820
15821 // Assign base classes.
15822 bool Invalid = false;
15823 for (auto &Base : ClassDecl->bases()) {
15824 // C++11 [class.copy]p28:
15825 // It is unspecified whether subobjects representing virtual base classes
15826 // are assigned more than once by the implicitly-defined copy assignment
15827 // operator.
15828 // FIXME: Do not assign to a vbase that will be assigned by some other base
15829 // class. For a move-assignment, this can result in the vbase being moved
15830 // multiple times.
15831
15832 // Form the assignment:
15833 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15834 QualType BaseType = Base.getType().getUnqualifiedType();
15835 if (!BaseType->isRecordType()) {
15836 Invalid = true;
15837 continue;
15838 }
15839
15840 CXXCastPath BasePath;
15841 BasePath.push_back(&Base);
15842
15843 // Construct the "from" expression, which is an implicit cast to the
15844 // appropriately-qualified base type.
15845 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15846
15847 // Implicitly cast "this" to the appropriately-qualified base type.
15848 // Dereference "this".
15849 CastBuilder To(
15850 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15851 : static_cast<ExprBuilder &>(*DerefThis),
15852 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15853 VK_LValue, BasePath);
15854
15855 // Build the move.
15856 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15857 To, From,
15858 /*CopyingBaseSubobject=*/true,
15859 /*Copying=*/false);
15860 if (Move.isInvalid()) {
15861 MoveAssignOperator->setInvalidDecl();
15862 return;
15863 }
15864
15865 // Success! Record the move.
15866 Statements.push_back(Move.getAs<Expr>());
15867 }
15868
15869 // Assign non-static members.
15870 for (auto *Field : ClassDecl->fields()) {
15871 // FIXME: We should form some kind of AST representation for the implied
15872 // memcpy in a union copy operation.
15873 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15874 continue;
15875
15876 if (Field->isInvalidDecl()) {
15877 Invalid = true;
15878 continue;
15879 }
15880
15881 // Check for members of reference type; we can't move those.
15882 if (Field->getType()->isReferenceType()) {
15883 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15884 << Context.getCanonicalTagType(ClassDecl) << 0
15885 << Field->getDeclName();
15886 Diag(Field->getLocation(), diag::note_declared_at);
15887 Invalid = true;
15888 continue;
15889 }
15890
15891 // Check for members of const-qualified, non-class type.
15892 QualType BaseType = Context.getBaseElementType(Field->getType());
15893 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15894 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15895 << Context.getCanonicalTagType(ClassDecl) << 1
15896 << Field->getDeclName();
15897 Diag(Field->getLocation(), diag::note_declared_at);
15898 Invalid = true;
15899 continue;
15900 }
15901
15902 // Suppress assigning zero-width bitfields.
15903 if (Field->isZeroLengthBitField())
15904 continue;
15905
15906 QualType FieldType = Field->getType().getNonReferenceType();
15907 if (FieldType->isIncompleteArrayType()) {
15908 assert(ClassDecl->hasFlexibleArrayMember() &&
15909 "Incomplete array type is not valid");
15910 continue;
15911 }
15912
15913 // Build references to the field in the object we're copying from and to.
15914 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15916 MemberLookup.addDecl(Field);
15917 MemberLookup.resolveKind();
15918 MemberBuilder From(MoveOther, OtherRefType,
15919 /*IsArrow=*/false, MemberLookup);
15920 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15921
15922 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15923 "Member reference with rvalue base must be rvalue except for reference "
15924 "members, which aren't allowed for move assignment.");
15925
15926 // Build the move of this field.
15927 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15928 To, From,
15929 /*CopyingBaseSubobject=*/false,
15930 /*Copying=*/false);
15931 if (Move.isInvalid()) {
15932 MoveAssignOperator->setInvalidDecl();
15933 return;
15934 }
15935
15936 // Success! Record the copy.
15937 Statements.push_back(Move.getAs<Stmt>());
15938 }
15939
15940 if (!Invalid) {
15941 // Add a "return *this;"
15942 Expr *ThisExpr =
15943 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15944 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15945 : static_cast<ExprBuilder &>(*DerefThis))
15946 .build(*this, Loc);
15947
15948 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15949 if (Return.isInvalid())
15950 Invalid = true;
15951 else
15952 Statements.push_back(Return.getAs<Stmt>());
15953 }
15954
15955 if (Invalid) {
15956 MoveAssignOperator->setInvalidDecl();
15957 return;
15958 }
15959
15960 StmtResult Body;
15961 {
15962 CompoundScopeRAII CompoundScope(*this);
15963 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15964 /*isStmtExpr=*/false);
15965 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15966 }
15967 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15968 MoveAssignOperator->markUsed(Context);
15969
15971 L->CompletedImplicitDefinition(MoveAssignOperator);
15972 }
15973}
15974
15976 CXXRecordDecl *ClassDecl) {
15977 // C++ [class.copy]p4:
15978 // If the class definition does not explicitly declare a copy
15979 // constructor, one is declared implicitly.
15980 assert(ClassDecl->needsImplicitCopyConstructor());
15981
15982 DeclaringSpecialMember DSM(*this, ClassDecl,
15984 if (DSM.isAlreadyBeingDeclared())
15985 return nullptr;
15986
15987 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
15988 /*Qualifier=*/std::nullopt, ClassDecl,
15989 /*OwnsTag=*/false);
15990 QualType ArgType = ClassType;
15991 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15992 if (Const)
15993 ArgType = ArgType.withConst();
15994
15996 if (AS != LangAS::Default)
15997 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15998
15999 ArgType = Context.getLValueReferenceType(ArgType);
16000
16002 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
16003
16004 DeclarationName Name
16005 = Context.DeclarationNames.getCXXConstructorName(
16006 Context.getCanonicalType(ClassType));
16007 SourceLocation ClassLoc = ClassDecl->getLocation();
16008 DeclarationNameInfo NameInfo(Name, ClassLoc);
16009
16010 // An implicitly-declared copy constructor is an inline public
16011 // member of its class.
16013 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16014 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16015 /*isInline=*/true,
16016 /*isImplicitlyDeclared=*/true,
16019 CopyConstructor->setAccess(AS_public);
16020 CopyConstructor->setDefaulted();
16021
16022 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16023
16024 if (getLangOpts().CUDA)
16025 CUDA().inferTargetForImplicitSpecialMember(
16027 /* ConstRHS */ Const,
16028 /* Diagnose */ false);
16029
16030 // During template instantiation of special member functions we need a
16031 // reliable TypeSourceInfo for the parameter types in order to allow functions
16032 // to be substituted.
16033 TypeSourceInfo *TSI = nullptr;
16034 if (inTemplateInstantiation() && ClassDecl->isLambda())
16035 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16036
16037 // Add the parameter to the constructor.
16038 ParmVarDecl *FromParam =
16039 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16040 /*IdentifierInfo=*/nullptr, ArgType,
16041 /*TInfo=*/TSI, SC_None, nullptr);
16042 CopyConstructor->setParams(FromParam);
16043
16044 CopyConstructor->setTrivial(
16048 : ClassDecl->hasTrivialCopyConstructor());
16049
16050 CopyConstructor->setTrivialForCall(
16051 ClassDecl->hasAttr<TrivialABIAttr>() ||
16056 : ClassDecl->hasTrivialCopyConstructorForCall()));
16057
16058 // Note that we have declared this constructor.
16059 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16060
16061 Scope *S = getScopeForContext(ClassDecl);
16063
16068 }
16069
16070 if (S)
16072 ClassDecl->addDecl(CopyConstructor);
16073
16074 return CopyConstructor;
16075}
16076
16079 assert((CopyConstructor->isDefaulted() &&
16080 CopyConstructor->isCopyConstructor() &&
16081 !CopyConstructor->doesThisDeclarationHaveABody() &&
16082 !CopyConstructor->isDeleted()) &&
16083 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16084 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16085 return;
16086
16087 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16088 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16089
16091
16092 // The exception specification is needed because we are defining the
16093 // function.
16094 ResolveExceptionSpec(CurrentLocation,
16095 CopyConstructor->getType()->castAs<FunctionProtoType>());
16096 MarkVTableUsed(CurrentLocation, ClassDecl);
16097
16098 // Add a context note for diagnostics produced after this point.
16099 Scope.addContextNote(CurrentLocation);
16100
16101 // C++11 [class.copy]p7:
16102 // The [definition of an implicitly declared copy constructor] is
16103 // deprecated if the class has a user-declared copy assignment operator
16104 // or a user-declared destructor.
16105 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16107
16108 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16109 CopyConstructor->setInvalidDecl();
16110 } else {
16111 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16112 ? CopyConstructor->getEndLoc()
16113 : CopyConstructor->getLocation();
16114 Sema::CompoundScopeRAII CompoundScope(*this);
16115 CopyConstructor->setBody(
16116 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16117 CopyConstructor->markUsed(Context);
16118 }
16119
16121 L->CompletedImplicitDefinition(CopyConstructor);
16122 }
16123}
16124
16126 CXXRecordDecl *ClassDecl) {
16127 assert(ClassDecl->needsImplicitMoveConstructor());
16128
16129 DeclaringSpecialMember DSM(*this, ClassDecl,
16131 if (DSM.isAlreadyBeingDeclared())
16132 return nullptr;
16133
16134 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16135 /*Qualifier=*/std::nullopt, ClassDecl,
16136 /*OwnsTag=*/false);
16137
16138 QualType ArgType = ClassType;
16140 if (AS != LangAS::Default)
16141 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16142 ArgType = Context.getRValueReferenceType(ArgType);
16143
16145 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16146
16147 DeclarationName Name
16148 = Context.DeclarationNames.getCXXConstructorName(
16149 Context.getCanonicalType(ClassType));
16150 SourceLocation ClassLoc = ClassDecl->getLocation();
16151 DeclarationNameInfo NameInfo(Name, ClassLoc);
16152
16153 // C++11 [class.copy]p11:
16154 // An implicitly-declared copy/move constructor is an inline public
16155 // member of its class.
16157 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16158 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16159 /*isInline=*/true,
16160 /*isImplicitlyDeclared=*/true,
16163 MoveConstructor->setAccess(AS_public);
16164 MoveConstructor->setDefaulted();
16165
16166 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16167
16168 if (getLangOpts().CUDA)
16169 CUDA().inferTargetForImplicitSpecialMember(
16171 /* ConstRHS */ false,
16172 /* Diagnose */ false);
16173
16174 // Add the parameter to the constructor.
16176 ClassLoc, ClassLoc,
16177 /*IdentifierInfo=*/nullptr,
16178 ArgType, /*TInfo=*/nullptr,
16179 SC_None, nullptr);
16180 MoveConstructor->setParams(FromParam);
16181
16182 MoveConstructor->setTrivial(
16186 : ClassDecl->hasTrivialMoveConstructor());
16187
16188 MoveConstructor->setTrivialForCall(
16189 ClassDecl->hasAttr<TrivialABIAttr>() ||
16194 : ClassDecl->hasTrivialMoveConstructorForCall()));
16195
16196 // Note that we have declared this constructor.
16197 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16198
16199 Scope *S = getScopeForContext(ClassDecl);
16201
16206 }
16207
16208 if (S)
16210 ClassDecl->addDecl(MoveConstructor);
16211
16212 return MoveConstructor;
16213}
16214
16217 assert((MoveConstructor->isDefaulted() &&
16218 MoveConstructor->isMoveConstructor() &&
16219 !MoveConstructor->doesThisDeclarationHaveABody() &&
16220 !MoveConstructor->isDeleted()) &&
16221 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16222 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16223 return;
16224
16225 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16226 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16227
16229
16230 // The exception specification is needed because we are defining the
16231 // function.
16232 ResolveExceptionSpec(CurrentLocation,
16233 MoveConstructor->getType()->castAs<FunctionProtoType>());
16234 MarkVTableUsed(CurrentLocation, ClassDecl);
16235
16236 // Add a context note for diagnostics produced after this point.
16237 Scope.addContextNote(CurrentLocation);
16238
16239 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16240 MoveConstructor->setInvalidDecl();
16241 } else {
16242 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16243 ? MoveConstructor->getEndLoc()
16244 : MoveConstructor->getLocation();
16245 Sema::CompoundScopeRAII CompoundScope(*this);
16246 MoveConstructor->setBody(
16247 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16248 MoveConstructor->markUsed(Context);
16249 }
16250
16252 L->CompletedImplicitDefinition(MoveConstructor);
16253 }
16254}
16255
16257 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16258}
16259
16261 SourceLocation CurrentLocation,
16262 CXXConversionDecl *Conv) {
16263 SynthesizedFunctionScope Scope(*this, Conv);
16264 assert(!Conv->getReturnType()->isUndeducedType());
16265
16266 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16267 CallingConv CC =
16268 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16269
16270 CXXRecordDecl *Lambda = Conv->getParent();
16271 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16272 FunctionDecl *Invoker =
16273 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16274 ? CallOp
16275 : Lambda->getLambdaStaticInvoker(CC);
16276
16277 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16279 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16280 if (!CallOp)
16281 return;
16282
16283 if (CallOp != Invoker) {
16285 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16286 CurrentLocation);
16287 if (!Invoker)
16288 return;
16289 }
16290 }
16291
16292 if (CallOp->isInvalidDecl())
16293 return;
16294
16295 // Mark the call operator referenced (and add to pending instantiations
16296 // if necessary).
16297 // For both the conversion and static-invoker template specializations
16298 // we construct their body's in this function, so no need to add them
16299 // to the PendingInstantiations.
16300 MarkFunctionReferenced(CurrentLocation, CallOp);
16301
16302 if (Invoker != CallOp) {
16303 // Fill in the __invoke function with a dummy implementation. IR generation
16304 // will fill in the actual details. Update its type in case it contained
16305 // an 'auto'.
16306 Invoker->markUsed(Context);
16307 Invoker->setReferenced();
16308 Invoker->setType(Conv->getReturnType()->getPointeeType());
16309 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16310 }
16311
16312 // Construct the body of the conversion function { return __invoke; }.
16313 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16314 Conv->getLocation());
16315 assert(FunctionRef && "Can't refer to __invoke function?");
16316 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16318 Conv->getLocation(), Conv->getLocation()));
16319 Conv->markUsed(Context);
16320 Conv->setReferenced();
16321
16323 L->CompletedImplicitDefinition(Conv);
16324 if (Invoker != CallOp)
16325 L->CompletedImplicitDefinition(Invoker);
16326 }
16327}
16328
16330 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16331 assert(!Conv->getParent()->isGenericLambda());
16332
16333 SynthesizedFunctionScope Scope(*this, Conv);
16334
16335 // Copy-initialize the lambda object as needed to capture it.
16336 Expr *This = ActOnCXXThis(CurrentLocation).get();
16337 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16338
16339 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16340 Conv->getLocation(),
16341 Conv, DerefThis);
16342
16343 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16344 // behavior. Note that only the general conversion function does this
16345 // (since it's unusable otherwise); in the case where we inline the
16346 // block literal, it has block literal lifetime semantics.
16347 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16348 BuildBlock = ImplicitCastExpr::Create(
16349 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16350 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16351
16352 if (BuildBlock.isInvalid()) {
16353 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16354 Conv->setInvalidDecl();
16355 return;
16356 }
16357
16358 // Create the return statement that returns the block from the conversion
16359 // function.
16360 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16361 if (Return.isInvalid()) {
16362 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16363 Conv->setInvalidDecl();
16364 return;
16365 }
16366
16367 // Set the body of the conversion function.
16368 Stmt *ReturnS = Return.get();
16370 Conv->getLocation(), Conv->getLocation()));
16371 Conv->markUsed(Context);
16372
16373 // We're done; notify the mutation listener, if any.
16375 L->CompletedImplicitDefinition(Conv);
16376 }
16377}
16378
16379/// Determine whether the given list arguments contains exactly one
16380/// "real" (non-default) argument.
16382 switch (Args.size()) {
16383 case 0:
16384 return false;
16385
16386 default:
16387 if (!Args[1]->isDefaultArgument())
16388 return false;
16389
16390 [[fallthrough]];
16391 case 1:
16392 return !Args[0]->isDefaultArgument();
16393 }
16394
16395 return false;
16396}
16397
16399 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16401 bool HadMultipleCandidates, bool IsListInitialization,
16402 bool IsStdInitListInitialization, bool RequiresZeroInit,
16403 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16404 bool Elidable = false;
16405
16406 // C++0x [class.copy]p34:
16407 // When certain criteria are met, an implementation is allowed to
16408 // omit the copy/move construction of a class object, even if the
16409 // copy/move constructor and/or destructor for the object have
16410 // side effects. [...]
16411 // - when a temporary class object that has not been bound to a
16412 // reference (12.2) would be copied/moved to a class object
16413 // with the same cv-unqualified type, the copy/move operation
16414 // can be omitted by constructing the temporary object
16415 // directly into the target of the omitted copy/move
16416 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16417 // FIXME: Converting constructors should also be accepted.
16418 // But to fix this, the logic that digs down into a CXXConstructExpr
16419 // to find the source object needs to handle it.
16420 // Right now it assumes the source object is passed directly as the
16421 // first argument.
16422 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16423 Expr *SubExpr = ExprArgs[0];
16424 // FIXME: Per above, this is also incorrect if we want to accept
16425 // converting constructors, as isTemporaryObject will
16426 // reject temporaries with different type from the
16427 // CXXRecord itself.
16428 Elidable = SubExpr->isTemporaryObject(
16430 }
16431
16432 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16433 FoundDecl, Constructor,
16434 Elidable, ExprArgs, HadMultipleCandidates,
16435 IsListInitialization,
16436 IsStdInitListInitialization, RequiresZeroInit,
16437 ConstructKind, ParenRange);
16438}
16439
16441 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16442 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16443 bool HadMultipleCandidates, bool IsListInitialization,
16444 bool IsStdInitListInitialization, bool RequiresZeroInit,
16445 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16446 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16447 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16448 // The only way to get here is if we did overload resolution to find the
16449 // shadow decl, so we don't need to worry about re-checking the trailing
16450 // requires clause.
16451 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16452 return ExprError();
16453 }
16454
16455 return BuildCXXConstructExpr(
16456 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16457 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16458 RequiresZeroInit, ConstructKind, ParenRange);
16459}
16460
16461/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16462/// including handling of its default argument expressions.
16464 SourceLocation ConstructLoc, QualType DeclInitType,
16465 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16466 bool HadMultipleCandidates, bool IsListInitialization,
16467 bool IsStdInitListInitialization, bool RequiresZeroInit,
16468 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16469 assert(declaresSameEntity(
16470 Constructor->getParent(),
16471 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16472 "given constructor for wrong type");
16473 MarkFunctionReferenced(ConstructLoc, Constructor);
16474 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16475 return ExprError();
16476
16479 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16480 HadMultipleCandidates, IsListInitialization,
16481 IsStdInitListInitialization, RequiresZeroInit,
16482 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16483 Constructor);
16484}
16485
16487 if (VD->isInvalidDecl()) return;
16488 // If initializing the variable failed, don't also diagnose problems with
16489 // the destructor, they're likely related.
16490 if (VD->getInit() && VD->getInit()->containsErrors())
16491 return;
16492
16493 ClassDecl = ClassDecl->getDefinitionOrSelf();
16494 if (ClassDecl->isInvalidDecl()) return;
16495 if (ClassDecl->hasIrrelevantDestructor()) return;
16496 if (ClassDecl->isDependentContext()) return;
16497
16498 if (VD->isNoDestroy(getASTContext()))
16499 return;
16500
16502 // The result of `LookupDestructor` might be nullptr if the destructor is
16503 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16504 // will not be selected by `CXXRecordDecl::getDestructor()`.
16505 if (!Destructor)
16506 return;
16507 // If this is an array, we'll require the destructor during initialization, so
16508 // we can skip over this. We still want to emit exit-time destructor warnings
16509 // though.
16510 if (!VD->getType()->isArrayType()) {
16513 PDiag(diag::err_access_dtor_var)
16514 << VD->getDeclName() << VD->getType());
16516 }
16517
16518 if (Destructor->isTrivial()) return;
16519
16520 // If the destructor is constexpr, check whether the variable has constant
16521 // destruction now.
16522 if (Destructor->isConstexpr()) {
16523 bool HasConstantInit = false;
16524 if (VD->getInit() && !VD->getInit()->isValueDependent())
16525 HasConstantInit = VD->evaluateValue();
16527 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16528 HasConstantInit) {
16529 Diag(VD->getLocation(),
16530 diag::err_constexpr_var_requires_const_destruction) << VD;
16531 for (const PartialDiagnosticAt &Note : Notes)
16532 Diag(Note.first, Note.second);
16533 }
16534 }
16535
16536 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16537 return;
16538
16539 // Emit warning for non-trivial dtor in global scope (a real global,
16540 // class-static, function-static).
16541 if (!VD->hasAttr<AlwaysDestroyAttr>())
16542 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16543
16544 // TODO: this should be re-enabled for static locals by !CXAAtExit
16545 if (!VD->isStaticLocal())
16546 Diag(VD->getLocation(), diag::warn_global_destructor);
16547}
16548
16550 QualType DeclInitType, MultiExprArg ArgsPtr,
16551 SourceLocation Loc,
16552 SmallVectorImpl<Expr *> &ConvertedArgs,
16553 bool AllowExplicit,
16554 bool IsListInitialization) {
16555 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16556 unsigned NumArgs = ArgsPtr.size();
16557 Expr **Args = ArgsPtr.data();
16558
16559 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16560 unsigned NumParams = Proto->getNumParams();
16561
16562 // If too few arguments are available, we'll fill in the rest with defaults.
16563 if (NumArgs < NumParams)
16564 ConvertedArgs.reserve(NumParams);
16565 else
16566 ConvertedArgs.reserve(NumArgs);
16567
16568 VariadicCallType CallType = Proto->isVariadic()
16571 SmallVector<Expr *, 8> AllArgs;
16573 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16574 CallType, AllowExplicit, IsListInitialization);
16575 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16576
16577 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16578
16579 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16580 Proto, Loc);
16581
16582 return Invalid;
16583}
16584
16586 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16587 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16588}
16589
16592 QualType DeallocType, SourceLocation Loc) {
16593 if (DeallocType.isNull())
16594 return nullptr;
16595
16596 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16597 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16598 return nullptr;
16599
16600 if (FnDecl->isVariadic())
16601 return nullptr;
16602
16603 unsigned NumParams = FnDecl->getNumParams();
16604 constexpr unsigned RequiredParameterCount =
16606 // A usual deallocation function has no placement parameters
16607 if (NumParams != RequiredParameterCount)
16608 return nullptr;
16609
16610 // A type aware allocation is only usual if the only dependent parameter is
16611 // the first parameter.
16612 if (llvm::any_of(FnDecl->parameters().drop_front(),
16613 [](const ParmVarDecl *ParamDecl) {
16614 return ParamDecl->getType()->isDependentType();
16615 }))
16616 return nullptr;
16617
16618 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16619 if (SpecializedTypeIdentity.isNull())
16620 return nullptr;
16621
16623 ArgTypes.reserve(NumParams);
16624
16625 // The first parameter to a type aware operator delete is by definition the
16626 // type-identity argument, so we explicitly set this to the target
16627 // type-identity type, the remaining usual parameters should then simply match
16628 // the type declared in the function template.
16629 ArgTypes.push_back(SpecializedTypeIdentity);
16630 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16631 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16632
16634 QualType ExpectedFunctionType =
16635 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16638 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16640 return nullptr;
16641 return Result;
16642}
16643
16644static inline bool
16646 const FunctionDecl *FnDecl) {
16647 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16648 if (isa<NamespaceDecl>(DC)) {
16649 return SemaRef.Diag(FnDecl->getLocation(),
16650 diag::err_operator_new_delete_declared_in_namespace)
16651 << FnDecl->getDeclName();
16652 }
16653
16654 if (isa<TranslationUnitDecl>(DC) &&
16655 FnDecl->getStorageClass() == SC_Static) {
16656 return SemaRef.Diag(FnDecl->getLocation(),
16657 diag::err_operator_new_delete_declared_static)
16658 << FnDecl->getDeclName();
16659 }
16660
16661 return false;
16662}
16663
16665 const PointerType *PtrTy) {
16666 auto &Ctx = SemaRef.Context;
16667 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16668 PtrQuals.removeAddressSpace();
16670 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16671}
16672
16674
16676 const FunctionDecl *FD,
16677 bool *WasMalformed) {
16678 const Decl *MalformedDecl = nullptr;
16679 if (FD->getNumParams() > 0 &&
16680 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16681 /*TypeArgument=*/nullptr, &MalformedDecl))
16682 return true;
16683
16684 if (!MalformedDecl)
16685 return false;
16686
16687 if (WasMalformed)
16688 *WasMalformed = true;
16689
16690 return true;
16691}
16692
16694 auto *RD = Type->getAsCXXRecordDecl();
16695 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16696 RD->getIdentifier()->isStr("destroying_delete_t");
16697}
16698
16700 const FunctionDecl *FD) {
16701 // C++ P0722:
16702 // Within a class C, a single object deallocation function with signature
16703 // (T, std::destroying_delete_t, <more params>)
16704 // is a destroying operator delete.
16705 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16706 SemaRef, FD, /*WasMalformed=*/nullptr);
16707 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16708 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16709 FD->getNumParams() > DestroyingDeleteIdx &&
16710 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16711}
16712
16714 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16715 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16716 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16717 auto NormalizeType = [&SemaRef](QualType T) {
16718 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16719 // The operator is valid on any address space for OpenCL.
16720 // Drop address space from actual and expected result types.
16721 if (const auto PtrTy = T->template getAs<PointerType>())
16722 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16723 }
16724 return SemaRef.Context.getCanonicalType(T);
16725 };
16726
16727 const unsigned NumParams = FnDecl->getNumParams();
16728 unsigned FirstNonTypeParam = 0;
16729 bool MalformedTypeIdentity = false;
16730 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16731 SemaRef, FnDecl, &MalformedTypeIdentity);
16732 unsigned MinimumMandatoryArgumentCount = 1;
16733 unsigned SizeParameterIndex = 0;
16734 if (IsPotentiallyTypeAware) {
16735 // We don't emit this diagnosis for template instantiations as we will
16736 // have already emitted it for the original template declaration.
16737 if (!FnDecl->isTemplateInstantiation())
16738 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16739
16740 if (OperatorKind == AllocationOperatorKind::New) {
16741 SizeParameterIndex = 1;
16742 MinimumMandatoryArgumentCount =
16744 } else {
16745 SizeParameterIndex = 2;
16746 MinimumMandatoryArgumentCount =
16748 }
16749 FirstNonTypeParam = 1;
16750 }
16751
16752 bool IsPotentiallyDestroyingDelete =
16754
16755 if (IsPotentiallyDestroyingDelete) {
16756 ++MinimumMandatoryArgumentCount;
16757 ++SizeParameterIndex;
16758 }
16759
16760 if (NumParams < MinimumMandatoryArgumentCount)
16761 return SemaRef.Diag(FnDecl->getLocation(),
16762 diag::err_operator_new_delete_too_few_parameters)
16763 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16764 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16765
16766 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16767 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16768 if (ParamDecl->hasDefaultArg())
16769 return SemaRef.Diag(FnDecl->getLocation(),
16770 diag::err_operator_new_default_arg)
16771 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16772 }
16773
16774 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16775 QualType CanResultType = NormalizeType(FnType->getReturnType());
16776 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16777 QualType CanExpectedSizeOrAddressParamType =
16778 NormalizeType(ExpectedSizeOrAddressParamType);
16779
16780 // Check that the result type is what we expect.
16781 if (CanResultType != CanExpectedResultType) {
16782 // Reject even if the type is dependent; an operator delete function is
16783 // required to have a non-dependent result type.
16784 return SemaRef.Diag(
16785 FnDecl->getLocation(),
16786 CanResultType->isDependentType()
16787 ? diag::err_operator_new_delete_dependent_result_type
16788 : diag::err_operator_new_delete_invalid_result_type)
16789 << FnDecl->getDeclName() << ExpectedResultType;
16790 }
16791
16792 // A function template must have at least 2 parameters.
16793 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16794 return SemaRef.Diag(FnDecl->getLocation(),
16795 diag::err_operator_new_delete_template_too_few_parameters)
16796 << FnDecl->getDeclName();
16797
16798 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16799 auto FallbackType) -> bool {
16800 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16801 if (ExpectedType.isNull()) {
16802 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16803 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16804 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16805 << ParamDecl->getSourceRange();
16806 }
16807 CanQualType CanExpectedTy =
16808 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16809 auto ActualParamType =
16810 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16811 if (ActualParamType == CanExpectedTy)
16812 return false;
16813 unsigned Diagnostic = ActualParamType->isDependentType()
16814 ? DependentParamTypeDiag
16815 : InvalidParamTypeDiag;
16816 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16817 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16818 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16819 << FallbackType << ParamDecl->getSourceRange();
16820 };
16821
16822 // Check that the first parameter type is what we expect.
16823 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16824 return true;
16825
16826 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16827
16828 // If the first parameter type is not a type-identity we're done, otherwise
16829 // we need to ensure the size and alignment parameters have the correct type
16830 if (!IsPotentiallyTypeAware)
16831 return false;
16832
16833 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16834 return true;
16835 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16836 CanQualType StdAlignValT =
16837 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16838 : CanQualType();
16839 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16840 return true;
16841
16843 return MalformedTypeIdentity;
16844}
16845
16846static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16847 // C++ [basic.stc.dynamic.allocation]p1:
16848 // A program is ill-formed if an allocation function is declared in a
16849 // namespace scope other than global scope or declared static in global
16850 // scope.
16851 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16852 return true;
16853
16854 CanQualType SizeTy =
16855 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16856
16857 // C++ [basic.stc.dynamic.allocation]p1:
16858 // The return type shall be void*. The first parameter shall have type
16859 // std::size_t.
16861 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16862 SizeTy, diag::err_operator_new_dependent_param_type,
16863 diag::err_operator_new_param_type);
16864}
16865
16866static bool
16868 // C++ [basic.stc.dynamic.deallocation]p1:
16869 // A program is ill-formed if deallocation functions are declared in a
16870 // namespace scope other than global scope or declared static in global
16871 // scope.
16872 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16873 return true;
16874
16875 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16876 auto ConstructDestroyingDeleteAddressType = [&]() {
16877 assert(MD);
16878 return SemaRef.Context.getPointerType(
16879 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16880 };
16881
16882 // C++ P2719: A destroying operator delete cannot be type aware
16883 // so for QoL we actually check for this explicitly by considering
16884 // an destroying-delete appropriate address type and the presence of
16885 // any parameter of type destroying_delete_t as an erroneous attempt
16886 // to declare a type aware destroying delete, rather than emitting a
16887 // pile of incorrect parameter type errors.
16889 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16890 QualType AddressParamType =
16891 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16892 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16893 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16894 // The address parameter type implies an author trying to construct a
16895 // type aware destroying delete, so we'll see if we can find a parameter
16896 // of type `std::destroying_delete_t`, and if we find it we'll report
16897 // this as being an attempt at a type aware destroying delete just stop
16898 // here. If we don't do this, the resulting incorrect parameter ordering
16899 // results in a pile mismatched argument type errors that don't explain
16900 // the core problem.
16901 for (auto Param : MD->parameters()) {
16902 if (isDestroyingDeleteT(Param->getType())) {
16903 SemaRef.Diag(MD->getLocation(),
16904 diag::err_type_aware_destroying_operator_delete)
16905 << Param->getSourceRange();
16906 return true;
16907 }
16908 }
16909 }
16910 }
16911
16912 // C++ P0722:
16913 // Within a class C, the first parameter of a destroying operator delete
16914 // shall be of type C *. The first parameter of any other deallocation
16915 // function shall be of type void *.
16916 CanQualType ExpectedAddressParamType =
16917 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16918 ? SemaRef.Context.getPointerType(
16919 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16920 : SemaRef.Context.VoidPtrTy;
16921
16922 // C++ [basic.stc.dynamic.deallocation]p2:
16923 // Each deallocation function shall return void
16925 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16926 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16927 diag::err_operator_delete_dependent_param_type,
16928 diag::err_operator_delete_param_type))
16929 return true;
16930
16931 // C++ P0722:
16932 // A destroying operator delete shall be a usual deallocation function.
16933 if (MD && !MD->getParent()->isDependentContext() &&
16935 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16936 SemaRef.Diag(MD->getLocation(),
16937 diag::err_destroying_operator_delete_not_usual);
16938 return true;
16939 }
16940 }
16941
16942 return false;
16943}
16944
16946 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16947 "Expected an overloaded operator declaration");
16948
16950
16951 // C++ [over.oper]p5:
16952 // The allocation and deallocation functions, operator new,
16953 // operator new[], operator delete and operator delete[], are
16954 // described completely in 3.7.3. The attributes and restrictions
16955 // found in the rest of this subclause do not apply to them unless
16956 // explicitly stated in 3.7.3.
16957 if (Op == OO_Delete || Op == OO_Array_Delete)
16958 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16959
16960 if (Op == OO_New || Op == OO_Array_New)
16961 return CheckOperatorNewDeclaration(*this, FnDecl);
16962
16963 // C++ [over.oper]p7:
16964 // An operator function shall either be a member function or
16965 // be a non-member function and have at least one parameter
16966 // whose type is a class, a reference to a class, an enumeration,
16967 // or a reference to an enumeration.
16968 // Note: Before C++23, a member function could not be static. The only member
16969 // function allowed to be static is the call operator function.
16970 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16971 if (MethodDecl->isStatic()) {
16972 if (Op == OO_Call || Op == OO_Subscript)
16973 Diag(FnDecl->getLocation(),
16974 (LangOpts.CPlusPlus23
16975 ? diag::warn_cxx20_compat_operator_overload_static
16976 : diag::ext_operator_overload_static))
16977 << FnDecl;
16978 else
16979 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16980 << FnDecl;
16981 }
16982 } else {
16983 bool ClassOrEnumParam = false;
16984 for (auto *Param : FnDecl->parameters()) {
16985 QualType ParamType = Param->getType().getNonReferenceType();
16986 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16987 ParamType->isEnumeralType()) {
16988 ClassOrEnumParam = true;
16989 break;
16990 }
16991 }
16992
16993 if (!ClassOrEnumParam)
16994 return Diag(FnDecl->getLocation(),
16995 diag::err_operator_overload_needs_class_or_enum)
16996 << FnDecl->getDeclName();
16997 }
16998
16999 // C++ [over.oper]p8:
17000 // An operator function cannot have default arguments (8.3.6),
17001 // except where explicitly stated below.
17002 //
17003 // Only the function-call operator (C++ [over.call]p1) and the subscript
17004 // operator (CWG2507) allow default arguments.
17005 if (Op != OO_Call) {
17006 ParmVarDecl *FirstDefaultedParam = nullptr;
17007 for (auto *Param : FnDecl->parameters()) {
17008 if (Param->hasDefaultArg()) {
17009 FirstDefaultedParam = Param;
17010 break;
17011 }
17012 }
17013 if (FirstDefaultedParam) {
17014 if (Op == OO_Subscript) {
17015 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17016 ? diag::ext_subscript_overload
17017 : diag::error_subscript_overload)
17018 << FnDecl->getDeclName() << 1
17019 << FirstDefaultedParam->getDefaultArgRange();
17020 } else {
17021 return Diag(FirstDefaultedParam->getLocation(),
17022 diag::err_operator_overload_default_arg)
17023 << FnDecl->getDeclName()
17024 << FirstDefaultedParam->getDefaultArgRange();
17025 }
17026 }
17027 }
17028
17029 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17030 { false, false, false }
17031#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17032 , { Unary, Binary, MemberOnly }
17033#include "clang/Basic/OperatorKinds.def"
17034 };
17035
17036 bool CanBeUnaryOperator = OperatorUses[Op][0];
17037 bool CanBeBinaryOperator = OperatorUses[Op][1];
17038 bool MustBeMemberOperator = OperatorUses[Op][2];
17039
17040 // C++ [over.oper]p8:
17041 // [...] Operator functions cannot have more or fewer parameters
17042 // than the number required for the corresponding operator, as
17043 // described in the rest of this subclause.
17044 unsigned NumParams = FnDecl->getNumParams() +
17045 (isa<CXXMethodDecl>(FnDecl) &&
17047 ? 1
17048 : 0);
17049 if (Op != OO_Call && Op != OO_Subscript &&
17050 ((NumParams == 1 && !CanBeUnaryOperator) ||
17051 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17052 (NumParams > 2))) {
17053 // We have the wrong number of parameters.
17054 unsigned ErrorKind;
17055 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17056 ErrorKind = 2; // 2 -> unary or binary.
17057 } else if (CanBeUnaryOperator) {
17058 ErrorKind = 0; // 0 -> unary
17059 } else {
17060 assert(CanBeBinaryOperator &&
17061 "All non-call overloaded operators are unary or binary!");
17062 ErrorKind = 1; // 1 -> binary
17063 }
17064 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17065 << FnDecl->getDeclName() << NumParams << ErrorKind;
17066 }
17067
17068 if (Op == OO_Subscript && NumParams != 2) {
17069 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17070 ? diag::ext_subscript_overload
17071 : diag::error_subscript_overload)
17072 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17073 }
17074
17075 // Overloaded operators other than operator() and operator[] cannot be
17076 // variadic.
17077 if (Op != OO_Call &&
17078 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17079 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17080 << FnDecl->getDeclName();
17081 }
17082
17083 // Some operators must be member functions.
17084 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17085 return Diag(FnDecl->getLocation(),
17086 diag::err_operator_overload_must_be_member)
17087 << FnDecl->getDeclName();
17088 }
17089
17090 // C++ [over.inc]p1:
17091 // The user-defined function called operator++ implements the
17092 // prefix and postfix ++ operator. If this function is a member
17093 // function with no parameters, or a non-member function with one
17094 // parameter of class or enumeration type, it defines the prefix
17095 // increment operator ++ for objects of that type. If the function
17096 // is a member function with one parameter (which shall be of type
17097 // int) or a non-member function with two parameters (the second
17098 // of which shall be of type int), it defines the postfix
17099 // increment operator ++ for objects of that type.
17100 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17101 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17102 QualType ParamType = LastParam->getType();
17103
17104 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17105 !ParamType->isDependentType())
17106 return Diag(LastParam->getLocation(),
17107 diag::err_operator_overload_post_incdec_must_be_int)
17108 << LastParam->getType() << (Op == OO_MinusMinus);
17109 }
17110
17111 return false;
17112}
17113
17114static bool
17116 FunctionTemplateDecl *TpDecl) {
17117 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17118
17119 // Must have one or two template parameters.
17120 if (TemplateParams->size() == 1) {
17121 NonTypeTemplateParmDecl *PmDecl =
17122 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17123
17124 // The template parameter must be a char parameter pack.
17125 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17126 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17127 return false;
17128
17129 // C++20 [over.literal]p5:
17130 // A string literal operator template is a literal operator template
17131 // whose template-parameter-list comprises a single non-type
17132 // template-parameter of class type.
17133 //
17134 // As a DR resolution, we also allow placeholders for deduced class
17135 // template specializations.
17136 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17137 !PmDecl->isTemplateParameterPack() &&
17138 (PmDecl->getType()->isRecordType() ||
17139 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17140 return false;
17141 } else if (TemplateParams->size() == 2) {
17142 TemplateTypeParmDecl *PmType =
17143 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17144 NonTypeTemplateParmDecl *PmArgs =
17145 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17146
17147 // The second template parameter must be a parameter pack with the
17148 // first template parameter as its type.
17149 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17150 PmArgs->isTemplateParameterPack()) {
17151 if (const auto *TArgs =
17152 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17153 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17154 TArgs->getIndex() == PmType->getIndex()) {
17155 if (!SemaRef.inTemplateInstantiation())
17156 SemaRef.Diag(TpDecl->getLocation(),
17157 diag::ext_string_literal_operator_template);
17158 return false;
17159 }
17160 }
17161 }
17162
17163 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17164 diag::err_literal_operator_template)
17165 << TpDecl->getTemplateParameters()->getSourceRange();
17166 return true;
17167}
17168
17170 if (isa<CXXMethodDecl>(FnDecl)) {
17171 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17172 << FnDecl->getDeclName();
17173 return true;
17174 }
17175
17176 if (FnDecl->isExternC()) {
17177 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17178 if (const LinkageSpecDecl *LSD =
17179 FnDecl->getDeclContext()->getExternCContext())
17180 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17181 return true;
17182 }
17183
17184 // This might be the definition of a literal operator template.
17186
17187 // This might be a specialization of a literal operator template.
17188 if (!TpDecl)
17189 TpDecl = FnDecl->getPrimaryTemplate();
17190
17191 // template <char...> type operator "" name() and
17192 // template <class T, T...> type operator "" name() are the only valid
17193 // template signatures, and the only valid signatures with no parameters.
17194 //
17195 // C++20 also allows template <SomeClass T> type operator "" name().
17196 if (TpDecl) {
17197 if (FnDecl->param_size() != 0) {
17198 Diag(FnDecl->getLocation(),
17199 diag::err_literal_operator_template_with_params);
17200 return true;
17201 }
17202
17204 return true;
17205
17206 } else if (FnDecl->param_size() == 1) {
17207 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17208
17209 QualType ParamType = Param->getType().getUnqualifiedType();
17210
17211 // Only unsigned long long int, long double, any character type, and const
17212 // char * are allowed as the only parameters.
17213 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17214 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17215 Context.hasSameType(ParamType, Context.CharTy) ||
17216 Context.hasSameType(ParamType, Context.WideCharTy) ||
17217 Context.hasSameType(ParamType, Context.Char8Ty) ||
17218 Context.hasSameType(ParamType, Context.Char16Ty) ||
17219 Context.hasSameType(ParamType, Context.Char32Ty)) {
17220 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17221 QualType InnerType = Ptr->getPointeeType();
17222
17223 // Pointer parameter must be a const char *.
17224 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17225 Context.CharTy) &&
17226 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17227 Diag(Param->getSourceRange().getBegin(),
17228 diag::err_literal_operator_param)
17229 << ParamType << "'const char *'" << Param->getSourceRange();
17230 return true;
17231 }
17232
17233 } else if (ParamType->isRealFloatingType()) {
17234 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17235 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17236 return true;
17237
17238 } else if (ParamType->isIntegerType()) {
17239 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17240 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17241 return true;
17242
17243 } else {
17244 Diag(Param->getSourceRange().getBegin(),
17245 diag::err_literal_operator_invalid_param)
17246 << ParamType << Param->getSourceRange();
17247 return true;
17248 }
17249
17250 } else if (FnDecl->param_size() == 2) {
17251 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17252
17253 // First, verify that the first parameter is correct.
17254
17255 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17256
17257 // Two parameter function must have a pointer to const as a
17258 // first parameter; let's strip those qualifiers.
17259 const PointerType *PT = FirstParamType->getAs<PointerType>();
17260
17261 if (!PT) {
17262 Diag((*Param)->getSourceRange().getBegin(),
17263 diag::err_literal_operator_param)
17264 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17265 return true;
17266 }
17267
17268 QualType PointeeType = PT->getPointeeType();
17269 // First parameter must be const
17270 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17271 Diag((*Param)->getSourceRange().getBegin(),
17272 diag::err_literal_operator_param)
17273 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17274 return true;
17275 }
17276
17277 QualType InnerType = PointeeType.getUnqualifiedType();
17278 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17279 // const char32_t* are allowed as the first parameter to a two-parameter
17280 // function
17281 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17282 Context.hasSameType(InnerType, Context.WideCharTy) ||
17283 Context.hasSameType(InnerType, Context.Char8Ty) ||
17284 Context.hasSameType(InnerType, Context.Char16Ty) ||
17285 Context.hasSameType(InnerType, Context.Char32Ty))) {
17286 Diag((*Param)->getSourceRange().getBegin(),
17287 diag::err_literal_operator_param)
17288 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17289 return true;
17290 }
17291
17292 // Move on to the second and final parameter.
17293 ++Param;
17294
17295 // The second parameter must be a std::size_t.
17296 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17297 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17298 Diag((*Param)->getSourceRange().getBegin(),
17299 diag::err_literal_operator_param)
17300 << SecondParamType << Context.getSizeType()
17301 << (*Param)->getSourceRange();
17302 return true;
17303 }
17304 } else {
17305 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17306 return true;
17307 }
17308
17309 // Parameters are good.
17310
17311 // A parameter-declaration-clause containing a default argument is not
17312 // equivalent to any of the permitted forms.
17313 for (auto *Param : FnDecl->parameters()) {
17314 if (Param->hasDefaultArg()) {
17315 Diag(Param->getDefaultArgRange().getBegin(),
17316 diag::err_literal_operator_default_argument)
17317 << Param->getDefaultArgRange();
17318 break;
17319 }
17320 }
17321
17322 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17325 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17326 // C++23 [usrlit.suffix]p1:
17327 // Literal suffix identifiers that do not start with an underscore are
17328 // reserved for future standardization. Literal suffix identifiers that
17329 // contain a double underscore __ are reserved for use by C++
17330 // implementations.
17331 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17332 << static_cast<int>(Status)
17334 }
17335
17336 return false;
17337}
17338
17340 Expr *LangStr,
17341 SourceLocation LBraceLoc) {
17342 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17343 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17344
17345 StringRef Lang = Lit->getString();
17347 if (Lang == "C")
17349 else if (Lang == "C++")
17351 else {
17352 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17353 << LangStr->getSourceRange();
17354 return nullptr;
17355 }
17356
17357 // FIXME: Add all the various semantics of linkage specifications
17358
17360 LangStr->getExprLoc(), Language,
17361 LBraceLoc.isValid());
17362
17363 /// C++ [module.unit]p7.2.3
17364 /// - Otherwise, if the declaration
17365 /// - ...
17366 /// - ...
17367 /// - appears within a linkage-specification,
17368 /// it is attached to the global module.
17369 ///
17370 /// If the declaration is already in global module fragment, we don't
17371 /// need to attach it again.
17372 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17373 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17374 D->setLocalOwningModule(GlobalModule);
17375 }
17376
17377 CurContext->addDecl(D);
17378 PushDeclContext(S, D);
17379 return D;
17380}
17381
17383 Decl *LinkageSpec,
17384 SourceLocation RBraceLoc) {
17385 if (RBraceLoc.isValid()) {
17386 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17387 LSDecl->setRBraceLoc(RBraceLoc);
17388 }
17389
17390 // If the current module doesn't has Parent, it implies that the
17391 // LinkageSpec isn't in the module created by itself. So we don't
17392 // need to pop it.
17393 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17394 getCurrentModule()->isImplicitGlobalModule() &&
17395 getCurrentModule()->Parent)
17396 PopImplicitGlobalModuleFragment();
17397
17399 return LinkageSpec;
17400}
17401
17403 const ParsedAttributesView &AttrList,
17404 SourceLocation SemiLoc) {
17405 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17406 // Attribute declarations appertain to empty declaration so we handle
17407 // them here.
17408 ProcessDeclAttributeList(S, ED, AttrList);
17409
17410 CurContext->addDecl(ED);
17411 return ED;
17412}
17413
17415 SourceLocation StartLoc,
17416 SourceLocation Loc,
17417 const IdentifierInfo *Name) {
17418 bool Invalid = false;
17419 QualType ExDeclType = TInfo->getType();
17420
17421 // Arrays and functions decay.
17422 if (ExDeclType->isArrayType())
17423 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17424 else if (ExDeclType->isFunctionType())
17425 ExDeclType = Context.getPointerType(ExDeclType);
17426
17427 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17428 // The exception-declaration shall not denote a pointer or reference to an
17429 // incomplete type, other than [cv] void*.
17430 // N2844 forbids rvalue references.
17431 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17432 Diag(Loc, diag::err_catch_rvalue_ref);
17433 Invalid = true;
17434 }
17435
17436 if (ExDeclType->isVariablyModifiedType()) {
17437 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17438 Invalid = true;
17439 }
17440
17441 QualType BaseType = ExDeclType;
17442 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17443 unsigned DK = diag::err_catch_incomplete;
17444 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17445 BaseType = Ptr->getPointeeType();
17446 Mode = 1;
17447 DK = diag::err_catch_incomplete_ptr;
17448 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17449 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17450 BaseType = Ref->getPointeeType();
17451 Mode = 2;
17452 DK = diag::err_catch_incomplete_ref;
17453 }
17454 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17455 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17456 Invalid = true;
17457
17458 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17459 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17460 Invalid = true;
17461 }
17462
17463 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17464 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17465 Invalid = true;
17466 }
17467
17468 if (!Invalid && !ExDeclType->isDependentType() &&
17469 RequireNonAbstractType(Loc, ExDeclType,
17470 diag::err_abstract_type_in_decl,
17472 Invalid = true;
17473
17474 // Only the non-fragile NeXT runtime currently supports C++ catches
17475 // of ObjC types, and no runtime supports catching ObjC types by value.
17476 if (!Invalid && getLangOpts().ObjC) {
17477 QualType T = ExDeclType;
17478 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17479 T = RT->getPointeeType();
17480
17481 if (T->isObjCObjectType()) {
17482 Diag(Loc, diag::err_objc_object_catch);
17483 Invalid = true;
17484 } else if (T->isObjCObjectPointerType()) {
17485 // FIXME: should this be a test for macosx-fragile specifically?
17487 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17488 }
17489 }
17490
17491 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17492 ExDeclType, TInfo, SC_None);
17493 ExDecl->setExceptionVariable(true);
17494
17495 // In ARC, infer 'retaining' for variables of retainable type.
17496 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17497 Invalid = true;
17498
17499 if (!Invalid && !ExDeclType->isDependentType()) {
17500 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17501 // Insulate this from anything else we might currently be parsing.
17504
17505 // C++ [except.handle]p16:
17506 // The object declared in an exception-declaration or, if the
17507 // exception-declaration does not specify a name, a temporary (12.2) is
17508 // copy-initialized (8.5) from the exception object. [...]
17509 // The object is destroyed when the handler exits, after the destruction
17510 // of any automatic objects initialized within the handler.
17511 //
17512 // We just pretend to initialize the object with itself, then make sure
17513 // it can be destroyed later.
17514 QualType initType = Context.getExceptionObjectType(ExDeclType);
17515
17516 InitializedEntity entity =
17518 InitializationKind initKind =
17520
17521 Expr *opaqueValue =
17522 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17523 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17524 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17525 if (result.isInvalid())
17526 Invalid = true;
17527 else {
17528 // If the constructor used was non-trivial, set this as the
17529 // "initializer".
17530 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17531 if (!construct->getConstructor()->isTrivial()) {
17532 Expr *init = MaybeCreateExprWithCleanups(construct);
17533 ExDecl->setInit(init);
17534 }
17535
17536 // And make sure it's destructable.
17537 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17538 }
17539 }
17540 }
17541
17542 if (Invalid)
17543 ExDecl->setInvalidDecl();
17544
17545 return ExDecl;
17546}
17547
17550 bool Invalid = D.isInvalidType();
17551
17552 // Check for unexpanded parameter packs.
17555 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17556 D.getIdentifierLoc());
17557 Invalid = true;
17558 }
17559
17560 const IdentifierInfo *II = D.getIdentifier();
17561 if (NamedDecl *PrevDecl =
17564 // The scope should be freshly made just for us. There is just no way
17565 // it contains any previous declaration, except for function parameters in
17566 // a function-try-block's catch statement.
17567 assert(!S->isDeclScope(PrevDecl));
17568 if (isDeclInScope(PrevDecl, CurContext, S)) {
17569 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17570 << D.getIdentifier();
17571 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17572 Invalid = true;
17573 } else if (PrevDecl->isTemplateParameter())
17574 // Maybe we will complain about the shadowed template parameter.
17576 }
17577
17578 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17579 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17580 << D.getCXXScopeSpec().getRange();
17581 Invalid = true;
17582 }
17583
17585 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17586 if (Invalid)
17587 ExDecl->setInvalidDecl();
17588
17589 // Add the exception declaration into this scope.
17590 if (II)
17591 PushOnScopeChains(ExDecl, S);
17592 else
17593 CurContext->addDecl(ExDecl);
17594
17595 ProcessDeclAttributes(S, ExDecl, D);
17596 return ExDecl;
17597}
17598
17600 Expr *AssertExpr,
17601 Expr *AssertMessageExpr,
17602 SourceLocation RParenLoc) {
17604 return nullptr;
17605
17606 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17607 AssertMessageExpr, RParenLoc, false);
17608}
17609
17610static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17611 switch (BTK) {
17612 case BuiltinType::Char_S:
17613 case BuiltinType::Char_U:
17614 break;
17615 case BuiltinType::Char8:
17616 OS << "u8";
17617 break;
17618 case BuiltinType::Char16:
17619 OS << 'u';
17620 break;
17621 case BuiltinType::Char32:
17622 OS << 'U';
17623 break;
17624 case BuiltinType::WChar_S:
17625 case BuiltinType::WChar_U:
17626 OS << 'L';
17627 break;
17628 default:
17629 llvm_unreachable("Non-character type");
17630 }
17631}
17632
17633/// Convert character's value, interpreted as a code unit, to a string.
17634/// The value needs to be zero-extended to 32-bits.
17635/// FIXME: This assumes Unicode literal encodings
17637 unsigned TyWidth,
17638 SmallVectorImpl<char> &Str) {
17639 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17640 char *Ptr = Arr;
17641 BuiltinType::Kind K = BTy->getKind();
17642 llvm::raw_svector_ostream OS(Str);
17643
17644 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17645 // other types.
17646 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17647 K == BuiltinType::Char8 || Value <= 0x7F) {
17648 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17649 if (!Escaped.empty())
17650 EscapeStringForDiagnostic(Escaped, Str);
17651 else
17652 OS << static_cast<char>(Value);
17653 return;
17654 }
17655
17656 switch (K) {
17657 case BuiltinType::Char16:
17658 case BuiltinType::Char32:
17659 case BuiltinType::WChar_S:
17660 case BuiltinType::WChar_U: {
17661 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17662 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17663 else
17664 OS << "\\x"
17665 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17666 break;
17667 }
17668 default:
17669 llvm_unreachable("Non-character type is passed");
17670 }
17671}
17672
17673/// Convert \V to a string we can present to the user in a diagnostic
17674/// \T is the type of the expression that has been evaluated into \V
17677 ASTContext &Context) {
17678 if (!V.hasValue())
17679 return false;
17680
17681 switch (V.getKind()) {
17683 if (T->isBooleanType()) {
17684 // Bools are reduced to ints during evaluation, but for
17685 // diagnostic purposes we want to print them as
17686 // true or false.
17687 int64_t BoolValue = V.getInt().getExtValue();
17688 assert((BoolValue == 0 || BoolValue == 1) &&
17689 "Bool type, but value is not 0 or 1");
17690 llvm::raw_svector_ostream OS(Str);
17691 OS << (BoolValue ? "true" : "false");
17692 } else {
17693 llvm::raw_svector_ostream OS(Str);
17694 // Same is true for chars.
17695 // We want to print the character representation for textual types
17696 const auto *BTy = T->getAs<BuiltinType>();
17697 if (BTy) {
17698 switch (BTy->getKind()) {
17699 case BuiltinType::Char_S:
17700 case BuiltinType::Char_U:
17701 case BuiltinType::Char8:
17702 case BuiltinType::Char16:
17703 case BuiltinType::Char32:
17704 case BuiltinType::WChar_S:
17705 case BuiltinType::WChar_U: {
17706 unsigned TyWidth = Context.getIntWidth(T);
17707 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17708 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17709 WriteCharTypePrefix(BTy->getKind(), OS);
17710 OS << '\'';
17711 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17712 OS << "' (0x"
17713 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17714 /*Upper=*/true)
17715 << ", " << V.getInt() << ')';
17716 return true;
17717 }
17718 default:
17719 break;
17720 }
17721 }
17722 V.getInt().toString(Str);
17723 }
17724
17725 break;
17726
17728 V.getFloat().toString(Str);
17729 break;
17730
17732 if (V.isNullPointer()) {
17733 llvm::raw_svector_ostream OS(Str);
17734 OS << "nullptr";
17735 } else
17736 return false;
17737 break;
17738
17740 llvm::raw_svector_ostream OS(Str);
17741 OS << '(';
17742 V.getComplexFloatReal().toString(Str);
17743 OS << " + ";
17744 V.getComplexFloatImag().toString(Str);
17745 OS << "i)";
17746 } break;
17747
17749 llvm::raw_svector_ostream OS(Str);
17750 OS << '(';
17751 V.getComplexIntReal().toString(Str);
17752 OS << " + ";
17753 V.getComplexIntImag().toString(Str);
17754 OS << "i)";
17755 } break;
17756
17757 default:
17758 return false;
17759 }
17760
17761 return true;
17762}
17763
17764/// Some Expression types are not useful to print notes about,
17765/// e.g. literals and values that have already been expanded
17766/// before such as int-valued template parameters.
17767static bool UsefulToPrintExpr(const Expr *E) {
17768 E = E->IgnoreParenImpCasts();
17769 // Literals are pretty easy for humans to understand.
17772 return false;
17773
17774 // These have been substituted from template parameters
17775 // and appear as literals in the static assert error.
17777 return false;
17778
17779 // -5 is also simple to understand.
17780 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17781 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17782
17783 // Only print nested arithmetic operators.
17784 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17785 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17786 BO->isBitwiseOp());
17787
17788 return true;
17789}
17790
17792 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17793 Op && Op->getOpcode() != BO_LOr) {
17794 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17795 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17796
17797 // Ignore comparisons of boolean expressions with a boolean literal.
17798 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17799 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17800 return;
17801
17802 // Don't print obvious expressions.
17803 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17804 return;
17805
17806 struct {
17807 const clang::Expr *Cond;
17809 SmallString<12> ValueString;
17810 bool Print;
17811 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17812 {RHS, Expr::EvalResult(), {}, false}};
17813 for (auto &DiagSide : DiagSides) {
17814 const Expr *Side = DiagSide.Cond;
17815
17816 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17817
17818 DiagSide.Print = ConvertAPValueToString(
17819 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17820 }
17821 if (DiagSides[0].Print && DiagSides[1].Print) {
17822 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17823 << DiagSides[0].ValueString << Op->getOpcodeStr()
17824 << DiagSides[1].ValueString << Op->getSourceRange();
17825 }
17826 } else {
17828 }
17829}
17830
17831template <typename ResultType>
17832static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17833 ResultType &Result, ASTContext &Ctx,
17835 bool ErrorOnInvalidMessage) {
17836
17837 assert(Message);
17838 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17839 "can't evaluate a dependant static assert message");
17840
17841 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17842 assert(SL->isUnevaluated() && "expected an unevaluated string");
17843 if constexpr (std::is_same_v<APValue, ResultType>) {
17844 Result =
17845 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17846 const ConstantArrayType *CAT =
17847 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17848 assert(CAT && "string literal isn't an array");
17849 QualType CharType = CAT->getElementType();
17850 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17851 CharType->isUnsignedIntegerType());
17852 for (unsigned I = 0; I < SL->getLength(); I++) {
17853 Value = SL->getCodeUnit(I);
17854 Result.getArrayInitializedElt(I) = APValue(Value);
17855 }
17856 } else {
17857 Result.assign(SL->getString().begin(), SL->getString().end());
17858 }
17859 return true;
17860 }
17861
17862 SourceLocation Loc = Message->getBeginLoc();
17863 QualType T = Message->getType().getNonReferenceType();
17864 auto *RD = T->getAsCXXRecordDecl();
17865 if (!RD) {
17866 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17867 return false;
17868 }
17869
17870 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17872 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17873 SemaRef.LookupQualifiedName(MemberLookup, RD);
17874 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17876 if (MemberLookup.empty())
17877 return std::nullopt;
17878 return std::move(MemberLookup);
17879 };
17880
17881 std::optional<LookupResult> SizeMember = FindMember("size");
17882 std::optional<LookupResult> DataMember = FindMember("data");
17883 if (!SizeMember || !DataMember) {
17884 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17885 << EvalContext
17886 << ((!SizeMember && !DataMember) ? 2
17887 : !SizeMember ? 0
17888 : 1);
17889 return false;
17890 }
17891
17892 auto BuildExpr = [&](LookupResult &LR) {
17894 Message, Message->getType(), Message->getBeginLoc(), false,
17895 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17896 if (Res.isInvalid())
17897 return ExprError();
17898 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17899 false, true);
17900 if (Res.isInvalid())
17901 return ExprError();
17902 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17903 return ExprError();
17904 return SemaRef.TemporaryMaterializationConversion(Res.get());
17905 };
17906
17907 ExprResult SizeE = BuildExpr(*SizeMember);
17908 ExprResult DataE = BuildExpr(*DataMember);
17909
17910 QualType SizeT = SemaRef.Context.getSizeType();
17911 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17912 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17913
17914 ExprResult EvaluatedSize =
17915 SizeE.isInvalid()
17916 ? ExprError()
17919 if (EvaluatedSize.isInvalid()) {
17920 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17921 << EvalContext << /*size*/ 0;
17922 return false;
17923 }
17924
17925 ExprResult EvaluatedData =
17926 DataE.isInvalid()
17927 ? ExprError()
17929 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17930 if (EvaluatedData.isInvalid()) {
17931 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17932 << EvalContext << /*data*/ 1;
17933 return false;
17934 }
17935
17936 if (!ErrorOnInvalidMessage &&
17937 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17938 return true;
17939
17940 Expr::EvalResult Status;
17942 Status.Diag = &Notes;
17943 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17944 EvaluatedData.get(), Ctx, Status) ||
17945 !Notes.empty()) {
17946 SemaRef.Diag(Message->getBeginLoc(),
17947 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17948 : diag::warn_user_defined_msg_constexpr)
17949 << EvalContext;
17950 for (const auto &Note : Notes)
17951 SemaRef.Diag(Note.first, Note.second);
17952 return !ErrorOnInvalidMessage;
17953 }
17954 return true;
17955}
17956
17958 StringEvaluationContext EvalContext,
17959 bool ErrorOnInvalidMessage) {
17960 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17961 ErrorOnInvalidMessage);
17962}
17963
17964bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17965 StringEvaluationContext EvalContext,
17966 bool ErrorOnInvalidMessage) {
17967 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17968 ErrorOnInvalidMessage);
17969}
17970
17972 Expr *AssertExpr, Expr *AssertMessage,
17973 SourceLocation RParenLoc,
17974 bool Failed) {
17975 assert(AssertExpr != nullptr && "Expected non-null condition");
17976 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17977 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17978 !AssertMessage->isValueDependent())) &&
17979 !Failed) {
17980 // In a static_assert-declaration, the constant-expression shall be a
17981 // constant expression that can be contextually converted to bool.
17982 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17983 if (Converted.isInvalid())
17984 Failed = true;
17985
17986 ExprResult FullAssertExpr =
17987 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17988 /*DiscardedValue*/ false,
17989 /*IsConstexpr*/ true);
17990 if (FullAssertExpr.isInvalid())
17991 Failed = true;
17992 else
17993 AssertExpr = FullAssertExpr.get();
17994
17995 llvm::APSInt Cond;
17996 Expr *BaseExpr = AssertExpr;
17998
17999 if (!getLangOpts().CPlusPlus) {
18000 // In C mode, allow folding as an extension for better compatibility with
18001 // C++ in terms of expressions like static_assert("test") or
18002 // static_assert(nullptr).
18003 FoldKind = AllowFoldKind::Allow;
18004 }
18005
18006 if (!Failed && VerifyIntegerConstantExpression(
18007 BaseExpr, &Cond,
18008 diag::err_static_assert_expression_is_not_constant,
18009 FoldKind).isInvalid())
18010 Failed = true;
18011
18012 // If the static_assert passes, only verify that
18013 // the message is grammatically valid without evaluating it.
18014 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18015 std::string Str;
18016 EvaluateAsString(AssertMessage, Str, Context,
18018 /*ErrorOnInvalidMessage=*/false);
18019 }
18020
18021 // CWG2518
18022 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18023 // template definition, the declaration has no effect.
18024 bool InTemplateDefinition =
18025 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18026
18027 if (!Failed && !Cond && !InTemplateDefinition) {
18028 SmallString<256> MsgBuffer;
18029 llvm::raw_svector_ostream Msg(MsgBuffer);
18030 bool HasMessage = AssertMessage;
18031 if (AssertMessage) {
18032 std::string Str;
18033 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18035 /*ErrorOnInvalidMessage=*/true) ||
18036 !Str.empty();
18037 Msg << Str;
18038 }
18039 Expr *InnerCond = nullptr;
18040 std::string InnerCondDescription;
18041 std::tie(InnerCond, InnerCondDescription) =
18042 findFailedBooleanCondition(Converted.get());
18043 if (const auto *ConceptIDExpr =
18044 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18045 const ASTConstraintSatisfaction &Satisfaction =
18046 ConceptIDExpr->getSatisfaction();
18047 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18048 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18049 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18050 // Drill down into concept specialization expressions to see why they
18051 // weren't satisfied.
18052 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18053 }
18054 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18055 !isa<IntegerLiteral>(InnerCond)) {
18056 Diag(InnerCond->getBeginLoc(),
18057 diag::err_static_assert_requirement_failed)
18058 << InnerCondDescription << !HasMessage << Msg.str()
18059 << InnerCond->getSourceRange();
18060 DiagnoseStaticAssertDetails(InnerCond);
18061 } else {
18062 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18063 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18065 }
18066 Failed = true;
18067 }
18068 } else {
18069 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18070 /*DiscardedValue*/false,
18071 /*IsConstexpr*/true);
18072 if (FullAssertExpr.isInvalid())
18073 Failed = true;
18074 else
18075 AssertExpr = FullAssertExpr.get();
18076 }
18077
18079 AssertExpr, AssertMessage, RParenLoc,
18080 Failed);
18081
18082 CurContext->addDecl(Decl);
18083 return Decl;
18084}
18085
18087 TemplateParameterList *FPL) {
18088 if (!NNS.isDependent() || !FPL || FPL->size() == 0)
18089 return false;
18090
18091 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18092 "dependent nested-name-specifier must be a type");
18093 QualType T(NNS.getCanonical().getAsType(), 0);
18094
18095 if (const auto *PIT = dyn_cast<PackIndexingType>(T))
18096 T = PIT->getPattern();
18097
18098 if (const auto *TST = dyn_cast<TemplateSpecializationType>(T)) {
18099 if (isa_and_nonnull<ClassTemplateDecl>(
18100 TST->getTemplateName().getAsTemplateDecl()))
18101 return false;
18102 }
18103
18105 return false;
18106
18107 Diag(Loc, diag::err_dependent_friend_not_member);
18108 return true;
18109}
18110
18112 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18113 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18114 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18115 MultiTemplateParamsArg TempParamLists) {
18117
18118 bool IsMemberSpecialization = false;
18119 bool Invalid = false;
18120
18121 if (TemplateParameterList *TemplateParams =
18123 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
18124 IsMemberSpecialization, Invalid)) {
18125 if (TemplateParams->size() > 0) {
18126 if (Invalid)
18127 return true;
18128
18129 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18131 S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc, Attr,
18132 TemplateParams, AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18133 FriendLoc, TempParamLists.size() - 1, TempParamLists.data(),
18134 IsMemberSpecialization);
18135 return Result.get();
18136 }
18137 } else {
18138 // The "template<>" header is extraneous.
18139 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18140 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18141 }
18142 }
18143
18144 if (Invalid) return true;
18145
18146 bool isAllExplicitSpecializations =
18147 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18148 return List->size() == 0;
18149 });
18150
18151 // FIXME: don't ignore attributes.
18152
18153 // If it's explicit specializations all the way down, just forget
18154 // about the template header and build an appropriate non-templated
18155 // friend. TODO: for source fidelity, remember the headers.
18157 if (isAllExplicitSpecializations) {
18158 if (SS.isEmpty()) {
18159 bool Owned = false;
18160 bool IsDependent = false;
18161 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18162 Attr, AS_public,
18163 /*ModulePrivateLoc=*/SourceLocation(),
18164 MultiTemplateParamsArg(), Owned, IsDependent,
18165 /*ScopedEnumKWLoc=*/SourceLocation(),
18166 /*ScopedEnumUsesClassTag=*/false,
18167 /*UnderlyingType=*/TypeResult(),
18168 /*IsTypeSpecifier=*/false,
18169 /*IsTemplateParamOrArg=*/false,
18170 /*OOK=*/OffsetOfKind::Outside);
18171 }
18172
18173 TypeSourceInfo *TSI = nullptr;
18176 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18177 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18178 if (T.isNull())
18179 return true;
18180
18182 FriendLoc, EllipsisLoc);
18183 Friend->setAccess(AS_public);
18184 CurContext->addDecl(Friend);
18185 return Friend;
18186 }
18187
18188 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18189
18190 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18191 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18192 // shall not have been introduced by the template-declaration.
18194 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
18195 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18196 for (UnexpandedParameterPack &U : Unexpanded) {
18197 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(U);
18198 DI && DI->first >= FriendDeclDepth) {
18199 auto *ND = dyn_cast<NamedDecl *>(U.first);
18200 if (!ND)
18201 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18202 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18203 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18204 return true;
18205 }
18206 }
18207
18209 if (EllipsisLoc.isInvalid() &&
18210 CheckDependentFriend(TagLoc, NNS, TempParamLists.front()))
18211 return true;
18212
18214 QualType T = Context.getDependentNameType(ETK, NNS, Name);
18215 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18216
18218 TL.setElaboratedKeywordLoc(TagLoc);
18220 TL.setNameLoc(NameLoc);
18221
18223 if (TempParamLists.empty())
18224 Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18225 EllipsisLoc);
18226 else {
18227 if (CheckTemplateDeclScope(S, TempParamLists.back()))
18228 return true;
18229
18231 FriendLoc, TempParamLists, EllipsisLoc);
18232 }
18233
18234 Friend->setAccess(AS_public);
18235 CurContext->addDecl(Friend);
18236
18237 return Friend;
18238}
18239
18241 MultiTemplateParamsArg TempParams,
18242 SourceLocation EllipsisLoc) {
18243 SourceLocation Loc = DS.getBeginLoc();
18244 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18245
18246 assert(DS.isFriendSpecified());
18248
18249 // C++ [class.friend]p3:
18250 // A friend declaration that does not declare a function shall have one of
18251 // the following forms:
18252 // friend elaborated-type-specifier ;
18253 // friend simple-type-specifier ;
18254 // friend typename-specifier ;
18255 //
18256 // If the friend keyword isn't first, or if the declarations has any type
18257 // qualifiers, then the declaration doesn't have that form.
18259 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18260 if (DS.getTypeQualifiers()) {
18262 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18264 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18266 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18268 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18270 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18271 }
18272
18273 // Try to convert the decl specifier to a type. This works for
18274 // friend templates because ActOnTag never produces a ClassTemplateDecl
18275 // for a TagUseKind::Friend.
18276 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18278 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18279 QualType T = TSI->getType();
18280 if (TheDeclarator.isInvalidType())
18281 return nullptr;
18282
18283 // If '...' is present, the type must contain an unexpanded parameter
18284 // pack, and vice versa.
18285 bool Invalid = false;
18286 if (EllipsisLoc.isInvalid() &&
18288 return nullptr;
18289 if (EllipsisLoc.isValid() &&
18291 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18292 << TSI->getTypeLoc().getSourceRange();
18293 Invalid = true;
18294 }
18295
18296 if (!T->isElaboratedTypeSpecifier()) {
18297 if (TempParams.size()) {
18298 // C++23 [dcl.pre]p5:
18299 // In a simple-declaration, the optional init-declarator-list can be
18300 // omitted only when declaring a class or enumeration, that is, when
18301 // the decl-specifier-seq contains either a class-specifier, an
18302 // elaborated-type-specifier with a class-key, or an enum-specifier.
18303 //
18304 // The declaration of a template-declaration or explicit-specialization
18305 // is never a member-declaration, so this must be a simple-declaration
18306 // with no init-declarator-list. Therefore, this is ill-formed.
18307 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18308 return nullptr;
18309 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18310 SmallString<16> InsertionText(" ");
18311 InsertionText += RD->getKindName();
18312
18314 ? diag::warn_cxx98_compat_unelaborated_friend_type
18315 : diag::ext_unelaborated_friend_type)
18316 << (unsigned)RD->getTagKind() << T
18318 InsertionText);
18319 } else {
18320 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18321 << T << DS.getSourceRange();
18322 }
18323 }
18324
18325 // C++98 [class.friend]p1: A friend of a class is a function
18326 // or class that is not a member of the class . . .
18327 // This is fixed in DR77, which just barely didn't make the C++03
18328 // deadline. It's also a very silly restriction that seriously
18329 // affects inner classes and which nobody else seems to implement;
18330 // thus we never diagnose it, not even in -pedantic.
18331 //
18332 // But note that we could warn about it: it's always useless to
18333 // friend one of your own members (it's not, however, worthless to
18334 // friend a member of an arbitrary specialization of your template).
18335
18336 Decl *D;
18337 if (!TempParams.empty()) {
18338 if (CheckTemplateDeclScope(S, TempParams.back()))
18339 return nullptr;
18340
18341 // TODO: Support variadic friend template decls?
18342 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TSI, FriendLoc,
18343 TempParams, EllipsisLoc);
18344 } else
18346 TSI, FriendLoc, EllipsisLoc);
18347
18348 if (!D)
18349 return nullptr;
18350
18351 D->setAccess(AS_public);
18352 CurContext->addDecl(D);
18353
18354 if (Invalid)
18355 D->setInvalidDecl();
18356
18357 return D;
18358}
18359
18361 MultiTemplateParamsArg TemplateParams) {
18362 const DeclSpec &DS = D.getDeclSpec();
18363
18364 assert(DS.isFriendSpecified());
18366
18369
18370 // C++ [class.friend]p1
18371 // A friend of a class is a function or class....
18372 // Note that this sees through typedefs, which is intended.
18373 // It *doesn't* see through dependent types, which is correct
18374 // according to [temp.arg.type]p3:
18375 // If a declaration acquires a function type through a
18376 // type dependent on a template-parameter and this causes
18377 // a declaration that does not use the syntactic form of a
18378 // function declarator to have a function type, the program
18379 // is ill-formed.
18380 if (!TInfo->getType()->isFunctionType()) {
18381 Diag(Loc, diag::err_unexpected_friend);
18382
18383 // It might be worthwhile to try to recover by creating an
18384 // appropriate declaration.
18385 return nullptr;
18386 }
18387
18388 // C++ [namespace.memdef]p3
18389 // - If a friend declaration in a non-local class first declares a
18390 // class or function, the friend class or function is a member
18391 // of the innermost enclosing namespace.
18392 // - The name of the friend is not found by simple name lookup
18393 // until a matching declaration is provided in that namespace
18394 // scope (either before or after the class declaration granting
18395 // friendship).
18396 // - If a friend function is called, its name may be found by the
18397 // name lookup that considers functions from namespaces and
18398 // classes associated with the types of the function arguments.
18399 // - When looking for a prior declaration of a class or a function
18400 // declared as a friend, scopes outside the innermost enclosing
18401 // namespace scope are not considered.
18402
18403 CXXScopeSpec &SS = D.getCXXScopeSpec();
18405 assert(NameInfo.getName());
18406
18407 // Check for unexpanded parameter packs.
18411 return nullptr;
18412
18413 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18414
18415 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18416 auto Kind = SS.getScopeRep().getKind();
18417 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18419 if (IsNamespaceOrGlobal) {
18420 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
18421 << SS.getScopeRep();
18422 SS.clear();
18423 }
18424 }
18425
18426 // The context we found the declaration in, or in which we should
18427 // create the declaration.
18428 DeclContext *DC;
18429 Scope *DCScope = S;
18430 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18432
18433 // There are five cases here.
18434 // - There's no scope specifier and we're in a local class. Only look
18435 // for functions declared in the immediately-enclosing block scope.
18436 // We recover from invalid scope qualifiers as if they just weren't there.
18437 FunctionDecl *FunctionContainingLocalClass = nullptr;
18438 if ((SS.isInvalid() || !SS.isSet()) &&
18439 (FunctionContainingLocalClass =
18440 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18441 // C++11 [class.friend]p11:
18442 // If a friend declaration appears in a local class and the name
18443 // specified is an unqualified name, a prior declaration is
18444 // looked up without considering scopes that are outside the
18445 // innermost enclosing non-class scope. For a friend function
18446 // declaration, if there is no prior declaration, the program is
18447 // ill-formed.
18448
18449 // Find the innermost enclosing non-class scope. This is the block
18450 // scope containing the local class definition (or for a nested class,
18451 // the outer local class).
18452 DCScope = S->getFnParent();
18453
18454 // Look up the function name in the scope.
18456 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18457
18458 if (!Previous.empty()) {
18459 // All possible previous declarations must have the same context:
18460 // either they were declared at block scope or they are members of
18461 // one of the enclosing local classes.
18462 DC = Previous.getRepresentativeDecl()->getDeclContext();
18463 } else {
18464 // This is ill-formed, but provide the context that we would have
18465 // declared the function in, if we were permitted to, for error recovery.
18466 DC = FunctionContainingLocalClass;
18467 }
18469
18470 // - There's no scope specifier, in which case we just go to the
18471 // appropriate scope and look for a function or function template
18472 // there as appropriate.
18473 } else if (SS.isInvalid() || !SS.isSet()) {
18474 // C++11 [namespace.memdef]p3:
18475 // If the name in a friend declaration is neither qualified nor
18476 // a template-id and the declaration is a function or an
18477 // elaborated-type-specifier, the lookup to determine whether
18478 // the entity has been previously declared shall not consider
18479 // any scopes outside the innermost enclosing namespace.
18480
18481 // Find the appropriate context according to the above.
18482 DC = CurContext;
18483
18484 // Skip class contexts. If someone can cite chapter and verse
18485 // for this behavior, that would be nice --- it's what GCC and
18486 // EDG do, and it seems like a reasonable intent, but the spec
18487 // really only says that checks for unqualified existing
18488 // declarations should stop at the nearest enclosing namespace,
18489 // not that they should only consider the nearest enclosing
18490 // namespace.
18491 while (DC->isRecord())
18492 DC = DC->getParent();
18493
18494 DeclContext *LookupDC = DC->getNonTransparentContext();
18495 while (true) {
18496 LookupQualifiedName(Previous, LookupDC);
18497
18498 if (!Previous.empty()) {
18499 DC = LookupDC;
18500 break;
18501 }
18502
18503 if (isTemplateId) {
18504 if (isa<TranslationUnitDecl>(LookupDC)) break;
18505 } else {
18506 if (LookupDC->isFileContext()) break;
18507 }
18508 LookupDC = LookupDC->getParent();
18509 }
18510
18511 DCScope = getScopeForDeclContext(S, DC);
18512
18513 // - There's a non-dependent scope specifier, in which case we
18514 // compute it and do a previous lookup there for a function
18515 // or function template.
18516 } else if (!SS.getScopeRep().isDependent()) {
18517 DC = computeDeclContext(SS);
18518 if (!DC) return nullptr;
18519
18520 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18521
18523
18524 // C++ [class.friend]p1: A friend of a class is a function or
18525 // class that is not a member of the class . . .
18526 if (DC->Equals(CurContext))
18529 diag::warn_cxx98_compat_friend_is_member :
18530 diag::err_friend_is_member);
18531
18532 // - There's a scope specifier that does not match any template
18533 // parameter lists, in which case we use some arbitrary context,
18534 // create a method or method template, and wait for instantiation.
18535 // - There's a scope specifier that does match some template
18536 // parameter lists, which we don't handle right now.
18537 } else {
18538 DC = CurContext;
18539 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18540 }
18541
18542 if (TemplateParams.size() && SS.isValid() &&
18543 CheckDependentFriend(NameInfo.getLoc(), SS.getScopeRep(),
18544 TemplateParams.front()))
18545 return nullptr;
18546
18547 if (!DC->isRecord()) {
18548 int DiagArg = -1;
18549 switch (D.getName().getKind()) {
18552 DiagArg = 0;
18553 break;
18555 DiagArg = 1;
18556 break;
18558 DiagArg = 2;
18559 break;
18561 DiagArg = 3;
18562 break;
18568 break;
18569 }
18570 // This implies that it has to be an operator or function.
18571 if (DiagArg >= 0) {
18572 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18573 return nullptr;
18574 }
18575 } else {
18576 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
18577 if (RC->isLambda()) {
18578 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
18579 }
18580 }
18581
18582 // FIXME: This is an egregious hack to cope with cases where the scope stack
18583 // does not contain the declaration context, i.e., in an out-of-line
18584 // definition of a class.
18585 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18586 if (!DCScope) {
18587 FakeDCScope.setEntity(DC);
18588 DCScope = &FakeDCScope;
18589 }
18590
18591 bool AddToScope = true;
18592 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18593 TemplateParams, AddToScope);
18594 if (!ND) return nullptr;
18595
18596 assert(ND->getLexicalDeclContext() == CurContext);
18597
18598 // If we performed typo correction, we might have added a scope specifier
18599 // and changed the decl context.
18600 DC = ND->getDeclContext();
18601
18602 // Add the function declaration to the appropriate lookup tables,
18603 // adjusting the redeclarations list as necessary. We don't
18604 // want to do this yet if the friending class is dependent.
18605 //
18606 // Also update the scope-based lookup if the target context's
18607 // lookup context is in lexical scope.
18608 if (!CurContext->isDependentContext()) {
18609 DC = DC->getRedeclContext();
18611 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18612 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18613 }
18614
18616
18617 if (ND->isInvalidDecl())
18618 return ND;
18619
18620 if (DC->isRecord())
18622
18623 FunctionDecl *FD;
18624 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18625 FD = FTD->getTemplatedDecl();
18626 else
18627 FD = cast<FunctionDecl>(ND);
18628
18629 // C++ [class.friend]p6:
18630 // A function may be defined in a friend declaration of a class if and
18631 // only if the class is a non-local class, and the function name is
18632 // unqualified.
18633 if (D.isFunctionDefinition()) {
18634 // Qualified friend function definition.
18635 if (SS.isNotEmpty()) {
18637 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18638
18639 DB << SS.getScopeRep();
18640
18641 // Friend function defined in a local class.
18642 } else if (FunctionContainingLocalClass) {
18643 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18644
18645 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18646 // a template-id, the function name is not unqualified because these is
18647 // no name. While the wording requires some reading in-between the
18648 // lines, GCC, MSVC, and EDG all consider a friend function
18649 // specialization definitions to be de facto explicit specialization
18650 // and diagnose them as such.
18651 } else if (isTemplateId) {
18652 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18653 }
18654 }
18655
18656 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18657 // default argument expression, that declaration shall be a definition
18658 // and shall be the only declaration of the function or function
18659 // template in the translation unit.
18661 // We can't look at FD->getPreviousDecl() because it may not have been set
18662 // if we're in a dependent context. If the function is known to be a
18663 // redeclaration, we will have narrowed Previous down to the right decl.
18664 if (D.isRedeclaration()) {
18665 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18666 Diag(Previous.getRepresentativeDecl()->getLocation(),
18667 diag::note_previous_declaration);
18668 } else if (!D.isFunctionDefinition())
18669 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18670 }
18671
18674 if (TPL.size() > 0 && SS.isValid()) {
18675 if (CheckTemplateDeclScope(S, TPL.back()))
18676 return nullptr;
18677
18678 Friend =
18680 ND, DS.getFriendSpecLoc(), TPL);
18681 } else {
18683 DS.getFriendSpecLoc());
18684 }
18685
18686 Friend->setAccess(AS_public);
18687 CurContext->addDecl(Friend);
18688
18689 return ND;
18690}
18691
18693 StringLiteral *Message) {
18695
18696 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18697 if (!Fn) {
18698 Diag(DelLoc, diag::err_deleted_non_function);
18699 return;
18700 }
18701
18702 // Deleted function does not have a body.
18703 Fn->setWillHaveBody(false);
18704
18705 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18706 // Don't consider the implicit declaration we generate for explicit
18707 // specializations. FIXME: Do not generate these implicit declarations.
18708 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18709 Prev->getPreviousDecl()) &&
18710 !Prev->isDefined()) {
18711 Diag(DelLoc, diag::err_deleted_decl_not_first);
18712 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18713 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18714 : diag::note_previous_declaration);
18715 // We can't recover from this; the declaration might have already
18716 // been used.
18717 Fn->setInvalidDecl();
18718 return;
18719 }
18720
18721 // To maintain the invariant that functions are only deleted on their first
18722 // declaration, mark the implicitly-instantiated declaration of the
18723 // explicitly-specialized function as deleted instead of marking the
18724 // instantiated redeclaration.
18725 Fn = Fn->getCanonicalDecl();
18726 }
18727
18728 // dllimport/dllexport cannot be deleted.
18729 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18730 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18731 Fn->setInvalidDecl();
18732 }
18733
18734 // C++11 [basic.start.main]p3:
18735 // A program that defines main as deleted [...] is ill-formed.
18736 if (Fn->isMain())
18737 Diag(DelLoc, diag::err_deleted_main);
18738
18739 // C++11 [dcl.fct.def.delete]p4:
18740 // A deleted function is implicitly inline.
18741 Fn->setImplicitlyInline();
18742 Fn->setDeletedAsWritten(true, Message);
18743}
18744
18746 if (!Dcl || Dcl->isInvalidDecl())
18747 return;
18748
18749 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18750 if (!FD) {
18751 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18752 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18753 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18754 return;
18755 }
18756 }
18757
18758 Diag(DefaultLoc, diag::err_default_special_members)
18759 << getLangOpts().CPlusPlus20;
18760 return;
18761 }
18762
18763 // Reject if this can't possibly be a defaultable function.
18765 if (!DefKind &&
18766 // A dependent function that doesn't locally look defaultable can
18767 // still instantiate to a defaultable function if it's a constructor
18768 // or assignment operator.
18769 (!FD->isDependentContext() ||
18771 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18772 Diag(DefaultLoc, diag::err_default_special_members)
18773 << getLangOpts().CPlusPlus20;
18774 return;
18775 }
18776
18777 // Issue compatibility warning. We already warned if the operator is
18778 // 'operator<=>' when parsing the '<=>' token.
18779 if (DefKind.isComparison() &&
18781 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18782 ? diag::warn_cxx17_compat_defaulted_comparison
18783 : diag::ext_defaulted_comparison);
18784 }
18785
18786 FD->setDefaulted();
18787 FD->setExplicitlyDefaulted();
18788 FD->setDefaultLoc(DefaultLoc);
18789
18790 // Defer checking functions that are defaulted in a dependent context.
18791 if (FD->isDependentContext())
18792 return;
18793
18794 // Unset that we will have a body for this function. We might not,
18795 // if it turns out to be trivial, and we don't need this marking now
18796 // that we've marked it as defaulted.
18797 FD->setWillHaveBody(false);
18798
18799 if (DefKind.isComparison()) {
18800 // If this comparison's defaulting occurs within the definition of its
18801 // lexical class context, we have to do the checking when complete.
18802 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18803 if (!RD->isCompleteDefinition())
18804 return;
18805 }
18806
18807 // If this member fn was defaulted on its first declaration, we will have
18808 // already performed the checking in CheckCompletedCXXClass. Such a
18809 // declaration doesn't trigger an implicit definition.
18810 if (isa<CXXMethodDecl>(FD)) {
18811 const FunctionDecl *Primary = FD;
18812 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18813 // Ask the template instantiation pattern that actually had the
18814 // '= default' on it.
18815 Primary = Pattern;
18816 if (Primary->getCanonicalDecl()->isDefaulted())
18817 return;
18818 }
18819
18820 if (DefKind.isComparison()) {
18821 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18822 FD->setInvalidDecl();
18823 else
18824 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18825 } else {
18826 auto *MD = cast<CXXMethodDecl>(FD);
18827
18829 DefaultLoc))
18830 MD->setInvalidDecl();
18831 else
18832 DefineDefaultedFunction(*this, MD, DefaultLoc);
18833 }
18834}
18835
18837 for (Stmt *SubStmt : S->children()) {
18838 if (!SubStmt)
18839 continue;
18840 if (isa<ReturnStmt>(SubStmt))
18841 Self.Diag(SubStmt->getBeginLoc(),
18842 diag::err_return_in_constructor_handler);
18843 if (!isa<Expr>(SubStmt))
18844 SearchForReturnInStmt(Self, SubStmt);
18845 }
18846}
18847
18849 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18850 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18851 SearchForReturnInStmt(*this, Handler);
18852 }
18853}
18854
18856 StringLiteral *DeletedMessage) {
18857 switch (BodyKind) {
18858 case FnBodyKind::Delete:
18859 SetDeclDeleted(D, Loc, DeletedMessage);
18860 break;
18862 SetDeclDefaulted(D, Loc);
18863 break;
18864 case FnBodyKind::Other:
18865 llvm_unreachable(
18866 "Parsed function body should be '= delete;' or '= default;'");
18867 }
18868}
18869
18871 const CXXMethodDecl *Old) {
18872 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18873 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18874
18875 if (OldFT->hasExtParameterInfos()) {
18876 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18877 // A parameter of the overriding method should be annotated with noescape
18878 // if the corresponding parameter of the overridden method is annotated.
18879 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18880 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18881 Diag(New->getParamDecl(I)->getLocation(),
18882 diag::warn_overriding_method_missing_noescape);
18883 Diag(Old->getParamDecl(I)->getLocation(),
18884 diag::note_overridden_marked_noescape);
18885 }
18886 }
18887
18888 // SME attributes must match when overriding a function declaration.
18889 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18890 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18891 << New << New->getType() << Old->getType();
18892 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18893 return true;
18894 }
18895
18896 // Virtual overrides must have the same code_seg.
18897 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18898 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18899 if ((NewCSA || OldCSA) &&
18900 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18901 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18902 Diag(Old->getLocation(), diag::note_previous_declaration);
18903 return true;
18904 }
18905
18906 // Virtual overrides: check for matching effects.
18907 if (Context.hasAnyFunctionEffects()) {
18908 const auto OldFX = Old->getFunctionEffects();
18909 const auto NewFXOrig = New->getFunctionEffects();
18910
18911 if (OldFX != NewFXOrig) {
18912 FunctionEffectSet NewFX(NewFXOrig);
18913 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18915 for (const auto &Diff : Diffs) {
18916 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18918 break;
18920 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
18921 << Diff.effectName();
18922 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18923 << Old->getReturnTypeSourceRange();
18924 break;
18926 NewFX.insert(Diff.Old.value(), Errs);
18927 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18928 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18930 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18931 NewFT->getParamTypes(), EPI);
18932 New->setType(ModQT);
18933 if (Errs.empty()) {
18934 // A warning here is somewhat pedantic. Skip this if there was
18935 // already a merge conflict, which is more serious.
18936 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18937 << Diff.effectName();
18938 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18939 << Old->getReturnTypeSourceRange();
18940 }
18941 break;
18942 }
18943 }
18944 }
18945 if (!Errs.empty())
18946 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18947 Old->getLocation());
18948 }
18949 }
18950
18951 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18952
18953 // If the calling conventions match, everything is fine
18954 if (NewCC == OldCC)
18955 return false;
18956
18957 // If the calling conventions mismatch because the new function is static,
18958 // suppress the calling convention mismatch error; the error about static
18959 // function override (err_static_overrides_virtual from
18960 // Sema::CheckFunctionDeclaration) is more clear.
18961 if (New->getStorageClass() == SC_Static)
18962 return false;
18963
18964 Diag(New->getLocation(),
18965 diag::err_conflicting_overriding_cc_attributes)
18966 << New->getDeclName() << New->getType() << Old->getType();
18967 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18968 return true;
18969}
18970
18972 const CXXMethodDecl *Old) {
18973 // CWG2553
18974 // A virtual function shall not be an explicit object member function.
18975 if (!New->isExplicitObjectMemberFunction())
18976 return true;
18977 Diag(New->getParamDecl(0)->getBeginLoc(),
18978 diag::err_explicit_object_parameter_nonmember)
18979 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18980 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18981 New->setInvalidDecl();
18982 return false;
18983}
18984
18986 const CXXMethodDecl *Old) {
18987 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18988 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18989
18990 if (Context.hasSameType(NewTy, OldTy) ||
18991 NewTy->isDependentType() || OldTy->isDependentType())
18992 return false;
18993
18994 // Check if the return types are covariant
18995 QualType NewClassTy, OldClassTy;
18996
18997 /// Both types must be pointers or references to classes.
18998 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18999 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19000 NewClassTy = NewPT->getPointeeType();
19001 OldClassTy = OldPT->getPointeeType();
19002 }
19003 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19004 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19005 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19006 NewClassTy = NewRT->getPointeeType();
19007 OldClassTy = OldRT->getPointeeType();
19008 }
19009 }
19010 }
19011
19012 // The return types aren't either both pointers or references to a class type.
19013 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19014 Diag(New->getLocation(),
19015 diag::err_different_return_type_for_overriding_virtual_function)
19016 << New->getDeclName() << NewTy << OldTy
19017 << New->getReturnTypeSourceRange();
19018 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19019 << Old->getReturnTypeSourceRange();
19020
19021 return true;
19022 }
19023
19024 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
19025 // C++14 [class.virtual]p8:
19026 // If the class type in the covariant return type of D::f differs from
19027 // that of B::f, the class type in the return type of D::f shall be
19028 // complete at the point of declaration of D::f or shall be the class
19029 // type D.
19030 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19031 if (!RD->isBeingDefined() &&
19032 RequireCompleteType(New->getLocation(), NewClassTy,
19033 diag::err_covariant_return_incomplete,
19034 New->getDeclName()))
19035 return true;
19036 }
19037
19038 // Check if the new class derives from the old class.
19039 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
19040 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
19041 << New->getDeclName() << NewTy << OldTy
19042 << New->getReturnTypeSourceRange();
19043 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19044 << Old->getReturnTypeSourceRange();
19045 return true;
19046 }
19047
19048 // Check if we the conversion from derived to base is valid.
19050 NewClassTy, OldClassTy,
19051 diag::err_covariant_return_inaccessible_base,
19052 diag::err_covariant_return_ambiguous_derived_to_base_conv,
19053 New->getLocation(), New->getReturnTypeSourceRange(),
19054 New->getDeclName(), nullptr)) {
19055 // FIXME: this note won't trigger for delayed access control
19056 // diagnostics, and it's impossible to get an undelayed error
19057 // here from access control during the original parse because
19058 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19059 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19060 << Old->getReturnTypeSourceRange();
19061 return true;
19062 }
19063 }
19064
19065 // The qualifiers of the return types must be the same.
19066 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19067 Diag(New->getLocation(),
19068 diag::err_covariant_return_type_different_qualifications)
19069 << New->getDeclName() << NewTy << OldTy
19070 << New->getReturnTypeSourceRange();
19071 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19072 << Old->getReturnTypeSourceRange();
19073 return true;
19074 }
19075
19076
19077 // The new class type must have the same or less qualifiers as the old type.
19078 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
19079 Diag(New->getLocation(),
19080 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19081 << New->getDeclName() << NewTy << OldTy
19082 << New->getReturnTypeSourceRange();
19083 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19084 << Old->getReturnTypeSourceRange();
19085 return true;
19086 }
19087
19088 return false;
19089}
19090
19092 SourceLocation EndLoc = InitRange.getEnd();
19093 if (EndLoc.isValid())
19094 Method->setRangeEnd(EndLoc);
19095
19096 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19097 Method->setIsPureVirtual();
19098 return false;
19099 }
19100
19101 if (!Method->isInvalidDecl())
19102 Diag(Method->getLocation(), diag::err_non_virtual_pure)
19103 << Method->getDeclName() << InitRange;
19104 return true;
19105}
19106
19108 if (D->getFriendObjectKind())
19109 Diag(D->getLocation(), diag::err_pure_friend);
19110 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19111 CheckPureMethod(M, ZeroLoc);
19112 else
19113 Diag(D->getLocation(), diag::err_illegal_initializer);
19114}
19115
19116/// Invoked when we are about to parse an initializer for the declaration
19117/// 'Dcl'.
19118///
19119/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19120/// static data member of class X, names should be looked up in the scope of
19121/// class X. If the declaration had a scope specifier, a scope will have
19122/// been created and passed in for this purpose. Otherwise, S will be null.
19124 assert(D && !D->isInvalidDecl());
19125
19126 // We will always have a nested name specifier here, but this declaration
19127 // might not be out of line if the specifier names the current namespace:
19128 // extern int n;
19129 // int ::n = 0;
19130 if (S && D->isOutOfLine())
19132
19136}
19137
19139 assert(D);
19140
19141 if (S && D->isOutOfLine())
19143
19145}
19146
19148 // C++ 6.4p2:
19149 // The declarator shall not specify a function or an array.
19150 // The type-specifier-seq shall not contain typedef and shall not declare a
19151 // new class or enumeration.
19153 "Parser allowed 'typedef' as storage class of condition decl.");
19154
19155 Decl *Dcl = ActOnDeclarator(S, D);
19156 if (!Dcl)
19157 return true;
19158
19159 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19160 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19161 << D.getSourceRange();
19162 return true;
19163 }
19164
19165 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19166 VD->setCXXCondDecl();
19167
19168 return Dcl;
19169}
19170
19172 if (!ExternalSource)
19173 return;
19174
19176 ExternalSource->ReadUsedVTables(VTables);
19178 for (const ExternalVTableUse &VTable : VTables) {
19179 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19180 VTablesUsed.find(VTable.Record);
19181 // Even if a definition wasn't required before, it may be required now.
19182 if (Pos != VTablesUsed.end()) {
19183 if (!Pos->second && VTable.DefinitionRequired)
19184 Pos->second = true;
19185 continue;
19186 }
19187
19188 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19189 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
19190 }
19191
19192 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19193}
19194
19196 bool DefinitionRequired) {
19197 // Ignore any vtable uses in unevaluated operands or for classes that do
19198 // not have a vtable.
19199 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19200 CurContext->isDependentContext() || isUnevaluatedContext())
19201 return;
19202 // Do not mark as used if compiling for the device outside of the target
19203 // region.
19204 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19205 !OpenMP().isInOpenMPDeclareTargetContext() &&
19206 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19207 if (!DefinitionRequired)
19209 return;
19210 }
19211
19212 // Try to insert this class into the map.
19214 Class = Class->getCanonicalDecl();
19215 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19216 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19217 if (!Pos.second) {
19218 // If we already had an entry, check to see if we are promoting this vtable
19219 // to require a definition. If so, we need to reappend to the VTableUses
19220 // list, since we may have already processed the first entry.
19221 if (DefinitionRequired && !Pos.first->second) {
19222 Pos.first->second = true;
19223 } else {
19224 // Otherwise, we can early exit.
19225 return;
19226 }
19227 } else {
19228 // The Microsoft ABI requires that we perform the destructor body
19229 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19230 // the deleting destructor is emitted with the vtable, not with the
19231 // destructor definition as in the Itanium ABI.
19232 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19233 CXXDestructorDecl *DD = Class->getDestructor();
19234 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19235 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19236 // If this is an out-of-line declaration, marking it referenced will
19237 // not do anything. Manually call CheckDestructor to look up operator
19238 // delete().
19239 ContextRAII SavedContext(*this, DD);
19240 CheckDestructor(DD);
19241 if (!DD->getOperatorDelete())
19242 DD->setInvalidDecl();
19243 } else {
19244 MarkFunctionReferenced(Loc, Class->getDestructor());
19245 }
19246 }
19247 }
19248 }
19249
19250 // Local classes need to have their virtual members marked
19251 // immediately. For all other classes, we mark their virtual members
19252 // at the end of the translation unit.
19253 if (Class->isLocalClass())
19254 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19255 else
19256 VTableUses.push_back(std::make_pair(Class, Loc));
19257}
19258
19261 if (VTableUses.empty())
19262 return false;
19263
19264 // Note: The VTableUses vector could grow as a result of marking
19265 // the members of a class as "used", so we check the size each
19266 // time through the loop and prefer indices (which are stable) to
19267 // iterators (which are not).
19268 bool DefinedAnything = false;
19269 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19270 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19271 if (!Class)
19272 continue;
19274 Class->getTemplateSpecializationKind();
19275
19276 SourceLocation Loc = VTableUses[I].second;
19277
19278 bool DefineVTable = true;
19279
19280 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19281 // V-tables for non-template classes with an owning module are always
19282 // uniquely emitted in that module.
19283 if (Class->isInCurrentModuleUnit()) {
19284 DefineVTable = true;
19285 } else if (KeyFunction && !KeyFunction->hasBody()) {
19286 // If this class has a key function, but that key function is
19287 // defined in another translation unit, we don't need to emit the
19288 // vtable even though we're using it.
19289 // The key function is in another translation unit.
19290 DefineVTable = false;
19292 KeyFunction->getTemplateSpecializationKind();
19295 "Instantiations don't have key functions");
19296 (void)TSK;
19297 } else if (!KeyFunction) {
19298 // If we have a class with no key function that is the subject
19299 // of an explicit instantiation declaration, suppress the
19300 // vtable; it will live with the explicit instantiation
19301 // definition.
19302 bool IsExplicitInstantiationDeclaration =
19304 for (auto *R : Class->redecls()) {
19306 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19308 IsExplicitInstantiationDeclaration = true;
19309 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19310 IsExplicitInstantiationDeclaration = false;
19311 break;
19312 }
19313 }
19314
19315 if (IsExplicitInstantiationDeclaration) {
19316 const bool HasExcludeFromExplicitInstantiation =
19317 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
19318 // If the class has a member function declared with
19319 // `__attribute__((exclude_from_explicit_instantiation))`, the
19320 // explicit instantiation declaration should not suppress emitting
19321 // the vtable, since the corresponding explicit instantiation
19322 // definition might not emit the vtable if a triggering method is
19323 // excluded.
19324 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19325 });
19326 if (!HasExcludeFromExplicitInstantiation)
19327 DefineVTable = false;
19328 }
19329 }
19330
19331 // The exception specifications for all virtual members may be needed even
19332 // if we are not providing an authoritative form of the vtable in this TU.
19333 // We may choose to emit it available_externally anyway.
19334 if (!DefineVTable) {
19336 continue;
19337 }
19338
19339 // Mark all of the virtual members of this class as referenced, so
19340 // that we can build a vtable. Then, tell the AST consumer that a
19341 // vtable for this class is required.
19342 DefinedAnything = true;
19344 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19345 // The vtable is assumed to be emitted in an external source only for
19346 // classes attached to a named module, which is guaranteed to have an object
19347 // file. This isn't true for -fmodules-debuginfo, which still has
19348 // shouldEmitInExternalSource as true so that debug info gets supressed.
19349 if (VTablesUsed[Canonical] &&
19350 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19351 Consumer.HandleVTable(Class);
19352
19353 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19354 // no key function or the key function is inlined. Don't warn in C++ ABIs
19355 // that lack key functions, since the user won't be able to make one.
19356 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19357 Class->isExternallyVisible() &&
19358 !(Class->getOwningModule() &&
19359 Class->getOwningModule()->isInterfaceOrPartition()) &&
19360 ClassTSK != TSK_ImplicitInstantiation &&
19363 const FunctionDecl *KeyFunctionDef = nullptr;
19364 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19365 KeyFunctionDef->isInlined()))
19366 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19367 }
19368 }
19369 VTableUses.clear();
19370
19371 return DefinedAnything;
19372}
19373
19375 const CXXRecordDecl *RD) {
19376 for (const auto *I : RD->methods())
19377 if (I->isVirtual() && !I->isPureVirtual())
19378 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19379}
19380
19382 const CXXRecordDecl *RD,
19383 bool ConstexprOnly) {
19384 // Mark all functions which will appear in RD's vtable as used.
19385 CXXFinalOverriderMap FinalOverriders;
19386 RD->getFinalOverriders(FinalOverriders);
19387 for (const auto &FinalOverrider : FinalOverriders) {
19388 for (const auto &OverridingMethod : FinalOverrider.second) {
19389 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19390 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19391
19392 // C++ [basic.def.odr]p2:
19393 // [...] A virtual member function is used if it is not pure. [...]
19394 if (!Overrider->isPureVirtual() &&
19395 (!ConstexprOnly || Overrider->isConstexpr()))
19396 MarkFunctionReferenced(Loc, Overrider);
19397 }
19398 }
19399
19400 // Only classes that have virtual bases need a VTT.
19401 if (RD->getNumVBases() == 0)
19402 return;
19403
19404 for (const auto &I : RD->bases()) {
19405 const auto *Base = I.getType()->castAsCXXRecordDecl();
19406 if (Base->getNumVBases() == 0)
19407 continue;
19409 }
19410}
19411
19412static
19417 Sema &S) {
19418 if (Ctor->isInvalidDecl())
19419 return;
19420
19422
19423 // Target may not be determinable yet, for instance if this is a dependent
19424 // call in an uninstantiated template.
19425 if (Target) {
19426 const FunctionDecl *FNTarget = nullptr;
19427 (void)Target->hasBody(FNTarget);
19428 Target = const_cast<CXXConstructorDecl*>(
19429 cast_or_null<CXXConstructorDecl>(FNTarget));
19430 }
19431
19432 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19433 // Avoid dereferencing a null pointer here.
19434 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19435
19436 if (!Current.insert(Canonical).second)
19437 return;
19438
19439 // We know that beyond here, we aren't chaining into a cycle.
19440 if (!Target || !Target->isDelegatingConstructor() ||
19441 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19442 Valid.insert_range(Current);
19443 Current.clear();
19444 // We've hit a cycle.
19445 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19446 Current.count(TCanonical)) {
19447 // If we haven't diagnosed this cycle yet, do so now.
19448 if (!Invalid.count(TCanonical)) {
19449 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19450 diag::warn_delegating_ctor_cycle)
19451 << Ctor;
19452
19453 // Don't add a note for a function delegating directly to itself.
19454 if (TCanonical != Canonical)
19455 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19456
19458 while (C->getCanonicalDecl() != Canonical) {
19459 const FunctionDecl *FNTarget = nullptr;
19460 (void)C->getTargetConstructor()->hasBody(FNTarget);
19461 assert(FNTarget && "Ctor cycle through bodiless function");
19462
19463 C = const_cast<CXXConstructorDecl*>(
19464 cast<CXXConstructorDecl>(FNTarget));
19465 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19466 }
19467 }
19468
19469 Invalid.insert_range(Current);
19470 Current.clear();
19471 } else {
19473 }
19474}
19475
19476
19479
19480 for (DelegatingCtorDeclsType::iterator
19481 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19482 E = DelegatingCtorDecls.end();
19483 I != E; ++I)
19484 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19485
19486 for (CXXConstructorDecl *CI : Invalid)
19487 CI->setInvalidDecl();
19488}
19489
19490namespace {
19491 /// AST visitor that finds references to the 'this' expression.
19492class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19493 Sema &S;
19494
19495public:
19496 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19497
19498 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19499 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19500 << E->isImplicit();
19501 return false;
19502 }
19503};
19504}
19505
19507 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19508 if (!TSInfo)
19509 return false;
19510
19511 TypeLoc TL = TSInfo->getTypeLoc();
19513 if (!ProtoTL)
19514 return false;
19515
19516 // C++11 [expr.prim.general]p3:
19517 // [The expression this] shall not appear before the optional
19518 // cv-qualifier-seq and it shall not appear within the declaration of a
19519 // static member function (although its type and value category are defined
19520 // within a static member function as they are within a non-static member
19521 // function). [ Note: this is because declaration matching does not occur
19522 // until the complete declarator is known. - end note ]
19523 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19524 FindCXXThisExpr Finder(*this);
19525
19526 // If the return type came after the cv-qualifier-seq, check it now.
19527 if (Proto->hasTrailingReturn() &&
19528 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19529 return true;
19530
19531 // Check the exception specification.
19533 return true;
19534
19535 // Check the trailing requires clause
19536 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19537 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19538 return true;
19539
19541}
19542
19544 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19545 if (!TSInfo)
19546 return false;
19547
19548 TypeLoc TL = TSInfo->getTypeLoc();
19550 if (!ProtoTL)
19551 return false;
19552
19553 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19554 FindCXXThisExpr Finder(*this);
19555
19556 switch (Proto->getExceptionSpecType()) {
19557 case EST_Unparsed:
19558 case EST_Uninstantiated:
19559 case EST_Unevaluated:
19560 case EST_BasicNoexcept:
19561 case EST_NoThrow:
19562 case EST_DynamicNone:
19563 case EST_MSAny:
19564 case EST_None:
19565 break;
19566
19568 case EST_NoexceptFalse:
19569 case EST_NoexceptTrue:
19570 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19571 return true;
19572 [[fallthrough]];
19573
19574 case EST_Dynamic:
19575 for (const auto &E : Proto->exceptions()) {
19576 if (!Finder.TraverseType(E))
19577 return true;
19578 }
19579 break;
19580 }
19581
19582 return false;
19583}
19584
19586 FindCXXThisExpr Finder(*this);
19587
19588 // Check attributes.
19589 for (const auto *A : Method->attrs()) {
19590 // FIXME: This should be emitted by tblgen.
19591 Expr *Arg = nullptr;
19592 ArrayRef<Expr *> Args;
19593 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19594 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19595 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19596 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19597 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19598 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19599 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19600 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19601 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19602 Arg = LR->getArg();
19603 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19604 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19605 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19606 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19607 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19608 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19609 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19610 Arg = AC->getSuccessValue();
19611 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19612 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19613 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19614
19615 if (Arg && !Finder.TraverseStmt(Arg))
19616 return true;
19617
19618 for (Expr *A : Args) {
19619 if (!Finder.TraverseStmt(A))
19620 return true;
19621 }
19622 }
19623
19624 return false;
19625}
19626
19628 bool IsTopLevel, ExceptionSpecificationType EST,
19629 ArrayRef<ParsedType> DynamicExceptions,
19630 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19631 SmallVectorImpl<QualType> &Exceptions,
19633 Exceptions.clear();
19634 ESI.Type = EST;
19635 if (EST == EST_Dynamic) {
19636 Exceptions.reserve(DynamicExceptions.size());
19637 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19638 // FIXME: Preserve type source info.
19639 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19640
19641 if (IsTopLevel) {
19643 collectUnexpandedParameterPacks(ET, Unexpanded);
19644 if (!Unexpanded.empty()) {
19646 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19647 Unexpanded);
19648 continue;
19649 }
19650 }
19651
19652 // Check that the type is valid for an exception spec, and
19653 // drop it if not.
19654 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19655 Exceptions.push_back(ET);
19656 }
19657 ESI.Exceptions = Exceptions;
19658 return;
19659 }
19660
19661 if (isComputedNoexcept(EST)) {
19662 assert((NoexceptExpr->isTypeDependent() ||
19663 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19664 Context.BoolTy) &&
19665 "Parser should have made sure that the expression is boolean");
19666 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19667 ESI.Type = EST_BasicNoexcept;
19668 return;
19669 }
19670
19671 ESI.NoexceptExpr = NoexceptExpr;
19672 return;
19673 }
19674}
19675
19677 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19678 ArrayRef<ParsedType> DynamicExceptions,
19679 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19680 if (!D)
19681 return;
19682
19683 // Dig out the function we're referring to.
19684 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19685 D = FTD->getTemplatedDecl();
19686
19687 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19688 if (!FD)
19689 return;
19690
19691 // Check the exception specification.
19694 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19695 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19696 ESI);
19697
19698 // Update the exception specification on the function type.
19699 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19700
19701 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19702 if (MD->isStatic())
19704
19705 if (MD->isVirtual()) {
19706 // Check overrides, which we previously had to delay.
19707 for (const CXXMethodDecl *O : MD->overridden_methods())
19709 }
19710 }
19711}
19712
19713/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19714///
19716 SourceLocation DeclStart, Declarator &D,
19717 Expr *BitWidth,
19718 InClassInitStyle InitStyle,
19719 AccessSpecifier AS,
19720 const ParsedAttr &MSPropertyAttr) {
19721 const IdentifierInfo *II = D.getIdentifier();
19722 if (!II) {
19723 Diag(DeclStart, diag::err_anonymous_property);
19724 return nullptr;
19725 }
19727
19729 QualType T = TInfo->getType();
19730 if (getLangOpts().CPlusPlus) {
19732
19735 D.setInvalidType();
19736 T = Context.IntTy;
19737 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19738 }
19739 }
19740
19742
19744 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19745 << getLangOpts().CPlusPlus17;
19748 diag::err_invalid_thread)
19750
19751 // Check to see if this name was declared as a member previously
19752 NamedDecl *PrevDecl = nullptr;
19753 LookupResult Previous(*this, II, Loc, LookupMemberName,
19755 LookupName(Previous, S);
19756 switch (Previous.getResultKind()) {
19759 PrevDecl = Previous.getAsSingle<NamedDecl>();
19760 break;
19761
19763 PrevDecl = Previous.getRepresentativeDecl();
19764 break;
19765
19769 break;
19770 }
19771
19772 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19773 // Maybe we will complain about the shadowed template parameter.
19775 // Just pretend that we didn't see the previous declaration.
19776 PrevDecl = nullptr;
19777 }
19778
19779 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19780 PrevDecl = nullptr;
19781
19782 SourceLocation TSSL = D.getBeginLoc();
19783 MSPropertyDecl *NewPD =
19784 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19785 MSPropertyAttr.getPropertyDataGetter(),
19786 MSPropertyAttr.getPropertyDataSetter());
19787 ProcessDeclAttributes(TUScope, NewPD, D);
19788 NewPD->setAccess(AS);
19789
19790 if (NewPD->isInvalidDecl())
19791 Record->setInvalidDecl();
19792
19794 NewPD->setModulePrivate();
19795
19796 if (NewPD->isInvalidDecl() && PrevDecl) {
19797 // Don't introduce NewFD into scope; there's already something
19798 // with the same name in the same scope.
19799 } else if (II) {
19800 PushOnScopeChains(NewPD, S);
19801 } else
19802 Record->addDecl(NewPD);
19803
19804 return NewPD;
19805}
19806
19808 Declarator &Declarator, unsigned TemplateParameterDepth) {
19809 auto &Info = InventedParameterInfos.emplace_back();
19810 TemplateParameterList *ExplicitParams = nullptr;
19811 ArrayRef<TemplateParameterList *> ExplicitLists =
19813 if (!ExplicitLists.empty()) {
19814 bool IsMemberSpecialization, IsInvalid;
19817 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19818 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19819 /*SuppressDiagnostic=*/true);
19820 }
19821 // C++23 [dcl.fct]p23:
19822 // An abbreviated function template can have a template-head. The invented
19823 // template-parameters are appended to the template-parameter-list after
19824 // the explicitly declared template-parameters.
19825 //
19826 // A template-head must have one or more template-parameters (read:
19827 // 'template<>' is *not* a template-head). Only append the invented
19828 // template parameters if we matched the nested-name-specifier to a non-empty
19829 // TemplateParameterList.
19830 if (ExplicitParams && !ExplicitParams->empty()) {
19831 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19832 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19833 Info.NumExplicitTemplateParams = ExplicitParams->size();
19834 } else {
19835 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19836 Info.NumExplicitTemplateParams = 0;
19837 }
19838}
19839
19841 auto &FSI = InventedParameterInfos.back();
19842 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19843 if (FSI.NumExplicitTemplateParams != 0) {
19844 TemplateParameterList *ExplicitParams =
19848 Context, ExplicitParams->getTemplateLoc(),
19849 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19850 ExplicitParams->getRAngleLoc(),
19851 ExplicitParams->getRequiresClause()));
19852 } else {
19855 FSI.TemplateParams, Declarator.getEndLoc(),
19856 /*RequiresClause=*/nullptr));
19857 }
19858 }
19859 InventedParameterInfos.pop_back();
19860}
19861
19863 CXXConstructorDecl *Ctor, bool IsCopy) {
19864 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
19865
19866 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
19867 // If we build args for default constructor closures, those will have
19868 // been generated *before* building args for any copy constructor closures.
19869 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
19870 return false;
19871 }
19872
19873 unsigned NumParams = Ctor->getNumParams();
19874 if (NumParams == 0)
19875 return false;
19876
19877 CXXDefaultArgExpr **Args =
19878 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
19879
19880 if (IsCopy)
19881 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
19882
19883 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
19884 ExprResult R = BuildCXXDefaultArgExpr(Loc, Ctor, Ctor->getParamDecl(I));
19886 if (R.isInvalid())
19887 return true;
19888 Args[I] = cast<CXXDefaultArgExpr>(R.get());
19889 }
19890
19891 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
19892 return false;
19893}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
static bool DeduceTemplateArguments(Sema &S, TemplateParameterList *TPL, TemplateDecl *TD, ArrayRef< TemplateArgument > PatternArgs, ArrayRef< TemplateArgument > Args, TemplateDeductionInfo &Info, TemplateSpecCandidateSet *FailedTSC, bool CopyDeducedArgs)
This file declares semantic analysis for CUDA constructs.
static void DiagnoseUnsatisfiedConstraint(Sema &S, ArrayRef< UnsatisfiedConstraintRecord > Records, SourceLocation Loc, bool First=true, concepts::NestedRequirement *Req=nullptr)
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static CXXDestructorDecl * LookupDestructorIfRelevant(Sema &S, CXXRecordDecl *Class)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef, const FunctionDecl *FD, bool *WasMalformed)
static bool RefersToRValueRef(Expr *MemRef)
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallPtrSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
#define CheckPolymorphic(Type)
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, unsigned &OutSize)
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef, const FunctionDecl *FD)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message, ResultType &Result, ASTContext &Ctx, Sema::StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD, QualType TypeParam, SourceLocation Loc)
AllocationOperatorKind
static NamespaceDecl * getNamespaceDecl(NamespaceBaseDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static bool isDestroyingDeleteT(QualType Type)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool IsUnusedPrivateField(const FieldDecl *FD)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, unsigned NumElems)
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static bool HasAttribute(const QualType &T)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind, CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static ClassTemplateDecl * LookupStdClassTemplate(Sema &S, SourceLocation Loc, const char *ClassName, bool *WasMalformed)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType, ArrayRef< BindingDecl * > Bindings, unsigned MemberCount)
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location, FieldDecl *Field)
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg, const char *ClassName, ClassTemplateDecl **CachedDecl, const Decl **MalformedDecl)
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location, CXXRecordDecl *ClassDecl)
static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc, const CXXRecordDecl *OrigRD, QualType DecompType, DeclAccessPair BasePair)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:809
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:805
const LangOptions & getLangOpts() const
Definition ASTContext.h:962
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:858
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType BuiltinFnTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:924
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition DeclCXX.h:117
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
TypeLoc getElementLoc() const
Definition TypeLoc.h:1807
QualType getElementType() const
Definition TypeBase.h:3798
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:99
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3517
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3595
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3514
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3587
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3523
Expr * getLHS() const
Definition Expr.h:4094
Expr * getRHS() const
Definition Expr.h:4096
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:5104
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4089
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2149
A binding in a decomposition declaration.
Definition DeclCXX.h:4206
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3705
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:4244
void setDecomposedDecl(ValueDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4250
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6675
Wrapper for source info for block pointers.
Definition TypeLoc.h:1526
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Kind getKind() const
Definition TypeBase.h:3276
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const CXXRecordDecl * getOrigin() const
Retrieve the type from which this base-paths search began.
CXXBasePath & front()
bool isRecordingPaths() const
Whether we are recording paths.
void setRecordingPaths(bool RP)
Specify whether we should be recording paths or not.
void setOrigin(const CXXRecordDecl *Rec)
void clear()
Clear the base-paths results.
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition ExprCXX.cpp:1187
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
bool isImmediateEscalating() const
Definition ExprCXX.h:1710
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2873
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:3061
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2727
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:3038
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:3056
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3047
void setCtorClosureDefaultArgs(ArrayRef< CXXDefaultArgExpr * > Args)
Definition DeclCXX.cpp:3141
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2868
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3016
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs() const
Definition DeclCXX.cpp:3137
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclCXX.h:2705
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3004
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2570
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2964
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2951
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2478
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2532
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2544
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3156
const FunctionDecl * getOperatorDelete() const
Definition DeclCXX.cpp:3228
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:748
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
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:2717
bool isVirtual() const
Definition DeclCXX.h:2200
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2502
unsigned getNumExplicitParams() const
Definition DeclCXX.h:2312
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2261
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2826
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2820
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2810
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isInstance() const
Definition DeclCXX.h:2172
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2749
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2308
bool isStatic() const
Definition DeclCXX.cpp:2415
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition DeclCXX.h:1281
friend_range friends() const
Definition DeclFriend.h:181
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1352
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:611
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1251
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1679
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1377
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1006
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:822
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:714
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1431
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1402
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1381
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:706
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.cpp:1506
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:965
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1367
base_class_range bases()
Definition DeclCXX.h:608
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:604
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1023
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1312
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:766
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:894
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:913
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
method_range methods() const
Definition DeclCXX.h:650
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:935
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1740
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1274
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1289
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:977
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:599
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1219
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:697
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1293
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:730
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2060
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1339
base_class_range vbases()
Definition DeclCXX.h:625
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
ctor_range ctors() const
Definition DeclCXX.h:670
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:869
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1226
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1241
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:860
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1153
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:800
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1413
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1304
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1205
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:794
bool hasDefinition() const
Definition DeclCXX.h:561
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:919
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1012
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2052
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:905
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2152
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:999
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2127
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1391
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1018
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1425
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1754
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:807
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:555
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:848
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:987
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:928
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1317
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition DeclCXX.h:950
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
Represents the this expression in C++.
Definition ExprCXX.h:1158
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1178
bool isImplicit() const
Definition ExprCXX.h:1181
SourceLocation getLocation() const
Definition ExprCXX.h:1175
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h: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:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
bool isCallToStdMove() const
Definition Expr.cpp:3651
Expr * getCallee()
Definition Expr.h:3096
arg_range arguments()
Definition Expr.h:3201
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3726
Expr * getSubExpr()
Definition Expr.h:3732
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
QualType getElementType() const
Definition TypeBase.h:3349
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
body_range body()
Definition Stmt.h:1813
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:399
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3698
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3762
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3496
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:5344
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
The results of name lookup within a DeclContext.
Definition DeclBase.h:1399
DeclListNode::iterator iterator
Definition DeclBase.h:1409
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2410
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2255
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2595
bool isFileContext() const
Definition DeclBase.h:2197
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2202
bool isRecord() const
Definition DeclBase.h:2206
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_iterator decls_end() const
Definition DeclBase.h:2392
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2390
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:494
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getBeginLoc() const
Definition Expr.h:1355
bool isImmediateEscalating() const
Definition Expr.h:1484
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
bool isModulePrivateSpecified() const
Definition DeclSpec.h:836
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:698
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:545
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
TST getTypeSpecType() const
Definition DeclSpec.h:522
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:834
ParsedType getRepAsType() const
Definition DeclSpec.h:532
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:832
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:662
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
TypeSpecifierType TST
Definition DeclSpec.h:250
bool SetTypeQual(TQ T, SourceLocation Loc)
void ClearConstexprSpec()
Definition DeclSpec.h:848
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:496
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
static const TST TST_auto
Definition DeclSpec.h:291
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
decl_range decls()
Definition Stmt.h:1689
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1667
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1078
bool isInStdNamespace() const
Definition DeclBase.cpp:450
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:591
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1236
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2810
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:596
unsigned getIdentifierNamespace() const
Definition DeclBase.h:906
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1186
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
void setLocalOwningModule(Module *M)
Definition DeclBase.h:841
void setImplicit(bool I=true)
Definition DeclBase.h:602
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Definition DeclBase.h:229
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:898
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2003
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:862
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition DeclSpec.cpp:296
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2562
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2391
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2463
bool hasGroupingParens() const
Definition DeclSpec.h:2771
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
bool isRedeclaration() const
Definition DeclSpec.h:2817
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2120
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
bool isFunctionDefinition() const
Definition DeclSpec.h:2789
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2701
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2708
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2263
bool isInvalidType() const
Definition DeclSpec.h:2766
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2378
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
A decomposition declaration.
Definition DeclCXX.h:4270
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4308
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1840
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1880
SourceRange getSourceRange() const
Definition DeclSpec.h:1888
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1886
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:961
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5892
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:3458
Represents an enum.
Definition Decl.h:4046
enumerator_range enumerators() const
Definition Decl.h:4192
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
const Expr * getExpr() const
Definition DeclCXX.h:1953
void setExpr(Expr *E)
Definition DeclCXX.h:1978
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1977
This represents one expression.
Definition Expr.h:112
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:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
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:3262
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3195
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3295
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4722
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3375
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4712
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3369
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4732
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3431
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3442
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3301
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition Diagnostic.h:118
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:105
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:45
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={})
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, FriendUnion Friend, SourceLocation FriendLoc, ArrayRef< TemplateParameterList * > FriendTypeTPLists={}, SourceLocation EllipsisLoc={})
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3117
Represents a function declaration or definition.
Definition Decl.h:2027
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2673
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2828
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3256
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:2900
bool isTrivialForCall() const
Definition Decl.h:2407
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2503
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3171
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3824
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4170
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2341
bool isImmediateFunction() const
Definition Decl.cpp:3317
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3137
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4001
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3528
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3842
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2952
SourceLocation getDefaultLoc() const
Definition Decl.h:2425
QualType getReturnType() const
Definition Decl.h:2876
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2805
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2416
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2404
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4290
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2813
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3724
param_iterator param_begin()
Definition Decl.h:2817
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2854
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3110
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2353
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2567
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2513
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4306
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3169
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4234
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2919
void setTrivial(bool IT)
Definition Decl.h:2405
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4121
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2497
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2669
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2380
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3595
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3288
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3532
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3536
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3540
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2412
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4546
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2964
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4107
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2500
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4394
void setDefaulted(bool D=true)
Definition Decl.h:2413
bool isConsteval() const
Definition Decl.h:2509
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2437
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:2893
void setBody(Stmt *B)
Definition Decl.cpp:3268
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2371
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3856
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3803
size_t param_size() const
Definition Decl.h:2821
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2238
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3176
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:3223
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2836
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2716
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5307
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5809
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1809
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5875
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5678
unsigned getNumParams() const
Definition TypeBase.h:5649
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5791
const QualType * param_type_iterator
Definition TypeBase.h:5809
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5736
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5825
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5840
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Wrapper for source info for functions.
Definition TypeLoc.h:1644
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4790
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2269
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1737
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3502
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3523
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2604
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2616
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5305
unsigned getNumInits() const
Definition Expr.h:5338
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
child_range children()
Definition Expr.h:5501
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeMemberImplicit(FieldDecl *Member)
Create the initialization entity for a member subobject with implicit field initializer.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1365
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1378
@ Default
Use default layout rules of the target.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1074
Represents a linkage specification.
Definition DeclCXX.h:3036
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3311
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:3078
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition Lookup.h:358
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4365
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3780
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
Wrapper for source info for member pointers.
Definition TypeLoc.h:1544
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:950
bool isExplicitGlobalModule() const
Definition Module.h:441
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
Represents a C++ namespace alias.
Definition DeclCXX.h:3222
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3412
Represents C++ namespaces and their aliases.
Definition Decl.h:573
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3349
Represent a C++ namespace.
Definition Decl.h:592
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:648
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3372
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition Decl.h:675
void setRBraceLoc(SourceLocation L)
Definition Decl.h:694
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition ObjCRuntime.h:97
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4976
Represents a parameter to a function.
Definition Decl.h:1817
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:2999
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1958
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1946
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3004
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3024
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1850
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1950
bool hasInheritedDefaultArg() const
Definition Decl.h:1962
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:2934
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3029
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3035
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1966
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2957
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
IdentifierInfo * getPropertyDataSetter() const
Definition ParsedAttr.h:470
IdentifierInfo * getPropertyDataGetter() const
Definition ParsedAttr.h:464
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:903
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
bool isAddressDiscriminated() const
Definition TypeBase.h:265
Wrapper for source info for pointers.
Definition TypeLoc.h:1513
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6879
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1472
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1240
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1457
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2792
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8612
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
void removeAddressSpace()
Definition TypeBase.h:596
void removeVolatile()
Definition TypeBase.h:469
LangAS getAddressSpace() const
Definition TypeBase.h:571
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3699
Represents a struct/union/class.
Definition Decl.h:4360
bool hasFlexibleArrayMember() const
Definition Decl.h:4393
bool hasObjectMember() const
Definition Decl.h:4420
field_iterator field_end() const
Definition Decl.h:4566
field_range fields() const
Definition Decl.h:4563
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4560
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4548
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4412
bool field_empty() const
Definition Decl.h:4571
field_iterator field_begin() const
Definition Decl.cpp:5272
RedeclarableTemplateDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5365
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
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:391
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
void AddDecl(Decl *D)
Definition Scope.h:344
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:380
void RemoveDecl(Decl *D)
Definition Scope.h:352
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:383
Scope * getDeclParent()
Definition Scope.h:317
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void PushUsingDirective(UsingDirectiveDecl *UDir)
Definition Scope.h:635
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
A RAII object to enter scope of a compound statement.
Definition Sema.h:1316
A RAII object to temporarily push a declaration context.
Definition Sema.h:3531
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6443
DefaultedComparisonKind asComparison() const
Definition Sema.h:6475
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6472
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5541
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
Definition Sema.h:5583
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:9373
CXXMethodDecl * getMethod() const
Definition Sema.h:9385
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13628
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7798
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13155
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:6632
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',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6394
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9442
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9450
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9438
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
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:417
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc)
Definition Sema.h:13773
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1534
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6369
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1263
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition Sema.h:6605
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:6586
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1474
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7919
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ AR_dependent
Definition Sema.h:1689
@ AR_accessible
Definition Sema.h:1687
@ AR_inaccessible
Definition Sema.h:1688
@ AR_delayed
Definition Sema.h:1690
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:2428
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)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
Definition Sema.h:4203
@ Default
= default ;
Definition Sema.h:4205
@ Delete
deleted-function-body
Definition Sema.h:4211
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:49
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2078
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, DeclarationName Name)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1309
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:937
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition Sema.h:1519
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void CleanupVarDeclMarking()
ASTContext & getASTContext() const
Definition Sema.h:940
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6612
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6696
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
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:6164
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6178
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6175
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6172
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6166
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6169
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6627
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:1213
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12248
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1745
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8443
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2447
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:935
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_RequiresClause
Definition Sema.h:14581
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14536
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14554
@ UPPC_Initializer
An initializer.
Definition Sema.h:14545
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14515
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14539
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14548
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14518
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14521
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14527
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:933
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:5943
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2559
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1308
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1307
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6590
SemaHLSL & HLSL()
Definition Sema.h:1484
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition Sema.h:5949
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5323
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5330
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6583
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6688
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6620
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifier NNS, TemplateParameterList *FPL)
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const CXXRecordDecl * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void ExitDeclaratorContext(Scope *S)
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, const CXXScopeSpec &SS)
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:13167
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:5939
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:645
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15620
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:9941
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7065
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6597
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1447
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6616
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8258
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14061
SourceManager & getSourceManager() const
Definition Sema.h:938
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9401
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
StringEvaluationContext
Definition Sema.h:6059
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15575
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void CheckCompleteVariableDeclaration(VarDecl *VD)
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
RedeclarationKind forRedeclarationInCurContext() const
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6608
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1585
ASTConsumer & Consumer
Definition Sema.h:1310
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:4703
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1347
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6818
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6828
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6797
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1268
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1312
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:1311
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7868
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6592
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1589
void PopDeclContext()
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6624
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:338
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6368
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
UnsignedOrNone GetDecompositionElementCount(QualType DecompType, SourceLocation Loc)
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
Decl * ActOnDeclarator(Scope *S, Declarator &D)
AbstractDiagSelID
Definition Sema.h:6314
@ AbstractVariableType
Definition Sema.h:6318
@ AbstractReturnType
Definition Sema.h:6316
@ AbstractNone
Definition Sema.h:6315
@ AbstractFieldType
Definition Sema.h:6319
@ AbstractArrayType
Definition Sema.h:6322
@ AbstractParamType
Definition Sema.h:6317
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8447
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6503
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6508
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6505
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:437
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition Sema.h:3524
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
ExprResult ActOnCXXThis(SourceLocation Loc)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:657
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8743
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition DeclCXX.cpp:3678
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1503
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
bool isUnevaluated() const
Definition Expr.h:1927
StringRef getString() const
Definition Expr.h:1873
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3752
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3873
StringRef getKindName() const
Definition Decl.h:3948
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3853
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4896
bool isUnion() const
Definition Decl.h:3963
TagKind getTagKind() const
Definition Decl.h:3952
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3898
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
TypeSourceInfo * getTypeSourceInfo() const
Represents a template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1917
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
The top declaration context.
Definition Decl.h:105
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3723
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5814
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3742
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:3548
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1437
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:116
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1970
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isUndeducedAutoType() const
Definition TypeBase.h:8880
bool isRValueReferenceType() const
Definition TypeBase.h:8716
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8783
bool isPointerType() const
Definition TypeBase.h:8684
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3183
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isFunctionProtoType() const
Definition TypeBase.h:2661
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9200
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8680
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2336
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isRecordType() const
Definition TypeBase.h:8811
bool isUnionType() const
Definition Type.cpp:755
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3597
QualType getUnderlyingType() const
Definition Decl.h:3652
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2346
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:5161
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1251
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1083
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1097
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1086
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1067
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
The iterator over UnresolvedSets.
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:4139
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3657
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3636
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3608
Represents a C++ using-declaration.
Definition DeclCXX.h:3612
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3661
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3649
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3653
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3545
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3639
Represents C++ using-directive.
Definition DeclCXX.h:3117
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3328
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3813
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3566
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3588
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3456
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3484
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3485
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5590
Represents a variable declaration or definition.
Definition Decl.h:932
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2771
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2130
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1591
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2239
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2169
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2797
void setCXXCondDecl()
Definition Decl.h:1637
bool isInlineSpecified() const
Definition Decl.h:1576
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1304
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1247
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:1214
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2812
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1183
const Expr * getInit() const
Definition Decl.h:1389
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2554
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:958
void setInit(Expr *I)
Definition Decl.cpp:2456
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1174
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:2507
void setExceptionVariable(bool EV)
Definition Decl.h:1519
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2832
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2852
SourceLocation getLastLocation() const
Definition DeclSpec.h:2864
bool isOverrideSpecified() const
Definition DeclSpec.h:2851
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2856
bool isFinalSpecified() const
Definition DeclSpec.h:2854
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2855
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition ScopeInfo.h:179
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool Comp(InterpState &S)
1) Pops the value from the stack.
Definition Interp.h:1190
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:974
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_decltype
Definition Specifiers.h:90
@ TST_typename_pack_indexing
Definition Specifiers.h:98
@ TST_decltype_auto
Definition Specifiers.h:94
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:213
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
VariadicCallType
Definition Sema.h:513
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3028
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
LLVM_READONLY auto escapeCStyle(CharT Ch) -> StringRef
Return C-style escaped string for special characters, or an empty string if there is no such mapping.
Definition CharInfo.h:191
@ Comparison
A comparison.
Definition Sema.h:667
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:272
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:275
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1797
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1803
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h:1544
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:238
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_protected
Definition Specifiers.h:126
@ AS_none
Definition Specifiers.h:128
@ AS_private
Definition Specifiers.h:127
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
StorageClass
Storage classes.
Definition Specifiers.h:249
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Language
The language for the input, used to select and validate the language standard and possible actions.
@ Default
Set to the current date and time.
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
llvm::Expected< QualType > ExpectedType
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
ReservedLiteralSuffixIdStatus
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5995
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6000
@ Struct
The "struct" keyword.
Definition TypeBase.h:5997
@ Class
The "class" keyword.
Definition TypeBase.h:6006
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
Definition Decl.h:4339
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4353
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4348
AllowFoldKind
Definition Sema.h:655
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Concept_template
The name refers to a concept.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2255
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TrivialABIHandling
Definition Sema.h:645
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:650
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:647
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
TypeAwareAllocationMode typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation)
Definition ExprCXX.h:2262
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:849
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:847
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5970
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5981
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:178
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
Represents an element in a path from a derived class to a base class.
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1412
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1472
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1421
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1475
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1573
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1602
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1605
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1511
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1598
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1387
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
SourceRange getSourceRange() const
Definition DeclSpec.h:1299
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
Holds information about the various types of exception specification.
Definition TypeBase.h:5428
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5440
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5430
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5433
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5436
Extra information about a function prototype.
Definition TypeBase.h:5456
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6034
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3389
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3371
Describes how types, statements, expressions, and declarations should be printed.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13206
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13334
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13297
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13294
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13250
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13268
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13337
Abstract class used to diagnose incomplete types.
Definition Sema.h:8339
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition Ownership.h:105