clang 24.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 // C++11 [dcl.fct.default]p3
363 // A default argument expression [...] shall not be specified for a
364 // parameter pack.
365 //
366 // Check this before looking for unexpanded parameter packs in DefaultArg:
367 // if DefaultArg references a pack from an enclosing lambda/block, that
368 // check would (incorrectly) mark the lambda as containing an unexpanded
369 // pack that never actually appears in the final AST once we discard
370 // DefaultArg below.
371 if (Param->isParameterPack()) {
372 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
373 << DefaultArg->getSourceRange();
374 // Recover by discarding the default argument.
375 Param->setDefaultArg(nullptr);
376 return;
377 }
378
379 // Check for unexpanded parameter packs.
381 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
382
383 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
384 if (Result.isInvalid())
385 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
386
387 DefaultArg = Result.getAs<Expr>();
388
389 // Check that the default argument is well-formed
390 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
391 if (DefaultArgChecker.Visit(DefaultArg))
392 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
393
394 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
395}
396
398 SourceLocation EqualLoc,
399 SourceLocation ArgLoc) {
400 if (!param)
401 return;
402
403 ParmVarDecl *Param = cast<ParmVarDecl>(param);
404 Param->setUnparsedDefaultArg();
405 UnparsedDefaultArgLocs[Param] = ArgLoc;
406}
407
409 Expr *DefaultArg) {
410 if (!param)
411 return;
412
413 ParmVarDecl *Param = cast<ParmVarDecl>(param);
414 Param->setInvalidDecl();
415 UnparsedDefaultArgLocs.erase(Param);
416 ExprResult RE;
417 if (DefaultArg) {
418 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
419 Param->getType().getNonReferenceType());
420 } else {
421 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
422 Param->getType().getNonReferenceType());
423 }
424 Param->setDefaultArg(RE.get());
425}
426
428 // C++ [dcl.fct.default]p3
429 // A default argument expression shall be specified only in the
430 // parameter-declaration-clause of a function declaration or in a
431 // template-parameter (14.1). It shall not be specified for a
432 // parameter pack. If it is specified in a
433 // parameter-declaration-clause, it shall not occur within a
434 // declarator or abstract-declarator of a parameter-declaration.
435 bool MightBeFunction = D.isFunctionDeclarationContext();
436 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
437 DeclaratorChunk &chunk = D.getTypeObject(i);
438 if (chunk.Kind == DeclaratorChunk::Function) {
439 if (MightBeFunction) {
440 // This is a function declaration. It can have default arguments, but
441 // keep looking in case its return type is a function type with default
442 // arguments.
443 MightBeFunction = false;
444 continue;
445 }
446 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
447 ++argIdx) {
448 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
449 if (Param->hasUnparsedDefaultArg()) {
450 std::unique_ptr<CachedTokens> Toks =
451 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
452 SourceRange SR;
453 if (Toks->size() > 1)
454 SR = SourceRange((*Toks)[1].getLocation(),
455 Toks->back().getLocation());
456 else
457 SR = UnparsedDefaultArgLocs[Param];
458 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
459 << SR;
460 } else if (Param->getDefaultArg()) {
461 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
462 << Param->getDefaultArg()->getSourceRange();
463 Param->setDefaultArg(nullptr);
464 }
465 }
466 } else if (chunk.Kind != DeclaratorChunk::Paren) {
467 MightBeFunction = false;
468 }
469 }
470}
471
473 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
474 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
475 });
476}
477
479 Scope *S) {
480 bool Invalid = false;
481
482 // The declaration context corresponding to the scope is the semantic
483 // parent, unless this is a local function declaration, in which case
484 // it is that surrounding function.
485 DeclContext *ScopeDC = New->isLocalExternDecl()
486 ? New->getLexicalDeclContext()
487 : New->getDeclContext();
488
489 // Find the previous declaration for the purpose of default arguments.
490 FunctionDecl *PrevForDefaultArgs = Old;
491 for (/**/; PrevForDefaultArgs;
492 // Don't bother looking back past the latest decl if this is a local
493 // extern declaration; nothing else could work.
494 PrevForDefaultArgs = New->isLocalExternDecl()
495 ? nullptr
496 : PrevForDefaultArgs->getPreviousDecl()) {
497 // Ignore hidden declarations.
498 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
499 continue;
500
501 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
502 !New->isCXXClassMember()) {
503 // Ignore default arguments of old decl if they are not in
504 // the same scope and this is not an out-of-line definition of
505 // a member function.
506 continue;
507 }
508
509 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
510 // If only one of these is a local function declaration, then they are
511 // declared in different scopes, even though isDeclInScope may think
512 // they're in the same scope. (If both are local, the scope check is
513 // sufficient, and if neither is local, then they are in the same scope.)
514 continue;
515 }
516
517 if (PrevForDefaultArgs->getFriendObjectKind()) {
518 // Don't inherit default arguments from a friend declaration. It's invalid
519 // to redeclare such a function at all if it owns the default arguments;
520 // we check for that later. Otherwise, it's not the declaration that we're
521 // inheriting them from.
522 continue;
523 }
524
525 // We found the right previous declaration.
526 break;
527 }
528
529 // C++ [dcl.fct.default]p4:
530 // For non-template functions, default arguments can be added in
531 // later declarations of a function in the same
532 // scope. Declarations in different scopes have completely
533 // distinct sets of default arguments. That is, declarations in
534 // inner scopes do not acquire default arguments from
535 // declarations in outer scopes, and vice versa. In a given
536 // function declaration, all parameters subsequent to a
537 // parameter with a default argument shall have default
538 // arguments supplied in this or previous declarations. A
539 // default argument shall not be redefined by a later
540 // declaration (not even to the same value).
541 //
542 // C++ [dcl.fct.default]p6:
543 // Except for member functions of class templates, the default arguments
544 // in a member function definition that appears outside of the class
545 // definition are added to the set of default arguments provided by the
546 // member function declaration in the class definition.
547 for (unsigned p = 0, NumParams = PrevForDefaultArgs
548 ? PrevForDefaultArgs->getNumParams()
549 : 0;
550 p < NumParams; ++p) {
551 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
552 ParmVarDecl *NewParam = New->getParamDecl(p);
553
554 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
555 bool NewParamHasDfl = NewParam->hasDefaultArg();
556
557 if (OldParamHasDfl && NewParamHasDfl) {
558 unsigned DiagDefaultParamID =
559 diag::err_param_default_argument_redefinition;
560
561 // MSVC accepts that default parameters be redefined for member functions
562 // of template class. The new default parameter's value is ignored.
563 Invalid = true;
564 if (getLangOpts().MicrosoftExt) {
565 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
566 if (MD && MD->getParent()->getDescribedClassTemplate()) {
567 // Merge the old default argument into the new parameter.
568 NewParam->setHasInheritedDefaultArg();
569 if (OldParam->hasUninstantiatedDefaultArg())
571 OldParam->getUninstantiatedDefaultArg());
572 else
573 NewParam->setDefaultArg(OldParam->getInit());
574 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
575 Invalid = false;
576 }
577 }
578
579 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
580 // hint here. Alternatively, we could walk the type-source information
581 // for NewParam to find the last source location in the type... but it
582 // isn't worth the effort right now. This is the kind of test case that
583 // is hard to get right:
584 // int f(int);
585 // void g(int (*fp)(int) = f);
586 // void g(int (*fp)(int) = &f);
587 Diag(NewParam->getLocation(), DiagDefaultParamID)
588 << NewParam->getDefaultArgRange();
589
590 // Look for the function declaration where the default argument was
591 // actually written, which may be a declaration prior to Old.
592 for (auto Older = PrevForDefaultArgs;
593 OldParam->hasInheritedDefaultArg(); /**/) {
594 Older = Older->getPreviousDecl();
595 OldParam = Older->getParamDecl(p);
596 }
597
598 Diag(OldParam->getLocation(), diag::note_previous_definition)
599 << OldParam->getDefaultArgRange();
600 } else if (OldParamHasDfl) {
601 // Merge the old default argument into the new parameter unless the new
602 // function is a friend declaration in a template class. In the latter
603 // case the default arguments will be inherited when the friend
604 // declaration will be instantiated.
605 if (New->getFriendObjectKind() == Decl::FOK_None ||
606 !New->getLexicalDeclContext()->isDependentContext()) {
607 // It's important to use getInit() here; getDefaultArg()
608 // strips off any top-level ExprWithCleanups.
609 NewParam->setHasInheritedDefaultArg();
610 if (OldParam->hasUnparsedDefaultArg())
611 NewParam->setUnparsedDefaultArg();
612 else if (OldParam->hasUninstantiatedDefaultArg())
614 OldParam->getUninstantiatedDefaultArg());
615 else
616 NewParam->setDefaultArg(OldParam->getInit());
617 }
618 } else if (NewParamHasDfl) {
619 if (New->getDescribedFunctionTemplate()) {
620 // Paragraph 4, quoted above, only applies to non-template functions.
621 Diag(NewParam->getLocation(),
622 diag::err_param_default_argument_template_redecl)
623 << NewParam->getDefaultArgRange();
624 Diag(PrevForDefaultArgs->getLocation(),
625 diag::note_template_prev_declaration)
626 << false;
627 } else if (New->getTemplateSpecializationKind()
629 New->getTemplateSpecializationKind() != TSK_Undeclared) {
630 // C++ [temp.expr.spec]p21:
631 // Default function arguments shall not be specified in a declaration
632 // or a definition for one of the following explicit specializations:
633 // - the explicit specialization of a function template;
634 // - the explicit specialization of a member function template;
635 // - the explicit specialization of a member function of a class
636 // template where the class template specialization to which the
637 // member function specialization belongs is implicitly
638 // instantiated.
639 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
640 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
641 << New->getDeclName()
642 << NewParam->getDefaultArgRange();
643 } else if (New->getDeclContext()
644 ->getEnclosingNonExpansionStatementContext()
645 ->isDependentContext()) {
646 // C++ [dcl.fct.default]p6 (DR217):
647 // Default arguments for a member function of a class template shall
648 // be specified on the initial declaration of the member function
649 // within the class template.
650 //
651 // Reading the tea leaves a bit in DR217 and its reference to DR205
652 // leads me to the conclusion that one cannot add default function
653 // arguments for an out-of-line definition of a member function of a
654 // dependent type.
655 int WhichKind = 2;
657 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
658 if (Record->getDescribedClassTemplate())
659 WhichKind = 0;
661 WhichKind = 1;
662 else
663 WhichKind = 2;
664 }
665
666 Diag(NewParam->getLocation(),
667 diag::err_param_default_argument_member_template_redecl)
668 << WhichKind
669 << NewParam->getDefaultArgRange();
670 }
671 }
672 }
673
674 // DR1344: If a default argument is added outside a class definition and that
675 // default argument makes the function a special member function, the program
676 // is ill-formed. This can only happen for constructors.
678 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
680 cast<CXXMethodDecl>(New)->getSpecialMemberKind(),
681 OldSM =
682 cast<CXXMethodDecl>(Old)->getSpecialMemberKind();
683 if (NewSM != OldSM) {
684 auto It = llvm::find_if(New->parameters(), [](const ParmVarDecl *P) {
685 return P->hasDefaultArg();
686 });
687 assert(It != New->param_end());
688 ParmVarDecl *NewParam = *It;
689 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
690 << NewParam->getDefaultArgRange() << NewSM;
691 Diag(Old->getLocation(), diag::note_previous_declaration);
692 }
693 }
694
695 const FunctionDecl *Def;
696 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
697 // template has a constexpr specifier then all its declarations shall
698 // contain the constexpr specifier.
699 if (New->getConstexprKind() != Old->getConstexprKind()) {
700 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
701 << New << static_cast<int>(New->getConstexprKind())
702 << static_cast<int>(Old->getConstexprKind());
703 Diag(Old->getLocation(), diag::note_previous_declaration);
704 Invalid = true;
705 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
706 Old->isDefined(Def) &&
707 // If a friend function is inlined but does not have 'inline'
708 // specifier, it is a definition. Do not report attribute conflict
709 // in this case, redefinition will be diagnosed later.
710 (New->isInlineSpecified() ||
711 New->getFriendObjectKind() == Decl::FOK_None)) {
712 // C++11 [dcl.fcn.spec]p4:
713 // If the definition of a function appears in a translation unit before its
714 // first declaration as inline, the program is ill-formed.
715 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
716 Diag(Def->getLocation(), diag::note_previous_definition);
717 Invalid = true;
718 }
719
720 // C++17 [temp.deduct.guide]p3:
721 // Two deduction guide declarations in the same translation unit
722 // for the same class template shall not have equivalent
723 // parameter-declaration-clauses.
725 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
726 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
727 Diag(Old->getLocation(), diag::note_previous_declaration);
728 }
729
730 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
731 // argument expression, that declaration shall be a definition and shall be
732 // the only declaration of the function or function template in the
733 // translation unit.
736 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
737 Diag(Old->getLocation(), diag::note_previous_declaration);
738 Invalid = true;
739 }
740
741 // C++11 [temp.friend]p4 (DR329):
742 // When a function is defined in a friend function declaration in a class
743 // template, the function is instantiated when the function is odr-used.
744 // The same restrictions on multiple declarations and definitions that
745 // apply to non-template function declarations and definitions also apply
746 // to these implicit definitions.
747 const FunctionDecl *OldDefinition = nullptr;
748 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
749 Old->isDefined(OldDefinition, true))
750 CheckForFunctionRedefinition(New, OldDefinition);
751
752 return Invalid;
753}
754
756 DiagCompat(Loc, diag_compat::placeholder_var_definition);
757}
758
759NamedDecl *
761 MultiTemplateParamsArg TemplateParamLists) {
762 assert(D.isDecompositionDeclarator());
764
765 // The syntax only allows a decomposition declarator as a simple-declaration,
766 // a for-range-declaration, or a condition in Clang, but we parse it in more
767 // cases than that.
769 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
770 << Decomp.getSourceRange();
771 return nullptr;
772 }
773
774 if (!TemplateParamLists.empty()) {
775 // C++17 [temp]/1:
776 // A template defines a family of class, functions, or variables, or an
777 // alias for a family of types.
778 //
779 // Structured bindings are not included.
780 Diag(TemplateParamLists.front()->getTemplateLoc(),
781 diag::err_decomp_decl_template);
782 return nullptr;
783 }
784
785 unsigned DiagID;
787 DiagID = diag::compat_pre_cxx17_decomp_decl;
789 DiagID = getLangOpts().CPlusPlus26
790 ? diag::compat_cxx26_decomp_decl_cond
791 : diag::compat_pre_cxx26_decomp_decl_cond;
792 else
793 DiagID = diag::compat_cxx17_decomp_decl;
794
795 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
796
797 // The semantic context is always just the current context.
798 DeclContext *const DC = CurContext;
799
800 // C++17 [dcl.dcl]/8:
801 // The decl-specifier-seq shall contain only the type-specifier auto
802 // and cv-qualifiers.
803 // C++20 [dcl.dcl]/8:
804 // If decl-specifier-seq contains any decl-specifier other than static,
805 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
806 // C++23 [dcl.pre]/6:
807 // Each decl-specifier in the decl-specifier-seq shall be static,
808 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
809 // C++23 [dcl.pre]/7:
810 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
811 // constinit, static, thread_local, auto, or a cv-qualifier
812 auto &DS = D.getDeclSpec();
813 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
814 Diag(Loc, diag::err_decomp_decl_spec) << Name;
815 };
816
817 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
818 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
819 };
820
821 if (auto SCS = DS.getStorageClassSpec()) {
822 if (SCS == DeclSpec::SCS_static)
823 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
824 DS.getStorageClassSpecLoc());
825 else
826 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
827 DS.getStorageClassSpecLoc());
828 }
829 if (auto TSCS = DS.getThreadStorageClassSpec())
830 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
831 DS.getThreadStorageClassSpecLoc());
832
833 if (DS.isInlineSpecified())
834 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
835
836 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
837 ConstexprSpec != ConstexprSpecKind::Unspecified) {
838 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
840 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
841 DS.getConstexprSpecLoc());
842 }
843
844 // We can't recover from it being declared as a typedef.
845 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
846 return nullptr;
847
848 // C++2a [dcl.struct.bind]p1:
849 // A cv that includes volatile is deprecated
850 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
852 Diag(DS.getVolatileSpecLoc(),
853 diag::warn_deprecated_volatile_structured_binding);
854
856 QualType R = TInfo->getType();
857
860 D.setInvalidType();
861
862 // The syntax only allows a single ref-qualifier prior to the decomposition
863 // declarator. No other declarator chunks are permitted. Also check the type
864 // specifier here.
865 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
866 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
867 (D.getNumTypeObjects() == 1 &&
869 Diag(Decomp.getLSquareLoc(),
870 (D.hasGroupingParens() ||
871 (D.getNumTypeObjects() &&
873 ? diag::err_decomp_decl_parens
874 : diag::err_decomp_decl_type)
875 << R;
876
877 // In most cases, there's no actual problem with an explicitly-specified
878 // type, but a function type won't work here, and ActOnVariableDeclarator
879 // shouldn't be called for such a type.
880 if (R->isFunctionType())
881 D.setInvalidType();
882 }
883
884 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
885 if (DS.isConstrainedAuto()) {
886 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
887 assert(TemplRep->Kind == TNK_Concept_template &&
888 "No other template kind should be possible for a constrained auto");
889
890 SourceRange TemplRange{TemplRep->TemplateNameLoc,
891 TemplRep->RAngleLoc.isValid()
892 ? TemplRep->RAngleLoc
893 : TemplRep->TemplateNameLoc};
894 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
895 << TemplRange << FixItHint::CreateRemoval(TemplRange);
896 }
897
898 // Build the BindingDecls.
900
901 // Build the BindingDecls.
902 for (auto &B : D.getDecompositionDeclarator().bindings()) {
903 // Check for name conflicts.
904 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
905 IdentifierInfo *VarName = B.Name;
906 assert(VarName && "Cannot have an unnamed binding declaration");
907
911 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
912
913 // It's not permitted to shadow a template parameter name.
914 if (Previous.isSingleResult() &&
915 Previous.getFoundDecl()->isTemplateParameter()) {
916 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
917 Previous.clear();
918 }
919
920 QualType QT;
921 if (B.EllipsisLoc.isValid()) {
922 if (!cast<Decl>(DC)->isTemplated())
923 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
924 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
925 /*ExpectsPackInType=*/false);
926 }
927
928 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
929
930 if (BD->isParameterPack()) {
932 CSI->LocalPacks.push_back(BD);
933 }
934
935 ProcessDeclAttributeList(S, BD, *B.Attrs);
936
937 // Find the shadowed declaration before filtering for scope.
938 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
940 : nullptr;
941
942 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
943 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
944 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
945 /*AllowInlineNamespace*/false);
946
947 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
948 DC->isFunctionOrMethod() && VarName->isPlaceholder();
949 if (!Previous.empty()) {
950 if (IsPlaceholder) {
951 bool sameDC = (Previous.end() - 1)
952 ->getDeclContext()
953 ->getRedeclContext()
954 ->Equals(DC->getRedeclContext());
955 if (sameDC &&
956 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
957 Previous.clear();
959 }
960 } else {
961 auto *Old = Previous.getRepresentativeDecl();
962 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
963 Diag(Old->getLocation(), diag::note_previous_definition);
964 }
965 } else if (ShadowedDecl && !D.isRedeclaration()) {
966 CheckShadow(BD, ShadowedDecl, Previous);
967 }
968 PushOnScopeChains(BD, S, true);
969 Bindings.push_back(BD);
970 ParsingInitForAutoVars.insert(BD);
971 }
972
973 // There are no prior lookup results for the variable itself, because it
974 // is unnamed.
975 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
976 Decomp.getLSquareLoc());
979
980 // Build the variable that holds the non-decomposed object.
981 bool AddToScope = true;
982 NamedDecl *New =
983 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
984 MultiTemplateParamsArg(), AddToScope, Bindings);
985 if (AddToScope) {
986 S->AddDecl(New);
987 CurContext->addHiddenDecl(New);
988 }
989
990 if (OpenMP().isInOpenMPDeclareTargetContext())
991 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
992
993 return New;
994}
995
996// Check the arity of the structured bindings.
997// Create the resolved pack expr if needed.
999 QualType DecompType,
1001 unsigned MemberCount) {
1002 auto BindingWithPackItr = llvm::find_if(
1003 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1004 bool HasPack = BindingWithPackItr != Bindings.end();
1005 bool IsValid;
1006 if (!HasPack) {
1007 IsValid = Bindings.size() == MemberCount;
1008 } else {
1009 // There may not be more members than non-pack bindings.
1010 IsValid = MemberCount >= Bindings.size() - 1;
1011 }
1012
1013 if (IsValid && HasPack) {
1014 // Create the pack expr and assign it to the binding.
1015 unsigned PackSize = MemberCount - Bindings.size() + 1;
1016
1017 BindingDecl *BPack = *BindingWithPackItr;
1018 BPack->setDecomposedDecl(DD);
1019 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1020 // Create the nested BindingDecls.
1021 for (unsigned I = 0; I < PackSize; ++I) {
1022 BindingDecl *NestedBD = BindingDecl::Create(
1023 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1024 BPack->getIdentifier(), QualType());
1025 NestedBD->setDecomposedDecl(DD);
1026 NestedBDs[I] = NestedBD;
1027 }
1028
1030 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1031 auto *PackExpr = FunctionParmPackExpr::Create(
1032 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1033 BPack->setBinding(PackType, PackExpr);
1034 }
1035
1036 if (IsValid)
1037 return false;
1038
1039 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1040 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1041 << (MemberCount < Bindings.size());
1042 return true;
1043}
1044
1047 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1048 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1049 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1050 auto *DD = cast<DecompositionDecl>(Src);
1051
1052 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1053 return true;
1054
1055 unsigned I = 0;
1056 for (auto *B : DD->flat_bindings()) {
1057 SourceLocation Loc = B->getLocation();
1058 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1059 if (E.isInvalid())
1060 return true;
1061 E = GetInit(Loc, E.get(), I++);
1062 if (E.isInvalid())
1063 return true;
1064 B->setBinding(ElemType, E.get());
1065 }
1066
1067 return false;
1068}
1069
1072 ValueDecl *Src, QualType DecompType,
1073 const llvm::APSInt &NumElems,
1074 QualType ElemType) {
1076 S, Bindings, Src, DecompType, NumElems, ElemType,
1077 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1078 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1079 if (E.isInvalid())
1080 return ExprError();
1081 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1082 });
1083}
1084
1086 ValueDecl *Src, QualType DecompType,
1087 const ConstantArrayType *CAT) {
1088 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1089 llvm::APSInt(CAT->getSize()),
1090 CAT->getElementType());
1091}
1092
1094 ValueDecl *Src, QualType DecompType,
1095 const VectorType *VT) {
1097 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1099 DecompType.getQualifiers()));
1100}
1101
1104 ValueDecl *Src, QualType DecompType,
1105 const ComplexType *CT) {
1107 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1109 DecompType.getQualifiers()),
1110 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1111 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1112 });
1113}
1114
1117 const TemplateParameterList *Params) {
1119 llvm::raw_svector_ostream OS(SS);
1120 bool First = true;
1121 unsigned I = 0;
1122 for (auto &Arg : Args.arguments()) {
1123 if (!First)
1124 OS << ", ";
1125 Arg.getArgument().print(PrintingPolicy, OS,
1127 PrintingPolicy, Params, I));
1128 First = false;
1129 I++;
1130 }
1131 return std::string(OS.str());
1132}
1133
1134static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1135 TemplateArgumentListInfo &Args, unsigned DiagID) {
1136 auto DiagnoseMissing = [&] {
1137 if (DiagID)
1138 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1139 Args, /*Params*/ nullptr);
1140 return QualType();
1141 };
1142
1143 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1144 NamespaceDecl *Std = S.getStdNamespace();
1145 if (!Std)
1146 return DiagnoseMissing();
1147
1148 // Look up the trait itself, within namespace std. We can diagnose various
1149 // problems with this lookup even if we've been asked to not diagnose a
1150 // missing specialization, because this can only fail if the user has been
1151 // declaring their own names in namespace std or we don't support the
1152 // standard library implementation in use.
1153 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1155 if (!S.LookupQualifiedName(Result, Std))
1156 return DiagnoseMissing();
1157 if (Result.isAmbiguous())
1158 return QualType();
1159
1160 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1161 if (!TraitTD) {
1162 Result.suppressDiagnostics();
1163 NamedDecl *Found = *Result.begin();
1164 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1165 S.Diag(Found->getLocation(), diag::note_declared_at);
1166 return QualType();
1167 }
1168
1169 // Build the template-id.
1170 QualType TraitTy = S.CheckTemplateIdType(
1171 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1172 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1173 if (TraitTy.isNull())
1174 return QualType();
1175
1176 if (!S.isCompleteType(Loc, TraitTy)) {
1177 if (DiagID)
1179 Loc, TraitTy, DiagID,
1181 TraitTD->getTemplateParameters()));
1182 return QualType();
1183 }
1184 return TraitTy;
1185}
1186
1187static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1188 LookupResult &MemberLookup) {
1189 assert(RD && "specialization of class template is not a class?");
1190 S.LookupQualifiedName(MemberLookup, RD);
1191 return MemberLookup.isAmbiguous();
1192}
1193
1194static TemplateArgumentLoc
1196 uint64_t I) {
1198 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1199}
1200
1201static TemplateArgumentLoc
1205
1206namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1207
1208static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1209 unsigned &OutSize) {
1212
1213 // Form template argument list for tuple_size<T>.
1214 TemplateArgumentListInfo Args(Loc, Loc);
1216
1217 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1218 if (TraitTy.isNull())
1219 return IsTupleLike::NotTupleLike;
1220
1223
1224 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1225 // it's not tuple-like.
1226 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1227 return IsTupleLike::NotTupleLike;
1228
1229 // If we get this far, we've committed to the tuple interpretation, but
1230 // we can still fail if there actually isn't a usable ::value.
1231
1232 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1233 LookupResult &R;
1235 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1236 : R(R), Args(Args) {}
1237 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1238 SourceLocation Loc) override {
1239 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1241 /*Params*/ nullptr);
1242 }
1243 } Diagnoser(R, Args);
1244
1245 ExprResult E =
1246 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1247 if (E.isInvalid())
1248 return IsTupleLike::Error;
1249
1250 llvm::APSInt Size;
1251 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1252 if (E.isInvalid())
1253 return IsTupleLike::Error;
1254
1255 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1256 // an UnsignedOrNone.
1257 if (Size < 0 || Size >= UINT_MAX) {
1259 Size.toString(Str);
1260 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1262 /*Params=*/nullptr)
1263 << StringRef(Str.data(), Str.size());
1264 return IsTupleLike::Error;
1265 }
1266
1267 OutSize = Size.getExtValue();
1268 return IsTupleLike::TupleLike;
1269}
1270
1271/// \return std::tuple_element<I, T>::type.
1273 unsigned I, QualType T) {
1274 // Form template argument list for tuple_element<I, T>.
1275 TemplateArgumentListInfo Args(Loc, Loc);
1276 Args.addArgument(
1279
1280 QualType TraitTy =
1281 getStdTrait(S, Loc, "tuple_element", Args,
1282 diag::err_decomp_decl_std_tuple_element_not_specialized);
1283 if (TraitTy.isNull())
1284 return QualType();
1285
1286 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1287 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1288 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1289 return QualType();
1290
1291 auto *TD = R.getAsSingle<TypeDecl>();
1292 if (!TD) {
1293 R.suppressDiagnostics();
1294 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1296 /*Params*/ nullptr);
1297 if (!R.empty())
1298 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1299 return QualType();
1300 }
1301
1302 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1303 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1304}
1305
1306namespace {
1307struct InitializingBinding {
1308 Sema &S;
1309 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1310 Sema::CodeSynthesisContext Ctx;
1313 Ctx.Entity = BD;
1315 }
1316 ~InitializingBinding() {
1318 }
1319};
1320}
1321
1324 VarDecl *Src, QualType DecompType,
1325 unsigned NumElems) {
1326 auto *DD = cast<DecompositionDecl>(Src);
1327 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1328 return true;
1329
1330 if (Bindings.empty())
1331 return false;
1332
1333 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1334
1335 // [dcl.decomp]p3:
1336 // The unqualified-id get is looked up in the scope of E by class member
1337 // access lookup ...
1338 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1339 bool UseMemberGet = false;
1340 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1341 if (auto *RD = DecompType->getAsCXXRecordDecl())
1342 S.LookupQualifiedName(MemberGet, RD);
1343 if (MemberGet.isAmbiguous())
1344 return true;
1345 // ... and if that finds at least one declaration that is a function
1346 // template whose first template parameter is a non-type parameter ...
1347 for (NamedDecl *D : MemberGet) {
1348 if (FunctionTemplateDecl *FTD =
1349 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1350 TemplateParameterList *TPL = FTD->getTemplateParameters();
1351 if (TPL->size() != 0 &&
1353 // ... the initializer is e.get<i>().
1354 UseMemberGet = true;
1355 break;
1356 }
1357 }
1358 }
1359 }
1360
1361 unsigned I = 0;
1362 for (auto *B : DD->flat_bindings()) {
1363 InitializingBinding InitContext(S, B);
1364 SourceLocation Loc = B->getLocation();
1365
1366 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1367 if (E.isInvalid())
1368 return true;
1369
1370 // e is an lvalue if the type of the entity is an lvalue reference and
1371 // an xvalue otherwise
1372 if (!Src->getType()->isLValueReferenceType())
1373 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1374 E.get(), nullptr, VK_XValue,
1376
1377 TemplateArgumentListInfo Args(Loc, Loc);
1378 Args.addArgument(
1380
1381 if (UseMemberGet) {
1382 // if [lookup of member get] finds at least one declaration, the
1383 // initializer is e.get<i-1>().
1384 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1385 CXXScopeSpec(), SourceLocation(), nullptr,
1386 MemberGet, &Args, nullptr);
1387 if (E.isInvalid())
1388 return true;
1389
1390 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1391 } else {
1392 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1393 // in the associated namespaces.
1396 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1398 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1399
1400 Expr *Arg = E.get();
1401 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1402 }
1403 if (E.isInvalid())
1404 return true;
1405 Expr *Init = E.get();
1406
1407 // Given the type T designated by std::tuple_element<i - 1, E>::type
1408 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1409 if (T.isNull())
1410 return true;
1411
1412 // C++26 [dcl.struct.bind]p7:
1413 // and the type Ui, defined as Ti if the initializer is a prvalue,
1414 // as "lvalue reference to Ti" if the initializer is an lvalue,
1415 // or as "rvalue reference to Ti" otherwise
1416 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1417 QualType U = E.get()->isPRValue()
1418 ? T
1419 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1420 B->getDeclName());
1421 if (U.isNull())
1422 return true;
1423
1424 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1425 // entity and this type was never written in source code.
1426 auto *BindingVD =
1427 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1428 B->getDeclName().getAsIdentifierInfo(), U,
1429 /*TInfo=*/nullptr, Src->getStorageClass());
1430 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1431 BindingVD->setTSCSpec(Src->getTSCSpec());
1432 BindingVD->setConstexpr(Src->isConstexpr());
1433 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1434 BindingVD->addAttr(CIAttr->clone(S.Context));
1435 BindingVD->setImplicit();
1436 if (Src->isInlineSpecified())
1437 BindingVD->setInlineSpecified();
1438 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1439
1442 InitializationSequence Seq(S, Entity, Kind, Init);
1443 E = Seq.Perform(S, Entity, Kind, Init);
1444 if (E.isInvalid())
1445 return true;
1446 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1447 if (E.isInvalid())
1448 return true;
1449 BindingVD->setInit(E.get());
1451
1453 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1454 if (E.isInvalid())
1455 return true;
1456
1457 B->setBinding(T, E.get());
1458 I++;
1459 }
1460
1461 return false;
1462}
1463
1464/// Find the base class to decompose in a built-in decomposition of a class type.
1465/// This base class search is, unfortunately, not quite like any other that we
1466/// perform anywhere else in C++.
1468 const CXXRecordDecl *RD,
1469 CXXCastPath &BasePath) {
1470 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1471 CXXBasePath &Path) {
1472 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1473 };
1474
1475 const CXXRecordDecl *ClassWithFields = nullptr;
1477 if (RD->hasDirectFields())
1478 // [dcl.decomp]p4:
1479 // Otherwise, all of E's non-static data members shall be public direct
1480 // members of E ...
1481 ClassWithFields = RD;
1482 else {
1483 // ... or of ...
1484 CXXBasePaths Paths;
1485 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1486 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1487 // If no classes have fields, just decompose RD itself. (This will work
1488 // if and only if zero bindings were provided.)
1489 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1490 }
1491
1492 CXXBasePath *BestPath = nullptr;
1493 for (auto &P : Paths) {
1494 if (!BestPath)
1495 BestPath = &P;
1496 else if (!S.Context.hasSameType(P.back().Base->getType(),
1497 BestPath->back().Base->getType())) {
1498 // ... the same ...
1499 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1500 << false << RD << BestPath->back().Base->getType()
1501 << P.back().Base->getType();
1502 return DeclAccessPair();
1503 } else if (P.Access < BestPath->Access) {
1504 BestPath = &P;
1505 }
1506 }
1507
1508 // ... unambiguous ...
1509 QualType BaseType = BestPath->back().Base->getType();
1510 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1511 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1512 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1513 return DeclAccessPair();
1514 }
1515
1516 // ... [accessible, implied by other rules] base class of E.
1517 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1518 *BestPath, diag::err_decomp_decl_inaccessible_base);
1519 AS = BestPath->Access;
1520
1521 ClassWithFields = BaseType->getAsCXXRecordDecl();
1522 S.BuildBasePathArray(Paths, BasePath);
1523 }
1524
1525 // The above search did not check whether the selected class itself has base
1526 // classes with fields, so check that now.
1527 CXXBasePaths Paths;
1528 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1529 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1530 << (ClassWithFields == RD) << RD << ClassWithFields
1531 << Paths.front().back().Base->getType();
1532 return DeclAccessPair();
1533 }
1534
1535 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1536}
1537
1539 const CXXRecordDecl *OrigRD,
1540 QualType DecompType,
1541 DeclAccessPair BasePair) {
1542 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1543 if (!RD)
1544 return true;
1545
1546 for (auto *FD : RD->fields()) {
1547 if (FD->isUnnamedBitField())
1548 continue;
1549
1550 // All the non-static data members are required to be nameable, so they
1551 // must all have names.
1552 if (!FD->getDeclName()) {
1553 if (RD->isLambda()) {
1554 S.Diag(Loc, diag::err_decomp_decl_lambda);
1555 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1556 return true;
1557 }
1558
1559 if (FD->isAnonymousStructOrUnion()) {
1560 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1561 << DecompType << FD->getType()->isUnionType();
1562 S.Diag(FD->getLocation(), diag::note_declared_at);
1563 return true;
1564 }
1565
1566 // FIXME: Are there any other ways we could have an anonymous member?
1567 }
1568 // The field must be accessible in the context of the structured binding.
1569 // We already checked that the base class is accessible.
1570 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1571 // const_cast here.
1573 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1575 BasePair.getAccess(), FD->getAccess())));
1576 }
1577 return false;
1578}
1579
1581 ValueDecl *Src, QualType DecompType,
1582 const CXXRecordDecl *OrigRD) {
1583 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1584 diag::err_incomplete_type))
1585 return true;
1586
1587 CXXCastPath BasePath;
1588 DeclAccessPair BasePair =
1589 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1590 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1591 if (!RD)
1592 return true;
1593 QualType BaseType = S.Context.getQualifiedType(
1594 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1595
1596 auto *DD = cast<DecompositionDecl>(Src);
1597 unsigned NumFields = llvm::count_if(
1598 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1599 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1600 return true;
1601
1602 // all of E's non-static data members shall be [...] well-formed
1603 // when named as e.name in the context of the structured binding,
1604 // E shall not have an anonymous union member, ...
1605 auto FlatBindings = DD->flat_bindings();
1606 assert(llvm::range_size(FlatBindings) == NumFields);
1607 auto FlatBindingsItr = FlatBindings.begin();
1608
1609 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1610 BasePair))
1611 return true;
1612
1613 for (auto *FD : RD->fields()) {
1614 if (FD->isUnnamedBitField())
1615 continue;
1616
1617 // We have a real field to bind.
1618 assert(FlatBindingsItr != FlatBindings.end());
1619 BindingDecl *B = *(FlatBindingsItr++);
1620 SourceLocation Loc = B->getLocation();
1621
1622 // Initialize the binding to Src.FD.
1623 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1624 if (E.isInvalid())
1625 return true;
1626 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1627 VK_LValue, &BasePath);
1628 if (E.isInvalid())
1629 return true;
1630 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1631 CXXScopeSpec(), FD,
1633 DeclarationNameInfo(FD->getDeclName(), Loc));
1634 if (E.isInvalid())
1635 return true;
1636
1637 // If the type of the member is T, the referenced type is cv T, where cv is
1638 // the cv-qualification of the decomposition expression.
1639 //
1640 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1641 // 'const' to the type of the field.
1642 Qualifiers Q = DecompType.getQualifiers();
1643 if (FD->isMutable())
1644 Q.removeConst();
1645 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1646 }
1647
1648 return false;
1649}
1650
1652 QualType DecompType = DD->getType();
1653
1654 // If the type of the decomposition is dependent, then so is the type of
1655 // each binding.
1656 if (DecompType->isDependentType()) {
1657 // Note that all of the types are still Null or PackExpansionType.
1658 for (auto *B : DD->bindings()) {
1659 // Do not overwrite any pack type.
1660 if (B->getType().isNull())
1661 B->setType(Context.DependentTy);
1662 }
1663 return;
1664 }
1665
1666 DecompType = DecompType.getNonReferenceType();
1668
1669 // C++1z [dcl.decomp]/2:
1670 // If E is an array type [...]
1671 // As an extension, we also support decomposition of built-in complex and
1672 // vector types.
1673 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1674 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1675 DD->setInvalidDecl();
1676 return;
1677 }
1678 if (auto *VT = DecompType->getAs<VectorType>()) {
1679 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1680 DD->setInvalidDecl();
1681 return;
1682 }
1683 if (auto *CT = DecompType->getAs<ComplexType>()) {
1684 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1685 DD->setInvalidDecl();
1686 return;
1687 }
1688
1689 // C++1z [dcl.decomp]/3:
1690 // if the expression std::tuple_size<E>::value is a well-formed integral
1691 // constant expression, [...]
1692 unsigned TupleSize;
1693 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1694 case IsTupleLike::Error:
1695 DD->setInvalidDecl();
1696 return;
1697
1698 case IsTupleLike::TupleLike:
1699 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1700 DD->setInvalidDecl();
1701 return;
1702
1703 case IsTupleLike::NotTupleLike:
1704 break;
1705 }
1706
1707 // C++1z [dcl.dcl]/8:
1708 // [E shall be of array or non-union class type]
1709 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1710 if (!RD || RD->isUnion()) {
1711 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1712 << DD << !RD << DecompType;
1713 DD->setInvalidDecl();
1714 return;
1715 }
1716
1717 // C++1z [dcl.decomp]/4:
1718 // all of E's non-static data members shall be [...] direct members of
1719 // E or of the same unambiguous public base class of E, ...
1720 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1721 DD->setInvalidDecl();
1722}
1723
1725 SourceLocation Loc) {
1726 const ASTContext &Ctx = getASTContext();
1727 assert(!T->isDependentType());
1728
1729 Qualifiers Quals;
1730 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1731 Quals.removeCVRQualifiers();
1732 T = Context.getQualifiedType(Unqual, Quals);
1733
1734 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1735 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1736 if (auto *VT = T->getAs<VectorType>())
1737 return VT->getNumElements();
1738 if (T->getAs<ComplexType>())
1739 return 2u;
1740
1741 unsigned TupleSize;
1742 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1743 case IsTupleLike::Error:
1744 return std::nullopt;
1745 case IsTupleLike::TupleLike:
1746 return TupleSize;
1747 case IsTupleLike::NotTupleLike:
1748 break;
1749 }
1750
1751 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1752 if (!OrigRD || OrigRD->isUnion())
1753 return std::nullopt;
1754
1755 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1756 return std::nullopt;
1757
1758 CXXCastPath BasePath;
1759 DeclAccessPair BasePair =
1760 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1761 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1762 if (!RD)
1763 return std::nullopt;
1764
1765 unsigned NumFields = llvm::count_if(
1766 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1767
1768 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1769 return std::nullopt;
1770
1771 return NumFields;
1772}
1773
1775 // Shortcut if exceptions are disabled.
1776 if (!getLangOpts().CXXExceptions)
1777 return;
1778
1779 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1780 "Should only be called if types are otherwise the same.");
1781
1782 QualType NewType = New->getType();
1783 QualType OldType = Old->getType();
1784
1785 // We're only interested in pointers and references to functions, as well
1786 // as pointers to member functions.
1787 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1788 NewType = R->getPointeeType();
1789 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1790 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1791 NewType = P->getPointeeType();
1792 OldType = OldType->castAs<PointerType>()->getPointeeType();
1793 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1794 NewType = M->getPointeeType();
1795 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1796 }
1797
1798 if (!NewType->isFunctionProtoType())
1799 return;
1800
1801 // There's lots of special cases for functions. For function pointers, system
1802 // libraries are hopefully not as broken so that we don't need these
1803 // workarounds.
1805 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1806 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1807 New->setInvalidDecl();
1808 }
1809}
1810
1811/// CheckCXXDefaultArguments - Verify that the default arguments for a
1812/// function declaration are well-formed according to C++
1813/// [dcl.fct.default].
1815 // This checking doesn't make sense for explicit specializations; their
1816 // default arguments are determined by the declaration we're specializing,
1817 // not by FD.
1819 return;
1820 if (auto *FTD = FD->getDescribedFunctionTemplate())
1821 if (FTD->isMemberSpecialization())
1822 return;
1823
1824 unsigned NumParams = FD->getNumParams();
1825 unsigned ParamIdx = 0;
1826
1827 // Find first parameter with a default argument
1828 for (; ParamIdx < NumParams; ++ParamIdx) {
1829 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1830 if (Param->hasDefaultArg())
1831 break;
1832 }
1833
1834 // C++20 [dcl.fct.default]p4:
1835 // In a given function declaration, each parameter subsequent to a parameter
1836 // with a default argument shall have a default argument supplied in this or
1837 // a previous declaration, unless the parameter was expanded from a
1838 // parameter pack, or shall be a function parameter pack.
1839 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1840 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1841 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1843 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1844 continue;
1845 if (Param->isInvalidDecl())
1846 /* We already complained about this parameter. */;
1847 else if (Param->getIdentifier())
1848 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1849 << Param->getIdentifier();
1850 else
1851 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1852 }
1853}
1854
1855/// Check that the given type is a literal type. Issue a diagnostic if not,
1856/// if Kind is Diagnose.
1857/// \return \c true if a problem has been found (and optionally diagnosed).
1858template <typename... Ts>
1860 SourceLocation Loc, QualType T, unsigned DiagID,
1861 Ts &&...DiagArgs) {
1862 if (T->isDependentType())
1863 return false;
1864
1865 switch (Kind) {
1867 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1868 std::forward<Ts>(DiagArgs)...);
1869
1871 return !T->isLiteralType(SemaRef.Context);
1872 }
1873
1874 llvm_unreachable("unknown CheckConstexprKind");
1875}
1876
1877/// Determine whether a destructor cannot be constexpr due to
1879 const CXXDestructorDecl *DD,
1881 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1882 "this check is obsolete for C++23");
1883 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1884 const CXXRecordDecl *RD =
1885 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1886 if (!RD || RD->hasConstexprDestructor())
1887 return true;
1888
1890 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1891 << static_cast<int>(DD->getConstexprKind()) << !FD
1892 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1893 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1894 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1895 }
1896 return false;
1897 };
1898
1899 const CXXRecordDecl *RD = DD->getParent();
1900 for (const CXXBaseSpecifier &B : RD->bases())
1901 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1902 return false;
1903 for (const FieldDecl *FD : RD->fields())
1904 if (!Check(FD->getLocation(), FD->getType(), FD))
1905 return false;
1906 return true;
1907}
1908
1909/// Check whether a function's parameter types are all literal types. If so,
1910/// return true. If not, produce a suitable diagnostic and return false.
1912 const FunctionDecl *FD,
1914 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1915 "this check is obsolete for C++23");
1916 unsigned ArgIndex = 0;
1917 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1918 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1919 e = FT->param_type_end();
1920 i != e; ++i, ++ArgIndex) {
1921 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1922 assert(PD && "null in a parameter list");
1923 SourceLocation ParamLoc = PD->getLocation();
1924 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1925 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1927 FD->isConsteval()))
1928 return false;
1929 }
1930 return true;
1931}
1932
1933/// Check whether a function's return type is a literal type. If so, return
1934/// true. If not, produce a suitable diagnostic and return false.
1935static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1937 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1938 "this check is obsolete for C++23");
1939 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1940 diag::err_constexpr_non_literal_return,
1941 FD->isConsteval()))
1942 return false;
1943 return true;
1944}
1945
1946/// Get diagnostic %select index for tag kind for
1947/// record diagnostic message.
1948/// WARNING: Indexes apply to particular diagnostics only!
1949///
1950/// \returns diagnostic %select index.
1952 switch (Tag) {
1954 return 0;
1956 return 1;
1957 case TagTypeKind::Class:
1958 return 2;
1959 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1960 }
1961}
1962
1963static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1964 Stmt *Body,
1966static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1967
1969 CheckConstexprKind Kind) {
1970 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1971 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1972 // C++11 [dcl.constexpr]p4:
1973 // The definition of a constexpr constructor shall satisfy the following
1974 // constraints:
1975 // - the class shall not have any virtual base classes;
1976 //
1977 // FIXME: This only applies to constructors and destructors, not arbitrary
1978 // member functions.
1979 const CXXRecordDecl *RD = MD->getParent();
1980 if (RD->getNumVBases()) {
1982 return false;
1983
1984 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1985 << isa<CXXConstructorDecl>(NewFD)
1987 for (const auto &I : RD->vbases())
1988 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1989 << I.getSourceRange();
1990 return false;
1991 }
1992 }
1993
1994 if (!isa<CXXConstructorDecl>(NewFD)) {
1995 // C++11 [dcl.constexpr]p3:
1996 // The definition of a constexpr function shall satisfy the following
1997 // constraints:
1998 // - it shall not be virtual; (removed in C++20)
1999 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
2000 if (Method && Method->isVirtual()) {
2001 if (getLangOpts().CPlusPlus20) {
2002 if (Kind == CheckConstexprKind::Diagnose)
2003 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
2004 } else {
2006 return false;
2007
2008 Method = Method->getCanonicalDecl();
2009 Diag(Method->getLocation(), diag::err_constexpr_virtual);
2010
2011 // If it's not obvious why this function is virtual, find an overridden
2012 // function which uses the 'virtual' keyword.
2013 const CXXMethodDecl *WrittenVirtual = Method;
2014 while (!WrittenVirtual->isVirtualAsWritten())
2015 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2016 if (WrittenVirtual != Method)
2017 Diag(WrittenVirtual->getLocation(),
2018 diag::note_overridden_virtual_function);
2019 return false;
2020 }
2021 }
2022
2023 // - its return type shall be a literal type; (removed in C++23)
2024 if (!getLangOpts().CPlusPlus23 &&
2025 !CheckConstexprReturnType(*this, NewFD, Kind))
2026 return false;
2027 }
2028
2029 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2030 // A destructor can be constexpr only if the defaulted destructor could be;
2031 // we don't need to check the members and bases if we already know they all
2032 // have constexpr destructors. (removed in C++23)
2033 if (!getLangOpts().CPlusPlus23 &&
2034 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2036 return false;
2037 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2038 return false;
2039 }
2040 }
2041
2042 // - each of its parameter types shall be a literal type; (removed in C++23)
2043 if (!getLangOpts().CPlusPlus23 &&
2044 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2045 return false;
2046
2047 Stmt *Body = NewFD->getBody();
2048 assert(Body &&
2049 "CheckConstexprFunctionDefinition called on function with no body");
2050 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2051}
2052
2053/// Check the given declaration statement is legal within a constexpr function
2054/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2055///
2056/// \return true if the body is OK (maybe only as an extension), false if we
2057/// have diagnosed a problem.
2058static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2059 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2061 // C++11 [dcl.constexpr]p3 and p4:
2062 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2063 // contain only
2064 for (const auto *DclIt : DS->decls()) {
2065 switch (DclIt->getKind()) {
2066 case Decl::StaticAssert:
2067 case Decl::Using:
2068 case Decl::UsingShadow:
2069 case Decl::UsingDirective:
2070 case Decl::UnresolvedUsingTypename:
2071 case Decl::UnresolvedUsingValue:
2072 case Decl::UsingEnum:
2073 // - static_assert-declarations
2074 // - using-declarations,
2075 // - using-directives,
2076 // - using-enum-declaration
2077 continue;
2078
2079 case Decl::Typedef:
2080 case Decl::TypeAlias: {
2081 // - typedef declarations and alias-declarations that do not define
2082 // classes or enumerations,
2083 const auto *TN = cast<TypedefNameDecl>(DclIt);
2084 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2085 // Don't allow variably-modified types in constexpr functions.
2087 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2088 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2089 << TL.getSourceRange() << TL.getType()
2091 }
2092 return false;
2093 }
2094 continue;
2095 }
2096
2097 case Decl::Enum:
2098 case Decl::CXXRecord:
2099 // C++1y allows types to be defined, not just declared.
2100 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2102 SemaRef.DiagCompat(DS->getBeginLoc(),
2103 diag_compat::constexpr_type_definition)
2105 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2106 return false;
2107 }
2108 }
2109 continue;
2110
2111 case Decl::EnumConstant:
2112 case Decl::IndirectField:
2113 case Decl::ParmVar:
2114 // These can only appear with other declarations which are banned in
2115 // C++11 and permitted in C++1y, so ignore them.
2116 continue;
2117
2118 case Decl::Var:
2119 case Decl::Decomposition: {
2120 // C++1y [dcl.constexpr]p3 allows anything except:
2121 // a definition of a variable of non-literal type or of static or
2122 // thread storage duration or [before C++2a] for which no
2123 // initialization is performed.
2124 const auto *VD = cast<VarDecl>(DclIt);
2125 if (VD->isThisDeclarationADefinition()) {
2126 if (VD->isStaticLocal()) {
2128 SemaRef.DiagCompat(VD->getLocation(),
2129 diag_compat::constexpr_static_var)
2131 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2132 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2133 return false;
2134 }
2135 }
2136 if (SemaRef.LangOpts.CPlusPlus23) {
2137 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2138 diag::warn_cxx20_compat_constexpr_var,
2140 } else if (CheckLiteralType(
2141 SemaRef, Kind, VD->getLocation(), VD->getType(),
2142 diag::err_constexpr_local_var_non_literal_type,
2144 return false;
2145 }
2146 if (!VD->getType()->isDependentType() &&
2147 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2149 SemaRef.DiagCompat(VD->getLocation(),
2150 diag_compat::constexpr_local_var_no_init)
2152 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2153 return false;
2154 }
2155 continue;
2156 }
2157 }
2159 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2161 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2162 return false;
2163 }
2164 continue;
2165 }
2166
2167 case Decl::NamespaceAlias:
2168 case Decl::Function:
2169 // These are disallowed in C++11 and permitted in C++1y. Allow them
2170 // everywhere as an extension.
2171 if (!Cxx1yLoc.isValid())
2172 Cxx1yLoc = DS->getBeginLoc();
2173 continue;
2174
2175 default:
2177 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2178 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2179 }
2180 return false;
2181 }
2182 }
2183
2184 return true;
2185}
2186
2187/// Check that the given field is initialized within a constexpr constructor.
2188///
2189/// \param Dcl The constexpr constructor being checked.
2190/// \param Field The field being checked. This may be a member of an anonymous
2191/// struct or union nested within the class being checked.
2192/// \param Inits All declarations, including anonymous struct/union members and
2193/// indirect members, for which any initialization was provided.
2194/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2195/// multiple notes for different members to the same error.
2196/// \param Kind Whether we're diagnosing a constructor as written or determining
2197/// whether the formal requirements are satisfied.
2198/// \return \c false if we're checking for validity and the constructor does
2199/// not satisfy the requirements on a constexpr constructor.
2201 const FunctionDecl *Dcl,
2202 FieldDecl *Field,
2204 bool &Diagnosed,
2206 // In C++20 onwards, there's nothing to check for validity.
2208 SemaRef.getLangOpts().CPlusPlus20)
2209 return true;
2210
2211 if (Field->isInvalidDecl())
2212 return true;
2213
2214 if (Field->isUnnamedBitField())
2215 return true;
2216
2217 // Anonymous unions with no variant members and empty anonymous structs do not
2218 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2219 // indirect fields don't need initializing.
2220 if (Field->isAnonymousStructOrUnion() &&
2221 (Field->getType()->isUnionType()
2222 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2223 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2224 return true;
2225
2226 if (!Inits.count(Field)) {
2228 if (!Diagnosed) {
2229 SemaRef.DiagCompat(Dcl->getLocation(),
2230 diag_compat::constexpr_ctor_missing_init);
2231 Diagnosed = true;
2232 }
2233 SemaRef.Diag(Field->getLocation(),
2234 diag::note_constexpr_ctor_missing_init);
2235 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2236 return false;
2237 }
2238 } else if (Field->isAnonymousStructOrUnion()) {
2239 const auto *RD = Field->getType()->castAsRecordDecl();
2240 for (auto *I : RD->fields())
2241 // If an anonymous union contains an anonymous struct of which any member
2242 // is initialized, all members must be initialized.
2243 if (!RD->isUnion() || Inits.count(I))
2244 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2245 Kind))
2246 return false;
2247 }
2248 return true;
2249}
2250
2251/// Check the provided statement is allowed in a constexpr function
2252/// definition.
2253static bool
2256 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2257 SourceLocation &Cxx2bLoc,
2259 // - its function-body shall be [...] a compound-statement that contains only
2260 switch (S->getStmtClass()) {
2261 case Stmt::NullStmtClass:
2262 // - null statements,
2263 return true;
2264
2265 case Stmt::DeclStmtClass: {
2266 auto *DS = cast<DeclStmt>(S);
2267
2268 // Expansion statement 'declarations' have substatements, so we need to
2269 // handle them separately.
2270 if (DS->isSingleDecl()) {
2271 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(DS->getSingleDecl())) {
2272 // Don't check unexpanded expansion statements.
2273 if (!ESD->getInstantiations())
2274 return true;
2275 for (auto *BodyIt : ESD->getInstantiations()->getInstantiations()) {
2276 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2277 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2278 return false;
2279 }
2280 return true;
2281 }
2282 }
2283
2284 // - static_assert-declarations
2285 // - using-declarations,
2286 // - using-directives,
2287 // - typedef declarations and alias-declarations that do not define
2288 // classes or enumerations,
2289 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS, Cxx1yLoc, Kind))
2290 return false;
2291 return true;
2292 }
2293
2294 case Stmt::ReturnStmtClass:
2295 // - and exactly one return statement;
2296 if (isa<CXXConstructorDecl>(Dcl)) {
2297 // C++1y allows return statements in constexpr constructors.
2298 if (!Cxx1yLoc.isValid())
2299 Cxx1yLoc = S->getBeginLoc();
2300 return true;
2301 }
2302
2303 ReturnStmts.push_back(S->getBeginLoc());
2304 return true;
2305
2306 case Stmt::AttributedStmtClass:
2307 // Attributes on a statement don't affect its formal kind and hence don't
2308 // affect its validity in a constexpr function.
2310 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2311 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2312
2313 case Stmt::CompoundStmtClass: {
2314 // C++1y allows compound-statements.
2315 if (!Cxx1yLoc.isValid())
2316 Cxx1yLoc = S->getBeginLoc();
2317
2318 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2319 for (auto *BodyIt : CompStmt->body()) {
2320 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2321 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2322 return false;
2323 }
2324 return true;
2325 }
2326
2327 case Stmt::IfStmtClass: {
2328 // C++1y allows if-statements.
2329 if (!Cxx1yLoc.isValid())
2330 Cxx1yLoc = S->getBeginLoc();
2331
2332 IfStmt *If = cast<IfStmt>(S);
2333 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2334 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2335 return false;
2336 if (If->getElse() &&
2337 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2338 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2339 return false;
2340 return true;
2341 }
2342
2343 case Stmt::WhileStmtClass:
2344 case Stmt::DoStmtClass:
2345 case Stmt::ForStmtClass:
2346 case Stmt::CXXForRangeStmtClass:
2347 case Stmt::ContinueStmtClass:
2348 // C++1y allows all of these. We don't allow them as extensions in C++11,
2349 // because they don't make sense without variable mutation.
2350 if (!SemaRef.getLangOpts().CPlusPlus14)
2351 break;
2352 if (!Cxx1yLoc.isValid())
2353 Cxx1yLoc = S->getBeginLoc();
2354 for (Stmt *SubStmt : S->children()) {
2355 if (SubStmt &&
2356 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2357 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2358 return false;
2359 }
2360 return true;
2361
2362 case Stmt::SwitchStmtClass:
2363 case Stmt::CaseStmtClass:
2364 case Stmt::DefaultStmtClass:
2365 case Stmt::BreakStmtClass:
2366 // C++1y allows switch-statements, and since they don't need variable
2367 // mutation, we can reasonably allow them in C++11 as an extension.
2368 if (!Cxx1yLoc.isValid())
2369 Cxx1yLoc = S->getBeginLoc();
2370 for (Stmt *SubStmt : S->children()) {
2371 if (SubStmt &&
2372 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2373 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2374 return false;
2375 }
2376 return true;
2377
2378 case Stmt::LabelStmtClass:
2379 case Stmt::GotoStmtClass:
2380 case Stmt::IndirectGotoStmtClass:
2381 if (Cxx2bLoc.isInvalid())
2382 Cxx2bLoc = S->getBeginLoc();
2383 for (Stmt *SubStmt : S->children()) {
2384 if (SubStmt &&
2385 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2386 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2387 return false;
2388 }
2389 return true;
2390
2391 case Stmt::GCCAsmStmtClass:
2392 case Stmt::MSAsmStmtClass:
2393 // C++2a allows inline assembly statements.
2394 case Stmt::CXXTryStmtClass:
2395 if (Cxx2aLoc.isInvalid())
2396 Cxx2aLoc = S->getBeginLoc();
2397 for (Stmt *SubStmt : S->children()) {
2398 if (SubStmt &&
2399 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2400 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2401 return false;
2402 }
2403 return true;
2404
2405 case Stmt::CXXCatchStmtClass:
2406 // Do not bother checking the language mode (already covered by the
2407 // try block check).
2409 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2410 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2411 return false;
2412 return true;
2413
2414 default:
2415 if (!isa<Expr>(S))
2416 break;
2417
2418 // C++1y allows expression-statements.
2419 if (!Cxx1yLoc.isValid())
2420 Cxx1yLoc = S->getBeginLoc();
2421 return true;
2422 }
2423
2425 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2426 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2427 }
2428 return false;
2429}
2430
2431/// Check the body for the given constexpr function declaration only contains
2432/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2433///
2434/// \return true if the body is OK, false if we have found or diagnosed a
2435/// problem.
2436static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2437 Stmt *Body,
2440
2441 if (isa<CXXTryStmt>(Body)) {
2442 // C++11 [dcl.constexpr]p3:
2443 // The definition of a constexpr function shall satisfy the following
2444 // constraints: [...]
2445 // - its function-body shall be = delete, = default, or a
2446 // compound-statement
2447 //
2448 // C++11 [dcl.constexpr]p4:
2449 // In the definition of a constexpr constructor, [...]
2450 // - its function-body shall not be a function-try-block;
2451 //
2452 // This restriction is lifted in C++2a, as long as inner statements also
2453 // apply the general constexpr rules.
2454 switch (Kind) {
2456 if (!SemaRef.getLangOpts().CPlusPlus20)
2457 return false;
2458 break;
2459
2461 SemaRef.DiagCompat(Body->getBeginLoc(),
2462 diag_compat::constexpr_function_try_block)
2464 break;
2465 }
2466 }
2467
2468 // - its function-body shall be [...] a compound-statement that contains only
2469 // [... list of cases ...]
2470 //
2471 // Note that walking the children here is enough to properly check for
2472 // CompoundStmt and CXXTryStmt body.
2473 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2474 for (Stmt *SubStmt : Body->children()) {
2475 if (SubStmt &&
2476 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2477 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2478 return false;
2479 }
2480
2482 // If this is only valid as an extension, report that we don't satisfy the
2483 // constraints of the current language.
2484 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2485 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2486 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2487 return false;
2488 } else if (Cxx2bLoc.isValid()) {
2489 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2491 } else if (Cxx2aLoc.isValid()) {
2492 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2494 } else if (Cxx1yLoc.isValid()) {
2495 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2497 }
2498
2500 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2501 const CXXRecordDecl *RD = Constructor->getParent();
2502 // DR1359:
2503 // - every non-variant non-static data member and base class sub-object
2504 // shall be initialized;
2505 // DR1460:
2506 // - if the class is a union having variant members, exactly one of them
2507 // shall be initialized;
2508 if (RD->isUnion()) {
2509 if (Constructor->getNumCtorInitializers() == 0 &&
2510 RD->hasVariantMembers()) {
2512 SemaRef.DiagCompat(Dcl->getLocation(),
2513 diag_compat::constexpr_union_ctor_no_init);
2514 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2515 return false;
2516 }
2517 }
2518 } else if (!Constructor->isDependentContext() &&
2519 !Constructor->isDelegatingConstructor()) {
2520 // Skip detailed checking if we have enough initializers, and we would
2521 // allow at most one initializer per member.
2522 bool AnyAnonStructUnionMembers = false;
2523 unsigned Fields = 0;
2525 E = RD->field_end(); I != E; ++I, ++Fields) {
2526 if (I->isAnonymousStructOrUnion()) {
2527 AnyAnonStructUnionMembers = true;
2528 break;
2529 }
2530 }
2531 // DR1460:
2532 // - if the class is a union-like class, but is not a union, for each of
2533 // its anonymous union members having variant members, exactly one of
2534 // them shall be initialized;
2535 if (AnyAnonStructUnionMembers ||
2536 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2537 // Check initialization of non-static data members. Base classes are
2538 // always initialized so do not need to be checked. Dependent bases
2539 // might not have initializers in the member initializer list.
2541 for (const auto *I: Constructor->inits()) {
2542 if (FieldDecl *FD = I->getMember())
2543 Inits.insert(FD);
2544 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2545 Inits.insert(ID->chain_begin(), ID->chain_end());
2546 }
2547
2548 bool Diagnosed = false;
2549 for (auto *I : RD->fields())
2550 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2551 Kind))
2552 return false;
2553 }
2554 }
2555 } else {
2556 if (ReturnStmts.empty()) {
2557 switch (Kind) {
2559 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2560 return false;
2561 break;
2562
2564 // The formal requirements don't include this rule in C++14, even
2565 // though the "must be able to produce a constant expression" rules
2566 // still imply it in some cases.
2567 if (!SemaRef.getLangOpts().CPlusPlus14)
2568 return false;
2569 break;
2570 }
2571 } else if (ReturnStmts.size() > 1) {
2572 switch (Kind) {
2574 SemaRef.DiagCompat(ReturnStmts.back(),
2575 diag_compat::constexpr_body_multiple_return);
2576 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2577 SemaRef.Diag(ReturnStmts[I],
2578 diag::note_constexpr_body_previous_return);
2579 break;
2580
2582 if (!SemaRef.getLangOpts().CPlusPlus14)
2583 return false;
2584 break;
2585 }
2586 }
2587 }
2588
2589 // C++11 [dcl.constexpr]p5:
2590 // if no function argument values exist such that the function invocation
2591 // substitution would produce a constant expression, the program is
2592 // ill-formed; no diagnostic required.
2593 // C++11 [dcl.constexpr]p3:
2594 // - every constructor call and implicit conversion used in initializing the
2595 // return value shall be one of those allowed in a constant expression.
2596 // C++11 [dcl.constexpr]p4:
2597 // - every constructor involved in initializing non-static data members and
2598 // base class sub-objects shall be a constexpr constructor.
2599 //
2600 // Note that this rule is distinct from the "requirements for a constexpr
2601 // function", so is not checked in CheckValid mode. Because the check for
2602 // constexpr potential is expensive, skip the check if the diagnostic is
2603 // disabled, the function is declared in a system header, or we're in C++23
2604 // or later mode (see https://wg21.link/P2448).
2605 bool SkipCheck =
2606 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2607 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2608 SemaRef.getDiagnostics().isIgnored(
2609 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2611 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2612 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2613 SemaRef.Diag(Dcl->getLocation(),
2614 diag::ext_constexpr_function_never_constant_expr)
2615 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2616 << Dcl->getNameInfo().getSourceRange();
2617 for (const auto &Diag : Diags)
2618 SemaRef.Diag(Diag.first, Diag.second);
2619 // Don't return false here: we allow this for compatibility in
2620 // system headers.
2621 }
2622
2623 return true;
2624}
2625
2627 const FunctionDecl *Dcl) {
2628 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2630 // Skip emitting a missing return error diagnostic for non-void functions
2631 // since C++23 no longer mandates constexpr functions to yield constant
2632 // expressions.
2633 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2634 return true;
2635
2636 // C++14 doesn't require constexpr functions to contain a 'return'
2637 // statement. We still do, unless the return type might be void, because
2638 // otherwise if there's no return statement, the function cannot
2639 // be used in a core constant expression.
2640 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2641 SemaRef.Diag(Dcl->getLocation(),
2642 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2643 : diag::err_constexpr_body_no_return)
2644 << Dcl->isConsteval();
2645 return OK;
2646}
2647
2649 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2651 return true;
2655 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2656 if (it != UndefinedButUsed.end()) {
2657 Diag(it->second, diag::err_immediate_function_used_before_definition)
2658 << it->first;
2659 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2660 if (FD->isImmediateFunction() && !FD->isConsteval())
2662 return false;
2663 }
2664 }
2665 return true;
2666}
2667
2669 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2670 "expected an immediate function");
2671 assert(FD->hasBody() && "expected the function to have a body");
2672 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2673 Sema &SemaRef;
2674
2675 const FunctionDecl *ImmediateFn;
2676 bool ImmediateFnIsConstructor;
2677 CXXConstructorDecl *CurrentConstructor = nullptr;
2678 CXXCtorInitializer *CurrentInit = nullptr;
2679
2680 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2681 : SemaRef(SemaRef), ImmediateFn(FD),
2682 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2683 ShouldVisitImplicitCode = true;
2684 ShouldVisitLambdaBody = false;
2685 }
2686
2687 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2688 SourceLocation Loc = E->getBeginLoc();
2689 SourceRange Range = E->getSourceRange();
2690 if (CurrentConstructor && CurrentInit) {
2691 Loc = CurrentConstructor->getLocation();
2692 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2693 : SourceRange();
2694 }
2695
2696 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2697
2698 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2699 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2700 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2701 << (InitializedField != nullptr)
2702 << (CurrentInit && !CurrentInit->isWritten())
2703 << InitializedField << Range;
2704 }
2705 bool TraverseCallExpr(CallExpr *E) override {
2706 if (const auto *DR =
2707 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2708 DR && DR->isImmediateEscalating()) {
2709 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2710 return false;
2711 }
2712
2713 for (Expr *A : E->arguments())
2714 if (!TraverseStmt(A))
2715 return false;
2716
2717 return true;
2718 }
2719
2720 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2721 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2722 ReferencedFn && E->isImmediateEscalating()) {
2723 Diag(E, ReferencedFn, /*IsCall=*/false);
2724 return false;
2725 }
2726
2727 return true;
2728 }
2729
2730 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2732 if (E->isImmediateEscalating()) {
2733 Diag(E, D, /*IsCall=*/true);
2734 return false;
2735 }
2736 return true;
2737 }
2738
2739 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2740 llvm::SaveAndRestore RAII(CurrentInit, Init);
2742 }
2743
2744 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2745 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2746 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2747 }
2748
2749 bool TraverseType(QualType T, bool TraverseQualifier) override {
2750 return true;
2751 }
2752 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2753
2754 } Visitor(*this, FD);
2755 Visitor.TraverseDecl(FD);
2756}
2757
2759 assert(getLangOpts().CPlusPlus && "No class names in C!");
2760
2761 if (SS && SS->isInvalid())
2762 return nullptr;
2763
2764 if (SS && SS->isNotEmpty()) {
2765 DeclContext *DC = computeDeclContext(*SS, true);
2766 return dyn_cast_or_null<CXXRecordDecl>(DC);
2767 }
2768
2769 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2770}
2771
2773 const CXXScopeSpec *SS) {
2774 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2775 return CurDecl && &II == CurDecl->getIdentifier();
2776}
2777
2779 assert(getLangOpts().CPlusPlus && "No class names in C!");
2780
2781 if (!getLangOpts().SpellChecking)
2782 return false;
2783
2784 CXXRecordDecl *CurDecl;
2785 if (SS && SS->isSet() && !SS->isInvalid()) {
2786 DeclContext *DC = computeDeclContext(*SS, true);
2787 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2788 } else
2789 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2790
2791 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2792 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2793 < II->getLength()) {
2794 II = CurDecl->getIdentifier();
2795 return true;
2796 }
2797
2798 return false;
2799}
2800
2802 SourceRange SpecifierRange,
2803 bool Virtual, AccessSpecifier Access,
2804 TypeSourceInfo *TInfo,
2805 SourceLocation EllipsisLoc) {
2806 QualType BaseType = TInfo->getType();
2807 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2808 if (BaseType->containsErrors()) {
2809 // Already emitted a diagnostic when parsing the error type.
2810 return nullptr;
2811 }
2812
2813 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2814 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2815 << TInfo->getTypeLoc().getSourceRange();
2816 EllipsisLoc = SourceLocation();
2817 }
2818
2819 auto *BaseDecl =
2820 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2821 // C++ [class.derived.general]p2:
2822 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2823 // that is not an incompletely defined class; any cv-qualifiers are
2824 // ignored.
2825 if (BaseDecl) {
2826 // C++ [class.union.general]p4:
2827 // [...] A union shall not be used as a base class.
2828 if (BaseDecl->isUnion()) {
2829 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2830 return nullptr;
2831 }
2832
2833 if (BaseType.hasQualifiers()) {
2834 std::string Quals =
2835 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2836 Diag(BaseLoc, diag::warn_qual_base_type)
2837 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2838 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2839 }
2840
2841 // For the MS ABI, propagate DLL attributes to base class templates.
2842 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2843 Context.getTargetInfo().getTriple().isPS()) {
2844 if (Attr *ClassAttr = getDLLAttr(Class)) {
2845 if (auto *BaseSpec =
2846 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2847 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2848 BaseLoc);
2849 }
2850 }
2851 }
2852
2853 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2854 SpecifierRange)) {
2855 Class->setInvalidDecl();
2856 return nullptr;
2857 }
2858
2859 BaseDecl = BaseDecl->getDefinition();
2860 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2861
2862 // Microsoft docs say:
2863 // "If a base-class has a code_seg attribute, derived classes must have the
2864 // same attribute."
2865 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2866 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2867 if ((DerivedCSA || BaseCSA) &&
2868 (!BaseCSA || !DerivedCSA ||
2869 BaseCSA->getName() != DerivedCSA->getName())) {
2870 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2871 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2872 << BaseDecl;
2873 return nullptr;
2874 }
2875
2876 // A class which contains a flexible array member is not suitable for use as
2877 // a base class:
2878 // - If the layout determines that a base comes before another base,
2879 // the flexible array member would index into the subsequent base.
2880 // - If the layout determines that base comes before the derived class,
2881 // the flexible array member would index into the derived class.
2882 if (BaseDecl->hasFlexibleArrayMember()) {
2883 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2884 << BaseDecl->getDeclName();
2885 return nullptr;
2886 }
2887
2888 // C++ [class]p3:
2889 // If a class is marked final and it appears as a base-type-specifier in
2890 // base-clause, the program is ill-formed.
2891 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2892 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2893 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2894 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2895 << BaseDecl->getDeclName() << FA->getRange();
2896 return nullptr;
2897 }
2898
2899 // If the base class is invalid the derived class is as well.
2900 if (BaseDecl->isInvalidDecl())
2901 Class->setInvalidDecl();
2902 } else if (BaseType->isDependentType()) {
2903 // Make sure that we don't make an ill-formed AST where the type of the
2904 // Class is non-dependent and its attached base class specifier is an
2905 // dependent type, which violates invariants in many clang code paths (e.g.
2906 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2907 // explicitly mark the Class decl invalid. The diagnostic was already
2908 // emitted.
2909 if (!Class->isDependentContext())
2910 Class->setInvalidDecl();
2911 } else {
2912 // The base class is some non-dependent non-class type.
2913 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2914 return nullptr;
2915 }
2916
2917 // In HLSL, unspecified class access is public rather than private.
2918 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2919 Access == AS_none)
2920 Access = AS_public;
2921
2922 // Create the base specifier.
2923 return new (Context) CXXBaseSpecifier(
2924 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2925 Access, TInfo, EllipsisLoc);
2926}
2927
2929 const ParsedAttributesView &Attributes,
2930 bool Virtual, AccessSpecifier Access,
2931 ParsedType basetype, SourceLocation BaseLoc,
2932 SourceLocation EllipsisLoc) {
2933 if (!classdecl)
2934 return true;
2935
2936 AdjustDeclIfTemplate(classdecl);
2937 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2938 if (!Class)
2939 return true;
2940
2941 // We haven't yet attached the base specifiers.
2942 Class->setIsParsingBaseSpecifiers();
2943
2944 // We do not support any C++11 attributes on base-specifiers yet.
2945 // Diagnose any attributes we see.
2946 for (const ParsedAttr &AL : Attributes) {
2947 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2948 continue;
2949 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2951 else
2952 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2953 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2954 }
2955
2956 TypeSourceInfo *TInfo = nullptr;
2957 GetTypeFromParser(basetype, &TInfo);
2958
2959 if (EllipsisLoc.isInvalid() &&
2960 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2962 return true;
2963
2964 // C++ [class.union.general]p4:
2965 // [...] A union shall not have base classes.
2966 if (Class->isUnion()) {
2967 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2968 << SpecifierRange;
2969 return true;
2970 }
2971
2972 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2973 Virtual, Access, TInfo,
2974 EllipsisLoc))
2975 return BaseSpec;
2976
2977 Class->setInvalidDecl();
2978 return true;
2979}
2980
2981/// Use small set to collect indirect bases. As this is only used
2982/// locally, there's no need to abstract the small size parameter.
2984
2985/// Recursively add the bases of Type. Don't add Type itself.
2986static void
2988 const QualType &Type)
2989{
2990 // Even though the incoming type is a base, it might not be
2991 // a class -- it could be a template parm, for instance.
2992 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2993 // Iterate over its bases.
2994 for (const auto &BaseSpec : Decl->bases()) {
2995 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2996 .getUnqualifiedType();
2997 if (Set.insert(Base).second)
2998 // If we've not already seen it, recurse.
2999 NoteIndirectBases(Context, Set, Base);
3000 }
3001 }
3002}
3003
3006 if (Bases.empty())
3007 return false;
3008
3009 // Used to keep track of which base types we have already seen, so
3010 // that we can properly diagnose redundant direct base types. Note
3011 // that the key is always the unqualified canonical type of the base
3012 // class.
3013 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
3014
3015 // Used to track indirect bases so we can see if a direct base is
3016 // ambiguous.
3017 IndirectBaseSet IndirectBaseTypes;
3018
3019 // Copy non-redundant base specifiers into permanent storage.
3020 unsigned NumGoodBases = 0;
3021 bool Invalid = false;
3022 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3023 QualType NewBaseType
3024 = Context.getCanonicalType(Bases[idx]->getType());
3025 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3026
3027 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3028 if (KnownBase) {
3029 // C++ [class.mi]p3:
3030 // A class shall not be specified as a direct base class of a
3031 // derived class more than once.
3032 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
3033 << KnownBase->getType() << Bases[idx]->getSourceRange();
3034
3035 // Delete the duplicate base class specifier; we're going to
3036 // overwrite its pointer later.
3037 Context.Deallocate(Bases[idx]);
3038
3039 Invalid = true;
3040 } else {
3041 // Okay, add this new base class.
3042 KnownBase = Bases[idx];
3043 Bases[NumGoodBases++] = Bases[idx];
3044
3045 if (NewBaseType->isDependentType())
3046 continue;
3047 // Note this base's direct & indirect bases, if there could be ambiguity.
3048 if (Bases.size() > 1)
3049 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3050
3051 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3052 if (Class->isInterface() &&
3053 (!RD->isInterfaceLike() ||
3054 KnownBase->getAccessSpecifier() != AS_public)) {
3055 // The Microsoft extension __interface does not permit bases that
3056 // are not themselves public interfaces.
3057 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3058 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3059 << RD->getSourceRange();
3060 Invalid = true;
3061 }
3062 if (RD->hasAttr<WeakAttr>())
3063 Class->addAttr(WeakAttr::CreateImplicit(Context));
3064 }
3065 }
3066 }
3067
3068 // Attach the remaining base class specifiers to the derived class.
3069 Class->setBases(Bases.data(), NumGoodBases);
3070
3071 // Check that the only base classes that are duplicate are virtual.
3072 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3073 // Check whether this direct base is inaccessible due to ambiguity.
3074 QualType BaseType = Bases[idx]->getType();
3075
3076 // Skip all dependent types in templates being used as base specifiers.
3077 // Checks below assume that the base specifier is a CXXRecord.
3078 if (BaseType->isDependentType())
3079 continue;
3080
3081 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3082 .getUnqualifiedType();
3083
3084 if (IndirectBaseTypes.count(CanonicalBase)) {
3085 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3086 /*DetectVirtual=*/true);
3087 bool found
3088 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3089 assert(found);
3090 (void)found;
3091
3092 if (Paths.isAmbiguous(CanonicalBase))
3093 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3094 << BaseType << getAmbiguousPathsDisplayString(Paths)
3095 << Bases[idx]->getSourceRange();
3096 else
3097 assert(Bases[idx]->isVirtual());
3098 }
3099
3100 // Delete the base class specifier, since its data has been copied
3101 // into the CXXRecordDecl.
3102 Context.Deallocate(Bases[idx]);
3103 }
3104
3105 return Invalid;
3106}
3107
3110 if (!ClassDecl || Bases.empty())
3111 return;
3112
3113 AdjustDeclIfTemplate(ClassDecl);
3114 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3115}
3116
3118 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3119 if (!getLangOpts().CPlusPlus)
3120 return false;
3121
3122 if (!Base || !Derived)
3123 return false;
3124
3125 // If either the base or the derived type is invalid, don't try to
3126 // check whether one is derived from the other.
3127 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3128 return false;
3129
3130 // FIXME: In a modules build, do we need the entire path to be visible for us
3131 // to be able to use the inheritance relationship?
3132 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3133 !Derived->isBeingDefined())
3134 return false;
3135
3136 return Derived->isDerivedFrom(Base, Paths);
3137}
3138
3141 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3142 /*DetectVirtual=*/false);
3143 return IsDerivedFrom(Loc, Derived, Base, Paths);
3144}
3145
3147 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3148 /*DetectVirtual=*/false);
3149 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3150 Base->getAsCXXRecordDecl(), Paths);
3151}
3152
3154 CXXBasePaths &Paths) {
3155 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3156 Base->getAsCXXRecordDecl(), Paths);
3157}
3158
3159static void BuildBasePathArray(const CXXBasePath &Path,
3160 CXXCastPath &BasePathArray) {
3161 // We first go backward and check if we have a virtual base.
3162 // FIXME: It would be better if CXXBasePath had the base specifier for
3163 // the nearest virtual base.
3164 unsigned Start = 0;
3165 for (unsigned I = Path.size(); I != 0; --I) {
3166 if (Path[I - 1].Base->isVirtual()) {
3167 Start = I - 1;
3168 break;
3169 }
3170 }
3171
3172 // Now add all bases.
3173 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3174 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3175}
3176
3177
3179 CXXCastPath &BasePathArray) {
3180 assert(BasePathArray.empty() && "Base path array must be empty!");
3181 assert(Paths.isRecordingPaths() && "Must record paths!");
3182 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3183}
3184
3185bool
3187 unsigned InaccessibleBaseID,
3188 unsigned AmbiguousBaseConvID,
3189 SourceLocation Loc, SourceRange Range,
3190 DeclarationName Name,
3191 CXXCastPath *BasePath,
3192 bool IgnoreAccess) {
3193 // First, determine whether the path from Derived to Base is
3194 // ambiguous. This is slightly more expensive than checking whether
3195 // the Derived to Base conversion exists, because here we need to
3196 // explore multiple paths to determine if there is an ambiguity.
3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3198 /*DetectVirtual=*/false);
3199 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3200 if (!DerivationOkay)
3201 return true;
3202
3203 const CXXBasePath *Path = nullptr;
3204 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3205 Path = &Paths.front();
3206
3207 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3208 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3209 // user to access such bases.
3210 if (!Path && getLangOpts().MSVCCompat) {
3211 for (const CXXBasePath &PossiblePath : Paths) {
3212 if (PossiblePath.size() == 1) {
3213 Path = &PossiblePath;
3214 if (AmbiguousBaseConvID)
3215 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3216 << Base << Derived << Range;
3217 break;
3218 }
3219 }
3220 }
3221
3222 if (Path) {
3223 if (!IgnoreAccess) {
3224 // Check that the base class can be accessed.
3225 switch (
3226 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3227 case AR_inaccessible:
3228 return true;
3229 case AR_accessible:
3230 case AR_dependent:
3231 case AR_delayed:
3232 break;
3233 }
3234 }
3235
3236 // Build a base path if necessary.
3237 if (BasePath)
3238 ::BuildBasePathArray(*Path, *BasePath);
3239 return false;
3240 }
3241
3242 if (AmbiguousBaseConvID) {
3243 // We know that the derived-to-base conversion is ambiguous, and
3244 // we're going to produce a diagnostic. Perform the derived-to-base
3245 // search just one more time to compute all of the possible paths so
3246 // that we can print them out. This is more expensive than any of
3247 // the previous derived-to-base checks we've done, but at this point
3248 // performance isn't as much of an issue.
3249 Paths.clear();
3250 Paths.setRecordingPaths(true);
3251 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3252 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3253 (void)StillOkay;
3254
3255 // Build up a textual representation of the ambiguous paths, e.g.,
3256 // D -> B -> A, that will be used to illustrate the ambiguous
3257 // conversions in the diagnostic. We only print one of the paths
3258 // to each base class subobject.
3259 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3260
3261 Diag(Loc, AmbiguousBaseConvID)
3262 << Derived << Base << PathDisplayStr << Range << Name;
3263 }
3264 return true;
3265}
3266
3267bool
3269 SourceLocation Loc, SourceRange Range,
3270 CXXCastPath *BasePath,
3271 bool IgnoreAccess) {
3273 Derived, Base, diag::err_upcast_to_inaccessible_base,
3274 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3275 BasePath, IgnoreAccess);
3276}
3277
3279 std::string PathDisplayStr;
3280 std::set<unsigned> DisplayedPaths;
3281 for (const CXXBasePath &Path : Paths) {
3282 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3283 // We haven't displayed a path to this particular base
3284 // class subobject yet.
3285 PathDisplayStr += "\n ";
3286 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3287 .getAsString();
3288 for (const CXXBasePathElement &Element : Path)
3289 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3290 }
3291 }
3292
3293 return PathDisplayStr;
3294}
3295
3296//===----------------------------------------------------------------------===//
3297// C++ class member Handling
3298//===----------------------------------------------------------------------===//
3299
3301 SourceLocation ColonLoc,
3302 const ParsedAttributesView &Attrs) {
3303 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3305 ASLoc, ColonLoc);
3306 CurContext->addHiddenDecl(ASDecl);
3307 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3308}
3309
3311 if (D->isInvalidDecl())
3312 return;
3313
3314 // We only care about "override" and "final" declarations.
3315 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3316 return;
3317
3318 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3319
3320 // We can't check dependent instance methods.
3321 if (MD && MD->isInstance() &&
3322 (MD->getParent()->hasAnyDependentBases() ||
3323 MD->getType()->isDependentType()))
3324 return;
3325
3326 if (MD && !MD->isVirtual()) {
3327 // If we have a non-virtual method, check if it hides a virtual method.
3328 // (In that case, it's most likely the method has the wrong type.)
3329 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3330 FindHiddenVirtualMethods(MD, OverloadedMethods);
3331
3332 if (!OverloadedMethods.empty()) {
3333 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3334 Diag(OA->getLocation(),
3335 diag::override_keyword_hides_virtual_member_function)
3336 << "override" << (OverloadedMethods.size() > 1);
3337 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3338 Diag(FA->getLocation(),
3339 diag::override_keyword_hides_virtual_member_function)
3340 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3341 << (OverloadedMethods.size() > 1);
3342 }
3343 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3344 MD->setInvalidDecl();
3345 return;
3346 }
3347 // Fall through into the general case diagnostic.
3348 // FIXME: We might want to attempt typo correction here.
3349 }
3350
3351 if (!MD || !MD->isVirtual()) {
3352 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3353 Diag(OA->getLocation(),
3354 diag::override_keyword_only_allowed_on_virtual_member_functions)
3355 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3356 D->dropAttr<OverrideAttr>();
3357 }
3358 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3359 Diag(FA->getLocation(),
3360 diag::override_keyword_only_allowed_on_virtual_member_functions)
3361 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3362 << FixItHint::CreateRemoval(FA->getLocation());
3363 D->dropAttr<FinalAttr>();
3364 }
3365 return;
3366 }
3367
3368 // C++11 [class.virtual]p5:
3369 // If a function is marked with the virt-specifier override and
3370 // does not override a member function of a base class, the program is
3371 // ill-formed.
3372 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3373 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3374 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3375 << MD->getDeclName();
3376}
3377
3379 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3380 return;
3381 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3382 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3383 return;
3384
3385 SourceLocation Loc = MD->getLocation();
3386 SourceLocation SpellingLoc = Loc;
3387 if (getSourceManager().isMacroArgExpansion(Loc))
3388 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3389 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3390 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3391 return;
3392
3393 if (MD->size_overridden_methods() > 0) {
3394 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3395 unsigned DiagID =
3396 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3397 ? DiagInconsistent
3398 : DiagSuggest;
3399 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3400 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3401 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3402 };
3403 if (isa<CXXDestructorDecl>(MD))
3404 EmitDiag(
3405 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3406 diag::warn_suggest_destructor_marked_not_override_overriding);
3407 else
3408 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3409 diag::warn_suggest_function_marked_not_override_overriding);
3410 }
3411}
3412
3414 const CXXMethodDecl *Old) {
3415 FinalAttr *FA = Old->getAttr<FinalAttr>();
3416 if (!FA)
3417 return false;
3418
3419 Diag(New->getLocation(), diag::err_final_function_overridden)
3420 << New->getDeclName()
3421 << FA->isSpelledAsSealed();
3422 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3423 return true;
3424}
3425
3427 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3428 // FIXME: Destruction of ObjC lifetime types has side-effects.
3429 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3430 return !RD->isCompleteDefinition() ||
3431 !RD->hasTrivialDefaultConstructor() ||
3432 !RD->hasTrivialDestructor();
3433 return false;
3434}
3435
3436void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3437 DeclarationName FieldName,
3438 const CXXRecordDecl *RD,
3439 bool DeclIsField) {
3440 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3441 return;
3442
3443 // To record a shadowed field in a base
3444 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3445 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3446 CXXBasePath &Path) {
3447 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3448 // Record an ambiguous path directly
3449 if (Bases.find(Base) != Bases.end())
3450 return true;
3451 for (const auto Field : Base->lookup(FieldName)) {
3452 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3453 Field->getAccess() != AS_private) {
3454 assert(Field->getAccess() != AS_none);
3455 assert(Bases.find(Base) == Bases.end());
3456 Bases[Base] = Field;
3457 return true;
3458 }
3459 }
3460 return false;
3461 };
3462
3463 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3464 /*DetectVirtual=*/true);
3465 if (!RD->lookupInBases(FieldShadowed, Paths))
3466 return;
3467
3468 for (const auto &P : Paths) {
3469 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3470 auto It = Bases.find(Base);
3471 // Skip duplicated bases
3472 if (It == Bases.end())
3473 continue;
3474 auto BaseField = It->second;
3475 assert(BaseField->getAccess() != AS_private);
3476 if (AS_none !=
3477 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3478 Diag(Loc, diag::warn_shadow_field)
3479 << FieldName << RD << Base << DeclIsField;
3480 Diag(BaseField->getLocation(), diag::note_shadow_field);
3481 Bases.erase(It);
3482 }
3483 }
3484}
3485
3486template <typename AttrType>
3487inline static bool HasAttribute(const QualType &T) {
3488 if (const TagDecl *TD = T->getAsTagDecl())
3489 return TD->hasAttr<AttrType>();
3490 if (const TypedefType *TDT = T->getAs<TypedefType>())
3491 return TDT->getDecl()->hasAttr<AttrType>();
3492 return false;
3493}
3494
3495static bool IsUnusedPrivateField(const FieldDecl *FD) {
3496 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3497 QualType FieldType = FD->getType();
3498 if (HasAttribute<WarnUnusedAttr>(FieldType))
3499 return true;
3500
3501 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3502 !FD->getParent()->isDependentContext() &&
3503 !HasAttribute<UnusedAttr>(FieldType) &&
3505 }
3506 return false;
3507}
3508
3509NamedDecl *
3511 MultiTemplateParamsArg TemplateParameterLists,
3512 Expr *BitWidth, const VirtSpecifiers &VS,
3513 InClassInitStyle InitStyle) {
3514 const DeclSpec &DS = D.getDeclSpec();
3516 DeclarationName Name = NameInfo.getName();
3517 SourceLocation Loc = NameInfo.getLoc();
3518
3519 // For anonymous bitfields, the location should point to the type.
3520 if (Loc.isInvalid())
3521 Loc = D.getBeginLoc();
3522
3524 assert(!DS.isFriendSpecified());
3525
3526 bool isFunc = D.isDeclarationOfFunction();
3527 const ParsedAttr *MSPropertyAttr =
3529
3530 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3531 // The Microsoft extension __interface only permits public member functions
3532 // and prohibits constructors, destructors, operators, non-public member
3533 // functions, static methods and data members.
3534 unsigned InvalidDecl;
3535 bool ShowDeclName = true;
3536 if (!isFunc &&
3537 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3538 InvalidDecl = 0;
3539 else if (!isFunc)
3540 InvalidDecl = 1;
3541 else if (AS != AS_public)
3542 InvalidDecl = 2;
3544 InvalidDecl = 3;
3545 else switch (Name.getNameKind()) {
3547 InvalidDecl = 4;
3548 ShowDeclName = false;
3549 break;
3550
3552 InvalidDecl = 5;
3553 ShowDeclName = false;
3554 break;
3555
3558 InvalidDecl = 6;
3559 break;
3560
3561 default:
3562 InvalidDecl = 0;
3563 break;
3564 }
3565
3566 if (InvalidDecl) {
3567 if (ShowDeclName)
3568 Diag(Loc, diag::err_invalid_member_in_interface)
3569 << (InvalidDecl-1) << Name;
3570 else
3571 Diag(Loc, diag::err_invalid_member_in_interface)
3572 << (InvalidDecl-1) << "";
3573 return nullptr;
3574 }
3575 }
3576
3577 // HLSL prohibits user defined constructors and destructors.
3578 if (getLangOpts().HLSL) {
3579 switch (Name.getNameKind()) {
3582 Diag(Loc, diag::err_hlsl_cstor_dstor);
3583 return nullptr;
3584 default:
3585 break;
3586 }
3587 }
3588
3589 // C++ 9.2p6: A member shall not be declared to have automatic storage
3590 // duration (auto, register) or with the extern storage-class-specifier.
3591 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3592 // data members and cannot be applied to names declared const or static,
3593 // and cannot be applied to reference members.
3594 switch (DS.getStorageClassSpec()) {
3598 break;
3600 if (isFunc) {
3601 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3602
3603 // FIXME: It would be nicer if the keyword was ignored only for this
3604 // declarator. Otherwise we could get follow-up errors.
3606 }
3607 break;
3608 default:
3610 diag::err_storageclass_invalid_for_member);
3612 break;
3613 }
3614
3615 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3617 !isFunc && TemplateParameterLists.empty();
3618
3619 if (DS.hasConstexprSpecifier() && isInstField) {
3621 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3622 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3623 if (InitStyle == ICIS_NoInit) {
3624 B << 0 << 0;
3626 B << FixItHint::CreateRemoval(ConstexprLoc);
3627 else {
3628 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3630 const char *PrevSpec;
3631 unsigned DiagID;
3632 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3633 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3634 (void)Failed;
3635 assert(!Failed && "Making a constexpr member const shouldn't fail");
3636 }
3637 } else {
3638 B << 1;
3639 const char *PrevSpec;
3640 unsigned DiagID;
3642 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3643 Context.getPrintingPolicy())) {
3645 "This is the only DeclSpec that should fail to be applied");
3646 B << 1;
3647 } else {
3648 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3649 isInstField = false;
3650 }
3651 }
3652 }
3653
3655 if (isInstField) {
3656 CXXScopeSpec &SS = D.getCXXScopeSpec();
3657
3658 // Data members must have identifiers for names.
3659 if (!Name.isIdentifier()) {
3660 Diag(Loc, diag::err_bad_variable_name)
3661 << Name;
3662 return nullptr;
3663 }
3664
3667 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3668 << II
3672 D.SetIdentifier(II, Loc);
3673 }
3674
3675 if (SS.isSet() && !SS.isInvalid()) {
3676 // The user provided a superfluous scope specifier inside a class
3677 // definition:
3678 //
3679 // class X {
3680 // int X::member;
3681 // };
3682 if (DeclContext *DC = computeDeclContext(SS, false)) {
3683 TemplateIdAnnotation *TemplateId =
3685 ? D.getName().TemplateId
3686 : nullptr;
3688 TemplateId,
3689 /*IsMemberSpecialization=*/false);
3690 } else {
3691 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3692 << Name << SS.getRange();
3693 }
3694 SS.clear();
3695 }
3696
3697 if (MSPropertyAttr) {
3699 BitWidth, InitStyle, AS, *MSPropertyAttr);
3700 if (!Member)
3701 return nullptr;
3702 isInstField = false;
3703 } else {
3705 BitWidth, InitStyle, AS);
3706 if (!Member)
3707 return nullptr;
3708 }
3709
3710 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3711 } else {
3712 Member = HandleDeclarator(S, D, TemplateParameterLists);
3713 if (!Member)
3714 return nullptr;
3715
3716 // Non-instance-fields can't have a bitfield.
3717 if (BitWidth) {
3718 if (Member->isInvalidDecl()) {
3719 // don't emit another diagnostic.
3721 // C++ 9.6p3: A bit-field shall not be a static member.
3722 // "static member 'A' cannot be a bit-field"
3723 Diag(Loc, diag::err_static_not_bitfield)
3724 << Name << BitWidth->getSourceRange();
3725 } else if (isa<TypedefDecl>(Member)) {
3726 // "typedef member 'x' cannot be a bit-field"
3727 Diag(Loc, diag::err_typedef_not_bitfield)
3728 << Name << BitWidth->getSourceRange();
3729 } else {
3730 // A function typedef ("typedef int f(); f a;").
3731 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3732 Diag(Loc, diag::err_not_integral_type_bitfield)
3733 << Name << cast<ValueDecl>(Member)->getType()
3734 << BitWidth->getSourceRange();
3735 }
3736
3737 BitWidth = nullptr;
3738 Member->setInvalidDecl();
3739 }
3740
3741 NamedDecl *NonTemplateMember = Member;
3742 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3743 NonTemplateMember = FunTmpl->getTemplatedDecl();
3744 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3745 NonTemplateMember = VarTmpl->getTemplatedDecl();
3746
3747 Member->setAccess(AS);
3748
3749 // If we have declared a member function template or static data member
3750 // template, set the access of the templated declaration as well.
3751 if (NonTemplateMember != Member)
3752 NonTemplateMember->setAccess(AS);
3753
3754 // C++ [temp.deduct.guide]p3:
3755 // A deduction guide [...] for a member class template [shall be
3756 // declared] with the same access [as the template].
3757 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3758 auto *TD = DG->getDeducedTemplate();
3759 // Access specifiers are only meaningful if both the template and the
3760 // deduction guide are from the same scope.
3761 if (AS != TD->getAccess() &&
3762 TD->getDeclContext()->getRedeclContext()->Equals(
3763 DG->getDeclContext()->getRedeclContext())) {
3764 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3765 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3766 << TD->getAccess();
3767 const AccessSpecDecl *LastAccessSpec = nullptr;
3768 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3769 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3770 LastAccessSpec = AccessSpec;
3771 }
3772 assert(LastAccessSpec && "differing access with no access specifier");
3773 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3774 << AS;
3775 }
3776 }
3777 }
3778
3779 if (VS.isOverrideSpecified())
3780 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3781 if (VS.isFinalSpecified())
3782 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3784 ? FinalAttr::Keyword_sealed
3785 : FinalAttr::Keyword_final));
3786
3787 if (VS.getLastLocation().isValid()) {
3788 // Update the end location of a method that has a virt-specifiers.
3789 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3790 MD->setRangeEnd(VS.getLastLocation());
3791 }
3792
3794
3795 assert((Name || isInstField) && "No identifier for non-field ?");
3796
3797 if (isInstField) {
3799 FieldCollector->Add(FD);
3800
3801 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3803 // Remember all explicit private FieldDecls that have a name, no side
3804 // effects and are not part of a dependent type declaration.
3805 UnusedPrivateFields.insert(FD);
3806 }
3807 }
3808
3809 return Member;
3810}
3811
3812namespace {
3813 class UninitializedFieldVisitor
3814 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3815 Sema &S;
3816 // List of Decls to generate a warning on. Also remove Decls that become
3817 // initialized.
3818 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3819 // List of base classes of the record. Classes are removed after their
3820 // initializers.
3821 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3822 // Vector of decls to be removed from the Decl set prior to visiting the
3823 // nodes. These Decls may have been initialized in the prior initializer.
3825 // If non-null, add a note to the warning pointing back to the constructor.
3827 // Variables to hold state when processing an initializer list. When
3828 // InitList is true, special case initialization of FieldDecls matching
3829 // InitListFieldDecl.
3830 bool InitList;
3831 FieldDecl *InitListFieldDecl;
3832 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3833
3834 public:
3836 UninitializedFieldVisitor(Sema &S,
3837 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3838 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3839 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3840 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3841
3842 // Returns true if the use of ME is not an uninitialized use.
3843 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3844 bool CheckReferenceOnly) {
3846 bool ReferenceField = false;
3847 while (ME) {
3848 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3849 if (!FD)
3850 return false;
3851 Fields.push_back(FD);
3852 if (FD->getType()->isReferenceType())
3853 ReferenceField = true;
3854 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3855 }
3856
3857 // Binding a reference to an uninitialized field is not an
3858 // uninitialized use.
3859 if (CheckReferenceOnly && !ReferenceField)
3860 return true;
3861
3862 // Discard the first field since it is the field decl that is being
3863 // initialized.
3864 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3865 auto UsedIter = UsedFields.begin();
3866 const auto UsedEnd = UsedFields.end();
3867
3868 for (const unsigned Orig : InitFieldIndex) {
3869 if (UsedIter == UsedEnd)
3870 break;
3871 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3872 if (UsedIndex < Orig)
3873 return true;
3874 if (UsedIndex > Orig)
3875 break;
3876 ++UsedIter;
3877 }
3878
3879 return false;
3880 }
3881
3882 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3883 bool AddressOf) {
3885 return;
3886
3887 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3888 // or union.
3889 MemberExpr *FieldME = ME;
3890
3891 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3892
3893 Expr *Base = ME;
3894 while (MemberExpr *SubME =
3895 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3896
3897 if (isa<VarDecl>(SubME->getMemberDecl()))
3898 return;
3899
3900 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3901 if (!FD->isAnonymousStructOrUnion())
3902 FieldME = SubME;
3903
3904 if (!FieldME->getType().isPODType(S.Context))
3905 AllPODFields = false;
3906
3907 Base = SubME->getBase();
3908 }
3909
3910 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3911 Visit(Base);
3912 return;
3913 }
3914
3915 if (AddressOf && AllPODFields)
3916 return;
3917
3918 ValueDecl* FoundVD = FieldME->getMemberDecl();
3919
3920 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3921 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3922 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3923 }
3924
3925 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3926 QualType T = BaseCast->getType();
3927 if (T->isPointerType() &&
3928 BaseClasses.count(T->getPointeeType())) {
3929 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3930 << T->getPointeeType() << FoundVD;
3931 }
3932 }
3933 }
3934
3935 if (!Decls.count(FoundVD))
3936 return;
3937
3938 const bool IsReference = FoundVD->getType()->isReferenceType();
3939
3940 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3941 // Special checking for initializer lists.
3942 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3943 return;
3944 }
3945 } else {
3946 // Prevent double warnings on use of unbounded references.
3947 if (CheckReferenceOnly && !IsReference)
3948 return;
3949 }
3950
3951 unsigned diag = IsReference
3952 ? diag::warn_reference_field_is_uninit
3953 : diag::warn_field_is_uninit;
3954 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3955 if (Constructor)
3956 S.Diag(Constructor->getLocation(),
3957 diag::note_uninit_in_this_constructor)
3958 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3959
3960 }
3961
3962 void HandleValue(Expr *E, bool AddressOf) {
3963 E = E->IgnoreParens();
3964
3965 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3966 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3967 AddressOf /*AddressOf*/);
3968 return;
3969 }
3970
3971 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3972 Visit(CO->getCond());
3973 HandleValue(CO->getTrueExpr(), AddressOf);
3974 HandleValue(CO->getFalseExpr(), AddressOf);
3975 return;
3976 }
3977
3978 if (BinaryConditionalOperator *BCO =
3979 dyn_cast<BinaryConditionalOperator>(E)) {
3980 Visit(BCO->getCond());
3981 HandleValue(BCO->getFalseExpr(), AddressOf);
3982 return;
3983 }
3984
3985 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3986 HandleValue(OVE->getSourceExpr(), AddressOf);
3987 return;
3988 }
3989
3990 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3991 switch (BO->getOpcode()) {
3992 default:
3993 break;
3994 case(BO_PtrMemD):
3995 case(BO_PtrMemI):
3996 HandleValue(BO->getLHS(), AddressOf);
3997 Visit(BO->getRHS());
3998 return;
3999 case(BO_Comma):
4000 Visit(BO->getLHS());
4001 HandleValue(BO->getRHS(), AddressOf);
4002 return;
4003 }
4004 }
4005
4006 Visit(E);
4007 }
4008
4009 void CheckInitListExpr(InitListExpr *ILE) {
4010 InitFieldIndex.push_back(0);
4011 for (auto *Child : ILE->children()) {
4012 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
4013 CheckInitListExpr(SubList);
4014 } else {
4015 Visit(Child);
4016 }
4017 ++InitFieldIndex.back();
4018 }
4019 InitFieldIndex.pop_back();
4020 }
4021
4022 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4023 FieldDecl *Field, const Type *BaseClass) {
4024 // Remove Decls that may have been initialized in the previous
4025 // initializer.
4026 for (ValueDecl* VD : DeclsToRemove)
4027 Decls.erase(VD);
4028 DeclsToRemove.clear();
4029
4030 Constructor = FieldConstructor;
4031 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
4032
4033 if (ILE && Field) {
4034 InitList = true;
4035 InitListFieldDecl = Field;
4036 InitFieldIndex.clear();
4037 CheckInitListExpr(ILE);
4038 } else {
4039 InitList = false;
4040 Visit(E);
4041 }
4042
4043 if (Field)
4044 Decls.erase(Field);
4045 if (BaseClass)
4046 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4047 }
4048
4049 void VisitMemberExpr(MemberExpr *ME) {
4050 // All uses of unbounded reference fields will warn.
4051 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4052 }
4053
4054 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4055 if (E->getCastKind() == CK_LValueToRValue) {
4056 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4057 return;
4058 }
4059
4060 Inherited::VisitImplicitCastExpr(E);
4061 }
4062
4063 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4064 if (E->getConstructor()->isCopyConstructor()) {
4065 Expr *ArgExpr = E->getArg(0);
4066 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4067 if (ILE->getNumInits() == 1)
4068 ArgExpr = ILE->getInit(0);
4069 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4070 if (ICE->getCastKind() == CK_NoOp)
4071 ArgExpr = ICE->getSubExpr();
4072 HandleValue(ArgExpr, false /*AddressOf*/);
4073 return;
4074 }
4075 Inherited::VisitCXXConstructExpr(E);
4076 }
4077
4078 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4079 Expr *Callee = E->getCallee();
4080 if (isa<MemberExpr>(Callee)) {
4081 HandleValue(Callee, false /*AddressOf*/);
4082 for (auto *Arg : E->arguments())
4083 Visit(Arg);
4084 return;
4085 }
4086
4087 Inherited::VisitCXXMemberCallExpr(E);
4088 }
4089
4090 void VisitCallExpr(CallExpr *E) {
4091 // Treat std::move as a use.
4092 if (E->isCallToStdMove()) {
4093 HandleValue(E->getArg(0), /*AddressOf=*/false);
4094 return;
4095 }
4096
4097 Inherited::VisitCallExpr(E);
4098 }
4099
4100 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4101 Expr *Callee = E->getCallee();
4102
4103 if (isa<UnresolvedLookupExpr>(Callee))
4104 return Inherited::VisitCXXOperatorCallExpr(E);
4105
4106 Visit(Callee);
4107 for (auto *Arg : E->arguments())
4108 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4109 }
4110
4111 void VisitBinaryOperator(BinaryOperator *E) {
4112 // If a field assignment is detected, remove the field from the
4113 // uninitiailized field set.
4114 if (E->getOpcode() == BO_Assign)
4115 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4116 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4117 if (!FD->getType()->isReferenceType())
4118 DeclsToRemove.push_back(FD);
4119
4120 if (E->isCompoundAssignmentOp()) {
4121 HandleValue(E->getLHS(), false /*AddressOf*/);
4122 Visit(E->getRHS());
4123 return;
4124 }
4125
4126 Inherited::VisitBinaryOperator(E);
4127 }
4128
4129 void VisitUnaryOperator(UnaryOperator *E) {
4130 if (E->isIncrementDecrementOp()) {
4131 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4132 return;
4133 }
4134 if (E->getOpcode() == UO_AddrOf) {
4135 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4136 HandleValue(ME->getBase(), true /*AddressOf*/);
4137 return;
4138 }
4139 }
4140
4141 Inherited::VisitUnaryOperator(E);
4142 }
4143 };
4144
4145 // Diagnose value-uses of fields to initialize themselves, e.g.
4146 // foo(foo)
4147 // where foo is not also a parameter to the constructor.
4148 // Also diagnose across field uninitialized use such as
4149 // x(y), y(x)
4150 // TODO: implement -Wuninitialized and fold this into that framework.
4151 static void DiagnoseUninitializedFields(
4152 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4153
4154 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4155 Constructor->getLocation())) {
4156 return;
4157 }
4158
4159 if (Constructor->isInvalidDecl())
4160 return;
4161
4162 const CXXRecordDecl *RD = Constructor->getParent();
4163
4164 if (RD->isDependentContext())
4165 return;
4166
4167 // Holds fields that are uninitialized.
4168 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4169
4170 // At the beginning, all fields are uninitialized.
4171 for (auto *I : RD->decls()) {
4172 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4173 UninitializedFields.insert(FD);
4174 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4175 UninitializedFields.insert(IFD->getAnonField());
4176 }
4177 }
4178
4179 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4180 for (const auto &I : RD->bases()) {
4181 // Virtual bases are initialized from the most derived class, so an
4182 // abstract base class constructor can assume it to be initialized.
4183 if (I.isVirtual() && RD->isAbstract())
4184 continue;
4185 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4186 }
4187
4188 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4189 return;
4190
4191 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4192 UninitializedFields,
4193 UninitializedBaseClasses);
4194
4195 for (const auto *FieldInit : Constructor->inits()) {
4196 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4197 break;
4198
4199 Expr *InitExpr = FieldInit->getInit();
4200 if (!InitExpr)
4201 continue;
4202
4203 if (CXXDefaultInitExpr *Default =
4204 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4205 InitExpr = Default->getExpr();
4206 if (!InitExpr)
4207 continue;
4208 // In class initializers will point to the constructor.
4209 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4210 FieldInit->getAnyMember(),
4211 FieldInit->getBaseClass());
4212 } else {
4213 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4214 FieldInit->getAnyMember(),
4215 FieldInit->getBaseClass());
4216 }
4217 }
4218 }
4219} // namespace
4220
4222 // Create a synthetic function scope to represent the call to the constructor
4223 // that notionally surrounds a use of this initializer.
4225}
4226
4228 if (!D.isFunctionDeclarator())
4229 return;
4230 auto &FTI = D.getFunctionTypeInfo();
4231 if (!FTI.Params)
4232 return;
4233 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4234 FTI.NumParams)) {
4235 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4236 if (ParamDecl->getDeclName())
4237 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4238 }
4239}
4240
4242 return ActOnRequiresClause(ConstraintExpr);
4243}
4244
4246 if (ConstraintExpr.isInvalid())
4247 return ExprError();
4248
4249 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4251 return ExprError();
4252
4253 return ConstraintExpr;
4254}
4255
4263
4265 FieldDecl *FD, const InitializedEntity &Entity, Expr *InitExpr,
4266 SourceLocation InitLoc) {
4267 InitializationKind Kind =
4270 InitExpr->getBeginLoc(),
4271 InitExpr->getEndLoc())
4272 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4273 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4274 return Seq.Perform(*this, Entity, Kind, InitExpr);
4275}
4276
4278 SourceLocation InitLoc,
4279 ExprResult InitExpr) {
4280 // Pop the notional constructor scope we created earlier.
4281 PopFunctionScopeInfo(nullptr, D);
4282
4283 // Microsoft C++'s property declaration cannot have a default member
4284 // initializer.
4285 if (isa<MSPropertyDecl>(D)) {
4286 D->setInvalidDecl();
4287 return;
4288 }
4289
4290 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4291 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4292 "must set init style when field is created");
4293
4294 if (!InitExpr.isUsable() ||
4296 FD->setInvalidDecl();
4297 ExprResult RecoveryInit =
4298 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4299 if (RecoveryInit.isUsable())
4300 FD->setInClassInitializer(RecoveryInit.get());
4301 return;
4302 }
4303
4304 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4305 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4306 // C++11 [class.base.init]p7:
4307 // The initialization of each base and member constitutes a
4308 // full-expression.
4309 if (!InitExpr.isInvalid())
4310 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4311 if (InitExpr.isInvalid()) {
4312 FD->setInvalidDecl();
4313 return;
4314 }
4315 }
4316
4317 FD->setInClassInitializer(InitExpr.get());
4318}
4319
4320/// Find the direct and/or virtual base specifiers that
4321/// correspond to the given base type, for use in base initialization
4322/// within a constructor.
4323static bool FindBaseInitializer(Sema &SemaRef,
4324 CXXRecordDecl *ClassDecl,
4325 QualType BaseType,
4326 const CXXBaseSpecifier *&DirectBaseSpec,
4327 const CXXBaseSpecifier *&VirtualBaseSpec) {
4328 // First, check for a direct base class.
4329 DirectBaseSpec = nullptr;
4330 for (const auto &Base : ClassDecl->bases()) {
4331 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4332 // We found a direct base of this type. That's what we're
4333 // initializing.
4334 DirectBaseSpec = &Base;
4335 break;
4336 }
4337 }
4338
4339 // Check for a virtual base class.
4340 // FIXME: We might be able to short-circuit this if we know in advance that
4341 // there are no virtual bases.
4342 VirtualBaseSpec = nullptr;
4343 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4344 // We haven't found a base yet; search the class hierarchy for a
4345 // virtual base class.
4346 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4347 /*DetectVirtual=*/false);
4348 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4349 SemaRef.Context.getCanonicalTagType(ClassDecl),
4350 BaseType, Paths)) {
4351 for (const CXXBasePath &Path : Paths) {
4352 if (Path.back().Base->isVirtual()) {
4353 VirtualBaseSpec = Path.back().Base;
4354 break;
4355 }
4356 }
4357 }
4358 }
4359
4360 return DirectBaseSpec || VirtualBaseSpec;
4361}
4362
4365 Scope *S,
4366 CXXScopeSpec &SS,
4367 IdentifierInfo *MemberOrBase,
4368 ParsedType TemplateTypeTy,
4369 const DeclSpec &DS,
4370 SourceLocation IdLoc,
4371 Expr *InitList,
4372 SourceLocation EllipsisLoc) {
4373 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4374 DS, IdLoc, InitList,
4375 EllipsisLoc);
4376}
4377
4380 Scope *S,
4381 CXXScopeSpec &SS,
4382 IdentifierInfo *MemberOrBase,
4383 ParsedType TemplateTypeTy,
4384 const DeclSpec &DS,
4385 SourceLocation IdLoc,
4386 SourceLocation LParenLoc,
4387 ArrayRef<Expr *> Args,
4388 SourceLocation RParenLoc,
4389 SourceLocation EllipsisLoc) {
4390 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4391 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4392 DS, IdLoc, List, EllipsisLoc);
4393}
4394
4395namespace {
4396
4397// Callback to only accept typo corrections that can be a valid C++ member
4398// initializer: either a non-static field member or a base class.
4399class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4400public:
4401 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4402 : ClassDecl(ClassDecl) {}
4403
4404 bool ValidateCandidate(const TypoCorrection &candidate) override {
4405 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4406 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4407 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4408 return isa<TypeDecl>(ND);
4409 }
4410 return false;
4411 }
4412
4413 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4414 return std::make_unique<MemInitializerValidatorCCC>(*this);
4415 }
4416
4417private:
4418 CXXRecordDecl *ClassDecl;
4419};
4420
4421}
4422
4424 RecordDecl *ClassDecl,
4425 const IdentifierInfo *Name) {
4426 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4428 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4429 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4431 });
4432 // We did not find a placeholder variable
4433 if (Found == Result.end())
4434 return false;
4435 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4436 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4437 const NamedDecl *ND = *It;
4438 if (ND->getDeclContext() != ND->getDeclContext())
4439 break;
4442 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4443 }
4444 return true;
4445}
4446
4447ValueDecl *
4449 const IdentifierInfo *MemberOrBase) {
4450 ValueDecl *ND = nullptr;
4451 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4453 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4454 if (ND) {
4455 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4456 return nullptr;
4457 break;
4458 }
4459 if (!IsPlaceholder)
4460 return cast<ValueDecl>(D);
4461 ND = cast<ValueDecl>(D);
4462 }
4463 }
4464 return ND;
4465}
4466
4468 CXXScopeSpec &SS,
4469 ParsedType TemplateTypeTy,
4470 IdentifierInfo *MemberOrBase) {
4471 if (SS.getScopeRep() || TemplateTypeTy)
4472 return nullptr;
4473 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4474}
4475
4478 Scope *S,
4479 CXXScopeSpec &SS,
4480 IdentifierInfo *MemberOrBase,
4481 ParsedType TemplateTypeTy,
4482 const DeclSpec &DS,
4483 SourceLocation IdLoc,
4484 Expr *Init,
4485 SourceLocation EllipsisLoc) {
4486 if (!ConstructorD || !Init)
4487 return true;
4488
4489 AdjustDeclIfTemplate(ConstructorD);
4490
4492 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4493 if (!Constructor) {
4494 // The user wrote a constructor initializer on a function that is
4495 // not a C++ constructor. Ignore the error for now, because we may
4496 // have more member initializers coming; we'll diagnose it just
4497 // once in ActOnMemInitializers.
4498 return true;
4499 }
4500
4501 CXXRecordDecl *ClassDecl = Constructor->getParent();
4502
4503 // C++ [class.base.init]p2:
4504 // Names in a mem-initializer-id are looked up in the scope of the
4505 // constructor's class and, if not found in that scope, are looked
4506 // up in the scope containing the constructor's definition.
4507 // [Note: if the constructor's class contains a member with the
4508 // same name as a direct or virtual base class of the class, a
4509 // mem-initializer-id naming the member or base class and composed
4510 // of a single identifier refers to the class member. A
4511 // mem-initializer-id for the hidden base class may be specified
4512 // using a qualified name. ]
4513
4514 // Look for a member, first.
4516 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4517 if (EllipsisLoc.isValid())
4518 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4519 << MemberOrBase
4520 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4521
4522 return BuildMemberInitializer(Member, Init, IdLoc);
4523 }
4524 // It didn't name a member, so see if it names a class.
4525 QualType BaseType;
4526 TypeSourceInfo *TInfo = nullptr;
4527
4528 if (TemplateTypeTy) {
4529 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4530 if (BaseType.isNull())
4531 return true;
4532 } else if (DS.getTypeSpecType() == TST_decltype) {
4533 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4534 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4535 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4536 return true;
4537 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4538 BaseType =
4540 DS.getBeginLoc(), DS.getEllipsisLoc());
4541 } else {
4542 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4543 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4544
4545 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4546 if (!TyD) {
4547 if (R.isAmbiguous()) return true;
4548
4549 // We don't want access-control diagnostics here.
4550 R.suppressDiagnostics();
4551
4552 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4553 bool NotUnknownSpecialization = false;
4554 DeclContext *DC = computeDeclContext(SS, false);
4555 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4556 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4557
4558 if (!NotUnknownSpecialization) {
4559 // When the scope specifier can refer to a member of an unknown
4560 // specialization, we take it as a type name.
4561 BaseType = CheckTypenameType(
4563 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4564 if (BaseType.isNull())
4565 return true;
4566
4567 TInfo = Context.CreateTypeSourceInfo(BaseType);
4570 if (!TL.isNull()) {
4571 TL.setNameLoc(IdLoc);
4574 }
4575
4576 R.clear();
4577 R.setLookupName(MemberOrBase);
4578 }
4579 }
4580
4581 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4582 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4583 auto *TempSpec = cast<TemplateSpecializationType>(
4584 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4585 TemplateName TN = TempSpec->getTemplateName();
4586 for (auto const &Base : ClassDecl->bases()) {
4587 auto BaseTemplate =
4588 Base.getType()->getAs<TemplateSpecializationType>();
4589 if (BaseTemplate &&
4590 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4591 /*IgnoreDeduced=*/true)) {
4592 Diag(IdLoc, diag::ext_unqualified_base_class)
4593 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4594 BaseType = Base.getType();
4595 break;
4596 }
4597 }
4598 }
4599 }
4600
4601 // If no results were found, try to correct typos.
4602 TypoCorrection Corr;
4603 MemInitializerValidatorCCC CCC(ClassDecl);
4604 if (R.empty() && BaseType.isNull() &&
4605 (Corr =
4606 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4607 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4609 // We have found a non-static data member with a similar
4610 // name to what was typed; complain and initialize that
4611 // member.
4612 diagnoseTypo(Corr,
4613 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4614 << MemberOrBase << true);
4615 return BuildMemberInitializer(Member, Init, IdLoc);
4616 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4617 const CXXBaseSpecifier *DirectBaseSpec;
4618 const CXXBaseSpecifier *VirtualBaseSpec;
4619 if (FindBaseInitializer(*this, ClassDecl,
4620 Context.getTypeDeclType(Type),
4621 DirectBaseSpec, VirtualBaseSpec)) {
4622 // We have found a direct or virtual base class with a
4623 // similar name to what was typed; complain and initialize
4624 // that base class.
4625 diagnoseTypo(Corr,
4626 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4627 << MemberOrBase << false,
4628 PDiag() /*Suppress note, we provide our own.*/);
4629
4630 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4631 : VirtualBaseSpec;
4632 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4633 << BaseSpec->getType() << BaseSpec->getSourceRange();
4634
4635 TyD = Type;
4636 }
4637 }
4638 }
4639
4640 if (!TyD && BaseType.isNull()) {
4641 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4642 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4643 return true;
4644 }
4645 }
4646
4647 if (BaseType.isNull()) {
4648 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4649
4650 TypeLocBuilder TLB;
4651 // FIXME: This is missing building the UsingType for TyD, if any.
4652 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4653 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4654 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4655 auto TL = TLB.push<TagTypeLoc>(BaseType);
4657 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4658 TL.setNameLoc(IdLoc);
4659 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4660 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4661 SS.getScopeRep(), TN);
4662 TLB.push<TypedefTypeLoc>(BaseType).set(
4663 /*ElaboratedKeywordLoc=*/SourceLocation(),
4664 SS.getWithLocInContext(Context), IdLoc);
4665 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4666 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4667 SS.getScopeRep(), UD);
4668 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4669 /*ElaboratedKeywordLoc=*/SourceLocation(),
4670 SS.getWithLocInContext(Context), IdLoc);
4671 } else {
4672 // FIXME: What else can appear here?
4673 assert(SS.isEmpty());
4674 BaseType = Context.getTypeDeclType(TyD);
4675 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4676 }
4677 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4678 }
4679 }
4680
4681 if (!TInfo)
4682 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4683
4684 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4685}
4686
4689 SourceLocation IdLoc) {
4690 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4691 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4692 assert((DirectMember || IndirectMember) &&
4693 "Member must be a FieldDecl or IndirectFieldDecl");
4694
4696 return true;
4697
4698 if (Member->isInvalidDecl())
4699 return true;
4700
4701 MultiExprArg Args;
4702 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4703 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4704 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4705 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4706 } else if (auto *ParenListInit = dyn_cast<CXXParenListInitExpr>(Init)) {
4707 // Template instantiation reverts the elements to their syntactic form;
4708 // redo the initialization from the written arguments.
4709 Args = ParenListInit->getUserSpecifiedInitExprs();
4710 } else {
4711 // Template instantiation doesn't reconstruct ParenListExprs for us.
4712 Args = Init;
4713 }
4714
4715 SourceRange InitRange = Init->getSourceRange();
4716
4717 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4718 // Can't check initialization for a member of dependent type or when
4719 // any of the arguments are type-dependent expressions.
4721 } else {
4722 bool InitList = false;
4723 if (isa<InitListExpr>(Init)) {
4724 InitList = true;
4725 Args = Init;
4726 }
4727
4728 // Initialize the member.
4729 InitializedEntity MemberEntity =
4730 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4731 : InitializedEntity::InitializeMember(IndirectMember,
4732 nullptr);
4733 InitializationKind Kind =
4735 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4736 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4737 InitRange.getEnd());
4738
4739 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4740 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4741 nullptr);
4742 if (!MemberInit.isInvalid()) {
4743 // C++11 [class.base.init]p7:
4744 // The initialization of each base and member constitutes a
4745 // full-expression.
4746 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4747 /*DiscardedValue*/ false);
4748 }
4749
4750 if (MemberInit.isInvalid()) {
4751 // Args were sensible expressions but we couldn't initialize the member
4752 // from them. Preserve them in a RecoveryExpr instead.
4753 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4754 Member->getType())
4755 .get();
4756 if (!Init)
4757 return true;
4758 } else {
4759 Init = MemberInit.get();
4760 }
4761 }
4762
4763 if (DirectMember) {
4764 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4765 InitRange.getBegin(), Init,
4766 InitRange.getEnd());
4767 } else {
4768 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4769 InitRange.getBegin(), Init,
4770 InitRange.getEnd());
4771 }
4772}
4773
4776 CXXRecordDecl *ClassDecl) {
4777 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4778 if (!LangOpts.CPlusPlus11)
4779 return Diag(NameLoc, diag::err_delegating_ctor)
4780 << TInfo->getTypeLoc().getSourceRange();
4781 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4782
4783 bool InitList = true;
4784 MultiExprArg Args = Init;
4785 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4786 InitList = false;
4787 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4788 }
4789
4790 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4791
4792 SourceRange InitRange = Init->getSourceRange();
4793 // Initialize the object.
4794 InitializedEntity DelegationEntity =
4796 InitializationKind Kind =
4798 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4799 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4800 InitRange.getEnd());
4801 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4802 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4803 Args, nullptr);
4804 if (!DelegationInit.isInvalid()) {
4805 assert((DelegationInit.get()->containsErrors() ||
4806 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4807 "Delegating constructor with no target?");
4808
4809 // C++11 [class.base.init]p7:
4810 // The initialization of each base and member constitutes a
4811 // full-expression.
4812 DelegationInit = ActOnFinishFullExpr(
4813 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4814 }
4815
4816 if (DelegationInit.isInvalid()) {
4817 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4818 InitRange.getEnd(), Args, ClassType);
4819 if (DelegationInit.isInvalid())
4820 return true;
4821 } else {
4822 // If we are in a dependent context, template instantiation will
4823 // perform this type-checking again. Just save the arguments that we
4824 // received in a ParenListExpr.
4825 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4826 // of the information that we have about the base
4827 // initializer. However, deconstructing the ASTs is a dicey process,
4828 // and this approach is far more likely to get the corner cases right.
4829 if (CurContext->isDependentContext())
4830 DelegationInit = Init;
4831 }
4832
4833 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4834 DelegationInit.getAs<Expr>(),
4835 InitRange.getEnd());
4836}
4837
4840 Expr *Init, CXXRecordDecl *ClassDecl,
4841 SourceLocation EllipsisLoc) {
4842 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4843
4844 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4845 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4846 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4847
4848 // C++ [class.base.init]p2:
4849 // [...] Unless the mem-initializer-id names a nonstatic data
4850 // member of the constructor's class or a direct or virtual base
4851 // of that class, the mem-initializer is ill-formed. A
4852 // mem-initializer-list can initialize a base class using any
4853 // name that denotes that base class type.
4854
4855 // We can store the initializers in "as-written" form and delay analysis until
4856 // instantiation if the constructor is dependent. But not for dependent
4857 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4858 bool Dependent = CurContext->isDependentContext() &&
4859 (BaseType->isDependentType() || Init->isTypeDependent());
4860
4861 SourceRange InitRange = Init->getSourceRange();
4862 if (EllipsisLoc.isValid()) {
4863 // This is a pack expansion.
4864 if (!BaseType->containsUnexpandedParameterPack()) {
4865 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4866 << SourceRange(BaseLoc, InitRange.getEnd());
4867
4868 EllipsisLoc = SourceLocation();
4869 }
4870 } else {
4871 // Check for any unexpanded parameter packs.
4872 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4873 return true;
4874
4876 return true;
4877 }
4878
4879 // Check for direct and virtual base classes.
4880 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4881 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4882 if (!Dependent) {
4883 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4884 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4885
4886 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4887 VirtualBaseSpec);
4888
4889 // C++ [base.class.init]p2:
4890 // Unless the mem-initializer-id names a nonstatic data member of the
4891 // constructor's class or a direct or virtual base of that class, the
4892 // mem-initializer is ill-formed.
4893 if (!DirectBaseSpec && !VirtualBaseSpec) {
4894 // If the class has any dependent bases, then it's possible that
4895 // one of those types will resolve to the same type as
4896 // BaseType. Therefore, just treat this as a dependent base
4897 // class initialization. FIXME: Should we try to check the
4898 // initialization anyway? It seems odd.
4899 if (ClassDecl->hasAnyDependentBases())
4900 Dependent = true;
4901 else
4902 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4903 << BaseType << Context.getCanonicalTagType(ClassDecl)
4904 << BaseTInfo->getTypeLoc().getSourceRange();
4905 }
4906 }
4907
4908 if (Dependent) {
4910
4911 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4912 /*IsVirtual=*/false,
4913 InitRange.getBegin(), Init,
4914 InitRange.getEnd(), EllipsisLoc);
4915 }
4916
4917 // C++ [base.class.init]p2:
4918 // If a mem-initializer-id is ambiguous because it designates both
4919 // a direct non-virtual base class and an inherited virtual base
4920 // class, the mem-initializer is ill-formed.
4921 if (DirectBaseSpec && VirtualBaseSpec)
4922 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4923 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4924
4925 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4926 if (!BaseSpec)
4927 BaseSpec = VirtualBaseSpec;
4928
4929 // Initialize the base.
4930 bool InitList = true;
4931 MultiExprArg Args = Init;
4932 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4933 InitList = false;
4934 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4935 }
4936
4937 InitializedEntity BaseEntity =
4938 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4939 InitializationKind Kind =
4940 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4941 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4942 InitRange.getEnd());
4943 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4944 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4945 if (!BaseInit.isInvalid()) {
4946 // C++11 [class.base.init]p7:
4947 // The initialization of each base and member constitutes a
4948 // full-expression.
4949 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4950 /*DiscardedValue*/ false);
4951 }
4952
4953 if (BaseInit.isInvalid()) {
4954 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4955 Args, BaseType);
4956 if (BaseInit.isInvalid())
4957 return true;
4958 } else {
4959 // If we are in a dependent context, template instantiation will
4960 // perform this type-checking again. Just save the arguments that we
4961 // received in a ParenListExpr.
4962 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4963 // of the information that we have about the base
4964 // initializer. However, deconstructing the ASTs is a dicey process,
4965 // and this approach is far more likely to get the corner cases right.
4966 if (CurContext->isDependentContext())
4967 BaseInit = Init;
4968 }
4969
4970 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4971 BaseSpec->isVirtual(),
4972 InitRange.getBegin(),
4973 BaseInit.getAs<Expr>(),
4974 InitRange.getEnd(), EllipsisLoc);
4975}
4976
4977// Create a static_cast<T&&>(expr).
4978static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4979 QualType TargetType =
4980 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4982 SourceLocation ExprLoc = E->getBeginLoc();
4983 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4984 TargetType, ExprLoc);
4985
4986 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4987 SourceRange(ExprLoc, ExprLoc),
4988 E->getSourceRange()).get();
4989}
4990
4991/// ImplicitInitializerKind - How an implicit base or member initializer should
4992/// initialize its base or member.
4999
5000static bool
5002 ImplicitInitializerKind ImplicitInitKind,
5003 CXXBaseSpecifier *BaseSpec,
5004 bool IsInheritedVirtualBase,
5005 CXXCtorInitializer *&CXXBaseInit) {
5006 InitializedEntity InitEntity
5007 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
5008 IsInheritedVirtualBase);
5009
5010 ExprResult BaseInit;
5011
5012 switch (ImplicitInitKind) {
5013 case IIK_Inherit:
5014 case IIK_Default: {
5015 InitializationKind InitKind
5017 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5018 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5019 break;
5020 }
5021
5022 case IIK_Move:
5023 case IIK_Copy: {
5024 bool Moving = ImplicitInitKind == IIK_Move;
5025 ParmVarDecl *Param = Constructor->getParamDecl(0);
5026 QualType ParamType = Param->getType().getNonReferenceType();
5027
5028 Expr *CopyCtorArg =
5030 SourceLocation(), Param, false,
5031 Constructor->getLocation(), ParamType,
5032 VK_LValue, nullptr);
5033
5034 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
5035
5036 // Cast to the base class to avoid ambiguities.
5037 QualType ArgTy =
5038 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
5039 ParamType.getQualifiers());
5040
5041 if (Moving) {
5042 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
5043 }
5044
5045 CXXCastPath BasePath;
5046 BasePath.push_back(BaseSpec);
5047 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
5048 CK_UncheckedDerivedToBase,
5049 Moving ? VK_XValue : VK_LValue,
5050 &BasePath).get();
5051
5052 InitializationKind InitKind
5055 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5056 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5057 break;
5058 }
5059 }
5060
5061 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5062 if (BaseInit.isInvalid())
5063 return true;
5064
5065 CXXBaseInit =
5066 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5067 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5068 SourceLocation()),
5069 BaseSpec->isVirtual(),
5071 BaseInit.getAs<Expr>(),
5073 SourceLocation());
5074
5075 return false;
5076}
5077
5078static bool RefersToRValueRef(Expr *MemRef) {
5079 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5080 return Referenced->getType()->isRValueReferenceType();
5081}
5082
5083static bool
5085 ImplicitInitializerKind ImplicitInitKind,
5086 FieldDecl *Field, IndirectFieldDecl *Indirect,
5087 CXXCtorInitializer *&CXXMemberInit) {
5088 if (Field->isInvalidDecl())
5089 return true;
5090
5091 SourceLocation Loc = Constructor->getLocation();
5092
5093 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5094 bool Moving = ImplicitInitKind == IIK_Move;
5095 ParmVarDecl *Param = Constructor->getParamDecl(0);
5096 QualType ParamType = Param->getType().getNonReferenceType();
5097
5098 // Suppress copying zero-width bitfields.
5099 if (Field->isZeroLengthBitField())
5100 return false;
5101
5102 Expr *MemberExprBase =
5104 SourceLocation(), Param, false,
5105 Loc, ParamType, VK_LValue, nullptr);
5106
5107 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5108
5109 if (Moving) {
5110 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5111 }
5112
5113 // Build a reference to this field within the parameter.
5114 CXXScopeSpec SS;
5115 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5117 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5118 : cast<ValueDecl>(Field), AS_public);
5119 MemberLookup.resolveKind();
5120 ExprResult CtorArg
5121 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5122 ParamType, Loc,
5123 /*IsArrow=*/false,
5124 SS,
5125 /*TemplateKWLoc=*/SourceLocation(),
5126 /*FirstQualifierInScope=*/nullptr,
5127 MemberLookup,
5128 /*TemplateArgs=*/nullptr,
5129 /*S*/nullptr);
5130 if (CtorArg.isInvalid())
5131 return true;
5132
5133 // C++11 [class.copy]p15:
5134 // - if a member m has rvalue reference type T&&, it is direct-initialized
5135 // with static_cast<T&&>(x.m);
5136 if (RefersToRValueRef(CtorArg.get())) {
5137 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5138 }
5139
5140 InitializedEntity Entity =
5143
5144 // Direct-initialize to use the copy constructor.
5145 InitializationKind InitKind =
5147
5148 Expr *CtorArgE = CtorArg.getAs<Expr>();
5149 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5150 ExprResult MemberInit =
5151 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5152 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5153 if (MemberInit.isInvalid())
5154 return true;
5155
5156 if (Indirect)
5157 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5158 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5159 else
5160 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5161 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5162 return false;
5163 }
5164
5165 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5166 "Unhandled implicit init kind!");
5167
5168 QualType FieldBaseElementType =
5169 SemaRef.Context.getBaseElementType(Field->getType());
5170
5171 if (FieldBaseElementType->isRecordType()) {
5172 InitializedEntity InitEntity =
5175 InitializationKind InitKind =
5177
5178 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5179 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5180
5181 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5182 if (MemberInit.isInvalid())
5183 return true;
5184
5185 if (Indirect)
5186 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5187 Indirect, Loc,
5188 Loc,
5189 MemberInit.get(),
5190 Loc);
5191 else
5192 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5193 Field, Loc, Loc,
5194 MemberInit.get(),
5195 Loc);
5196 return false;
5197 }
5198
5199 if (!Field->getParent()->isUnion()) {
5200 if (FieldBaseElementType->isReferenceType()) {
5201 SemaRef.Diag(Constructor->getLocation(),
5202 diag::err_uninitialized_member_in_ctor)
5203 << (int)Constructor->isImplicit()
5204 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5205 << Field->getDeclName();
5206 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5207 return true;
5208 }
5209
5210 if (FieldBaseElementType.isConstQualified()) {
5211 SemaRef.Diag(Constructor->getLocation(),
5212 diag::err_uninitialized_member_in_ctor)
5213 << (int)Constructor->isImplicit()
5214 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5215 << Field->getDeclName();
5216 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5217 return true;
5218 }
5219 }
5220
5221 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5222 // ARC and Weak:
5223 // Default-initialize Objective-C pointers to NULL.
5224 CXXMemberInit
5225 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5226 Loc, Loc,
5227 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5228 Loc);
5229 return false;
5230 }
5231
5232 // Nothing to initialize.
5233 CXXMemberInit = nullptr;
5234 return false;
5235}
5236
5237namespace {
5238struct BaseAndFieldInfo {
5239 Sema &S;
5240 CXXConstructorDecl *Ctor;
5241 bool AnyErrorsInInits;
5243 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5244 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5245 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5246
5247 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5248 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5249 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5250 if (Ctor->getInheritedConstructor())
5251 IIK = IIK_Inherit;
5252 else if (Generated && Ctor->isCopyConstructor())
5253 IIK = IIK_Copy;
5254 else if (Generated && Ctor->isMoveConstructor())
5255 IIK = IIK_Move;
5256 else
5257 IIK = IIK_Default;
5258 }
5259
5260 bool isImplicitCopyOrMove() const {
5261 switch (IIK) {
5262 case IIK_Copy:
5263 case IIK_Move:
5264 return true;
5265
5266 case IIK_Default:
5267 case IIK_Inherit:
5268 return false;
5269 }
5270
5271 llvm_unreachable("Invalid ImplicitInitializerKind!");
5272 }
5273
5274 bool addFieldInitializer(CXXCtorInitializer *Init) {
5275 AllToInit.push_back(Init);
5276
5277 // Check whether this initializer makes the field "used".
5278 if (Init->getInit()->HasSideEffects(S.Context))
5279 S.UnusedPrivateFields.remove(Init->getAnyMember());
5280
5281 return false;
5282 }
5283
5284 bool isInactiveUnionMember(FieldDecl *Field) {
5285 RecordDecl *Record = Field->getParent();
5286 if (!Record->isUnion())
5287 return false;
5288
5289 if (FieldDecl *Active =
5290 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5291 return Active != Field->getCanonicalDecl();
5292
5293 // In an implicit copy or move constructor, ignore any in-class initializer.
5294 if (isImplicitCopyOrMove())
5295 return true;
5296
5297 // If there's no explicit initialization, the field is active only if it
5298 // has an in-class initializer...
5299 if (Field->hasInClassInitializer())
5300 return false;
5301 // ... or it's an anonymous struct or union whose class has an in-class
5302 // initializer.
5303 if (!Field->isAnonymousStructOrUnion())
5304 return true;
5305 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5306 return !FieldRD->hasInClassInitializer();
5307 }
5308
5309 /// Determine whether the given field is, or is within, a union member
5310 /// that is inactive (because there was an initializer given for a different
5311 /// member of the union, or because the union was not initialized at all).
5312 bool isWithinInactiveUnionMember(FieldDecl *Field,
5313 IndirectFieldDecl *Indirect) {
5314 if (!Indirect)
5315 return isInactiveUnionMember(Field);
5316
5317 for (auto *C : Indirect->chain()) {
5318 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5319 if (Field && isInactiveUnionMember(Field))
5320 return true;
5321 }
5322 return false;
5323 }
5324};
5325}
5326
5327/// Determine whether the given type is an incomplete or zero-lenfgth
5328/// array type.
5330 if (T->isIncompleteArrayType())
5331 return true;
5332
5333 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5334 if (ArrayT->isZeroSize())
5335 return true;
5336
5337 T = ArrayT->getElementType();
5338 }
5339
5340 return false;
5341}
5342
5343static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5344 FieldDecl *Field,
5345 IndirectFieldDecl *Indirect = nullptr) {
5346 if (Field->isInvalidDecl())
5347 return false;
5348
5349 // Overwhelmingly common case: we have a direct initializer for this field.
5351 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5352 return Info.addFieldInitializer(Init);
5353
5354 // C++11 [class.base.init]p8:
5355 // if the entity is a non-static data member that has a
5356 // brace-or-equal-initializer and either
5357 // -- the constructor's class is a union and no other variant member of that
5358 // union is designated by a mem-initializer-id or
5359 // -- the constructor's class is not a union, and, if the entity is a member
5360 // of an anonymous union, no other member of that union is designated by
5361 // a mem-initializer-id,
5362 // the entity is initialized as specified in [dcl.init].
5363 //
5364 // We also apply the same rules to handle anonymous structs within anonymous
5365 // unions.
5366 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5367 return false;
5368
5369 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5370 ExprResult DIE =
5371 SemaRef.BuildCXXCtorDefaultInitExpr(Info.Ctor->getLocation(), Field);
5372 if (DIE.isInvalid())
5373 return true;
5374
5376 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5377
5379 if (Indirect)
5380 Init = new (SemaRef.Context)
5381 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5382 SourceLocation(), DIE.get(), SourceLocation());
5383 else
5384 Init = new (SemaRef.Context)
5385 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5386 SourceLocation(), DIE.get(), SourceLocation());
5387 return Info.addFieldInitializer(Init);
5388 }
5389
5390 // Don't initialize incomplete or zero-length arrays.
5391 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5392 return false;
5393
5394 // Don't try to build an implicit initializer if there were semantic
5395 // errors in any of the initializers (and therefore we might be
5396 // missing some that the user actually wrote).
5397 if (Info.AnyErrorsInInits)
5398 return false;
5399
5400 CXXCtorInitializer *Init = nullptr;
5401 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5402 Indirect, Init))
5403 return true;
5404
5405 if (!Init)
5406 return false;
5407
5408 return Info.addFieldInitializer(Init);
5409}
5410
5411bool
5414 assert(Initializer->isDelegatingInitializer());
5415 Constructor->setNumCtorInitializers(1);
5416 CXXCtorInitializer **initializer =
5417 new (Context) CXXCtorInitializer*[1];
5418 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5419 Constructor->setCtorInitializers(initializer);
5420
5421 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5422 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5423 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5424 }
5425
5427
5428 DiagnoseUninitializedFields(*this, Constructor);
5429
5430 return false;
5431}
5432
5434 CXXRecordDecl *Class) {
5435 if (Class->isInvalidDecl())
5436 return nullptr;
5437 if (Class->hasIrrelevantDestructor())
5438 return nullptr;
5439
5440 // Dtor might still be missing, e.g because it's invalid.
5441 return S.LookupDestructor(Class);
5442}
5443
5445 FieldDecl *Field) {
5446 if (Field->isInvalidDecl())
5447 return;
5448
5449 // Don't destroy incomplete or zero-length arrays.
5450 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5451 return;
5452
5453 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5454
5455 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5456 if (!FieldClassDecl)
5457 return;
5458
5459 // The destructor for an implicit anonymous union member is never invoked.
5460 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5461 return;
5462
5463 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5464 if (!Dtor)
5465 return;
5466
5467 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5468 S.PDiag(diag::err_access_dtor_field)
5469 << Field->getDeclName() << FieldType);
5470
5471 S.MarkFunctionReferenced(Location, Dtor);
5472 S.DiagnoseUseOfDecl(Dtor, Location);
5473}
5474
5476 CXXRecordDecl *ClassDecl) {
5477 if (ClassDecl->isDependentContext())
5478 return;
5479
5480 // We only potentially invoke the destructors of potentially constructed
5481 // subobjects.
5482 bool VisitVirtualBases = !ClassDecl->isAbstract();
5483
5484 // If the destructor exists and has already been marked used in the MS ABI,
5485 // then virtual base destructors have already been checked and marked used.
5486 // Skip checking them again to avoid duplicate diagnostics.
5488 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5489 if (Dtor && Dtor->isUsed())
5490 VisitVirtualBases = false;
5491 }
5492
5494
5495 // Bases.
5496 for (const auto &Base : ClassDecl->bases()) {
5497 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5498 if (!BaseClassDecl)
5499 continue;
5500
5501 // Remember direct virtual bases.
5502 if (Base.isVirtual()) {
5503 if (!VisitVirtualBases)
5504 continue;
5505 DirectVirtualBases.insert(BaseClassDecl);
5506 }
5507
5508 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5509 if (!Dtor)
5510 continue;
5511
5512 // FIXME: caret should be on the start of the class name
5513 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5514 S.PDiag(diag::err_access_dtor_base)
5515 << Base.getType() << Base.getSourceRange(),
5516 S.Context.getCanonicalTagType(ClassDecl));
5517
5518 S.MarkFunctionReferenced(Location, Dtor);
5519 S.DiagnoseUseOfDecl(Dtor, Location);
5520 }
5521
5522 if (VisitVirtualBases)
5523 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5524 &DirectVirtualBases);
5525}
5526
5528 ArrayRef<CXXCtorInitializer *> Initializers) {
5529 if (Constructor->isDependentContext()) {
5530 // Just store the initializers as written, they will be checked during
5531 // instantiation.
5532 if (!Initializers.empty()) {
5533 Constructor->setNumCtorInitializers(Initializers.size());
5534 CXXCtorInitializer **baseOrMemberInitializers =
5535 new (Context) CXXCtorInitializer*[Initializers.size()];
5536 memcpy(baseOrMemberInitializers, Initializers.data(),
5537 Initializers.size() * sizeof(CXXCtorInitializer*));
5538 Constructor->setCtorInitializers(baseOrMemberInitializers);
5539 }
5540
5541 // Let template instantiation know whether we had errors.
5542 if (AnyErrors)
5543 Constructor->setInvalidDecl();
5544
5545 return false;
5546 }
5547
5548 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5549
5550 // We need to build the initializer AST according to order of construction
5551 // and not what user specified in the Initializers list.
5552 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5553 if (!ClassDecl)
5554 return true;
5555
5556 bool HadError = false;
5557
5558 for (CXXCtorInitializer *Member : Initializers) {
5559 if (Member->isBaseInitializer())
5560 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5561 Member;
5562 else {
5563 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5564
5565 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5566 for (auto *C : F->chain()) {
5567 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5568 if (FD && FD->getParent()->isUnion())
5569 Info.ActiveUnionMember.insert(std::make_pair(
5571 }
5572 } else if (FieldDecl *FD = Member->getMember()) {
5573 if (FD->getParent()->isUnion())
5574 Info.ActiveUnionMember.insert(std::make_pair(
5576 }
5577 }
5578 }
5579
5580 // Keep track of the direct virtual bases.
5582 for (auto &I : ClassDecl->bases()) {
5583 if (I.isVirtual())
5584 DirectVBases.insert(&I);
5585 }
5586
5587 // Push virtual bases before others.
5588 for (auto &VBase : ClassDecl->vbases()) {
5589 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5590 VBase.getType()->getAsCanonical<RecordType>())) {
5591 // [class.base.init]p7, per DR257:
5592 // A mem-initializer where the mem-initializer-id names a virtual base
5593 // class is ignored during execution of a constructor of any class that
5594 // is not the most derived class.
5595 if (ClassDecl->isAbstract()) {
5596 // FIXME: Provide a fixit to remove the base specifier. This requires
5597 // tracking the location of the associated comma for a base specifier.
5598 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5599 << VBase.getType() << ClassDecl;
5600 DiagnoseAbstractType(ClassDecl);
5601 }
5602
5603 Info.AllToInit.push_back(Value);
5604 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5605 // [class.base.init]p8, per DR257:
5606 // If a given [...] base class is not named by a mem-initializer-id
5607 // [...] and the entity is not a virtual base class of an abstract
5608 // class, then [...] the entity is default-initialized.
5609 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5610 CXXCtorInitializer *CXXBaseInit;
5611 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5612 &VBase, IsInheritedVirtualBase,
5613 CXXBaseInit)) {
5614 HadError = true;
5615 continue;
5616 }
5617
5618 Info.AllToInit.push_back(CXXBaseInit);
5619 }
5620 }
5621
5622 // Non-virtual bases.
5623 for (auto &Base : ClassDecl->bases()) {
5624 // Virtuals are in the virtual base list and already constructed.
5625 if (Base.isVirtual())
5626 continue;
5627
5628 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5629 Base.getType()->getAsCanonical<RecordType>())) {
5630 Info.AllToInit.push_back(Value);
5631 } else if (!AnyErrors) {
5632 CXXCtorInitializer *CXXBaseInit;
5633 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5634 &Base, /*IsInheritedVirtualBase=*/false,
5635 CXXBaseInit)) {
5636 HadError = true;
5637 continue;
5638 }
5639
5640 Info.AllToInit.push_back(CXXBaseInit);
5641 }
5642 }
5643
5644 // Fields.
5645 for (auto *Mem : ClassDecl->decls()) {
5646 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5647 // C++ [class.bit]p2:
5648 // A declaration for a bit-field that omits the identifier declares an
5649 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5650 // initialized.
5651 if (F->isUnnamedBitField())
5652 continue;
5653
5654 // If we're not generating the implicit copy/move constructor, then we'll
5655 // handle anonymous struct/union fields based on their individual
5656 // indirect fields.
5657 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5658 continue;
5659
5660 if (CollectFieldInitializer(*this, Info, F))
5661 HadError = true;
5662 continue;
5663 }
5664
5665 // Beyond this point, we only consider default initialization.
5666 if (Info.isImplicitCopyOrMove())
5667 continue;
5668
5669 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5670 if (F->getType()->isIncompleteArrayType()) {
5671 assert(ClassDecl->hasFlexibleArrayMember() &&
5672 "Incomplete array type is not valid");
5673 continue;
5674 }
5675
5676 // Initialize each field of an anonymous struct individually.
5677 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5678 HadError = true;
5679
5680 continue;
5681 }
5682 }
5683
5684 unsigned NumInitializers = Info.AllToInit.size();
5685 if (NumInitializers > 0) {
5686 Constructor->setNumCtorInitializers(NumInitializers);
5687 CXXCtorInitializer **baseOrMemberInitializers =
5688 new (Context) CXXCtorInitializer*[NumInitializers];
5689 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5690 NumInitializers * sizeof(CXXCtorInitializer*));
5691 Constructor->setCtorInitializers(baseOrMemberInitializers);
5692
5693 SourceLocation Location = Constructor->getLocation();
5694
5695 // Constructors implicitly reference the base and member
5696 // destructors.
5697
5698 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5699 FieldDecl *Field = Initializer->getAnyMember();
5700 if (!Field)
5701 continue;
5702
5703 // C++ [class.base.init]p12:
5704 // In a non-delegating constructor, the destructor for each
5705 // potentially constructed subobject of class type is potentially
5706 // invoked.
5707 MarkFieldDestructorReferenced(*this, Location, Field);
5708 }
5709
5710 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5711 }
5712
5713 return HadError;
5714}
5715
5717 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5718 const RecordDecl *RD = RT->getDecl();
5719 if (RD->isAnonymousStructOrUnion()) {
5720 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5721 PopulateKeysForFields(Field, IdealInits);
5722 return;
5723 }
5724 }
5725 IdealInits.push_back(Field->getCanonicalDecl());
5726}
5727
5728static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5729 return Context.getCanonicalType(BaseType).getTypePtr();
5730}
5731
5732static const void *GetKeyForMember(ASTContext &Context,
5734 if (!Member->isAnyMemberInitializer())
5735 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5736
5737 return Member->getAnyMember()->getCanonicalDecl();
5738}
5739
5742 const CXXCtorInitializer *Current) {
5743 if (Previous->isAnyMemberInitializer())
5744 Diag << 0 << Previous->getAnyMember();
5745 else
5746 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5747
5748 if (Current->isAnyMemberInitializer())
5749 Diag << 0 << Current->getAnyMember();
5750 else
5751 Diag << 1 << Current->getTypeSourceInfo()->getType();
5752}
5753
5755 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5757 if (Constructor->getDeclContext()->isDependentContext())
5758 return;
5759
5760 // Don't check initializers order unless the warning is enabled at the
5761 // location of at least one initializer.
5762 bool ShouldCheckOrder = false;
5763 for (const CXXCtorInitializer *Init : Inits) {
5764 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5765 Init->getSourceLocation())) {
5766 ShouldCheckOrder = true;
5767 break;
5768 }
5769 }
5770 if (!ShouldCheckOrder)
5771 return;
5772
5773 // Build the list of bases and members in the order that they'll
5774 // actually be initialized. The explicit initializers should be in
5775 // this same order but may be missing things.
5776 SmallVector<const void*, 32> IdealInitKeys;
5777
5778 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5779
5780 // 1. Virtual bases.
5781 for (const auto &VBase : ClassDecl->vbases())
5782 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5783
5784 // 2. Non-virtual bases.
5785 for (const auto &Base : ClassDecl->bases()) {
5786 if (Base.isVirtual())
5787 continue;
5788 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5789 }
5790
5791 // 3. Direct fields.
5792 for (auto *Field : ClassDecl->fields()) {
5793 if (Field->isUnnamedBitField())
5794 continue;
5795
5796 PopulateKeysForFields(Field, IdealInitKeys);
5797 }
5798
5799 unsigned NumIdealInits = IdealInitKeys.size();
5800 unsigned IdealIndex = 0;
5801
5802 // Track initializers that are in an incorrect order for either a warning or
5803 // note if multiple ones occur.
5804 SmallVector<unsigned> WarnIndexes;
5805 // Correlates the index of an initializer in the init-list to the index of
5806 // the field/base in the class.
5807 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5808
5809 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5810 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5811
5812 // Scan forward to try to find this initializer in the idealized
5813 // initializers list.
5814 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5815 if (InitKey == IdealInitKeys[IdealIndex])
5816 break;
5817
5818 // If we didn't find this initializer, it must be because we
5819 // scanned past it on a previous iteration. That can only
5820 // happen if we're out of order; emit a warning.
5821 if (IdealIndex == NumIdealInits && InitIndex) {
5822 WarnIndexes.push_back(InitIndex);
5823
5824 // Move back to the initializer's location in the ideal list.
5825 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5826 if (InitKey == IdealInitKeys[IdealIndex])
5827 break;
5828
5829 assert(IdealIndex < NumIdealInits &&
5830 "initializer not found in initializer list");
5831 }
5832 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5833 }
5834
5835 if (WarnIndexes.empty())
5836 return;
5837
5838 // Sort based on the ideal order, first in the pair.
5839 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5840
5841 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5842 // emit the diagnostic before we can try adding notes.
5843 {
5845 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5846 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5847 : diag::warn_some_initializers_out_of_order);
5848
5849 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5850 if (CorrelatedInitOrder[I].second == I)
5851 continue;
5852 // Ideally we would be using InsertFromRange here, but clang doesn't
5853 // appear to handle InsertFromRange correctly when the source range is
5854 // modified by another fix-it.
5856 Inits[I]->getSourceRange(),
5859 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5860 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5861 }
5862
5863 // If there is only 1 item out of order, the warning expects the name and
5864 // type of each being added to it.
5865 if (WarnIndexes.size() == 1) {
5866 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5867 Inits[WarnIndexes.front()]);
5868 return;
5869 }
5870 }
5871 // More than 1 item to warn, create notes letting the user know which ones
5872 // are bad.
5873 for (unsigned WarnIndex : WarnIndexes) {
5874 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5875 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5876 diag::note_initializer_out_of_order);
5877 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5878 D << PrevInit->getSourceRange();
5879 }
5880}
5881
5882namespace {
5883bool CheckRedundantInit(Sema &S,
5884 CXXCtorInitializer *Init,
5885 CXXCtorInitializer *&PrevInit) {
5886 if (!PrevInit) {
5887 PrevInit = Init;
5888 return false;
5889 }
5890
5891 if (FieldDecl *Field = Init->getAnyMember())
5892 S.Diag(Init->getSourceLocation(),
5893 diag::err_multiple_mem_initialization)
5894 << Field->getDeclName()
5895 << Init->getSourceRange();
5896 else {
5897 const Type *BaseClass = Init->getBaseClass();
5898 assert(BaseClass && "neither field nor base");
5899 S.Diag(Init->getSourceLocation(),
5900 diag::err_multiple_base_initialization)
5901 << QualType(BaseClass, 0)
5902 << Init->getSourceRange();
5903 }
5904 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5905 << 0 << PrevInit->getSourceRange();
5906
5907 return true;
5908}
5909
5910typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5911typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5912
5913bool CheckRedundantUnionInit(Sema &S,
5914 CXXCtorInitializer *Init,
5915 RedundantUnionMap &Unions) {
5916 FieldDecl *Field = Init->getAnyMember();
5917 RecordDecl *Parent = Field->getParent();
5918 NamedDecl *Child = Field;
5919
5920 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5921 if (Parent->isUnion()) {
5922 UnionEntry &En = Unions[Parent];
5923 if (En.first && En.first != Child) {
5924 S.Diag(Init->getSourceLocation(),
5925 diag::err_multiple_mem_union_initialization)
5926 << Field->getDeclName()
5927 << Init->getSourceRange();
5928 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5929 << 0 << En.second->getSourceRange();
5930 return true;
5931 }
5932 if (!En.first) {
5933 En.first = Child;
5934 En.second = Init;
5935 }
5936 if (!Parent->isAnonymousStructOrUnion())
5937 return false;
5938 }
5939
5940 Child = Parent;
5941 Parent = cast<RecordDecl>(Parent->getDeclContext());
5942 }
5943
5944 return false;
5945}
5946} // namespace
5947
5948void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5949 SourceLocation ColonLoc,
5951 bool AnyErrors) {
5952 if (!ConstructorDecl)
5953 return;
5954
5955 AdjustDeclIfTemplate(ConstructorDecl);
5956
5958 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5959
5960 if (!Constructor) {
5961 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5962 return;
5963 }
5964
5965 // Mapping for the duplicate initializers check.
5966 // For member initializers, this is keyed with a FieldDecl*.
5967 // For base initializers, this is keyed with a Type*.
5968 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5969
5970 // Mapping for the inconsistent anonymous-union initializers check.
5971 RedundantUnionMap MemberUnions;
5972
5973 bool HadError = false;
5974 for (unsigned i = 0; i < MemInits.size(); i++) {
5975 CXXCtorInitializer *Init = MemInits[i];
5976
5977 // Set the source order index.
5978 Init->setSourceOrder(i);
5979
5980 if (Init->isAnyMemberInitializer()) {
5981 const void *Key = GetKeyForMember(Context, Init);
5982 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5983 CheckRedundantUnionInit(*this, Init, MemberUnions))
5984 HadError = true;
5985 } else if (Init->isBaseInitializer()) {
5986 const void *Key = GetKeyForMember(Context, Init);
5987 if (CheckRedundantInit(*this, Init, Members[Key]))
5988 HadError = true;
5989 } else {
5990 assert(Init->isDelegatingInitializer());
5991 // This must be the only initializer
5992 if (MemInits.size() != 1) {
5993 Diag(Init->getSourceLocation(),
5994 diag::err_delegating_initializer_alone)
5995 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5996 // We will treat this as being the only initializer.
5997 }
5999 // Return immediately as the initializer is set.
6000 return;
6001 }
6002 }
6003
6004 if (HadError)
6005 return;
6006
6008
6009 SetCtorInitializers(Constructor, AnyErrors, MemInits);
6010
6011 DiagnoseUninitializedFields(*this, Constructor);
6012}
6013
6015 CXXRecordDecl *ClassDecl) {
6016 // Ignore dependent contexts. Also ignore unions, since their members never
6017 // have destructors implicitly called.
6018 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
6019 return;
6020
6021 // FIXME: all the access-control diagnostics are positioned on the
6022 // field/base declaration. That's probably good; that said, the
6023 // user might reasonably want to know why the destructor is being
6024 // emitted, and we currently don't say.
6025
6026 // Non-static data members.
6027 for (auto *Field : ClassDecl->fields()) {
6028 MarkFieldDestructorReferenced(*this, Location, Field);
6029 }
6030
6031 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
6032}
6033
6035 SourceLocation Location, CXXRecordDecl *ClassDecl,
6036 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6037 // Virtual bases.
6038 for (const auto &VBase : ClassDecl->vbases()) {
6039 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6040 if (!BaseClassDecl)
6041 continue;
6042
6043 // Ignore already visited direct virtual bases.
6044 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
6045 continue;
6046
6047 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
6048 if (!Dtor)
6049 continue;
6050
6051 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
6052 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
6053 PDiag(diag::err_access_dtor_vbase)
6054 << CT << VBase.getType(),
6055 CT) == AR_accessible) {
6057 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6058 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6059 }
6060
6061 MarkFunctionReferenced(Location, Dtor);
6062 DiagnoseUseOfDecl(Dtor, Location);
6063 }
6064}
6065
6067 if (!CDtorDecl)
6068 return;
6069
6071 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6072 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6073 !ClassDecl || ClassDecl->isInvalidDecl()) {
6074 return;
6075 }
6076 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6077 DiagnoseUninitializedFields(*this, Constructor);
6078 }
6079}
6080
6082 if (!getLangOpts().CPlusPlus)
6083 return false;
6084
6085 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6086 if (!RD)
6087 return false;
6088
6089 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6090 // class template specialization here, but doing so breaks a lot of code.
6091
6092 // We can't answer whether something is abstract until it has a
6093 // definition. If it's currently being defined, we'll walk back
6094 // over all the declarations when we have a full definition.
6095 const CXXRecordDecl *Def = RD->getDefinition();
6096 if (!Def || Def->isBeingDefined())
6097 return false;
6098
6099 return RD->isAbstract();
6100}
6101
6103 TypeDiagnoser &Diagnoser) {
6104 if (!isAbstractType(Loc, T))
6105 return false;
6106
6107 T = Context.getBaseElementType(T);
6108 Diagnoser.diagnose(*this, Loc, T);
6109 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6110 return true;
6111}
6112
6114 // Check if we've already emitted the list of pure virtual functions
6115 // for this class.
6117 return;
6118
6119 // If the diagnostic is suppressed, don't emit the notes. We're only
6120 // going to emit them once, so try to attach them to a diagnostic we're
6121 // actually going to show.
6122 if (Diags.isLastDiagnosticIgnored())
6123 return;
6124
6125 CXXFinalOverriderMap FinalOverriders;
6126 RD->getFinalOverriders(FinalOverriders);
6127
6128 // Keep a set of seen pure methods so we won't diagnose the same method
6129 // more than once.
6131
6132 for (const auto &M : FinalOverriders) {
6133 for (const auto &SO : M.second) {
6134 // C++ [class.abstract]p4:
6135 // A class is abstract if it contains or inherits at least one
6136 // pure virtual function for which the final overrider is pure
6137 // virtual.
6138
6139 if (SO.second.size() != 1)
6140 continue;
6141 const CXXMethodDecl *Method = SO.second.front().Method;
6142
6143 if (!Method->isPureVirtual())
6144 continue;
6145
6146 if (!SeenPureMethods.insert(Method).second)
6147 continue;
6148
6149 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6150 << Method->getDeclName() << RD->getDeclName();
6151 }
6152 }
6153
6156 PureVirtualClassDiagSet->insert(RD);
6157}
6158
6159namespace {
6160struct AbstractUsageInfo {
6161 Sema &S;
6163 CanQualType AbstractType;
6164 bool Invalid;
6165
6166 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6167 : S(S), Record(Record),
6168 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6169
6170 void DiagnoseAbstractType() {
6171 if (Invalid) return;
6173 Invalid = true;
6174 }
6175
6176 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6177};
6178
6179struct CheckAbstractUsage {
6180 AbstractUsageInfo &Info;
6181 const NamedDecl *Ctx;
6182
6183 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6184 : Info(Info), Ctx(Ctx) {}
6185
6186 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6187 switch (TL.getTypeLocClass()) {
6188#define ABSTRACT_TYPELOC(CLASS, PARENT)
6189#define TYPELOC(CLASS, PARENT) \
6190 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6191#include "clang/AST/TypeLocNodes.def"
6192 }
6193 }
6194
6195 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6197 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6198 if (!TL.getParam(I))
6199 continue;
6200
6201 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6202 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6203 }
6204 }
6205
6206 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6208 }
6209
6210 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6211 // Visit the type parameters from a permissive context.
6212 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6213 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6215 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6216 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6217 // TODO: other template argument types?
6218 }
6219 }
6220
6221 // Visit pointee types from a permissive context.
6222#define CheckPolymorphic(Type) \
6223 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6224 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6225 }
6231
6232 /// Handle all the types we haven't given a more specific
6233 /// implementation for above.
6234 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6235 // Every other kind of type that we haven't called out already
6236 // that has an inner type is either (1) sugar or (2) contains that
6237 // inner type in some way as a subobject.
6238 if (TypeLoc Next = TL.getNextTypeLoc())
6239 return Visit(Next, Sel);
6240
6241 // If there's no inner type and we're in a permissive context,
6242 // don't diagnose.
6243 if (Sel == Sema::AbstractNone) return;
6244
6245 // Check whether the type matches the abstract type.
6246 QualType T = TL.getType();
6247 if (T->isArrayType()) {
6249 T = Info.S.Context.getBaseElementType(T);
6250 }
6251 CanQualType CT = T->getCanonicalTypeUnqualified();
6252 if (CT != Info.AbstractType) return;
6253
6254 // It matched; do some magic.
6255 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6256 if (Sel == Sema::AbstractArrayType) {
6257 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6258 << T << TL.getSourceRange();
6259 } else {
6260 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6261 << Sel << T << TL.getSourceRange();
6262 }
6263 Info.DiagnoseAbstractType();
6264 }
6265};
6266
6267void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6269 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6270}
6271
6272}
6273
6274/// Check for invalid uses of an abstract type in a function declaration.
6275static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6276 FunctionDecl *FD) {
6277 // Only definitions are required to refer to complete and
6278 // non-abstract types.
6280 return;
6281
6282 // For safety's sake, just ignore it if we don't have type source
6283 // information. This should never happen for non-implicit methods,
6284 // but...
6285 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6286 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6287}
6288
6289/// Check for invalid uses of an abstract type in a variable0 declaration.
6290static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6291 VarDecl *VD) {
6292 // No need to do the check on definitions, which require that
6293 // the type is complete.
6295 return;
6296
6297 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6299}
6300
6301/// Check for invalid uses of an abstract type within a class definition.
6302static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6303 CXXRecordDecl *RD) {
6304 for (auto *D : RD->decls()) {
6305 if (D->isImplicit()) continue;
6306
6307 // Step through friends to the befriended declaration.
6308 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6309 D = FD->getFriendDecl();
6310 if (!D) continue;
6311 }
6312
6313 // Functions and function templates.
6314 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6315 CheckAbstractClassUsage(Info, FD);
6316 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6317 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6318
6319 // Fields and static variables.
6320 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6321 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6322 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6323 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6324 CheckAbstractClassUsage(Info, VD);
6325 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6326 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6327
6328 // Nested classes and class templates.
6329 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6330 CheckAbstractClassUsage(Info, RD);
6331 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6332 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6333 }
6334 }
6335}
6336
6338 Attr *ClassAttr = getDLLAttr(Class);
6339 if (!ClassAttr)
6340 return;
6341
6342 assert(ClassAttr->getKind() == attr::DLLExport);
6343
6344 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6345
6347 // Don't go any further if this is just an explicit instantiation
6348 // declaration.
6349 return;
6350
6351 // Add a context note to explain how we got to any diagnostics produced below.
6352 struct MarkingClassDllexported {
6353 Sema &S;
6354 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6355 SourceLocation AttrLoc)
6356 : S(S) {
6359 Ctx.PointOfInstantiation = AttrLoc;
6360 Ctx.Entity = Class;
6362 }
6363 ~MarkingClassDllexported() {
6365 }
6366 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6367
6368 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6369 S.MarkVTableUsed(Class->getLocation(), Class, true);
6370
6371 for (Decl *Member : Class->decls()) {
6372 // Skip members that were not marked exported.
6373 if (!Member->hasAttr<DLLExportAttr>())
6374 continue;
6375
6376 // Defined static variables that are members of an exported base
6377 // class must be marked export too.
6378 auto *VD = dyn_cast<VarDecl>(Member);
6379 if (VD && VD->getStorageClass() == SC_Static &&
6381 S.MarkVariableReferenced(VD->getLocation(), VD);
6382
6383 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6384 if (!MD)
6385 continue;
6386
6387 if (MD->isUserProvided()) {
6388 // Instantiate non-default class member functions ...
6389
6390 // .. except for certain kinds of template specializations.
6391 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6392 continue;
6393
6394 // If this is an MS ABI dllexport default constructor, instantiate any
6395 // default arguments.
6397 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6398 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6400 CD->getAttr<DLLExportAttr>()->getLocation(), CD);
6401 }
6402 }
6403
6404 S.MarkFunctionReferenced(Class->getLocation(), MD);
6405
6406 // The function will be passed to the consumer when its definition is
6407 // encountered.
6408 } else if (MD->isExplicitlyDefaulted()) {
6409 // Synthesize and instantiate explicitly defaulted methods.
6410 S.MarkFunctionReferenced(Class->getLocation(), MD);
6411
6413 // Except for explicit instantiation defs, we will not see the
6414 // definition again later, so pass it to the consumer now.
6416 }
6417 } else if (!MD->isTrivial() ||
6418 MD->isCopyAssignmentOperator() ||
6419 MD->isMoveAssignmentOperator()) {
6420 // Synthesize and instantiate non-trivial implicit methods, and the copy
6421 // and move assignment operators. The latter are exported even if they
6422 // are trivial, because the address of an operator can be taken and
6423 // should compare equal across libraries.
6424 S.MarkFunctionReferenced(Class->getLocation(), MD);
6425
6426 // There is no later point when we will see the definition of this
6427 // function, so pass it to the consumer now.
6429 }
6430 }
6431}
6432
6434 CXXRecordDecl *Class) {
6435 // Only the MS ABI has default constructor closures, so we don't need to do
6436 // this semantic checking anywhere else.
6438 return;
6439
6440 if (Class->isInvalidDecl())
6441 return;
6442
6443 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6444 for (Decl *Member : Class->decls()) {
6445 // Nested classes finish delayed default argument parsing with the outermost
6446 // class, so check each nested definition here.
6447 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Member)) {
6448 if (NestedClass->isThisDeclarationADefinition())
6450 continue;
6451 }
6452
6453 // Look for exported default constructors.
6454 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6455 if (!CD || !CD->isDefaultConstructor())
6456 continue;
6457 auto *Attr = CD->getAttr<DLLExportAttr>();
6458 if (!Attr)
6459 continue;
6460
6461 // If the class is non-dependent, mark the default arguments as ODR-used so
6462 // that we can properly codegen the constructor closure.
6463 if (!Class->isDependentContext()) {
6466 }
6467
6468 if (LastExportedDefaultCtor) {
6469 S.Diag(LastExportedDefaultCtor->getLocation(),
6470 diag::err_attribute_dll_ambiguous_default_ctor)
6471 << Class;
6472 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6473 << CD->getDeclName();
6474 return;
6475 }
6476 LastExportedDefaultCtor = CD;
6477 }
6478}
6479
6481 CXXRecordDecl *Class) {
6482 bool ErrorReported = false;
6483 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6484 ClassTemplateDecl *TD) {
6485 if (ErrorReported)
6486 return;
6487 S.Diag(TD->getLocation(),
6488 diag::err_cuda_device_builtin_surftex_cls_template)
6489 << /*surface*/ 0 << TD;
6490 ErrorReported = true;
6491 };
6492
6493 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6494 if (!TD) {
6495 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6496 if (!SD) {
6497 S.Diag(Class->getLocation(),
6498 diag::err_cuda_device_builtin_surftex_ref_decl)
6499 << /*surface*/ 0 << Class;
6500 S.Diag(Class->getLocation(),
6501 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6502 << Class;
6503 return;
6504 }
6505 TD = SD->getSpecializedTemplate();
6506 }
6507
6509 unsigned N = Params->size();
6510
6511 if (N != 2) {
6512 reportIllegalClassTemplate(S, TD);
6513 S.Diag(TD->getLocation(),
6514 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6515 << TD << 2;
6516 }
6517 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6518 reportIllegalClassTemplate(S, TD);
6519 S.Diag(TD->getLocation(),
6520 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6521 << TD << /*1st*/ 0 << /*type*/ 0;
6522 }
6523 if (N > 1) {
6524 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6525 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6526 reportIllegalClassTemplate(S, TD);
6527 S.Diag(TD->getLocation(),
6528 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6529 << TD << /*2nd*/ 1 << /*integer*/ 1;
6530 }
6531 }
6532}
6533
6535 CXXRecordDecl *Class) {
6536 bool ErrorReported = false;
6537 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6538 ClassTemplateDecl *TD) {
6539 if (ErrorReported)
6540 return;
6541 S.Diag(TD->getLocation(),
6542 diag::err_cuda_device_builtin_surftex_cls_template)
6543 << /*texture*/ 1 << TD;
6544 ErrorReported = true;
6545 };
6546
6547 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6548 if (!TD) {
6549 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6550 if (!SD) {
6551 S.Diag(Class->getLocation(),
6552 diag::err_cuda_device_builtin_surftex_ref_decl)
6553 << /*texture*/ 1 << Class;
6554 S.Diag(Class->getLocation(),
6555 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6556 << Class;
6557 return;
6558 }
6559 TD = SD->getSpecializedTemplate();
6560 }
6561
6563 unsigned N = Params->size();
6564
6565 if (N != 3) {
6566 reportIllegalClassTemplate(S, TD);
6567 S.Diag(TD->getLocation(),
6568 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6569 << TD << 3;
6570 }
6571 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6572 reportIllegalClassTemplate(S, TD);
6573 S.Diag(TD->getLocation(),
6574 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6575 << TD << /*1st*/ 0 << /*type*/ 0;
6576 }
6577 if (N > 1) {
6578 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6579 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6580 reportIllegalClassTemplate(S, TD);
6581 S.Diag(TD->getLocation(),
6582 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6583 << TD << /*2nd*/ 1 << /*integer*/ 1;
6584 }
6585 }
6586 if (N > 2) {
6587 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6588 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6589 reportIllegalClassTemplate(S, TD);
6590 S.Diag(TD->getLocation(),
6591 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6592 << TD << /*3rd*/ 2 << /*integer*/ 1;
6593 }
6594 }
6595}
6596
6598 // Mark any compiler-generated routines with the implicit code_seg attribute.
6599 for (auto *Method : Class->methods()) {
6600 if (Method->isUserProvided())
6601 continue;
6602 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6603 Method->addAttr(A);
6604 }
6605}
6606
6608 Attr *ClassAttr = getDLLAttr(Class);
6609
6610 // MSVC inherits DLL attributes to partial class template specializations.
6611 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6612 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6613 if (Attr *TemplateAttr =
6614 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6615 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6616 A->setInherited(true);
6617 ClassAttr = A;
6618 }
6619 }
6620 }
6621
6622 if (!ClassAttr)
6623 return;
6624
6625 // MSVC allows imported or exported template classes that have UniqueExternal
6626 // linkage. This occurs when the template class has been instantiated with
6627 // a template parameter which itself has internal linkage.
6628 // We drop the attribute to avoid exporting or importing any members.
6629 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6630 Context.getTargetInfo().getTriple().isPS()) &&
6631 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6632 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6633 return;
6634 }
6635
6636 if (!Class->isExternallyVisible()) {
6637 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6638 << Class << ClassAttr;
6639 return;
6640 }
6641
6642 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6643 !ClassAttr->isInherited()) {
6644 // Diagnose dll attributes on members of class with dll attribute.
6645 for (Decl *Member : Class->decls()) {
6647 continue;
6648 InheritableAttr *MemberAttr = getDLLAttr(Member);
6649 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6650 continue;
6651
6652 Diag(MemberAttr->getLocation(),
6653 diag::err_attribute_dll_member_of_dll_class)
6654 << MemberAttr << ClassAttr;
6655 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6656 Member->setInvalidDecl();
6657 }
6658 }
6659
6660 if (Class->getDescribedClassTemplate())
6661 // Don't inherit dll attribute until the template is instantiated.
6662 return;
6663
6664 // The class is either imported or exported.
6665 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6666
6667 // Check if this was a dllimport attribute propagated from a derived class to
6668 // a base class template specialization. We don't apply these attributes to
6669 // static data members.
6670 const bool PropagatedImport =
6671 !ClassExported &&
6672 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6673
6674 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6675
6676 // Ignore explicit dllexport on explicit class template instantiation
6677 // declarations, except in MinGW mode.
6678 if (ClassExported && !ClassAttr->isInherited() &&
6680 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6681 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6682 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6683 Class->dropAttr<DLLExportAttr>();
6684 }
6685 return;
6686 }
6687
6688 // Force declaration of implicit members so they can inherit the attribute.
6690
6691 // Inherited constructors are created lazily; force their creation now so the
6692 // loop below can propagate the DLL attribute to them.
6693 if (ClassExported && getLangOpts().DllExportInlines) {
6695 for (Decl *D : Class->decls())
6696 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6697 Shadows.push_back(S);
6698 for (ConstructorUsingShadowDecl *S : Shadows) {
6699 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6700 if (!BC || BC->isDeleted())
6701 continue;
6702 // Skip constructors whose requires clause is not satisfied.
6703 // Normally overload resolution filters these, but we are bypassing
6704 // it to eagerly create inherited constructors for dllexport.
6705 if (BC->getTrailingRequiresClause()) {
6706 ConstraintSatisfaction Satisfaction;
6707 if (CheckFunctionConstraints(BC, Satisfaction) ||
6708 !Satisfaction.IsSatisfied)
6709 continue;
6710 }
6711 findInheritingConstructor(Class->getLocation(), BC, S);
6712 }
6713 }
6714
6715 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6716 // seem to be true in practice?
6717
6718 for (Decl *Member : Class->decls()) {
6719 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6720 continue;
6721
6722 VarDecl *VD = dyn_cast<VarDecl>(Member);
6723 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6724
6725 // Only methods and static fields inherit the attributes.
6726 if (!VD && !MD)
6727 continue;
6728
6729 if (MD) {
6730 // Don't process deleted methods.
6731 if (MD->isDeleted())
6732 continue;
6733
6734 if (ClassExported && getLangOpts().DllExportInlines) {
6735 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6736 if (CD && CD->getInheritedConstructor()) {
6737 // Inherited constructors already had their base constructor's
6738 // constraints checked before creation via
6739 // findInheritingConstructor, so only ABI-compatibility checks
6740 // are needed here.
6741 //
6742 // Don't export inherited constructors whose parameters prevent
6743 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6744 // CodeGen) returns false, Clang inlines the constructor body
6745 // instead of emitting a forwarding thunk, producing code that
6746 // is not ABI-compatible with MSVC. Suppress the export and warn
6747 // so the user gets a linker error rather than a silent runtime
6748 // mismatch.
6749 if (CD->isVariadic()) {
6750 Diag(CD->getLocation(),
6751 diag::warn_dllexport_inherited_ctor_unsupported)
6752 << /*variadic=*/0;
6753 continue;
6754 }
6755 if (Context.getTargetInfo()
6756 .getCXXABI()
6757 .areArgsDestroyedLeftToRightInCallee()) {
6758 bool HasCalleeCleanupParam = false;
6759 for (const ParmVarDecl *P : CD->parameters())
6760 if (P->needsDestruction(Context)) {
6761 HasCalleeCleanupParam = true;
6762 break;
6763 }
6764 if (HasCalleeCleanupParam) {
6765 Diag(CD->getLocation(),
6766 diag::warn_dllexport_inherited_ctor_unsupported)
6767 << /*callee-cleanup=*/1;
6768 continue;
6769 }
6770 }
6771 } else if (MD->getTrailingRequiresClause()) {
6772 // Don't export methods whose requires clause is not satisfied.
6773 // For class template specializations, member constraints may
6774 // depend on template arguments and an unsatisfied constraint
6775 // means the member should not be available in this
6776 // specialization.
6777 ConstraintSatisfaction Satisfaction;
6778 if (CheckFunctionConstraints(MD, Satisfaction) ||
6779 !Satisfaction.IsSatisfied)
6780 continue;
6781 }
6782 }
6783
6784 if (MD->isInlined()) {
6785 // MinGW does not import or export inline methods. But do it for
6786 // template instantiations and inherited constructors (which are
6787 // marked inline but must be exported to match MSVC behavior).
6788 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6791 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6792 !CD || !CD->getInheritedConstructor())
6793 continue;
6794 }
6795
6796 // MSVC versions before 2015 don't export the move assignment operators
6797 // and move constructor, so don't attempt to import/export them if
6798 // we have a definition.
6799 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6800 if ((MD->isMoveAssignmentOperator() ||
6801 (Ctor && Ctor->isMoveConstructor())) &&
6802 getLangOpts().isCompatibleWithMSVC() &&
6803 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6804 continue;
6805
6806 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6807 // operator is exported anyway.
6808 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6809 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6810 continue;
6811 }
6812 }
6813
6814 // Don't apply dllimport attributes to static data members of class template
6815 // instantiations when the attribute is propagated from a derived class.
6816 if (VD && PropagatedImport)
6817 continue;
6818
6820 continue;
6821
6822 if (!getDLLAttr(Member)) {
6823 InheritableAttr *NewAttr = nullptr;
6824
6825 // Do not export/import inline function when -fno-dllexport-inlines is
6826 // passed. But add attribute for later local static var check.
6827 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6830 if (ClassExported) {
6831 NewAttr = ::new (getASTContext())
6832 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6833 } else {
6834 NewAttr = ::new (getASTContext())
6835 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6836 }
6837 } else {
6838 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6839 }
6840
6841 NewAttr->setInherited(true);
6842 Member->addAttr(NewAttr);
6843
6844 if (MD) {
6845 // Propagate DLLAttr to friend re-declarations of MD that have already
6846 // been constructed.
6847 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6848 FD = FD->getPreviousDecl()) {
6850 continue;
6851 assert(!getDLLAttr(FD) &&
6852 "friend re-decl should not already have a DLLAttr");
6853 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6854 NewAttr->setInherited(true);
6855 FD->addAttr(NewAttr);
6856 }
6857 }
6858 }
6859 }
6860
6861 if (ClassExported)
6862 DelayedDllExportClasses.push_back(Class);
6863}
6864
6866 CXXRecordDecl *Class, Attr *ClassAttr,
6867 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6868 if (getDLLAttr(
6869 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6870 // If the base class template has a DLL attribute, don't try to change it.
6871 return;
6872 }
6873
6874 auto TSK = BaseTemplateSpec->getSpecializationKind();
6875 if (!getDLLAttr(BaseTemplateSpec) &&
6877 TSK == TSK_ImplicitInstantiation)) {
6878 // The template hasn't been instantiated yet (or it has, but only as an
6879 // explicit instantiation declaration or implicit instantiation, which means
6880 // we haven't codegenned any members yet), so propagate the attribute.
6881 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6882 NewAttr->setInherited(true);
6883 BaseTemplateSpec->addAttr(NewAttr);
6884
6885 // If this was an import, mark that we propagated it from a derived class to
6886 // a base class template specialization.
6887 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6888 ImportAttr->setPropagatedToBaseTemplate();
6889
6890 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6891 // needs to be run again to work see the new attribute. Otherwise this will
6892 // get run whenever the template is instantiated.
6893 if (TSK != TSK_Undeclared)
6894 checkClassLevelDLLAttribute(BaseTemplateSpec);
6895
6896 return;
6897 }
6898
6899 if (getDLLAttr(BaseTemplateSpec)) {
6900 // The template has already been specialized or instantiated with an
6901 // attribute, explicitly or through propagation. We should not try to change
6902 // it.
6903 return;
6904 }
6905
6906 // The template was previously instantiated or explicitly specialized without
6907 // a dll attribute, It's too late for us to add an attribute, so warn that
6908 // this is unsupported.
6909 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6910 << BaseTemplateSpec->isExplicitSpecialization();
6911 Diag(ClassAttr->getLocation(), diag::note_attribute);
6912 if (BaseTemplateSpec->isExplicitSpecialization()) {
6913 Diag(BaseTemplateSpec->getLocation(),
6914 diag::note_template_class_explicit_specialization_was_here)
6915 << BaseTemplateSpec;
6916 } else {
6917 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6918 diag::note_template_class_instantiation_was_here)
6919 << BaseTemplateSpec;
6920 }
6921}
6922
6923namespace {
6924/// RAII object to restore the floating-point (FP) features active at the time
6925/// a defaulted function was declared. This ensures that the synthesized body
6926/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6927/// that were in effect when the function was explicitly defaulted.
6928struct DefaultedFunctionFPFeaturesRAII {
6929 Sema::FPFeaturesStateRAII SavedFPFeatures;
6930 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6931 : SavedFPFeatures(S) {
6932 auto *Info = FD->getDefaultedOrDeletedInfo();
6933 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6935 S.FpPragmaStack.CurrentValue = FPO;
6936 }
6937
6938 ~DefaultedFunctionFPFeaturesRAII() = default;
6939};
6940} // namespace
6941
6943 SourceLocation DefaultLoc) {
6945 if (DFK.isComparison())
6946 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6947
6948 switch (DFK.asSpecialMember()) {
6952 break;
6955 break;
6958 break;
6961 break;
6964 break;
6967 break;
6969 llvm_unreachable("Invalid special member.");
6970 }
6971}
6972
6973/// Determine whether a type is permitted to be passed or returned in
6974/// registers, per C++ [class.temporary]p3.
6977 if (D->isDependentType() || D->isInvalidDecl())
6978 return false;
6979
6980 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6981 // The PS4 platform ABI follows the behavior of Clang 3.2.
6983 return !D->hasNonTrivialDestructorForCall() &&
6985
6986 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6987 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6988 bool DtorIsTrivialForCall = false;
6989
6990 // If a class has at least one eligible, trivial copy constructor, it
6991 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6992 //
6993 // Note: This permits classes with non-trivial copy or move ctors to be
6994 // passed in registers, so long as they *also* have a trivial copy ctor,
6995 // which is non-conforming.
6999 CopyCtorIsTrivial = true;
7001 CopyCtorIsTrivialForCall = true;
7002 }
7003 } else {
7004 for (const CXXConstructorDecl *CD : D->ctors()) {
7005 if (CD->isCopyConstructor() && !CD->isDeleted() &&
7006 !CD->isIneligibleOrNotSelected()) {
7007 if (CD->isTrivial())
7008 CopyCtorIsTrivial = true;
7009 if (CD->isTrivialForCall())
7010 CopyCtorIsTrivialForCall = true;
7011 }
7012 }
7013 }
7014
7015 if (D->needsImplicitDestructor()) {
7016 if (!D->defaultedDestructorIsDeleted() &&
7018 DtorIsTrivialForCall = true;
7019 } else if (const auto *DD = D->getDestructor()) {
7020 if (!DD->isDeleted() && DD->isTrivialForCall())
7021 DtorIsTrivialForCall = true;
7022 }
7023
7024 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7025 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7026 return true;
7027
7028 // If a class has a destructor, we'd really like to pass it indirectly
7029 // because it allows us to elide copies. Unfortunately, MSVC makes that
7030 // impossible for small types, which it will pass in a single register or
7031 // stack slot. Most objects with dtors are large-ish, so handle that early.
7032 // We can't call out all large objects as being indirect because there are
7033 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7034 // how we pass large POD types.
7035
7036 // Note: This permits small classes with nontrivial destructors to be
7037 // passed in registers, which is non-conforming.
7038 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7039 uint64_t TypeSize = isAArch64 ? 128 : 64;
7040
7041 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7042 S.Context.getCanonicalTagType(D)) <= TypeSize)
7043 return true;
7044 return false;
7045 }
7046
7047 // Per C++ [class.temporary]p3, the relevant condition is:
7048 // each copy constructor, move constructor, and destructor of X is
7049 // either trivial or deleted, and X has at least one non-deleted copy
7050 // or move constructor
7051 bool HasNonDeletedCopyOrMove = false;
7052
7056 return false;
7057 HasNonDeletedCopyOrMove = true;
7058 }
7059
7060 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7063 return false;
7064 HasNonDeletedCopyOrMove = true;
7065 }
7066
7069 return false;
7070
7071 for (const CXXMethodDecl *MD : D->methods()) {
7072 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7073 continue;
7074
7075 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7076 if (CD && CD->isCopyOrMoveConstructor())
7077 HasNonDeletedCopyOrMove = true;
7078 else if (!isa<CXXDestructorDecl>(MD))
7079 continue;
7080
7081 if (!MD->isTrivialForCall())
7082 return false;
7083 }
7084
7085 return HasNonDeletedCopyOrMove;
7086}
7087
7088/// Report an error regarding overriding, along with any relevant
7089/// overridden methods.
7090///
7091/// \param DiagID the primary error to report.
7092/// \param MD the overriding method.
7093static bool
7094ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7095 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7096 bool IssuedDiagnostic = false;
7097 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7098 if (Report(O)) {
7099 if (!IssuedDiagnostic) {
7100 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7101 IssuedDiagnostic = true;
7102 }
7103 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7104 }
7105 }
7106 return IssuedDiagnostic;
7107}
7108
7110 if (!Record)
7111 return;
7112
7113 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7114 AbstractUsageInfo Info(*this, Record);
7116 }
7117
7118 // If this is not an aggregate type and has no user-declared constructor,
7119 // complain about any non-static data members of reference or const scalar
7120 // type, since they will never get initializers.
7121 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7122 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7123 !Record->isLambda()) {
7124 bool Complained = false;
7125 for (const auto *F : Record->fields()) {
7126 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7127 continue;
7128
7129 if (F->getType()->isReferenceType() ||
7130 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7131 if (!Complained) {
7132 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7133 << Record->getTagKind() << Record;
7134 Complained = true;
7135 }
7136
7137 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7138 << F->getType()->isReferenceType()
7139 << F->getDeclName();
7140 }
7141 }
7142 }
7143
7144 if (Record->getIdentifier()) {
7145 // C++ [class.mem]p13:
7146 // If T is the name of a class, then each of the following shall have a
7147 // name different from T:
7148 // - every member of every anonymous union that is a member of class T.
7149 //
7150 // C++ [class.mem]p14:
7151 // In addition, if class T has a user-declared constructor (12.1), every
7152 // non-static data member of class T shall have a name different from T.
7153 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7154 const NamedDecl *D = Element->getUnderlyingDecl();
7155 // Invalid IndirectFieldDecls have already been diagnosed with
7156 // err_anonymous_record_member_redecl in
7157 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7159 Record->hasUserDeclaredConstructor()) ||
7160 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7161 Diag(Element->getLocation(), diag::err_member_name_of_class)
7162 << D->getDeclName();
7163 break;
7164 }
7165 }
7166 }
7167
7168 // Warn if the class has virtual methods but non-virtual public destructor.
7169 if (Record->isPolymorphic() && !Record->isDependentType()) {
7170 CXXDestructorDecl *dtor = Record->getDestructor();
7171 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7172 !Record->hasAttr<FinalAttr>())
7173 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7174 diag::warn_non_virtual_dtor)
7175 << Context.getCanonicalTagType(Record);
7176 }
7177
7178 if (Record->isAbstract()) {
7179 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7180 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7181 << FA->isSpelledAsSealed();
7183 }
7184 }
7185
7186 // Warn if the class has a final destructor but is not itself marked final.
7187 if (!Record->hasAttr<FinalAttr>()) {
7188 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7189 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7190 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7191 << FA->isSpelledAsSealed()
7193 getLocForEndOfToken(Record->getLocation()),
7194 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7195 Diag(Record->getLocation(),
7196 diag::note_final_dtor_non_final_class_silence)
7197 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7198 }
7199 }
7200 }
7201
7202 // See if trivial_abi has to be dropped.
7203 if (Record->hasAttr<TrivialABIAttr>())
7205
7206 // Set HasTrivialSpecialMemberForCall if the record has attribute
7207 // "trivial_abi".
7208 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7209
7210 if (HasTrivialABI)
7211 Record->setHasTrivialSpecialMemberForCall();
7212
7213 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7214 // We check these last because they can depend on the properties of the
7215 // primary comparison functions (==, <=>).
7216 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7217
7218 // Perform checks that can't be done until we know all the properties of a
7219 // member function (whether it's defaulted, deleted, virtual, overriding,
7220 // ...).
7221 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7222 // A static function cannot override anything.
7223 if (MD->getStorageClass() == SC_Static) {
7224 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7225 [](const CXXMethodDecl *) { return true; }))
7226 return;
7227 }
7228
7229 // A deleted function cannot override a non-deleted function and vice
7230 // versa.
7231 if (ReportOverrides(*this,
7232 MD->isDeleted() ? diag::err_deleted_override
7233 : diag::err_non_deleted_override,
7234 MD, [&](const CXXMethodDecl *V) {
7235 return MD->isDeleted() != V->isDeleted();
7236 })) {
7237 if (MD->isDefaulted() && MD->isDeleted())
7238 // Explain why this defaulted function was deleted.
7240 return;
7241 }
7242
7243 // A consteval function cannot override a non-consteval function and vice
7244 // versa.
7245 if (ReportOverrides(*this,
7246 MD->isConsteval() ? diag::err_consteval_override
7247 : diag::err_non_consteval_override,
7248 MD, [&](const CXXMethodDecl *V) {
7249 return MD->isConsteval() != V->isConsteval();
7250 })) {
7251 if (MD->isDefaulted() && MD->isDeleted())
7252 // Explain why this defaulted function was deleted.
7254 return;
7255 }
7256 };
7257
7258 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7259 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7260 return false;
7261
7265 DefaultedSecondaryComparisons.push_back(FD);
7266 return true;
7267 }
7268
7270 return false;
7271 };
7272
7273 if (!Record->isInvalidDecl() &&
7274 Record->hasAttr<VTablePointerAuthenticationAttr>())
7276
7277 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7278 // Check whether the explicitly-defaulted members are valid.
7279 bool Incomplete = CheckForDefaultedFunction(M);
7280
7281 // Skip the rest of the checks for a member of a dependent class.
7282 if (Record->isDependentType())
7283 return;
7284
7285 // For an explicitly defaulted or deleted special member, we defer
7286 // determining triviality until the class is complete. That time is now!
7287 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7288 if (!M->isImplicit() && !M->isUserProvided()) {
7289 if (CSM != CXXSpecialMemberKind::Invalid) {
7290 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7291 // Inform the class that we've finished declaring this member.
7292 Record->finishedDefaultedOrDeletedMember(M);
7293 M->setTrivialForCall(
7294 HasTrivialABI ||
7297 Record->setTrivialForCallFlags(M);
7298 }
7299 }
7300
7301 // Set triviality for the purpose of calls if this is a user-provided
7302 // copy/move constructor or destructor.
7306 M->isUserProvided()) {
7307 M->setTrivialForCall(HasTrivialABI);
7308 Record->setTrivialForCallFlags(M);
7309 }
7310
7311 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7312 M->hasAttr<DLLExportAttr>()) {
7313 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7314 M->isTrivial() &&
7318 M->dropAttr<DLLExportAttr>();
7319
7320 if (M->hasAttr<DLLExportAttr>()) {
7321 // Define after any fields with in-class initializers have been parsed.
7323 }
7324 }
7325
7326 bool EffectivelyConstexprDestructor = true;
7327 // Avoid triggering vtable instantiation due to a dtor that is not
7328 // "effectively constexpr" for better compatibility.
7329 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7330 if (isa<CXXDestructorDecl>(M)) {
7331 llvm::SmallDenseSet<QualType> Visited;
7332 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7333 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7334 return false;
7335 const CXXRecordDecl *RD =
7336 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7337 if (!RD || !RD->isCompleteDefinition())
7338 return true;
7339
7340 if (!RD->hasConstexprDestructor())
7341 return false;
7342
7343 for (const CXXBaseSpecifier &B : RD->bases())
7344 if (!Check(B.getType(), Check))
7345 return false;
7346 for (const FieldDecl *FD : RD->fields())
7347 if (!Check(FD->getType(), Check))
7348 return false;
7349 return true;
7350 };
7351 EffectivelyConstexprDestructor =
7352 Check(Context.getCanonicalTagType(Record), Check);
7353 }
7354
7355 // Define defaulted constexpr virtual functions that override a base class
7356 // function right away.
7357 // FIXME: We can defer doing this until the vtable is marked as used.
7358 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7359 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7360 EffectivelyConstexprDestructor)
7361 DefineDefaultedFunction(*this, M, M->getLocation());
7362
7363 if (!Incomplete)
7364 CheckCompletedMemberFunction(M);
7365 };
7366
7367 // Check the destructor before any other member function. We need to
7368 // determine whether it's trivial in order to determine whether the claas
7369 // type is a literal type, which is a prerequisite for determining whether
7370 // other special member functions are valid and whether they're implicitly
7371 // 'constexpr'.
7372 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7373 CompleteMemberFunction(Dtor);
7374
7375 bool HasMethodWithOverrideControl = false,
7376 HasOverridingMethodWithoutOverrideControl = false;
7377 for (auto *D : Record->decls()) {
7378 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7379 // FIXME: We could do this check for dependent types with non-dependent
7380 // bases.
7381 if (!Record->isDependentType()) {
7382 // See if a method overloads virtual methods in a base
7383 // class without overriding any.
7384 if (!M->isStatic())
7386
7387 if (M->hasAttr<OverrideAttr>()) {
7388 HasMethodWithOverrideControl = true;
7389 } else if (M->size_overridden_methods() > 0) {
7390 HasOverridingMethodWithoutOverrideControl = true;
7391 } else {
7392 // Warn on newly-declared virtual methods in `final` classes
7393 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7394 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7395 << M;
7396 }
7397 }
7398 }
7399
7400 if (!isa<CXXDestructorDecl>(M))
7401 CompleteMemberFunction(M);
7402 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7403 CheckForDefaultedFunction(
7404 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7405 }
7406 }
7407
7408 if (HasOverridingMethodWithoutOverrideControl) {
7409 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7410 for (auto *M : Record->methods())
7411 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7412 }
7413
7414 // Check the defaulted secondary comparisons after any other member functions.
7415 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7417
7418 // If this is a member function, we deferred checking it until now.
7419 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7420 CheckCompletedMemberFunction(MD);
7421 }
7422
7423 // {ms,gcc}_struct is a request to change ABI rules to either follow
7424 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7425 // present, we do not layout classes following foreign ABI rules, but
7426 // instead enter a special "compatibility mode", which only changes
7427 // alignments of fundamental types and layout of bit fields.
7428 // Check whether this class uses any C++ features that are implemented
7429 // completely differently in the requested ABI, and if so, emit a
7430 // diagnostic. That diagnostic defaults to an error, but we allow
7431 // projects to map it down to a warning (or ignore it). It's a fairly
7432 // common practice among users of the ms_struct pragma to
7433 // mass-annotate headers, sweeping up a bunch of types that the
7434 // project doesn't really rely on MSVC-compatible layout for. We must
7435 // therefore support "ms_struct except for C++ stuff" as a secondary
7436 // ABI.
7437 // Don't emit this diagnostic if the feature was enabled as a
7438 // language option (as opposed to via a pragma or attribute), as
7439 // the option -mms-bitfields otherwise essentially makes it impossible
7440 // to build C++ code, unless this diagnostic is turned off.
7441 if (Context.getLangOpts().getLayoutCompatibility() ==
7443 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7444 (Record->isPolymorphic() || Record->getNumBases())) {
7445 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7446 }
7447
7450
7451 bool ClangABICompat4 =
7452 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7454 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7455 bool CanPass = canPassInRegisters(*this, Record, CCK);
7456
7457 // Do not change ArgPassingRestrictions if it has already been set to
7458 // RecordArgPassingKind::CanNeverPassInRegs.
7459 if (Record->getArgPassingRestrictions() !=
7461 Record->setArgPassingRestrictions(
7464
7465 // If canPassInRegisters returns true despite the record having a non-trivial
7466 // destructor, the record is destructed in the callee. This happens only when
7467 // the record or one of its subobjects has a field annotated with trivial_abi
7468 // or a field qualified with ObjC __strong/__weak.
7469 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7470 Record->setParamDestroyedInCallee(true);
7471 else if (Record->hasNonTrivialDestructor())
7472 Record->setParamDestroyedInCallee(CanPass);
7473
7474 if (getLangOpts().ForceEmitVTables) {
7475 // If we want to emit all the vtables, we need to mark it as used. This
7476 // is especially required for cases like vtable assumption loads.
7477 MarkVTableUsed(Record->getInnerLocStart(), Record);
7478 }
7479
7480 if (getLangOpts().CUDA) {
7481 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7483 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7485 }
7486
7487 llvm::SmallDenseMap<OverloadedOperatorKind,
7489 TypeAwareDecls{{OO_New, {}},
7490 {OO_Array_New, {}},
7491 {OO_Delete, {}},
7492 {OO_Array_New, {}}};
7493 for (auto *D : Record->decls()) {
7494 const FunctionDecl *FnDecl = D->getAsFunction();
7495 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7496 continue;
7497 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7498 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7499 }
7500 auto CheckMismatchedTypeAwareAllocators =
7501 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7502 OverloadedOperatorKind DeleteKind) {
7503 auto &NewDecls = TypeAwareDecls[NewKind];
7504 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7505 if (NewDecls.empty() == DeleteDecls.empty())
7506 return;
7507 DeclarationName FoundOperator =
7508 Context.DeclarationNames.getCXXOperatorName(
7509 NewDecls.empty() ? DeleteKind : NewKind);
7510 DeclarationName MissingOperator =
7511 Context.DeclarationNames.getCXXOperatorName(
7512 NewDecls.empty() ? NewKind : DeleteKind);
7513 Diag(Record->getLocation(),
7514 diag::err_type_aware_allocator_missing_matching_operator)
7515 << FoundOperator << Context.getCanonicalTagType(Record)
7516 << MissingOperator;
7517 for (auto MD : NewDecls)
7518 Diag(MD->getLocation(),
7519 diag::note_unmatched_type_aware_allocator_declared)
7520 << MD;
7521 for (auto MD : DeleteDecls)
7522 Diag(MD->getLocation(),
7523 diag::note_unmatched_type_aware_allocator_declared)
7524 << MD;
7525 };
7526 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7527 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7528}
7529
7530/// Look up the special member function that would be called by a special
7531/// member function for a subobject of class type.
7532///
7533/// \param Class The class type of the subobject.
7534/// \param CSM The kind of special member function.
7535/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7536/// \param ConstRHS True if this is a copy operation with a const object
7537/// on its RHS, that is, if the argument to the outer special member
7538/// function is 'const' and this is not a field marked 'mutable'.
7541 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7542 bool ConstRHS) {
7543 unsigned LHSQuals = 0;
7546 LHSQuals = FieldQuals;
7547
7548 unsigned RHSQuals = FieldQuals;
7551 RHSQuals = 0;
7552 else if (ConstRHS)
7553 RHSQuals |= Qualifiers::Const;
7554
7555 return S.LookupSpecialMember(Class, CSM,
7556 RHSQuals & Qualifiers::Const,
7557 RHSQuals & Qualifiers::Volatile,
7558 false,
7559 LHSQuals & Qualifiers::Const,
7560 LHSQuals & Qualifiers::Volatile);
7561}
7562
7564 Sema &S;
7565 SourceLocation UseLoc;
7566
7567 /// A mapping from the base classes through which the constructor was
7568 /// inherited to the using shadow declaration in that base class (or a null
7569 /// pointer if the constructor was declared in that base class).
7570 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7571 InheritedFromBases;
7572
7573public:
7576 : S(S), UseLoc(UseLoc) {
7577 bool DiagnosedMultipleConstructedBases = false;
7578 CXXRecordDecl *ConstructedBase = nullptr;
7579 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7580
7581 // Find the set of such base class subobjects and check that there's a
7582 // unique constructed subobject.
7583 for (auto *D : Shadow->redecls()) {
7584 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7585 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7586 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7587
7588 InheritedFromBases.insert(
7589 std::make_pair(DNominatedBase->getCanonicalDecl(),
7590 DShadow->getNominatedBaseClassShadowDecl()));
7591 if (DShadow->constructsVirtualBase())
7592 InheritedFromBases.insert(
7593 std::make_pair(DConstructedBase->getCanonicalDecl(),
7594 DShadow->getConstructedBaseClassShadowDecl()));
7595 else
7596 assert(DNominatedBase == DConstructedBase);
7597
7598 // [class.inhctor.init]p2:
7599 // If the constructor was inherited from multiple base class subobjects
7600 // of type B, the program is ill-formed.
7601 if (!ConstructedBase) {
7602 ConstructedBase = DConstructedBase;
7603 ConstructedBaseIntroducer = D->getIntroducer();
7604 } else if (ConstructedBase != DConstructedBase &&
7605 !Shadow->isInvalidDecl()) {
7606 if (!DiagnosedMultipleConstructedBases) {
7607 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7608 << Shadow->getTargetDecl();
7609 S.Diag(ConstructedBaseIntroducer->getLocation(),
7610 diag::note_ambiguous_inherited_constructor_using)
7611 << ConstructedBase;
7612 DiagnosedMultipleConstructedBases = true;
7613 }
7614 S.Diag(D->getIntroducer()->getLocation(),
7615 diag::note_ambiguous_inherited_constructor_using)
7616 << DConstructedBase;
7617 }
7618 }
7619
7620 if (DiagnosedMultipleConstructedBases)
7621 Shadow->setInvalidDecl();
7622 }
7623
7624 /// Find the constructor to use for inherited construction of a base class,
7625 /// and whether that base class constructor inherits the constructor from a
7626 /// virtual base class (in which case it won't actually invoke it).
7627 std::pair<CXXConstructorDecl *, bool>
7629 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7630 if (It == InheritedFromBases.end())
7631 return std::make_pair(nullptr, false);
7632
7633 // This is an intermediary class.
7634 if (It->second)
7635 return std::make_pair(
7636 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7637 It->second->constructsVirtualBase());
7638
7639 // This is the base class from which the constructor was inherited.
7640 return std::make_pair(Ctor, false);
7641 }
7642};
7643
7644/// Is the special member function which would be selected to perform the
7645/// specified operation on the specified class type a constexpr constructor?
7647 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7648 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7649 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7650 // Suppress duplicate constraint checking here, in case a constraint check
7651 // caused us to decide to do this. Any truely recursive checks will get
7652 // caught during these checks anyway.
7654
7655 // If we're inheriting a constructor, see if we need to call it for this base
7656 // class.
7657 if (InheritedCtor) {
7659 auto BaseCtor =
7660 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7661 if (BaseCtor)
7662 return BaseCtor->isConstexpr();
7663 }
7664
7666 return ClassDecl->hasConstexprDefaultConstructor();
7668 return ClassDecl->hasConstexprDestructor();
7669
7671 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7672 if (!SMOR.getMethod())
7673 // A constructor we wouldn't select can't be "involved in initializing"
7674 // anything.
7675 return true;
7676 return SMOR.getMethod()->isConstexpr();
7677}
7678
7679/// Determine whether the specified special member function would be constexpr
7680/// if it were implicitly defined.
7682 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7683 CXXConstructorDecl *InheritedCtor = nullptr,
7684 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7685 if (!S.getLangOpts().CPlusPlus11)
7686 return false;
7687
7688 // C++11 [dcl.constexpr]p4:
7689 // In the definition of a constexpr constructor [...]
7690 bool Ctor = true;
7691 switch (CSM) {
7693 if (Inherited)
7694 break;
7695 // Since default constructor lookup is essentially trivial (and cannot
7696 // involve, for instance, template instantiation), we compute whether a
7697 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7698 //
7699 // This is important for performance; we need to know whether the default
7700 // constructor is constexpr to determine whether the type is a literal type.
7701 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7702
7705 // For copy or move constructors, we need to perform overload resolution.
7706 break;
7707
7710 if (!S.getLangOpts().CPlusPlus14)
7711 return false;
7712 // In C++1y, we need to perform overload resolution.
7713 Ctor = false;
7714 break;
7715
7717 return ClassDecl->defaultedDestructorIsConstexpr();
7718
7720 return false;
7721 }
7722
7723 // -- if the class is a non-empty union, or for each non-empty anonymous
7724 // union member of a non-union class, exactly one non-static data member
7725 // shall be initialized; [DR1359]
7726 //
7727 // If we squint, this is guaranteed, since exactly one non-static data member
7728 // will be initialized (if the constructor isn't deleted), we just don't know
7729 // which one.
7730 if (Ctor && ClassDecl->isUnion())
7732 ? ClassDecl->hasInClassInitializer() ||
7733 !ClassDecl->hasVariantMembers()
7734 : true;
7735
7736 // -- the class shall not have any virtual base classes;
7737 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7738 return false;
7739
7740 // C++1y [class.copy]p26:
7741 // -- [the class] is a literal type, and
7742 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7743 return false;
7744
7745 // -- every constructor involved in initializing [...] base class
7746 // sub-objects shall be a constexpr constructor;
7747 // -- the assignment operator selected to copy/move each direct base
7748 // class is a constexpr function, and
7749 if (!S.getLangOpts().CPlusPlus23) {
7750 for (const auto &B : ClassDecl->bases()) {
7751 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7752 if (!BaseClassDecl)
7753 continue;
7754 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7755 InheritedCtor, Inherited))
7756 return false;
7757 }
7758 }
7759
7760 // -- every constructor involved in initializing non-static data members
7761 // [...] shall be a constexpr constructor;
7762 // -- every non-static data member and base class sub-object shall be
7763 // initialized
7764 // -- for each non-static data member of X that is of class type (or array
7765 // thereof), the assignment operator selected to copy/move that member is
7766 // a constexpr function
7767 if (!S.getLangOpts().CPlusPlus23) {
7768 for (const auto *F : ClassDecl->fields()) {
7769 if (F->isInvalidDecl())
7770 continue;
7772 F->hasInClassInitializer())
7773 continue;
7774 QualType BaseType = S.Context.getBaseElementType(F->getType());
7775 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7776 auto *FieldRecDecl =
7777 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7778 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7779 BaseType.getCVRQualifiers(),
7780 ConstArg && !F->isMutable()))
7781 return false;
7782 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7783 return false;
7784 }
7785 }
7786 }
7787
7788 // All OK, it's constexpr!
7789 return true;
7790}
7791
7792namespace {
7793/// RAII object to register a defaulted function as having its exception
7794/// specification computed.
7795struct ComputingExceptionSpec {
7796 Sema &S;
7797
7798 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7799 : S(S) {
7800 Sema::CodeSynthesisContext Ctx;
7802 Ctx.PointOfInstantiation = Loc;
7803 Ctx.Entity = FD;
7805 }
7806 ~ComputingExceptionSpec() {
7808 }
7809};
7810}
7811
7812static Sema::ImplicitExceptionSpecification
7813ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7814 CXXMethodDecl *MD,
7816 Sema::InheritedConstructorInfo *ICI);
7817
7818static Sema::ImplicitExceptionSpecification
7819ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7820 FunctionDecl *FD,
7822
7823static Sema::ImplicitExceptionSpecification
7825 auto DFK = FD->getDefaultedFunctionKind();
7826 if (DFK.isSpecialMember())
7828 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7829 if (DFK.isComparison())
7831 DFK.asComparison());
7832
7833 auto *CD = cast<CXXConstructorDecl>(FD);
7834 assert(CD->getInheritedConstructor() &&
7835 "only defaulted functions and inherited constructors have implicit "
7836 "exception specs");
7838 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7841}
7842
7844 CXXMethodDecl *MD) {
7846
7847 // Build an exception specification pointing back at this member.
7849 EPI.ExceptionSpec.SourceDecl = MD;
7850
7851 // Set the calling convention to the default for C++ instance methods.
7853 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7854 /*IsCXXMethod=*/true));
7855 return EPI;
7856}
7857
7859 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7861 return;
7862
7863 // Evaluate the exception specification.
7864 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7865 auto ESI = IES.getExceptionSpec();
7866
7867 // Update the type of the special member to use it.
7868 UpdateExceptionSpec(FD, ESI);
7869}
7870
7872 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7873
7875 if (!DefKind) {
7876 assert(FD->getDeclContext()->isDependentContext());
7877 return;
7878 }
7879
7880 if (DefKind.isComparison()) {
7881 auto PT = FD->getParamDecl(0)->getType();
7882 if (const CXXRecordDecl *RD =
7883 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7884 for (FieldDecl *Field : RD->fields()) {
7885 UnusedPrivateFields.remove(Field);
7886 }
7887 }
7888 }
7889
7890 if (DefKind.isSpecialMember()
7892 DefKind.asSpecialMember(),
7893 FD->getDefaultLoc())
7895 FD->setInvalidDecl();
7896}
7897
7900 SourceLocation DefaultLoc) {
7901 CXXRecordDecl *RD = MD->getParent();
7902
7904 "not an explicitly-defaulted special member");
7905
7906 // Defer all checking for special members of a dependent type.
7907 if (RD->isDependentType())
7908 return false;
7909
7910 // Whether this was the first-declared instance of the constructor.
7911 // This affects whether we implicitly add an exception spec and constexpr.
7912 bool First = MD == MD->getCanonicalDecl();
7913
7914 bool HadError = false;
7915
7916 // C++11 [dcl.fct.def.default]p1:
7917 // A function that is explicitly defaulted shall
7918 // -- be a special member function [...] (checked elsewhere),
7919 // -- have the same type (except for ref-qualifiers, and except that a
7920 // copy operation can take a non-const reference) as an implicit
7921 // declaration, and
7922 // -- not have default arguments.
7923 // C++2a changes the second bullet to instead delete the function if it's
7924 // defaulted on its first declaration, unless it's "an assignment operator,
7925 // and its return type differs or its parameter type is not a reference".
7926 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7927 bool ShouldDeleteForTypeMismatch = false;
7928 unsigned ExpectedParams = 1;
7931 ExpectedParams = 0;
7932 if (MD->getNumExplicitParams() != ExpectedParams) {
7933 // This checks for default arguments: a copy or move constructor with a
7934 // default argument is classified as a default constructor, and assignment
7935 // operations and destructors can't have default arguments.
7936 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7937 << CSM << MD->getSourceRange();
7938 HadError = true;
7939 } else if (MD->isVariadic()) {
7940 if (DeleteOnTypeMismatch)
7941 ShouldDeleteForTypeMismatch = true;
7942 else {
7943 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7944 << CSM << MD->getSourceRange();
7945 HadError = true;
7946 }
7947 }
7948
7950
7951 bool CanHaveConstParam = false;
7953 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7955 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7956
7957 QualType ReturnType = Context.VoidTy;
7960 // Check for return type matching.
7961 ReturnType = Type->getReturnType();
7963
7964 QualType DeclType =
7966 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7967 DeclType = Context.getAddrSpaceQualType(
7968 DeclType, ThisType.getQualifiers().getAddressSpace());
7969 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7970
7971 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7972 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7974 << ExpectedReturnType;
7975 HadError = true;
7976 }
7977
7978 // A defaulted special member cannot have cv-qualifiers.
7979 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7980 if (DeleteOnTypeMismatch)
7981 ShouldDeleteForTypeMismatch = true;
7982 else {
7983 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7985 << getLangOpts().CPlusPlus14;
7986 HadError = true;
7987 }
7988 }
7989 // [C++23][dcl.fct.def.default]/p2.2
7990 // if F2 has an implicit object parameter of type “reference to C”,
7991 // F1 may be an explicit object member function whose explicit object
7992 // parameter is of (possibly different) type “reference to C”,
7993 // in which case the type of F1 would differ from the type of F2
7994 // in that the type of F1 has an additional parameter;
7995 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7996 ? MD->getParamDecl(0)->getType()
7997 : QualType();
7998 if (!ExplicitObjectParameter.isNull() &&
7999 (!ExplicitObjectParameter->isReferenceType() ||
8000 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
8001 Context.getCanonicalTagType(RD)))) {
8002 if (DeleteOnTypeMismatch)
8003 ShouldDeleteForTypeMismatch = true;
8004 else {
8005 Diag(MD->getLocation(),
8006 diag::err_defaulted_special_member_explicit_object_mismatch)
8007 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
8008 << MD->getSourceRange();
8009 HadError = true;
8010 }
8011 }
8012 }
8013
8014 // Check for parameter type matching.
8016 ExpectedParams
8017 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
8018 : QualType();
8019 bool HasConstParam = false;
8020 if (ExpectedParams && ArgType->isReferenceType()) {
8021 // Argument must be reference to possibly-const T.
8022 QualType ReferentType = ArgType->getPointeeType();
8023 HasConstParam = ReferentType.isConstQualified();
8024
8025 if (ReferentType.isVolatileQualified()) {
8026 if (DeleteOnTypeMismatch)
8027 ShouldDeleteForTypeMismatch = true;
8028 else {
8029 Diag(MD->getLocation(),
8030 diag::err_defaulted_special_member_volatile_param)
8031 << CSM;
8032 HadError = true;
8033 }
8034 }
8035
8036 if (HasConstParam && !CanHaveConstParam) {
8037 if (DeleteOnTypeMismatch)
8038 ShouldDeleteForTypeMismatch = true;
8039 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8041 Diag(MD->getLocation(),
8042 diag::err_defaulted_special_member_copy_const_param)
8044 // FIXME: Explain why this special member can't be const.
8045 HadError = true;
8046 } else {
8047 Diag(MD->getLocation(),
8048 diag::err_defaulted_special_member_move_const_param)
8050 HadError = true;
8051 }
8052 }
8053 } else if (ExpectedParams) {
8054 // A copy assignment operator can take its argument by value, but a
8055 // defaulted one cannot.
8057 "unexpected non-ref argument");
8058 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8059 HadError = true;
8060 }
8061
8062 // C++11 [dcl.fct.def.default]p2:
8063 // An explicitly-defaulted function may be declared constexpr only if it
8064 // would have been implicitly declared as constexpr,
8065 // Do not apply this rule to members of class templates, since core issue 1358
8066 // makes such functions always instantiate to constexpr functions. For
8067 // functions which cannot be constexpr (for non-constructors in C++11 and for
8068 // destructors in C++14 and C++17), this is checked elsewhere.
8069 //
8070 // FIXME: This should not apply if the member is deleted.
8071 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8072 HasConstParam);
8073
8074 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8075 // If the instantiated template specialization of a constexpr function
8076 // template or member function of a class template would fail to satisfy
8077 // the requirements for a constexpr function or constexpr constructor, that
8078 // specialization is still a constexpr function or constexpr constructor,
8079 // even though a call to such a function cannot appear in a constant
8080 // expression.
8081 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8082 Constexpr = true;
8083
8084 if ((getLangOpts().CPlusPlus20 ||
8086 : isa<CXXConstructorDecl>(MD))) &&
8087 MD->isConstexpr() && !Constexpr &&
8089 if (!MD->isConsteval() && RD->getNumVBases()) {
8090 Diag(MD->getBeginLoc(),
8091 diag::err_incorrect_defaulted_constexpr_with_vb)
8092 << CSM;
8093 for (const auto &I : RD->vbases())
8094 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8095 } else {
8096 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8097 << CSM << MD->isConsteval();
8098 }
8099 HadError = true;
8100 // FIXME: Explain why the special member can't be constexpr.
8101 }
8102 if (First) {
8103 // C++2a [dcl.fct.def.default]p3:
8104 // If a function is explicitly defaulted on its first declaration, it is
8105 // implicitly considered to be constexpr if the implicit declaration
8106 // would be.
8111
8112 if (!Type->hasExceptionSpec()) {
8113 // C++2a [except.spec]p3:
8114 // If a declaration of a function does not have a noexcept-specifier
8115 // [and] is defaulted on its first declaration, [...] the exception
8116 // specification is as specified below
8117 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8119 EPI.ExceptionSpec.SourceDecl = MD;
8120 MD->setType(
8121 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8122 }
8123 }
8124
8125 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8126 if (First) {
8127 SetDeclDeleted(MD, MD->getLocation());
8128 if (!inTemplateInstantiation() && !HadError) {
8129 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8130 if (ShouldDeleteForTypeMismatch) {
8131 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8132 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8133 /*Diagnose*/ true) &&
8134 DefaultLoc.isValid()) {
8135 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8136 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8137 }
8138 }
8139 if (ShouldDeleteForTypeMismatch && !HadError) {
8140 Diag(MD->getLocation(),
8141 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8142 << CSM;
8143 }
8144 } else {
8145 // C++11 [dcl.fct.def.default]p4:
8146 // [For a] user-provided explicitly-defaulted function [...] if such a
8147 // function is implicitly defined as deleted, the program is ill-formed.
8148 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8149 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8150 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8151 HadError = true;
8152 }
8153 }
8154
8155 return HadError;
8156}
8157
8158namespace {
8159/// Helper class for building and checking a defaulted comparison.
8160///
8161/// Defaulted functions are built in two phases:
8162///
8163/// * First, the set of operations that the function will perform are
8164/// identified, and some of them are checked. If any of the checked
8165/// operations is invalid in certain ways, the comparison function is
8166/// defined as deleted and no body is built.
8167/// * Then, if the function is not defined as deleted, the body is built.
8168///
8169/// This is accomplished by performing two visitation steps over the eventual
8170/// body of the function.
8171template<typename Derived, typename ResultList, typename Result,
8172 typename Subobject>
8173class DefaultedComparisonVisitor {
8174public:
8175 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8177 : S(S), RD(RD), FD(FD), DCK(DCK) {
8178 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8179 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8180 // UnresolvedSet to avoid this copy.
8181 Fns.assign(Info->getUnqualifiedLookups().begin(),
8182 Info->getUnqualifiedLookups().end());
8183 }
8184 }
8185
8186 ResultList visit() {
8187 // The type of an lvalue naming a parameter of this function.
8188 QualType ParamLvalType =
8190
8191 ResultList Results;
8192
8193 switch (DCK) {
8195 llvm_unreachable("not a defaulted comparison");
8196
8199 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8200 return Results;
8201
8204 Results.add(getDerived().visitExpandedSubobject(
8205 ParamLvalType, getDerived().getCompleteObject()));
8206 return Results;
8207 }
8208 llvm_unreachable("");
8209 }
8210
8211protected:
8212 Derived &getDerived() { return static_cast<Derived&>(*this); }
8213
8214 /// Visit the expanded list of subobjects of the given type, as specified in
8215 /// C++2a [class.compare.default].
8216 ///
8217 /// \return \c true if the ResultList object said we're done, \c false if not.
8218 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8219 Qualifiers Quals) {
8220 // C++2a [class.compare.default]p4:
8221 // The direct base class subobjects of C
8222 for (CXXBaseSpecifier &Base : Record->bases())
8223 if (Results.add(getDerived().visitSubobject(
8224 S.Context.getQualifiedType(Base.getType(), Quals),
8225 getDerived().getBase(&Base))))
8226 return true;
8227
8228 // followed by the non-static data members of C
8229 for (FieldDecl *Field : Record->fields()) {
8230 // C++23 [class.bit]p2:
8231 // Unnamed bit-fields are not members ...
8232 if (Field->isUnnamedBitField())
8233 continue;
8234 if (Field->isInvalidDecl())
8235 continue;
8236 // Recursively expand anonymous structs.
8237 if (Field->isAnonymousStructOrUnion()) {
8238 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8239 Quals))
8240 return true;
8241 continue;
8242 }
8243
8244 // Figure out the type of an lvalue denoting this field.
8245 Qualifiers FieldQuals = Quals;
8246 if (Field->isMutable())
8247 FieldQuals.removeConst();
8248 QualType FieldType =
8249 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8250
8251 if (Results.add(getDerived().visitSubobject(
8252 FieldType, getDerived().getField(Field))))
8253 return true;
8254 }
8255
8256 // form a list of subobjects.
8257 return false;
8258 }
8259
8260 Result visitSubobject(QualType Type, Subobject Subobj) {
8261 // In that list, any subobject of array type is recursively expanded
8262 const ArrayType *AT = S.Context.getAsArrayType(Type);
8263 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8264 return getDerived().visitSubobjectArray(CAT->getElementType(),
8265 CAT->getSize(), Subobj);
8266 return getDerived().visitExpandedSubobject(Type, Subobj);
8267 }
8268
8269 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8270 Subobject Subobj) {
8271 return getDerived().visitSubobject(Type, Subobj);
8272 }
8273
8274protected:
8275 Sema &S;
8276 CXXRecordDecl *RD;
8277 FunctionDecl *FD;
8279 UnresolvedSet<16> Fns;
8280};
8281
8282/// Information about a defaulted comparison, as determined by
8283/// DefaultedComparisonAnalyzer.
8284struct DefaultedComparisonInfo {
8285 bool Deleted = false;
8286 bool Constexpr = true;
8287 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8288
8289 static DefaultedComparisonInfo deleted() {
8290 DefaultedComparisonInfo Deleted;
8291 Deleted.Deleted = true;
8292 return Deleted;
8293 }
8294
8295 bool add(const DefaultedComparisonInfo &R) {
8296 Deleted |= R.Deleted;
8297 Constexpr &= R.Constexpr;
8298 Category = commonComparisonType(Category, R.Category);
8299 return Deleted;
8300 }
8301};
8302
8303/// An element in the expanded list of subobjects of a defaulted comparison, as
8304/// specified in C++2a [class.compare.default]p4.
8305struct DefaultedComparisonSubobject {
8306 enum { CompleteObject, Member, Base } Kind;
8307 NamedDecl *Decl;
8308 SourceLocation Loc;
8309};
8310
8311/// A visitor over the notional body of a defaulted comparison that determines
8312/// whether that body would be deleted or constexpr.
8313class DefaultedComparisonAnalyzer
8314 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8315 DefaultedComparisonInfo,
8316 DefaultedComparisonInfo,
8317 DefaultedComparisonSubobject> {
8318public:
8319 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8320
8321private:
8322 DiagnosticKind Diagnose;
8323
8324public:
8325 using Base = DefaultedComparisonVisitor;
8326 using Result = DefaultedComparisonInfo;
8327 using Subobject = DefaultedComparisonSubobject;
8328
8329 friend Base;
8330
8331 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8333 DiagnosticKind Diagnose = NoDiagnostics)
8334 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8335
8336 Result visit() {
8337 if ((DCK == DefaultedComparisonKind::Equal ||
8338 DCK == DefaultedComparisonKind::ThreeWay) &&
8339 RD->hasVariantMembers()) {
8340 // C++2a [class.compare.default]p2 [P2002R0]:
8341 // A defaulted comparison operator function for class C is defined as
8342 // deleted if [...] C has variant members.
8343 if (Diagnose == ExplainDeleted) {
8344 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8345 << FD << RD->isUnion() << RD;
8346 }
8347 return Result::deleted();
8348 }
8349
8350 return Base::visit();
8351 }
8352
8353private:
8354 Subobject getCompleteObject() {
8355 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8356 }
8357
8358 Subobject getBase(CXXBaseSpecifier *Base) {
8359 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8360 Base->getBaseTypeLoc()};
8361 }
8362
8363 Subobject getField(FieldDecl *Field) {
8364 return Subobject{Subobject::Member, Field, Field->getLocation()};
8365 }
8366
8367 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8368 // C++2a [class.compare.default]p2 [P2002R0]:
8369 // A defaulted <=> or == operator function for class C is defined as
8370 // deleted if any non-static data member of C is of reference type
8371 if (Type->isReferenceType()) {
8372 if (Diagnose == ExplainDeleted) {
8373 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8374 << FD << RD;
8375 }
8376 return Result::deleted();
8377 }
8378
8379 // [...] Let xi be an lvalue denoting the ith element [...]
8380 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8381 Expr *Args[] = {&Xi, &Xi};
8382
8383 // All operators start by trying to apply that same operator recursively.
8385 assert(OO != OO_None && "not an overloaded operator!");
8386 return visitBinaryOperator(OO, Args, Subobj);
8387 }
8388
8389 Result
8390 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8391 Subobject Subobj,
8392 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8393 // Note that there is no need to consider rewritten candidates here if
8394 // we've already found there is no viable 'operator<=>' candidate (and are
8395 // considering synthesizing a '<=>' from '==' and '<').
8396 OverloadCandidateSet CandidateSet(
8398 OverloadCandidateSet::OperatorRewriteInfo(
8399 OO, FD->getLocation(),
8400 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8401
8402 /// C++2a [class.compare.default]p1 [P2002R0]:
8403 /// [...] the defaulted function itself is never a candidate for overload
8404 /// resolution [...]
8405 CandidateSet.exclude(FD);
8406
8407 if (Args[0]->getType()->isOverloadableType())
8408 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8409 else
8410 // FIXME: We determine whether this is a valid expression by checking to
8411 // see if there's a viable builtin operator candidate for it. That isn't
8412 // really what the rules ask us to do, but should give the right results.
8413 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8414
8415 Result R;
8416
8418 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8419 case OR_Success: {
8420 // C++2a [class.compare.secondary]p2 [P2002R0]:
8421 // The operator function [...] is defined as deleted if [...] the
8422 // candidate selected by overload resolution is not a rewritten
8423 // candidate.
8424 if ((DCK == DefaultedComparisonKind::NotEqual ||
8425 DCK == DefaultedComparisonKind::Relational) &&
8426 !Best->RewriteKind) {
8427 if (Diagnose == ExplainDeleted) {
8428 if (Best->Function) {
8429 S.Diag(Best->Function->getLocation(),
8430 diag::note_defaulted_comparison_not_rewritten_callee)
8431 << FD;
8432 } else {
8433 assert(Best->Conversions.size() == 2 &&
8434 Best->Conversions[0].isUserDefined() &&
8435 "non-user-defined conversion from class to built-in "
8436 "comparison");
8437 S.Diag(Best->Conversions[0]
8438 .UserDefined.FoundConversionFunction.getDecl()
8439 ->getLocation(),
8440 diag::note_defaulted_comparison_not_rewritten_conversion)
8441 << FD;
8442 }
8443 }
8444 return Result::deleted();
8445 }
8446
8447 // Throughout C++2a [class.compare]: if overload resolution does not
8448 // result in a usable function, the candidate function is defined as
8449 // deleted. This requires that we selected an accessible function.
8450 //
8451 // Note that this only considers the access of the function when named
8452 // within the type of the subobject, and not the access path for any
8453 // derived-to-base conversion.
8454 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8455 if (ArgClass && Best->FoundDecl.getDecl() &&
8456 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8457 QualType ObjectType = Subobj.Kind == Subobject::Member
8458 ? Args[0]->getType()
8461 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8462 Diagnose == ExplainDeleted
8463 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8464 << FD << Subobj.Kind << Subobj.Decl
8465 : S.PDiag()))
8466 return Result::deleted();
8467 }
8468
8469 bool NeedsDeducing =
8470 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8471
8472 if (FunctionDecl *BestFD = Best->Function) {
8473 // C++2a [class.compare.default]p3 [P2002R0]:
8474 // A defaulted comparison function is constexpr-compatible if
8475 // [...] no overlod resolution performed [...] results in a
8476 // non-constexpr function.
8477 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8478 // If it's not constexpr, explain why not.
8479 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8480 if (Subobj.Kind != Subobject::CompleteObject)
8481 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8482 << Subobj.Kind << Subobj.Decl;
8483 S.Diag(BestFD->getLocation(),
8484 diag::note_defaulted_comparison_not_constexpr_here);
8485 // Bail out after explaining; we don't want any more notes.
8486 return Result::deleted();
8487 }
8488 R.Constexpr &= BestFD->isConstexpr();
8489
8490 if (NeedsDeducing) {
8491 // If any callee has an undeduced return type, deduce it now.
8492 // FIXME: It's not clear how a failure here should be handled. For
8493 // now, we produce an eager diagnostic, because that is forward
8494 // compatible with most (all?) other reasonable options.
8495 if (BestFD->getReturnType()->isUndeducedType() &&
8496 S.DeduceReturnType(BestFD, FD->getLocation(),
8497 /*Diagnose=*/false)) {
8498 // Don't produce a duplicate error when asked to explain why the
8499 // comparison is deleted: we diagnosed that when initially checking
8500 // the defaulted operator.
8501 if (Diagnose == NoDiagnostics) {
8502 S.Diag(
8503 FD->getLocation(),
8504 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8505 << Subobj.Kind << Subobj.Decl;
8506 S.Diag(
8507 Subobj.Loc,
8508 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8509 << Subobj.Kind << Subobj.Decl;
8510 S.Diag(BestFD->getLocation(),
8511 diag::note_defaulted_comparison_cannot_deduce_callee)
8512 << Subobj.Kind << Subobj.Decl;
8513 }
8514 return Result::deleted();
8515 }
8517 BestFD->getCallResultType());
8518 if (!Info) {
8519 if (Diagnose == ExplainDeleted) {
8520 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8521 << Subobj.Kind << Subobj.Decl
8522 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8523 S.Diag(BestFD->getLocation(),
8524 diag::note_defaulted_comparison_cannot_deduce_callee)
8525 << Subobj.Kind << Subobj.Decl;
8526 }
8527 return Result::deleted();
8528 }
8529 R.Category = Info->Kind;
8530 }
8531 } else {
8532 QualType T = Best->BuiltinParamTypes[0];
8533 assert(T == Best->BuiltinParamTypes[1] &&
8534 "builtin comparison for different types?");
8535 assert(Best->BuiltinParamTypes[2].isNull() &&
8536 "invalid builtin comparison");
8537
8538 // FIXME: If the type we deduced is a vector type, we mark the
8539 // comparison as deleted because we don't yet support this.
8540 if (isa<VectorType>(T)) {
8541 if (Diagnose == ExplainDeleted) {
8542 S.Diag(FD->getLocation(),
8543 diag::note_defaulted_comparison_vector_types)
8544 << FD;
8545 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8546 }
8547 return Result::deleted();
8548 }
8549
8550 if (NeedsDeducing) {
8551 std::optional<ComparisonCategoryType> Cat =
8553 assert(Cat && "no category for builtin comparison?");
8554 R.Category = *Cat;
8555 }
8556 }
8557
8558 // Note that we might be rewriting to a different operator. That call is
8559 // not considered until we come to actually build the comparison function.
8560 break;
8561 }
8562
8563 case OR_Ambiguous:
8564 if (Diagnose == ExplainDeleted) {
8565 unsigned Kind = 0;
8566 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8567 Kind = OO == OO_EqualEqual ? 1 : 2;
8568 CandidateSet.NoteCandidates(
8570 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8571 << FD << Kind << Subobj.Kind << Subobj.Decl),
8572 S, OCD_AmbiguousCandidates, Args);
8573 }
8574 R = Result::deleted();
8575 break;
8576
8577 case OR_Deleted:
8578 if (Diagnose == ExplainDeleted) {
8579 if ((DCK == DefaultedComparisonKind::NotEqual ||
8580 DCK == DefaultedComparisonKind::Relational) &&
8581 !Best->RewriteKind) {
8582 S.Diag(Best->Function->getLocation(),
8583 diag::note_defaulted_comparison_not_rewritten_callee)
8584 << FD;
8585 } else {
8586 S.Diag(Subobj.Loc,
8587 diag::note_defaulted_comparison_calls_deleted)
8588 << FD << Subobj.Kind << Subobj.Decl;
8589 S.NoteDeletedFunction(Best->Function);
8590 }
8591 }
8592 R = Result::deleted();
8593 break;
8594
8596 // If there's no usable candidate, we're done unless we can rewrite a
8597 // '<=>' in terms of '==' and '<'.
8598 if (OO == OO_Spaceship &&
8600 // For any kind of comparison category return type, we need a usable
8601 // '==' and a usable '<'.
8602 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8603 &CandidateSet)))
8604 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8605 break;
8606 }
8607
8608 if (Diagnose == ExplainDeleted) {
8609 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8610 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8611 << Subobj.Kind << Subobj.Decl;
8612
8613 // For a three-way comparison, list both the candidates for the
8614 // original operator and the candidates for the synthesized operator.
8615 if (SpaceshipCandidates) {
8616 SpaceshipCandidates->NoteCandidates(
8617 S, Args,
8618 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8619 Args, FD->getLocation()));
8620 S.Diag(Subobj.Loc,
8621 diag::note_defaulted_comparison_no_viable_function_synthesized)
8622 << (OO == OO_EqualEqual ? 0 : 1);
8623 }
8624
8625 CandidateSet.NoteCandidates(
8626 S, Args,
8627 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8628 FD->getLocation()));
8629 }
8630 R = Result::deleted();
8631 break;
8632 }
8633
8634 return R;
8635 }
8636};
8637
8638/// A list of statements.
8639struct StmtListResult {
8640 bool IsInvalid = false;
8641 llvm::SmallVector<Stmt*, 16> Stmts;
8642
8643 bool add(const StmtResult &S) {
8644 IsInvalid |= S.isInvalid();
8645 if (IsInvalid)
8646 return true;
8647 Stmts.push_back(S.get());
8648 return false;
8649 }
8650};
8651
8652/// A visitor over the notional body of a defaulted comparison that synthesizes
8653/// the actual body.
8654class DefaultedComparisonSynthesizer
8655 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8656 StmtListResult, StmtResult,
8657 std::pair<ExprResult, ExprResult>> {
8658 SourceLocation Loc;
8659 unsigned ArrayDepth = 0;
8660
8661public:
8662 using Base = DefaultedComparisonVisitor;
8663 using ExprPair = std::pair<ExprResult, ExprResult>;
8664
8665 friend Base;
8666
8667 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8669 SourceLocation BodyLoc)
8670 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8671
8672 /// Build a suitable function body for this defaulted comparison operator.
8673 StmtResult build() {
8674 Sema::CompoundScopeRAII CompoundScope(S);
8675
8676 StmtListResult Stmts = visit();
8677 if (Stmts.IsInvalid)
8678 return StmtError();
8679
8680 ExprResult RetVal;
8681 switch (DCK) {
8682 case DefaultedComparisonKind::None:
8683 llvm_unreachable("not a defaulted comparison");
8684
8685 case DefaultedComparisonKind::Equal: {
8686 // C++2a [class.eq]p3:
8687 // [...] compar[e] the corresponding elements [...] until the first
8688 // index i where xi == yi yields [...] false. If no such index exists,
8689 // V is true. Otherwise, V is false.
8690 //
8691 // Join the comparisons with '&&'s and return the result. Use a right
8692 // fold (traversing the conditions right-to-left), because that
8693 // short-circuits more naturally.
8694 auto OldStmts = std::move(Stmts.Stmts);
8695 Stmts.Stmts.clear();
8696 ExprResult CmpSoFar;
8697 // Finish a particular comparison chain.
8698 auto FinishCmp = [&] {
8699 if (Expr *Prior = CmpSoFar.get()) {
8700 // Convert the last expression to 'return ...;'
8701 if (RetVal.isUnset() && Stmts.Stmts.empty())
8702 RetVal = CmpSoFar;
8703 // Convert any prior comparison to 'if (!(...)) return false;'
8704 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8705 return true;
8706 CmpSoFar = ExprResult();
8707 }
8708 return false;
8709 };
8710 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8711 Expr *E = dyn_cast<Expr>(EAsStmt);
8712 if (!E) {
8713 // Found an array comparison.
8714 if (FinishCmp() || Stmts.add(EAsStmt))
8715 return StmtError();
8716 continue;
8717 }
8718
8719 if (CmpSoFar.isUnset()) {
8720 CmpSoFar = E;
8721 continue;
8722 }
8723 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8724 if (CmpSoFar.isInvalid())
8725 return StmtError();
8726 }
8727 if (FinishCmp())
8728 return StmtError();
8729 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8730 // If no such index exists, V is true.
8731 if (RetVal.isUnset())
8732 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8733 break;
8734 }
8735
8736 case DefaultedComparisonKind::ThreeWay: {
8737 // Per C++2a [class.spaceship]p3, as a fallback add:
8738 // return static_cast<R>(std::strong_ordering::equal);
8739 QualType StrongOrdering = S.CheckComparisonCategoryType(
8740 ComparisonCategoryType::StrongOrdering, Loc,
8741 Sema::ComparisonCategoryUsage::DefaultedOperator);
8742 if (StrongOrdering.isNull())
8743 return StmtError();
8744 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8745 .getValueInfo(ComparisonCategoryResult::Equal)
8746 ->VD;
8747 RetVal = getDecl(EqualVD);
8748 if (RetVal.isInvalid())
8749 return StmtError();
8750 RetVal = buildStaticCastToR(RetVal.get());
8751 break;
8752 }
8753
8754 case DefaultedComparisonKind::NotEqual:
8755 case DefaultedComparisonKind::Relational:
8756 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8757 break;
8758 }
8759
8760 // Build the final return statement.
8761 if (RetVal.isInvalid())
8762 return StmtError();
8763 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8764 if (ReturnStmt.isInvalid())
8765 return StmtError();
8766 Stmts.Stmts.push_back(ReturnStmt.get());
8767
8768 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8769 }
8770
8771private:
8772 ExprResult getDecl(ValueDecl *VD) {
8773 return S.BuildDeclarationNameExpr(
8774 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8775 }
8776
8777 ExprResult getParam(unsigned I) {
8778 ParmVarDecl *PD = FD->getParamDecl(I);
8779 return getDecl(PD);
8780 }
8781
8782 ExprPair getCompleteObject() {
8783 unsigned Param = 0;
8784 ExprResult LHS;
8785 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8786 MD && MD->isImplicitObjectMemberFunction()) {
8787 // LHS is '*this'.
8788 LHS = S.ActOnCXXThis(Loc);
8789 if (!LHS.isInvalid())
8790 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8791 } else {
8792 LHS = getParam(Param++);
8793 }
8794 ExprResult RHS = getParam(Param++);
8795 assert(Param == FD->getNumParams());
8796 return {LHS, RHS};
8797 }
8798
8799 ExprPair getBase(CXXBaseSpecifier *Base) {
8800 ExprPair Obj = getCompleteObject();
8801 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8802 return {ExprError(), ExprError()};
8803 CXXCastPath Path = {Base};
8804 const auto CastToBase = [&](Expr *E) {
8805 QualType ToType = S.Context.getQualifiedType(
8806 Base->getType(), E->getType().getQualifiers());
8807 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8808 };
8809 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8810 }
8811
8812 ExprPair getField(FieldDecl *Field) {
8813 ExprPair Obj = getCompleteObject();
8814 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8815 return {ExprError(), ExprError()};
8816
8817 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8818 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8819 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8820 CXXScopeSpec(), Field, Found, NameInfo),
8821 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8822 CXXScopeSpec(), Field, Found, NameInfo)};
8823 }
8824
8825 // FIXME: When expanding a subobject, register a note in the code synthesis
8826 // stack to say which subobject we're comparing.
8827
8828 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8829 if (Cond.isInvalid())
8830 return StmtError();
8831
8832 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8833 if (NotCond.isInvalid())
8834 return StmtError();
8835
8836 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8837 assert(!False.isInvalid() && "should never fail");
8838 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8839 if (ReturnFalse.isInvalid())
8840 return StmtError();
8841
8842 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8843 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8844 Sema::ConditionKind::Boolean),
8845 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8846 }
8847
8848 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8849 ExprPair Subobj) {
8850 QualType SizeType = S.Context.getSizeType();
8851 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8852
8853 // Build 'size_t i$n = 0'.
8854 IdentifierInfo *IterationVarName = nullptr;
8855 {
8856 SmallString<8> Str;
8857 llvm::raw_svector_ostream OS(Str);
8858 OS << "i" << ArrayDepth;
8859 IterationVarName = &S.Context.Idents.get(OS.str());
8860 }
8861 VarDecl *IterationVar = VarDecl::Create(
8862 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8863 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8864 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8865 IterationVar->setInit(
8866 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8867 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8868
8869 auto IterRef = [&] {
8870 ExprResult Ref = S.BuildDeclarationNameExpr(
8871 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8872 IterationVar);
8873 assert(!Ref.isInvalid() && "can't reference our own variable?");
8874 return Ref.get();
8875 };
8876
8877 // Build 'i$n != Size'.
8878 ExprResult Cond = S.CreateBuiltinBinOp(
8879 Loc, BO_NE, IterRef(),
8880 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8881 assert(!Cond.isInvalid() && "should never fail");
8882
8883 // Build '++i$n'.
8884 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8885 assert(!Inc.isInvalid() && "should never fail");
8886
8887 // Build 'a[i$n]' and 'b[i$n]'.
8888 auto Index = [&](ExprResult E) {
8889 if (E.isInvalid())
8890 return ExprError();
8891 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8892 };
8893 Subobj.first = Index(Subobj.first);
8894 Subobj.second = Index(Subobj.second);
8895
8896 // Compare the array elements.
8897 ++ArrayDepth;
8898 StmtResult Substmt = visitSubobject(Type, Subobj);
8899 --ArrayDepth;
8900
8901 if (Substmt.isInvalid())
8902 return StmtError();
8903
8904 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8905 // For outer levels or for an 'operator<=>' we already have a suitable
8906 // statement that returns as necessary.
8907 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8908 assert(DCK == DefaultedComparisonKind::Equal &&
8909 "should have non-expression statement");
8910 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8911 if (Substmt.isInvalid())
8912 return StmtError();
8913 }
8914
8915 // Build 'for (...) ...'
8916 return S.ActOnForStmt(Loc, Loc, Init,
8917 S.ActOnCondition(nullptr, Loc, Cond.get(),
8918 Sema::ConditionKind::Boolean),
8919 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8920 Substmt.get());
8921 }
8922
8923 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8924 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8925 return StmtError();
8926
8929 ExprResult Op;
8930 if (Type->isOverloadableType())
8931 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8932 Obj.second.get(), /*PerformADL=*/true,
8933 /*AllowRewrittenCandidates=*/true, FD);
8934 else
8935 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8936 if (Op.isInvalid())
8937 return StmtError();
8938
8939 switch (DCK) {
8940 case DefaultedComparisonKind::None:
8941 llvm_unreachable("not a defaulted comparison");
8942
8943 case DefaultedComparisonKind::Equal:
8944 // Per C++2a [class.eq]p2, each comparison is individually contextually
8945 // converted to bool.
8946 Op = S.PerformContextuallyConvertToBool(Op.get());
8947 if (Op.isInvalid())
8948 return StmtError();
8949 return Op.get();
8950
8951 case DefaultedComparisonKind::ThreeWay: {
8952 // Per C++2a [class.spaceship]p3, form:
8953 // if (R cmp = static_cast<R>(op); cmp != 0)
8954 // return cmp;
8955 QualType R = FD->getReturnType();
8956 Op = buildStaticCastToR(Op.get());
8957 if (Op.isInvalid())
8958 return StmtError();
8959
8960 // R cmp = ...;
8961 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8962 VarDecl *VD =
8963 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8964 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8965 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8966 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8967
8968 // cmp != 0
8969 ExprResult VDRef = getDecl(VD);
8970 if (VDRef.isInvalid())
8971 return StmtError();
8972 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8973 Expr *Zero =
8974 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8976 if (VDRef.get()->getType()->isOverloadableType())
8977 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8978 true, FD);
8979 else
8980 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8981 if (Comp.isInvalid())
8982 return StmtError();
8983 Sema::ConditionResult Cond = S.ActOnCondition(
8984 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8985 if (Cond.isInvalid())
8986 return StmtError();
8987
8988 // return cmp;
8989 VDRef = getDecl(VD);
8990 if (VDRef.isInvalid())
8991 return StmtError();
8992 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8993 if (ReturnStmt.isInvalid())
8994 return StmtError();
8995
8996 // if (...)
8997 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8998 Loc, ReturnStmt.get(),
8999 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
9000 }
9001
9002 case DefaultedComparisonKind::NotEqual:
9003 case DefaultedComparisonKind::Relational:
9004 // C++2a [class.compare.secondary]p2:
9005 // Otherwise, the operator function yields x @ y.
9006 return Op.get();
9007 }
9008 llvm_unreachable("");
9009 }
9010
9011 /// Build "static_cast<R>(E)".
9012 ExprResult buildStaticCastToR(Expr *E) {
9013 QualType R = FD->getReturnType();
9014 assert(!R->isUndeducedType() && "type should have been deduced already");
9015
9016 // Don't bother forming a no-op cast in the common case.
9017 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
9018 return E;
9019 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
9020 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
9021 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
9022 }
9023};
9024}
9025
9026/// Perform the unqualified lookups that might be needed to form a defaulted
9027/// comparison function for the given operator.
9029 UnresolvedSetImpl &Operators,
9031 auto Lookup = [&](OverloadedOperatorKind OO) {
9032 Self.LookupOverloadedOperatorName(OO, S, Operators);
9033 };
9034
9035 // Every defaulted operator looks up itself.
9036 Lookup(Op);
9037 // ... and the rewritten form of itself, if any.
9039 Lookup(ExtraOp);
9040
9041 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9042 // synthesize a three-way comparison from '<' and '=='. In a dependent
9043 // context, we also need to look up '==' in case we implicitly declare a
9044 // defaulted 'operator=='.
9045 if (Op == OO_Spaceship) {
9046 Lookup(OO_ExclaimEqual);
9047 Lookup(OO_Less);
9048 Lookup(OO_EqualEqual);
9049 }
9050}
9051
9054 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9055
9056 // Perform any unqualified lookups we're going to need to default this
9057 // function.
9058 if (S) {
9059 UnresolvedSet<32> Operators;
9060 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9061 FD->getOverloadedOperator());
9064 Context, Operators.pairs(), CurFPFeatureOverrides()));
9065 }
9066
9067 // C++2a [class.compare.default]p1:
9068 // A defaulted comparison operator function for some class C shall be a
9069 // non-template function declared in the member-specification of C that is
9070 // -- a non-static const non-volatile member of C having one parameter of
9071 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9072 // -- a friend of C having two parameters of type const C& or two
9073 // parameters of type C.
9074
9075 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9076 bool IsMethod = isa<CXXMethodDecl>(FD);
9077 if (IsMethod) {
9078 auto *MD = cast<CXXMethodDecl>(FD);
9079 assert(!MD->isStatic() && "comparison function cannot be a static member");
9080
9081 if (MD->getRefQualifier() == RQ_RValue) {
9082 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9083
9084 // Remove the ref qualifier to recover.
9085 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9086 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9087 EPI.RefQualifier = RQ_None;
9088 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9089 FPT->getParamTypes(), EPI));
9090 }
9091
9092 // If we're out-of-class, this is the class we're comparing.
9093 if (!RD)
9094 RD = MD->getParent();
9095 QualType T = MD->getFunctionObjectParameterReferenceType();
9096 if (!T.getNonReferenceType().isConstQualified() &&
9097 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9098 SourceLocation Loc, InsertLoc;
9099 if (MD->isExplicitObjectMemberFunction()) {
9100 Loc = MD->getParamDecl(0)->getBeginLoc();
9101 InsertLoc = getLocForEndOfToken(
9102 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9103 } else {
9104 Loc = MD->getLocation();
9105 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9106 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9107 }
9108 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9109 // corresponding defaulted 'operator<=>' already.
9110 if (!MD->isImplicit()) {
9111 Diag(Loc, diag::err_defaulted_comparison_non_const)
9112 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9113 }
9114
9115 // Add the 'const' to the type to recover.
9116 if (MD->isExplicitObjectMemberFunction()) {
9117 assert(T->isLValueReferenceType());
9118 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9119 T.getNonReferenceType().withConst()));
9120 } else {
9121 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9122 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9123 EPI.TypeQuals.addConst();
9124 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9125 FPT->getParamTypes(), EPI));
9126 }
9127 }
9128
9129 if (MD->isVolatile()) {
9130 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9131
9132 // Remove the 'volatile' from the type to recover.
9133 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9134 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9136 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9137 FPT->getParamTypes(), EPI));
9138 }
9139 }
9140
9141 if ((FD->getNumParams() -
9142 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9143 (IsMethod ? 1 : 2)) {
9144 // Let's not worry about using a variadic template pack here -- who would do
9145 // such a thing?
9146 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9147 << int(IsMethod) << int(DCK);
9148 return true;
9149 }
9150
9151 const ParmVarDecl *KnownParm = nullptr;
9152 for (const ParmVarDecl *Param : FD->parameters()) {
9153 QualType ParmTy = Param->getType();
9154 if (!KnownParm) {
9155 auto CTy = ParmTy;
9156 // Is it `T const &`?
9157 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9158 QualType ExpectedTy;
9159 if (RD)
9160 ExpectedTy = Context.getCanonicalTagType(RD);
9161 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9162 CTy = Ref->getPointeeType();
9163 if (RD)
9164 ExpectedTy.addConst();
9165 Ok = true;
9166 }
9167
9168 // Is T a class?
9169 if (RD) {
9170 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9171 } else {
9172 RD = CTy->getAsCXXRecordDecl();
9173 Ok &= RD != nullptr;
9174 }
9175
9176 if (Ok) {
9177 KnownParm = Param;
9178 } else {
9179 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9180 // corresponding defaulted 'operator<=>' already.
9181 if (!FD->isImplicit()) {
9182 if (RD) {
9183 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9184 QualType RefTy =
9185 Context.getLValueReferenceType(PlainTy.withConst());
9186 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9187 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9188 << Param->getSourceRange();
9189 } else {
9190 assert(!IsMethod && "should know expected type for method");
9191 Diag(FD->getLocation(),
9192 diag::err_defaulted_comparison_param_unknown)
9193 << int(DCK) << ParmTy << Param->getSourceRange();
9194 }
9195 }
9196 return true;
9197 }
9198 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9199 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9200 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9201 << ParmTy << Param->getSourceRange();
9202 return true;
9203 }
9204 }
9205
9206 assert(RD && "must have determined class");
9207 if (IsMethod) {
9208 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9209 // In-class, must be a friend decl.
9210 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9211 } else {
9212 // Out of class, require the defaulted comparison to be a friend (of a
9213 // complete type, per CWG2547).
9214 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9215 diag::err_defaulted_comparison_not_friend, int(DCK),
9216 int(1)))
9217 return true;
9218
9219 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9220 return declaresSameEntity(F->getFriendDecl(), FD);
9221 })) {
9222 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9223 << int(DCK) << int(0) << RD;
9224 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9225 return true;
9226 }
9227 }
9228
9229 // C++2a [class.eq]p1, [class.rel]p1:
9230 // A [defaulted comparison other than <=>] shall have a declared return
9231 // type bool.
9234 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9235 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9236 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9237 << FD->getReturnTypeSourceRange();
9238 return true;
9239 }
9240 // C++2a [class.spaceship]p2 [P2002R0]:
9241 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9242 // R shall not contain a placeholder type.
9243 if (QualType RT = FD->getDeclaredReturnType();
9245 RT->getContainedDeducedType() &&
9246 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9247 RT->getContainedAutoType()->isConstrained())) {
9248 Diag(FD->getLocation(),
9249 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9250 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9251 << FD->getReturnTypeSourceRange();
9252 return true;
9253 }
9254
9255 // For a defaulted function in a dependent class, defer all remaining checks
9256 // until instantiation.
9257 if (RD->isDependentType())
9258 return false;
9259
9260 // Determine whether the function should be defined as deleted.
9261 DefaultedComparisonInfo Info =
9262 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9263
9264 bool First = FD == FD->getCanonicalDecl();
9265
9266 if (!First) {
9267 if (Info.Deleted) {
9268 // C++11 [dcl.fct.def.default]p4:
9269 // [For a] user-provided explicitly-defaulted function [...] if such a
9270 // function is implicitly defined as deleted, the program is ill-formed.
9271 //
9272 // This is really just a consequence of the general rule that you can
9273 // only delete a function on its first declaration.
9274 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9275 << FD->isImplicit() << (int)DCK;
9276 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9277 DefaultedComparisonAnalyzer::ExplainDeleted)
9278 .visit();
9279 return true;
9280 }
9282 // C++20 [class.compare.default]p1:
9283 // [...] A definition of a comparison operator as defaulted that appears
9284 // in a class shall be the first declaration of that function.
9285 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9286 << (int)DCK;
9288 diag::note_previous_declaration);
9289 return true;
9290 }
9291 }
9292
9293 // If we want to delete the function, then do so; there's nothing else to
9294 // check in that case.
9295 if (Info.Deleted) {
9296 SetDeclDeleted(FD, FD->getLocation());
9297 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9298 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9299 << (int)DCK;
9300 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9301 DefaultedComparisonAnalyzer::ExplainDeleted)
9302 .visit();
9303 if (FD->getDefaultLoc().isValid())
9304 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9305 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9306 }
9307 return false;
9308 }
9309
9310 // C++2a [class.spaceship]p2:
9311 // The return type is deduced as the common comparison type of R0, R1, ...
9315 if (RetLoc.isInvalid())
9316 RetLoc = FD->getBeginLoc();
9317 // FIXME: Should we really care whether we have the complete type and the
9318 // 'enumerator' constants here? A forward declaration seems sufficient.
9320 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9321 if (Cat.isNull())
9322 return true;
9323 Context.adjustDeducedFunctionResultType(
9324 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9325 }
9326
9327 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9328 // An explicitly-defaulted function that is not defined as deleted may be
9329 // declared constexpr or consteval only if it is constexpr-compatible.
9330 // C++2a [class.compare.default]p3 [P2002R0]:
9331 // A defaulted comparison function is constexpr-compatible if it satisfies
9332 // the requirements for a constexpr function [...]
9333 // The only relevant requirements are that the parameter and return types are
9334 // literal types. The remaining conditions are checked by the analyzer.
9335 //
9336 // We support P2448R2 in language modes earlier than C++23 as an extension.
9337 // The concept of constexpr-compatible was removed.
9338 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9339 // A function explicitly defaulted on its first declaration is implicitly
9340 // inline, and is implicitly constexpr if it is constexpr-suitable.
9341 // C++23 [dcl.constexpr]p3
9342 // A function is constexpr-suitable if
9343 // - it is not a coroutine, and
9344 // - if the function is a constructor or destructor, its class does not
9345 // have any virtual base classes.
9346 if (FD->isConstexpr()) {
9347 if (!getLangOpts().CPlusPlus23 &&
9350 !Info.Constexpr) {
9351 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9352 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9353 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9354 DefaultedComparisonAnalyzer::ExplainConstexpr)
9355 .visit();
9356 }
9357 }
9358
9359 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9360 // If a constexpr-compatible function is explicitly defaulted on its first
9361 // declaration, it is implicitly considered to be constexpr.
9362 // FIXME: Only applying this to the first declaration seems problematic, as
9363 // simple reorderings can affect the meaning of the program.
9364 if (First && !FD->isConstexpr() && Info.Constexpr)
9366
9367 // C++2a [except.spec]p3:
9368 // If a declaration of a function does not have a noexcept-specifier
9369 // [and] is defaulted on its first declaration, [...] the exception
9370 // specification is as specified below
9371 if (FD->getExceptionSpecType() == EST_None) {
9372 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9373 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9375 EPI.ExceptionSpec.SourceDecl = FD;
9376 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9377 FPT->getParamTypes(), EPI));
9378 }
9379
9380 return false;
9381}
9382
9384 FunctionDecl *Spaceship) {
9387 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9388 Ctx.Entity = Spaceship;
9390
9391 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9392 EqualEqual->setImplicit();
9393
9395}
9396
9399 assert(FD->isDefaulted() && !FD->isDeleted() &&
9401 if (FD->willHaveBody() || FD->isInvalidDecl())
9402 return;
9403
9405
9406 // Add a context note for diagnostics produced after this point.
9407 Scope.addContextNote(UseLoc);
9408
9409 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9410
9411 {
9412 // Build and set up the function body.
9413 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9414 // the type of the class being compared.
9415 auto PT = FD->getParamDecl(0)->getType();
9416 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9417 SourceLocation BodyLoc =
9418 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9419 StmtResult Body =
9420 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9421 if (Body.isInvalid()) {
9422 FD->setInvalidDecl();
9423 return;
9424 }
9425 FD->setBody(Body.get());
9426 FD->markUsed(Context);
9427 }
9428
9429 // The exception specification is needed because we are defining the
9430 // function. Note that this will reuse the body we just built.
9432
9434 L->CompletedImplicitDefinition(FD);
9435}
9436
9439 FunctionDecl *FD,
9441 ComputingExceptionSpec CES(S, FD, Loc);
9443
9444 if (FD->isInvalidDecl())
9445 return ExceptSpec;
9446
9447 // The common case is that we just defined the comparison function. In that
9448 // case, just look at whether the body can throw.
9449 if (Stmt *FunctionBody = FD->getBody()) {
9450 ExceptSpec.CalledStmt(FunctionBody);
9451 } else {
9452 // Otherwise, build a body so we can check it. This should ideally only
9453 // happen when we're not actually marking the function referenced. (This is
9454 // only really important for efficiency: we don't want to build and throw
9455 // away bodies for comparison functions more than we strictly need to.)
9456
9457 // Pretend to synthesize the function body in an unevaluated context.
9458 // Note that we can't actually just go ahead and define the function here:
9459 // we are not permitted to mark its callees as referenced.
9463
9464 CXXRecordDecl *RD =
9466 ? FD->getDeclContext()
9467 : FD->getLexicalDeclContext());
9468 SourceLocation BodyLoc =
9469 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9470 StmtResult Body =
9471 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9472 if (!Body.isInvalid())
9473 ExceptSpec.CalledStmt(Body.get());
9474
9475 // FIXME: Can we hold onto this body and just transform it to potentially
9476 // evaluated when we're asked to define the function rather than rebuilding
9477 // it? Either that, or we should only build the bits of the body that we
9478 // need (the expressions, not the statements).
9479 }
9480
9481 return ExceptSpec;
9482}
9483
9485 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9487
9488 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9490
9491 // Perform any deferred checking of exception specifications for virtual
9492 // destructors.
9493 for (auto &Check : Overriding)
9494 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9495
9496 // Perform any deferred checking of exception specifications for befriended
9497 // special members.
9498 for (auto &Check : Equivalent)
9499 CheckEquivalentExceptionSpec(Check.second, Check.first);
9500}
9501
9502namespace {
9503/// CRTP base class for visiting operations performed by a special member
9504/// function (or inherited constructor).
9505template<typename Derived>
9506struct SpecialMemberVisitor {
9507 Sema &S;
9508 CXXMethodDecl *MD;
9511
9512 // Properties of the special member, computed for convenience.
9513 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9514
9515 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9517 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9518 switch (CSM) {
9522 IsConstructor = true;
9523 break;
9526 IsAssignment = true;
9527 break;
9529 break;
9531 llvm_unreachable("invalid special member kind");
9532 }
9533
9534 if (MD->getNumExplicitParams()) {
9535 if (const ReferenceType *RT =
9536 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9537 ConstArg = RT->getPointeeType().isConstQualified();
9538 }
9539 }
9540
9541 Derived &getDerived() { return static_cast<Derived&>(*this); }
9542
9543 /// Is this a "move" special member?
9544 bool isMove() const {
9545 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9546 CSM == CXXSpecialMemberKind::MoveAssignment;
9547 }
9548
9549 /// Look up the corresponding special member in the given class.
9550 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9551 unsigned Quals, bool IsMutable) {
9552 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9553 ConstArg && !IsMutable);
9554 }
9555
9556 /// Look up the constructor for the specified base class to see if it's
9557 /// overridden due to this being an inherited constructor.
9558 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9559 if (!ICI)
9560 return {};
9561 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9562 auto *BaseCtor =
9563 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9564 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9565 return MD;
9566 return {};
9567 }
9568
9569 /// A base or member subobject.
9570 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9571
9572 /// Get the location to use for a subobject in diagnostics.
9573 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9574 // FIXME: For an indirect virtual base, the direct base leading to
9575 // the indirect virtual base would be a more useful choice.
9576 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9577 return B->getBaseTypeLoc();
9578 else
9579 return cast<FieldDecl *>(Subobj)->getLocation();
9580 }
9581
9582 enum BasesToVisit {
9583 /// Visit all non-virtual (direct) bases.
9584 VisitNonVirtualBases,
9585 /// Visit all direct bases, virtual or not.
9586 VisitDirectBases,
9587 /// Visit all non-virtual bases, and all virtual bases if the class
9588 /// is not abstract.
9589 VisitPotentiallyConstructedBases,
9590 /// Visit all direct or virtual bases.
9591 VisitAllBases
9592 };
9593
9594 // Visit the bases and members of the class.
9595 bool visit(BasesToVisit Bases) {
9596 CXXRecordDecl *RD = MD->getParent();
9597
9598 if (Bases == VisitPotentiallyConstructedBases)
9599 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9600
9601 for (auto &B : RD->bases())
9602 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9603 getDerived().visitBase(&B))
9604 return true;
9605
9606 if (Bases == VisitAllBases)
9607 for (auto &B : RD->vbases())
9608 if (getDerived().visitBase(&B))
9609 return true;
9610
9611 for (auto *F : RD->fields())
9612 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9613 getDerived().visitField(F))
9614 return true;
9615
9616 return false;
9617 }
9618};
9619}
9620
9621namespace {
9622struct SpecialMemberDeletionInfo
9623 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9624 bool Diagnose;
9625
9626 SourceLocation Loc;
9627
9628 bool AllFieldsAreConst;
9629
9630 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9632 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9633 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9634 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9635
9636 bool inUnion() const { return MD->getParent()->isUnion(); }
9637
9638 CXXSpecialMemberKind getEffectiveCSM() {
9639 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9640 }
9641
9642 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9643
9644 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9645
9646 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9647 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9648
9649 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9650 bool shouldDeleteForField(FieldDecl *FD);
9651 bool shouldDeleteForAllConstMembers();
9652
9653 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9654 unsigned Quals);
9655 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9656 Sema::SpecialMemberOverloadResult SMOR,
9657 bool IsDtorCallInCtor);
9658
9659 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9660};
9661}
9662
9663/// Is the given special member inaccessible when used on the given
9664/// sub-object.
9665bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9666 CXXMethodDecl *target) {
9667 /// If we're operating on a base class, the object type is the
9668 /// type of this special member.
9669 CanQualType objectTy;
9670 AccessSpecifier access = target->getAccess();
9671 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9672 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9673 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9674
9675 // If we're operating on a field, the object type is the type of the field.
9676 } else {
9677 objectTy = S.Context.getCanonicalTagType(target->getParent());
9678 }
9679
9681 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9682}
9683
9684/// Check whether we should delete a special member due to the implicit
9685/// definition containing a call to a special member of a subobject.
9686bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9687 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9688 bool IsDtorCallInCtor) {
9689 CXXMethodDecl *Decl = SMOR.getMethod();
9690 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9691
9692 enum {
9693 NotSet = -1,
9694 NoDecl,
9695 DeletedDecl,
9696 MultipleDecl,
9697 InaccessibleDecl,
9698 NonTrivialDecl
9699 } DiagKind = NotSet;
9700
9702 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9703 Field->getParent()->isUnion()) {
9704 // [class.default.ctor]p2:
9705 // A defaulted default constructor for class X is defined as deleted if
9706 // - X is a union that has a variant member with a non-trivial default
9707 // constructor and no variant member of X has a default member
9708 // initializer
9709 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9710 if (RD->hasInClassInitializer())
9711 return false;
9712 }
9713 DiagKind = !Decl ? NoDecl : DeletedDecl;
9715 DiagKind = MultipleDecl;
9716 else if (!isAccessible(Subobj, Decl))
9717 DiagKind = InaccessibleDecl;
9718 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9719 !Decl->isTrivial()) {
9720 // A member of a union must have a trivial corresponding special member.
9721 // As a weird special case, a destructor call from a union's constructor
9722 // must be accessible and non-deleted, but need not be trivial. Such a
9723 // destructor is never actually called, but is semantically checked as
9724 // if it were.
9725 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9726 // [class.default.ctor]p2:
9727 // A defaulted default constructor for class X is defined as deleted if
9728 // - X is a union that has a variant member with a non-trivial default
9729 // constructor and no variant member of X has a default member
9730 // initializer
9731 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9732 if (!RD->hasInClassInitializer())
9733 DiagKind = NonTrivialDecl;
9734 } else {
9735 DiagKind = NonTrivialDecl;
9736 }
9737 }
9738
9739 if (DiagKind == NotSet)
9740 return false;
9741
9742 if (Diagnose) {
9743 if (Field) {
9744 S.Diag(Field->getLocation(),
9745 diag::note_deleted_special_member_class_subobject)
9746 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9747 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9748 } else {
9749 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9750 S.Diag(Base->getBeginLoc(),
9751 diag::note_deleted_special_member_class_subobject)
9752 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9753 << Base->getType() << DiagKind << IsDtorCallInCtor
9754 << /*IsObjCPtr*/ false;
9755 }
9756
9757 if (DiagKind == DeletedDecl)
9758 S.NoteDeletedFunction(Decl);
9759 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9760 }
9761
9762 return true;
9763}
9764
9765/// Check whether we should delete a special member function due to having a
9766/// direct or virtual base class or non-static data member of class type M.
9767bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9768 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9769 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9770 bool IsMutable = Field && Field->isMutable();
9771
9772 // C++11 [class.ctor]p5:
9773 // -- any direct or virtual base class, or non-static data member with no
9774 // brace-or-equal-initializer, has class type M (or array thereof) and
9775 // either M has no default constructor or overload resolution as applied
9776 // to M's default constructor results in an ambiguity or in a function
9777 // that is deleted or inaccessible
9778 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9779 // -- a direct or virtual base class B that cannot be copied/moved because
9780 // overload resolution, as applied to B's corresponding special member,
9781 // results in an ambiguity or a function that is deleted or inaccessible
9782 // from the defaulted special member
9783 // C++11 [class.dtor]p5:
9784 // -- any direct or virtual base class [...] has a type with a destructor
9785 // that is deleted or inaccessible
9786 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9787 Field->hasInClassInitializer()) &&
9788 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9789 false))
9790 return true;
9791
9792 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9793 // -- any direct or virtual base class or non-static data member has a
9794 // type with a destructor that is deleted or inaccessible
9795 if (IsConstructor) {
9796 Sema::SpecialMemberOverloadResult SMOR =
9797 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9798 false, false, false, false);
9799 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9800 return true;
9801 }
9802
9803 return false;
9804}
9805
9806bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9807 FieldDecl *FD, QualType FieldType) {
9808 // The defaulted special functions are defined as deleted if this is a variant
9809 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9810 // type under ARC.
9811 if (!FieldType.hasNonTrivialObjCLifetime())
9812 return false;
9813
9814 // Don't make the defaulted default constructor defined as deleted if the
9815 // member has an in-class initializer.
9816 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9818 return false;
9819
9820 if (Diagnose) {
9821 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9822 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9823 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9824 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9825 }
9826
9827 return true;
9828}
9829
9830bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9831 const FieldDecl *FD) {
9832 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9833 // Copy/move constructors/assignment operators are deleted if the field has an
9834 // address-discriminated ptrauth qualifier.
9835 PointerAuthQualifier Q = FieldType.getPointerAuth();
9836
9837 if (!Q || !Q.isAddressDiscriminated())
9838 return false;
9839
9840 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9841 CSM == CXXSpecialMemberKind::Destructor)
9842 return false;
9843
9844 if (Diagnose) {
9845 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9846 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9847 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9848 << /*IsDtorCallInCtor*/ false << 2;
9849 }
9850
9851 return true;
9852}
9853
9854/// Check whether we should delete a special member function due to the class
9855/// having a particular direct or virtual base class.
9856bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9857 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9858 // If program is correct, BaseClass cannot be null, but if it is, the error
9859 // must be reported elsewhere.
9860 if (!BaseClass)
9861 return false;
9862 // If we have an inheriting constructor, check whether we're calling an
9863 // inherited constructor instead of a default constructor.
9864 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9865 if (auto *BaseCtor = SMOR.getMethod()) {
9866 // Note that we do not check access along this path; other than that,
9867 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9868 // FIXME: Check that the base has a usable destructor! Sink this into
9869 // shouldDeleteForClassSubobject.
9870 if (BaseCtor->isDeleted() && Diagnose) {
9871 S.Diag(Base->getBeginLoc(),
9872 diag::note_deleted_special_member_class_subobject)
9873 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9874 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9875 << /*IsObjCPtr*/ false;
9876 S.NoteDeletedFunction(BaseCtor);
9877 }
9878 return BaseCtor->isDeleted();
9879 }
9880 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9881}
9882
9883/// Check whether we should delete a special member function due to the class
9884/// having a particular non-static data member.
9885bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9886 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9887 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9888
9889 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9890 return true;
9891
9892 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9893 return true;
9894
9895 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9896 // For a default constructor, all references must be initialized in-class
9897 // and, if a union, it must have a non-const member.
9898 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9899 if (Diagnose)
9900 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9901 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9902 return true;
9903 }
9904 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9905 // data member of const-qualified type (or array thereof) with no
9906 // brace-or-equal-initializer is not const-default-constructible.
9907 if (!inUnion() && FieldType.isConstQualified() &&
9908 !FD->hasInClassInitializer() &&
9909 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9910 if (Diagnose)
9911 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9912 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9913 return true;
9914 }
9915
9916 if (inUnion() && !FieldType.isConstQualified())
9917 AllFieldsAreConst = false;
9918 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9919 // For a copy constructor, data members must not be of rvalue reference
9920 // type.
9921 if (FieldType->isRValueReferenceType()) {
9922 if (Diagnose)
9923 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9924 << MD->getParent() << FD << FieldType;
9925 return true;
9926 }
9927 } else if (IsAssignment) {
9928 // For an assignment operator, data members must not be of reference type.
9929 if (FieldType->isReferenceType()) {
9930 if (Diagnose)
9931 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9932 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9933 return true;
9934 }
9935 if (!FieldRecord && FieldType.isConstQualified()) {
9936 // C++11 [class.copy]p23:
9937 // -- a non-static data member of const non-class type (or array thereof)
9938 if (Diagnose)
9939 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9940 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9941 return true;
9942 }
9943 }
9944
9945 if (FieldRecord) {
9946 // Some additional restrictions exist on the variant members.
9947 if (!inUnion() && FieldRecord->isUnion() &&
9948 FieldRecord->isAnonymousStructOrUnion()) {
9949 bool AllVariantFieldsAreConst = true;
9950
9951 // FIXME: Handle anonymous unions declared within anonymous unions.
9952 for (auto *UI : FieldRecord->fields()) {
9953 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9954
9955 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9956 return true;
9957
9958 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9959 return true;
9960
9961 if (!UnionFieldType.isConstQualified())
9962 AllVariantFieldsAreConst = false;
9963
9964 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9965 if (UnionFieldRecord &&
9966 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9967 UnionFieldType.getCVRQualifiers()))
9968 return true;
9969 }
9970
9971 // At least one member in each anonymous union must be non-const
9972 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9973 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9974 if (Diagnose)
9975 S.Diag(FieldRecord->getLocation(),
9976 diag::note_deleted_default_ctor_all_const)
9977 << !!ICI << MD->getParent() << /*anonymous union*/1;
9978 return true;
9979 }
9980
9981 // Don't check the implicit member of the anonymous union type.
9982 // This is technically non-conformant but supported, and we have a
9983 // diagnostic for this elsewhere.
9984 return false;
9985 }
9986
9987 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9988 FieldType.getCVRQualifiers()))
9989 return true;
9990 }
9991
9992 return false;
9993}
9994
9995/// C++11 [class.ctor] p5:
9996/// A defaulted default constructor for a class X is defined as deleted if
9997/// X is a union and all of its variant members are of const-qualified type.
9998bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9999 // This is a silly definition, because it gives an empty union a deleted
10000 // default constructor. Don't do that.
10001 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
10002 AllFieldsAreConst) {
10003 bool AnyFields = false;
10004 for (auto *F : MD->getParent()->fields())
10005 if ((AnyFields = !F->isUnnamedBitField()))
10006 break;
10007 if (!AnyFields)
10008 return false;
10009 if (Diagnose)
10010 S.Diag(MD->getParent()->getLocation(),
10011 diag::note_deleted_default_ctor_all_const)
10012 << !!ICI << MD->getParent() << /*not anonymous union*/0;
10013 return true;
10014 }
10015 return false;
10016}
10017
10018/// Determine whether a defaulted special member function should be defined as
10019/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10020/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10024 bool Diagnose) {
10025 if (MD->isInvalidDecl())
10026 return false;
10027 CXXRecordDecl *RD = MD->getParent();
10028 assert(!RD->isDependentType() && "do deletion after instantiation");
10029 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10030 RD->isInvalidDecl())
10031 return false;
10032
10033 // C++11 [expr.lambda.prim]p19:
10034 // The closure type associated with a lambda-expression has a
10035 // deleted (8.4.3) default constructor and a deleted copy
10036 // assignment operator.
10037 // C++2a adds back these operators if the lambda has no lambda-capture.
10041 if (Diagnose)
10042 Diag(RD->getLocation(), diag::note_lambda_decl);
10043 return true;
10044 }
10045
10046 // C++11 [class.copy]p7, p18:
10047 // If the class definition declares a move constructor or move assignment
10048 // operator, an implicitly declared copy constructor or copy assignment
10049 // operator is defined as deleted.
10052 CXXMethodDecl *UserDeclaredMove = nullptr;
10053
10054 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10055 // deletion of the corresponding copy operation, not both copy operations.
10056 // MSVC 2015 has adopted the standards conforming behavior.
10057 bool DeletesOnlyMatchingCopy =
10058 getLangOpts().MSVCCompat &&
10059 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10060
10062 (!DeletesOnlyMatchingCopy ||
10064 if (!Diagnose) return true;
10065
10066 // Find any user-declared move constructor.
10067 for (auto *I : RD->ctors()) {
10068 if (I->isMoveConstructor()) {
10069 UserDeclaredMove = I;
10070 break;
10071 }
10072 }
10073 assert(UserDeclaredMove);
10074 } else if (RD->hasUserDeclaredMoveAssignment() &&
10075 (!DeletesOnlyMatchingCopy ||
10077 if (!Diagnose) return true;
10078
10079 // Find any user-declared move assignment operator.
10080 for (auto *I : RD->methods()) {
10081 if (I->isMoveAssignmentOperator()) {
10082 UserDeclaredMove = I;
10083 break;
10084 }
10085 }
10086 assert(UserDeclaredMove);
10087 }
10088
10089 if (UserDeclaredMove) {
10090 Diag(UserDeclaredMove->getLocation(),
10091 diag::note_deleted_copy_user_declared_move)
10092 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10093 << UserDeclaredMove->isMoveAssignmentOperator();
10094 return true;
10095 }
10096 }
10097
10098 // Do access control from the special member function
10099 ContextRAII MethodContext(*this, MD);
10100
10101 // C++11 [class.dtor]p5:
10102 // -- for a virtual destructor, lookup of the non-array deallocation function
10103 // results in an ambiguity or in a function that is deleted or inaccessible
10104 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10105 FunctionDecl *OperatorDelete = nullptr;
10106 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10107 DeclarationName Name =
10108 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10112 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10113 OperatorDelete, IDP,
10114 /*Diagnose=*/false)) {
10115 if (Diagnose)
10116 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10117 return true;
10118 }
10119 }
10120
10121 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10122
10123 // Per DR1611, do not consider virtual bases of constructors of abstract
10124 // classes, since we are not going to construct them.
10125 // Per DR1658, do not consider virtual bases of destructors of abstract
10126 // classes either.
10127 // Per DR2180, for assignment operators we only assign (and thus only
10128 // consider) direct bases.
10129 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10130 : SMI.VisitPotentiallyConstructedBases))
10131 return true;
10132
10133 if (SMI.shouldDeleteForAllConstMembers())
10134 return true;
10135
10136 if (getLangOpts().CUDA) {
10137 // We should delete the special member in CUDA mode if target inference
10138 // failed.
10139 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10140 // is treated as certain special member, which may not reflect what special
10141 // member MD really is. However inferTargetForImplicitSpecialMember
10142 // expects CSM to match MD, therefore recalculate CSM.
10143 assert(ICI || CSM == MD->getSpecialMemberKind());
10144 auto RealCSM = CSM;
10145 if (ICI)
10146 RealCSM = MD->getSpecialMemberKind();
10147
10148 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10149 SMI.ConstArg, Diagnose);
10150 }
10151
10152 return false;
10153}
10154
10157 assert(DFK && "not a defaultable function");
10158 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10159
10160 if (DFK.isSpecialMember()) {
10162 nullptr, /*Diagnose=*/true);
10163 } else {
10164 DefaultedComparisonAnalyzer(
10166 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10167 .visit();
10168 }
10169}
10170
10171/// Perform lookup for a special member of the specified kind, and determine
10172/// whether it is trivial. If the triviality can be determined without the
10173/// lookup, skip it. This is intended for use when determining whether a
10174/// special member of a containing object is trivial, and thus does not ever
10175/// perform overload resolution for default constructors.
10176///
10177/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10178/// member that was most likely to be intended to be trivial, if any.
10179///
10180/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10181/// determine whether the special member is trivial.
10183 CXXSpecialMemberKind CSM, unsigned Quals,
10184 bool ConstRHS, TrivialABIHandling TAH,
10185 CXXMethodDecl **Selected) {
10186 if (Selected)
10187 *Selected = nullptr;
10188
10189 switch (CSM) {
10191 llvm_unreachable("not a special member");
10192
10194 // C++11 [class.ctor]p5:
10195 // A default constructor is trivial if:
10196 // - all the [direct subobjects] have trivial default constructors
10197 //
10198 // Note, no overload resolution is performed in this case.
10200 return true;
10201
10202 if (Selected) {
10203 // If there's a default constructor which could have been trivial, dig it
10204 // out. Otherwise, if there's any user-provided default constructor, point
10205 // to that as an example of why there's not a trivial one.
10206 CXXConstructorDecl *DefCtor = nullptr;
10209 for (auto *CI : RD->ctors()) {
10210 if (!CI->isDefaultConstructor())
10211 continue;
10212 DefCtor = CI;
10213 if (!DefCtor->isUserProvided())
10214 break;
10215 }
10216
10217 *Selected = DefCtor;
10218 }
10219
10220 return false;
10221
10223 // C++11 [class.dtor]p5:
10224 // A destructor is trivial if:
10225 // - all the direct [subobjects] have trivial destructors
10226 if (RD->hasTrivialDestructor() ||
10229 return true;
10230
10231 if (Selected) {
10232 if (RD->needsImplicitDestructor())
10234 *Selected = RD->getDestructor();
10235 }
10236
10237 return false;
10238
10240 // C++11 [class.copy]p12:
10241 // A copy constructor is trivial if:
10242 // - the constructor selected to copy each direct [subobject] is trivial
10243 if (RD->hasTrivialCopyConstructor() ||
10246 if (Quals == Qualifiers::Const)
10247 // We must either select the trivial copy constructor or reach an
10248 // ambiguity; no need to actually perform overload resolution.
10249 return true;
10250 } else if (!Selected) {
10251 return false;
10252 }
10253 // In C++98, we are not supposed to perform overload resolution here, but we
10254 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10255 // cases like B as having a non-trivial copy constructor:
10256 // struct A { template<typename T> A(T&); };
10257 // struct B { mutable A a; };
10258 goto NeedOverloadResolution;
10259
10261 // C++11 [class.copy]p25:
10262 // A copy assignment operator is trivial if:
10263 // - the assignment operator selected to copy each direct [subobject] is
10264 // trivial
10265 if (RD->hasTrivialCopyAssignment()) {
10266 if (Quals == Qualifiers::Const)
10267 return true;
10268 } else if (!Selected) {
10269 return false;
10270 }
10271 // In C++98, we are not supposed to perform overload resolution here, but we
10272 // treat that as a language defect.
10273 goto NeedOverloadResolution;
10274
10277 NeedOverloadResolution:
10279 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10280
10281 // The standard doesn't describe how to behave if the lookup is ambiguous.
10282 // We treat it as not making the member non-trivial, just like the standard
10283 // mandates for the default constructor. This should rarely matter, because
10284 // the member will also be deleted.
10286 return true;
10287
10288 if (!SMOR.getMethod()) {
10289 assert(SMOR.getKind() ==
10291 return false;
10292 }
10293
10294 // We deliberately don't check if we found a deleted special member. We're
10295 // not supposed to!
10296 if (Selected)
10297 *Selected = SMOR.getMethod();
10298
10302 return SMOR.getMethod()->isTrivialForCall();
10303 return SMOR.getMethod()->isTrivial();
10304 }
10305
10306 llvm_unreachable("unknown special method kind");
10307}
10308
10310 for (auto *CI : RD->ctors())
10311 if (!CI->isImplicit())
10312 return CI;
10313
10314 // Look for constructor templates.
10316 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10317 if (CXXConstructorDecl *CD =
10318 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10319 return CD;
10320 }
10321
10322 return nullptr;
10323}
10324
10325/// The kind of subobject we are checking for triviality. The values of this
10326/// enumeration are used in diagnostics.
10328 /// The subobject is a base class.
10330 /// The subobject is a non-static data member.
10332 /// The object is actually the complete object.
10334};
10335
10336/// Check whether the special member selected for a given type would be trivial.
10338 QualType SubType, bool ConstRHS,
10341 TrivialABIHandling TAH, bool Diagnose) {
10342 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10343 if (!SubRD)
10344 return true;
10345
10346 CXXMethodDecl *Selected;
10347 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10348 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10349 return true;
10350
10351 if (Diagnose) {
10352 if (ConstRHS)
10353 SubType.addConst();
10354
10355 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10356 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10357 << Kind << SubType.getUnqualifiedType();
10359 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10360 } else if (!Selected)
10361 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10362 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10363 else if (Selected->isUserProvided()) {
10364 if (Kind == TSK_CompleteObject)
10365 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10366 << Kind << SubType.getUnqualifiedType() << CSM;
10367 else {
10368 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10369 << Kind << SubType.getUnqualifiedType() << CSM;
10370 S.Diag(Selected->getLocation(), diag::note_declared_at);
10371 }
10372 } else {
10373 if (Kind != TSK_CompleteObject)
10374 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10375 << Kind << SubType.getUnqualifiedType() << CSM;
10376
10377 // Explain why the defaulted or deleted special member isn't trivial.
10378 S.SpecialMemberIsTrivial(Selected, CSM,
10380 }
10381 }
10382
10383 return false;
10384}
10385
10386/// Check whether the members of a class type allow a special member to be
10387/// trivial.
10389 CXXSpecialMemberKind CSM, bool ConstArg,
10390 TrivialABIHandling TAH, bool Diagnose) {
10391 for (const auto *FI : RD->fields()) {
10392 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10393 continue;
10394
10395 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10396
10397 // Pretend anonymous struct or union members are members of this class.
10398 if (FI->isAnonymousStructOrUnion()) {
10399 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10400 CSM, ConstArg, TAH, Diagnose))
10401 return false;
10402 continue;
10403 }
10404
10405 // C++11 [class.ctor]p5:
10406 // A default constructor is trivial if [...]
10407 // -- no non-static data member of its class has a
10408 // brace-or-equal-initializer
10410 FI->hasInClassInitializer()) {
10411 if (Diagnose)
10412 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10413 << FI;
10414 return false;
10415 }
10416
10417 // Objective C ARC 4.3.5:
10418 // [...] nontrivally ownership-qualified types are [...] not trivially
10419 // default constructible, copy constructible, move constructible, copy
10420 // assignable, move assignable, or destructible [...]
10421 if (FieldType.hasNonTrivialObjCLifetime()) {
10422 if (Diagnose)
10423 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10424 << RD << FieldType.getObjCLifetime();
10425 return false;
10426 }
10427
10428 bool ConstRHS = ConstArg && !FI->isMutable();
10429 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10430 CSM, TSK_Field, TAH, Diagnose))
10431 return false;
10432 }
10433
10434 return true;
10435}
10436
10439 CanQualType Ty = Context.getCanonicalTagType(RD);
10440
10441 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10443 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10446 /*Diagnose*/ true);
10447}
10448
10450 TrivialABIHandling TAH, bool Diagnose) {
10451 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10452 "not special enough");
10453
10454 CXXRecordDecl *RD = MD->getParent();
10455
10456 bool ConstArg = false;
10457
10458 // C++11 [class.copy]p12, p25: [DR1593]
10459 // A [special member] is trivial if [...] its parameter-type-list is
10460 // equivalent to the parameter-type-list of an implicit declaration [...]
10461 switch (CSM) {
10464 // Trivial default constructors and destructors cannot have parameters.
10465 break;
10466
10469 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10470 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10471
10472 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10473 // if they are not user-provided and their parameter-type-list is equivalent
10474 // to the parameter-type-list of an implicit declaration. This maintains the
10475 // behavior before dr2171 was implemented.
10476 //
10477 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10478 // trivial, if they are not user-provided, regardless of the qualifiers on
10479 // the reference type.
10480 const bool ClangABICompat14 =
10481 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
10482 if (!RT ||
10484 ClangABICompat14)) {
10485 if (Diagnose)
10486 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10487 << Param0->getSourceRange() << Param0->getType()
10488 << Context.getLValueReferenceType(
10489 Context.getCanonicalTagType(RD).withConst());
10490 return false;
10491 }
10492
10493 ConstArg = RT->getPointeeType().isConstQualified();
10494 break;
10495 }
10496
10499 // Trivial move operations always have non-cv-qualified parameters.
10500 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10501 const RValueReferenceType *RT =
10502 Param0->getType()->getAs<RValueReferenceType>();
10503 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10504 if (Diagnose)
10505 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10506 << Param0->getSourceRange() << Param0->getType()
10507 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10508 return false;
10509 }
10510 break;
10511 }
10512
10514 llvm_unreachable("not a special member");
10515 }
10516
10517 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10518 if (Diagnose)
10520 diag::note_nontrivial_default_arg)
10522 return false;
10523 }
10524 if (MD->isVariadic()) {
10525 if (Diagnose)
10526 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10527 return false;
10528 }
10529
10530 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10531 // A copy/move [constructor or assignment operator] is trivial if
10532 // -- the [member] selected to copy/move each direct base class subobject
10533 // is trivial
10534 //
10535 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10536 // A [default constructor or destructor] is trivial if
10537 // -- all the direct base classes have trivial [default constructors or
10538 // destructors]
10539 for (const auto &BI : RD->bases())
10540 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10541 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10542 return false;
10543
10544 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10545 // A copy/move [constructor or assignment operator] for a class X is
10546 // trivial if
10547 // -- for each non-static data member of X that is of class type (or array
10548 // thereof), the constructor selected to copy/move that member is
10549 // trivial
10550 //
10551 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10552 // A [default constructor or destructor] is trivial if
10553 // -- for all of the non-static data members of its class that are of class
10554 // type (or array thereof), each such class has a trivial [default
10555 // constructor or destructor]
10556 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10557 return false;
10558
10559 // C++11 [class.dtor]p5:
10560 // A destructor is trivial if [...]
10561 // -- the destructor is not virtual
10562 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10563 if (Diagnose)
10564 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10565 return false;
10566 }
10567
10568 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10569 // A [special member] for class X is trivial if [...]
10570 // -- class X has no virtual functions and no virtual base classes
10572 MD->getParent()->isDynamicClass()) {
10573 if (!Diagnose)
10574 return false;
10575
10576 if (RD->getNumVBases()) {
10577 // Check for virtual bases. We already know that the corresponding
10578 // member in all bases is trivial, so vbases must all be direct.
10579 CXXBaseSpecifier &BS = *RD->vbases_begin();
10580 assert(BS.isVirtual());
10581 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10582 return false;
10583 }
10584
10585 // Must have a virtual method.
10586 for (const auto *MI : RD->methods()) {
10587 if (MI->isVirtual()) {
10588 SourceLocation MLoc = MI->getBeginLoc();
10589 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10590 return false;
10591 }
10592 }
10593
10594 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10595 }
10596
10597 // Looks like it's trivial!
10598 return true;
10599}
10600
10601namespace {
10602struct FindHiddenVirtualMethod {
10603 Sema *S;
10605 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10606 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10607
10608private:
10609 /// Check whether any most overridden method from MD in Methods
10610 static bool CheckMostOverridenMethods(
10611 const CXXMethodDecl *MD,
10612 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10613 if (MD->size_overridden_methods() == 0)
10614 return Methods.count(MD->getCanonicalDecl());
10615 for (const CXXMethodDecl *O : MD->overridden_methods())
10616 if (CheckMostOverridenMethods(O, Methods))
10617 return true;
10618 return false;
10619 }
10620
10621public:
10622 /// Member lookup function that determines whether a given C++
10623 /// method overloads virtual methods in a base class without overriding any,
10624 /// to be used with CXXRecordDecl::lookupInBases().
10625 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10626 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10627 DeclarationName Name = Method->getDeclName();
10628 assert(Name.getNameKind() == DeclarationName::Identifier);
10629
10630 bool foundSameNameMethod = false;
10631 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10632 for (Path.Decls = BaseRecord->lookup(Name).begin();
10633 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10634 NamedDecl *D = *Path.Decls;
10635 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10636 MD = MD->getCanonicalDecl();
10637 foundSameNameMethod = true;
10638 // Interested only in hidden virtual methods.
10639 if (!MD->isVirtual())
10640 continue;
10641 // If the method we are checking overrides a method from its base
10642 // don't warn about the other overloaded methods. Clang deviates from
10643 // GCC by only diagnosing overloads of inherited virtual functions that
10644 // do not override any other virtual functions in the base. GCC's
10645 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10646 // function from a base class. These cases may be better served by a
10647 // warning (not specific to virtual functions) on call sites when the
10648 // call would select a different function from the base class, were it
10649 // visible.
10650 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10651 if (!S->IsOverload(Method, MD, false))
10652 return true;
10653 // Collect the overload only if its hidden.
10654 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10655 overloadedMethods.push_back(MD);
10656 }
10657 }
10658
10659 if (foundSameNameMethod)
10660 OverloadedMethods.append(overloadedMethods.begin(),
10661 overloadedMethods.end());
10662 return foundSameNameMethod;
10663 }
10664};
10665} // end anonymous namespace
10666
10667/// Add the most overridden methods from MD to Methods
10669 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10670 if (MD->size_overridden_methods() == 0)
10671 Methods.insert(MD->getCanonicalDecl());
10672 else
10673 for (const CXXMethodDecl *O : MD->overridden_methods())
10674 AddMostOverridenMethods(O, Methods);
10675}
10676
10678 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10679 if (!MD->getDeclName().isIdentifier())
10680 return;
10681
10682 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10683 /*bool RecordPaths=*/false,
10684 /*bool DetectVirtual=*/false);
10685 FindHiddenVirtualMethod FHVM;
10686 FHVM.Method = MD;
10687 FHVM.S = this;
10688
10689 // Keep the base methods that were overridden or introduced in the subclass
10690 // by 'using' in a set. A base method not in this set is hidden.
10691 CXXRecordDecl *DC = MD->getParent();
10692 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10693 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10694 ND = shad->getTargetDecl();
10695 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10696 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10697 }
10698
10699 if (DC->lookupInBases(FHVM, Paths))
10700 OverloadedMethods = FHVM.OverloadedMethods;
10701}
10702
10704 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10705 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10707 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10708 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10709 Diag(overloadedMD->getLocation(), PD);
10710 }
10711}
10712
10714 if (MD->isInvalidDecl())
10715 return;
10716
10717 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10718 return;
10719
10720 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10721 FindHiddenVirtualMethods(MD, OverloadedMethods);
10722 if (!OverloadedMethods.empty()) {
10723 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10724 << MD << (OverloadedMethods.size() > 1);
10725
10726 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10727 }
10728}
10729
10731 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10732 // No diagnostics if this is a template instantiation.
10734 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10735 diag::ext_cannot_use_trivial_abi) << &RD;
10736 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10737 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10738 }
10739 RD.dropAttr<TrivialABIAttr>();
10740 };
10741
10742 // Ill-formed if the struct has virtual functions.
10743 if (RD.isPolymorphic()) {
10744 PrintDiagAndRemoveAttr(1);
10745 return;
10746 }
10747
10748 for (const auto &B : RD.bases()) {
10749 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10750 // virtual base.
10751 if (!B.getType()->isDependentType() &&
10752 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10753 PrintDiagAndRemoveAttr(2);
10754 return;
10755 }
10756
10757 if (B.isVirtual()) {
10758 PrintDiagAndRemoveAttr(3);
10759 return;
10760 }
10761 }
10762
10763 for (const auto *FD : RD.fields()) {
10764 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10765 // non-trivial for the purpose of calls.
10766 QualType FT = FD->getType();
10768 PrintDiagAndRemoveAttr(4);
10769 return;
10770 }
10771
10772 // Ill-formed if the field is an address-discriminated value.
10774 PrintDiagAndRemoveAttr(6);
10775 return;
10776 }
10777
10778 if (const auto *RT =
10779 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10780 if (!RT->isDependentType() &&
10781 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10782 ->canPassInRegisters()) {
10783 PrintDiagAndRemoveAttr(5);
10784 return;
10785 }
10786 }
10787
10789 return;
10790
10791 // Ill-formed if the copy and move constructors are deleted.
10792 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10793 // If the type is dependent, then assume it might have
10794 // implicit copy or move ctor because we won't know yet at this point.
10795 if (RD.isDependentType())
10796 return true;
10799 return true;
10802 return true;
10803 for (const CXXConstructorDecl *CD : RD.ctors())
10804 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10805 return true;
10806 return false;
10807 };
10808
10809 if (!HasNonDeletedCopyOrMoveConstructor()) {
10810 PrintDiagAndRemoveAttr(0);
10811 return;
10812 }
10813}
10814
10816 CXXRecordDecl &RD) {
10817 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10818 diag::err_incomplete_type_vtable_pointer_auth))
10819 return;
10820
10821 const CXXRecordDecl *PrimaryBase = &RD;
10822 if (PrimaryBase->hasAnyDependentBases())
10823 return;
10824
10825 while (1) {
10826 assert(PrimaryBase);
10827 const CXXRecordDecl *Base = nullptr;
10828 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10829 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10830 continue;
10831 Base = BasePtr.getType()->getAsCXXRecordDecl();
10832 break;
10833 }
10834 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10835 break;
10836 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10837 diag::err_non_top_level_vtable_pointer_auth)
10838 << &RD << Base;
10839 PrimaryBase = Base;
10840 }
10841
10842 if (!RD.isPolymorphic())
10843 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10844 diag::err_non_polymorphic_vtable_pointer_auth)
10845 << &RD;
10846}
10847
10850 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10851 if (!TagDecl)
10852 return;
10853
10855
10856 for (const ParsedAttr &AL : AttrList) {
10857 if (AL.getKind() != ParsedAttr::AT_Visibility)
10858 continue;
10859 AL.setInvalid();
10860 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10861 }
10862
10863 ActOnFields(S, RLoc, TagDecl,
10865 // strict aliasing violation!
10866 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10867 FieldCollector->getCurNumFields()),
10868 LBrac, RBrac, AttrList);
10869
10871}
10872
10873/// Find the equality comparison functions that should be implicitly declared
10874/// in a given class definition, per C++2a [class.compare.default]p3.
10876 ASTContext &Ctx, CXXRecordDecl *RD,
10878 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10879 if (!RD->lookup(EqEq).empty())
10880 // Member operator== explicitly declared: no implicit operator==s.
10881 return;
10882
10883 // Traverse friends looking for an '==' or a '<=>'.
10884 for (FriendDecl *Friend : RD->friends()) {
10885 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10886 if (!FD) continue;
10887
10888 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10889 // Friend operator== explicitly declared: no implicit operator==s.
10890 Spaceships.clear();
10891 return;
10892 }
10893
10894 if (FD->getOverloadedOperator() == OO_Spaceship &&
10896 Spaceships.push_back(FD);
10897 }
10898
10899 // Look for members named 'operator<=>'.
10901 for (NamedDecl *ND : RD->lookup(Cmp)) {
10902 // Note that we could find a non-function here (either a function template
10903 // or a using-declaration). Neither case results in an implicit
10904 // 'operator=='.
10905 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10906 if (FD->isExplicitlyDefaulted())
10907 Spaceships.push_back(FD);
10908 }
10909}
10910
10912 // Don't add implicit special members to templated classes.
10913 // FIXME: This means unqualified lookups for 'operator=' within a class
10914 // template don't work properly.
10915 if (!ClassDecl->isDependentType()) {
10916 if (ClassDecl->needsImplicitDefaultConstructor()) {
10917 ++getASTContext().NumImplicitDefaultConstructors;
10918
10919 if (ClassDecl->hasInheritedConstructor())
10921 }
10922
10923 if (ClassDecl->needsImplicitCopyConstructor()) {
10924 ++getASTContext().NumImplicitCopyConstructors;
10925
10926 // If the properties or semantics of the copy constructor couldn't be
10927 // determined while the class was being declared, force a declaration
10928 // of it now.
10930 ClassDecl->hasInheritedConstructor())
10932 // For the MS ABI we need to know whether the copy ctor is deleted. A
10933 // prerequisite for deleting the implicit copy ctor is that the class has
10934 // a move ctor or move assignment that is either user-declared or whose
10935 // semantics are inherited from a subobject. FIXME: We should provide a
10936 // more direct way for CodeGen to ask whether the constructor was deleted.
10937 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10938 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10940 ClassDecl->hasUserDeclaredMoveAssignment() ||
10943 }
10944
10945 if (getLangOpts().CPlusPlus11 &&
10946 ClassDecl->needsImplicitMoveConstructor()) {
10947 ++getASTContext().NumImplicitMoveConstructors;
10948
10950 ClassDecl->hasInheritedConstructor())
10952 }
10953
10954 if (ClassDecl->needsImplicitCopyAssignment()) {
10955 ++getASTContext().NumImplicitCopyAssignmentOperators;
10956
10957 // If we have a dynamic class, then the copy assignment operator may be
10958 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10959 // it shows up in the right place in the vtable and that we diagnose
10960 // problems with the implicit exception specification.
10961 if (ClassDecl->isDynamicClass() ||
10963 ClassDecl->hasInheritedAssignment())
10965 }
10966
10967 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10968 ++getASTContext().NumImplicitMoveAssignmentOperators;
10969
10970 // Likewise for the move assignment operator.
10971 if (ClassDecl->isDynamicClass() ||
10973 ClassDecl->hasInheritedAssignment())
10975 }
10976
10977 if (ClassDecl->needsImplicitDestructor()) {
10978 ++getASTContext().NumImplicitDestructors;
10979
10980 // If we have a dynamic class, then the destructor may be virtual, so we
10981 // have to declare the destructor immediately. This ensures that, e.g., it
10982 // shows up in the right place in the vtable and that we diagnose problems
10983 // with the implicit exception specification.
10984 if (ClassDecl->isDynamicClass() ||
10986 DeclareImplicitDestructor(ClassDecl);
10987 }
10988 }
10989
10990 // C++2a [class.compare.default]p3:
10991 // If the member-specification does not explicitly declare any member or
10992 // friend named operator==, an == operator function is declared implicitly
10993 // for each defaulted three-way comparison operator function defined in
10994 // the member-specification
10995 // FIXME: Consider doing this lazily.
10996 // We do this during the initial parse for a class template, not during
10997 // instantiation, so that we can handle unqualified lookups for 'operator=='
10998 // when parsing the template.
11000 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
11002 DefaultedSpaceships);
11003 for (auto *FD : DefaultedSpaceships)
11004 DeclareImplicitEqualityComparison(ClassDecl, FD);
11005 }
11006}
11007
11008unsigned
11010 llvm::function_ref<Scope *()> EnterScope) {
11011 if (!D)
11012 return 0;
11014
11015 // In order to get name lookup right, reenter template scopes in order from
11016 // outermost to innermost.
11018 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
11019
11020 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
11021 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11022 ParameterLists.push_back(TPL);
11023
11024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11025 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11026 ParameterLists.push_back(FTD->getTemplateParameters());
11027 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11028 LookupDC = VD->getDeclContext();
11029
11031 ParameterLists.push_back(VTD->getTemplateParameters());
11032 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
11033 ParameterLists.push_back(PSD->getTemplateParameters());
11034 }
11035 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11036 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11037 ParameterLists.push_back(TPL);
11038
11039 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11041 ParameterLists.push_back(CTD->getTemplateParameters());
11042 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11043 ParameterLists.push_back(PSD->getTemplateParameters());
11044 }
11045 }
11046 // FIXME: Alias declarations and concepts.
11047
11048 unsigned Count = 0;
11049 Scope *InnermostTemplateScope = nullptr;
11050 for (TemplateParameterList *Params : ParameterLists) {
11051 // Ignore explicit specializations; they don't contribute to the template
11052 // depth.
11053 if (Params->size() == 0)
11054 continue;
11055
11056 InnermostTemplateScope = EnterScope();
11057 for (NamedDecl *Param : *Params) {
11058 if (Param->getDeclName()) {
11059 InnermostTemplateScope->AddDecl(Param);
11060 IdResolver.AddDecl(Param);
11061 }
11062 }
11063 ++Count;
11064 }
11065
11066 // Associate the new template scopes with the corresponding entities.
11067 if (InnermostTemplateScope) {
11068 assert(LookupDC && "no enclosing DeclContext for template lookup");
11069 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11070 }
11071
11072 return Count;
11073}
11074
11076 if (!RecordD) return;
11077 AdjustDeclIfTemplate(RecordD);
11080}
11081
11083 if (!RecordD) return;
11085}
11086
11088 if (!Param)
11089 return;
11090
11091 S->AddDecl(Param);
11092 if (Param->getDeclName())
11093 IdResolver.AddDecl(Param);
11094}
11095
11098
11099/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11100/// C++ method declaration. We're (re-)introducing the given
11101/// function parameter into scope for use in parsing later parts of
11102/// the method declaration. For example, we could see an
11103/// ActOnParamDefaultArgument event for this parameter.
11105 if (!ParamD)
11106 return;
11107
11108 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11109
11110 S->AddDecl(Param);
11111 if (Param->getDeclName())
11112 IdResolver.AddDecl(Param);
11113}
11114
11116 if (!MethodD)
11117 return;
11118
11119 AdjustDeclIfTemplate(MethodD);
11120
11122
11123 // Now that we have our default arguments, check the constructor
11124 // again. It could produce additional diagnostics or affect whether
11125 // the class has implicitly-declared destructors, among other
11126 // things.
11127 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11129
11130 // Check the default arguments, which we may have added.
11131 if (!Method->isInvalidDecl())
11133}
11134
11135// Emit the given diagnostic for each non-address-space qualifier.
11136// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11137static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11139 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11140 bool DiagOccurred = false;
11142 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11143 SourceLocation SL) {
11144 // This diagnostic should be emitted on any qualifier except an addr
11145 // space qualifier. However, forEachQualifier currently doesn't visit
11146 // addr space qualifiers, so there's no way to write this condition
11147 // right now; we just diagnose on everything.
11148 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11149 DiagOccurred = true;
11150 });
11151 if (DiagOccurred)
11152 D.setInvalidType();
11153 }
11154}
11155
11157 unsigned Kind) {
11158 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11159 return;
11160
11162 if (Chunk.Kind == DeclaratorChunk::Paren ||
11164 return;
11165
11166 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11167 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11168 << Kind << Chunk.getSourceRange();
11169 D.setInvalidType();
11170}
11171
11173 StorageClass &SC) {
11174 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11175
11176 // C++ [class.ctor]p3:
11177 // A constructor shall not be virtual (10.3) or static (9.4). A
11178 // constructor can be invoked for a const, volatile or const
11179 // volatile object. A constructor shall not be declared const,
11180 // volatile, or const volatile (9.3.2).
11181 if (isVirtual) {
11182 if (!D.isInvalidType())
11183 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11184 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11186 D.setInvalidType();
11187 }
11188 if (SC == SC_Static) {
11189 if (!D.isInvalidType())
11190 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11191 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11193 D.setInvalidType();
11194 SC = SC_None;
11195 }
11196
11197 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11199 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11203 D.setInvalidType();
11204 }
11205
11206 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11207 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11208
11209 // C++0x [class.ctor]p4:
11210 // A constructor shall not be declared with a ref-qualifier.
11212 if (FTI.hasRefQualifier()) {
11213 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11216 D.setInvalidType();
11217 }
11218
11219 // Rebuild the function type "R" without any type qualifiers (in
11220 // case any of the errors above fired) and with "void" as the
11221 // return type, since constructors don't have return types.
11222 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11223 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11224 return R;
11225
11227 EPI.TypeQuals = Qualifiers();
11228 EPI.RefQualifier = RQ_None;
11229
11230 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11231}
11232
11234 CXXRecordDecl *ClassDecl
11235 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11236 if (!ClassDecl)
11237 return Constructor->setInvalidDecl();
11238
11239 // C++ [class.copy]p3:
11240 // A declaration of a constructor for a class X is ill-formed if
11241 // its first parameter is of type (optionally cv-qualified) X and
11242 // either there are no other parameters or else all other
11243 // parameters have default arguments.
11244 if (!Constructor->isInvalidDecl() &&
11245 Constructor->hasOneParamOrDefaultArgs() &&
11246 !Constructor->isFunctionTemplateSpecialization()) {
11247 CanQualType ParamType =
11248 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11249 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11250 if (ParamType == ClassTy) {
11251 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11252 const char *ConstRef
11253 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11254 : " const &";
11255 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11256 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11257
11258 // FIXME: Rather that making the constructor invalid, we should endeavor
11259 // to fix the type.
11260 Constructor->setInvalidDecl();
11261 }
11262 }
11263}
11264
11266 CXXRecordDecl *RD = Destructor->getParent();
11267
11268 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11269 SourceLocation Loc;
11270
11271 if (!Destructor->isImplicit())
11272 Loc = Destructor->getLocation();
11273 else
11274 Loc = RD->getLocation();
11275
11276 DeclarationName Name =
11277 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11278 // If we have a virtual destructor, look up the deallocation function
11280 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11281 Expr *ThisArg = nullptr;
11282
11283 // If the notional 'delete this' expression requires a non-trivial
11284 // conversion from 'this' to the type of a destroying operator delete's
11285 // first parameter, perform that conversion now.
11286 if (OperatorDelete->isDestroyingOperatorDelete()) {
11287 unsigned AddressParamIndex = 0;
11288 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11289 ++AddressParamIndex;
11290 QualType ParamType =
11291 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11292 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11293 // C++ [class.dtor]p13:
11294 // ... as if for the expression 'delete this' appearing in a
11295 // non-virtual destructor of the destructor's class.
11296 ContextRAII SwitchContext(*this, Destructor);
11298 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11299 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11300 This = PerformImplicitConversion(This.get(), ParamType,
11302 if (This.isInvalid()) {
11303 // FIXME: Register this as a context note so that it comes out
11304 // in the right order.
11305 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11306 return true;
11307 }
11308 ThisArg = This.get();
11309 }
11310 }
11311
11312 DiagnoseUseOfDecl(OperatorDelete, Loc);
11313 MarkFunctionReferenced(Loc, OperatorDelete);
11314 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11315
11316 if (isa<CXXMethodDecl>(OperatorDelete) &&
11317 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11318 Context.getLangOpts())) {
11319 // In Microsoft ABI whenever a class has a defined operator delete,
11320 // scalar deleting destructors check the 3rd bit of the implicit
11321 // parameter and if it is set, then, global operator delete must be
11322 // called instead of the class-specific one. Find and save the global
11323 // operator delete for that case. Do not diagnose at this point because
11324 // the lack of a global operator delete is not an error if there are no
11325 // delete calls that require it.
11326 FunctionDecl *GlobalOperatorDelete =
11327 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11328 /*LookForGlobal*/ true, Name);
11329 if (GlobalOperatorDelete) {
11330 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11331 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11332 }
11333 }
11334
11335 if (Context.getTargetInfo().emitVectorDeletingDtors(
11336 Context.getLangOpts())) {
11337 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11338 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11339 DeclarationName VDeleteName =
11340 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11342 Loc, RD, /*Diagnose*/ false,
11343 /*LookForGlobal*/ false, VDeleteName);
11344 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11345 FunctionDecl *GlobalArrOperatorDelete =
11346 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11347 /*LookForGlobal*/ true,
11348 VDeleteName);
11349 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11350 if (GlobalArrOperatorDelete &&
11351 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11352 DestructorIsExported))
11353 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11354 } else if (!ArrOperatorDelete) {
11355 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11356 Loc, RD, /*Diagnose*/ false,
11357 /*LookForGlobal*/ true, VDeleteName);
11358 }
11359 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11360 if (ArrOperatorDelete &&
11361 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11362 DestructorIsExported))
11363 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11364 }
11365 }
11366 }
11367
11368 return false;
11369}
11370
11372 StorageClass& SC) {
11373 // C++ [class.dtor]p1:
11374 // [...] A typedef-name that names a class is a class-name
11375 // (7.1.3); however, a typedef-name that names a class shall not
11376 // be used as the identifier in the declarator for a destructor
11377 // declaration.
11378 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11379 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11380 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11381 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11382 else if (const TemplateSpecializationType *TST =
11383 DeclaratorType->getAs<TemplateSpecializationType>())
11384 if (TST->isTypeAlias())
11385 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11386 << DeclaratorType << 1;
11387
11388 // C++ [class.dtor]p2:
11389 // A destructor is used to destroy objects of its class type. A
11390 // destructor takes no parameters, and no return type can be
11391 // specified for it (not even void). The address of a destructor
11392 // shall not be taken. A destructor shall not be static. A
11393 // destructor can be invoked for a const, volatile or const
11394 // volatile object. A destructor shall not be declared const,
11395 // volatile or const volatile (9.3.2).
11396 if (SC == SC_Static) {
11397 if (!D.isInvalidType())
11398 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11399 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11402
11403 SC = SC_None;
11404 }
11405 if (!D.isInvalidType()) {
11406 // Destructors don't have return types, but the parser will
11407 // happily parse something like:
11408 //
11409 // class X {
11410 // float ~X();
11411 // };
11412 //
11413 // The return type will be eliminated later.
11414 if (D.getDeclSpec().hasTypeSpecifier())
11415 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11418 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11419 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11425 D.setInvalidType();
11426 }
11427 }
11428
11429 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11430 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11431
11432 // C++0x [class.dtor]p2:
11433 // A destructor shall not be declared with a ref-qualifier.
11435 if (FTI.hasRefQualifier()) {
11436 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11439 D.setInvalidType();
11440 }
11441
11442 // Make sure we don't have any parameters.
11443 if (FTIHasNonVoidParameters(FTI)) {
11444 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11445
11446 // Delete the parameters.
11447 FTI.freeParams();
11448 D.setInvalidType();
11449 }
11450
11451 // Make sure the destructor isn't variadic.
11452 if (FTI.isVariadic) {
11453 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11454 D.setInvalidType();
11455 }
11456
11457 // Rebuild the function type "R" without any type qualifiers or
11458 // parameters (in case any of the errors above fired) and with
11459 // "void" as the return type, since destructors don't have return
11460 // types.
11461 if (!D.isInvalidType())
11462 return R;
11463
11464 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11466 EPI.Variadic = false;
11467 EPI.TypeQuals = Qualifiers();
11468 EPI.RefQualifier = RQ_None;
11469 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11470}
11471
11472static void extendLeft(SourceRange &R, SourceRange Before) {
11473 if (Before.isInvalid())
11474 return;
11475 R.setBegin(Before.getBegin());
11476 if (R.getEnd().isInvalid())
11477 R.setEnd(Before.getEnd());
11478}
11479
11480static void extendRight(SourceRange &R, SourceRange After) {
11481 if (After.isInvalid())
11482 return;
11483 if (R.getBegin().isInvalid())
11484 R.setBegin(After.getBegin());
11485 R.setEnd(After.getEnd());
11486}
11487
11489 StorageClass& SC) {
11490 // C++ [class.conv.fct]p1:
11491 // Neither parameter types nor return type can be specified. The
11492 // type of a conversion function (8.3.5) is "function taking no
11493 // parameter returning conversion-type-id."
11494 if (SC == SC_Static) {
11495 if (!D.isInvalidType())
11496 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11498 << D.getName().getSourceRange();
11499 D.setInvalidType();
11500 SC = SC_None;
11501 }
11502
11503 TypeSourceInfo *ConvTSI = nullptr;
11504 QualType ConvType =
11506
11507 const DeclSpec &DS = D.getDeclSpec();
11508 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11509 // Conversion functions don't have return types, but the parser will
11510 // happily parse something like:
11511 //
11512 // class X {
11513 // float operator bool();
11514 // };
11515 //
11516 // The return type will be changed later anyway.
11517 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11520 D.setInvalidType();
11521 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11522 // It's also plausible that the user writes type qualifiers in the wrong
11523 // place, such as:
11524 // struct S { const operator int(); };
11525 // FIXME: we could provide a fixit to move the qualifiers onto the
11526 // conversion type.
11527 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11528 << SourceRange(D.getIdentifierLoc()) << 0;
11529 D.setInvalidType();
11530 }
11531 const auto *Proto = R->castAs<FunctionProtoType>();
11532 // Make sure we don't have any parameters.
11534 unsigned NumParam = Proto->getNumParams();
11535
11536 // [C++2b]
11537 // A conversion function shall have no non-object parameters.
11538 if (NumParam == 1) {
11540 if (const auto *First =
11541 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11542 First && First->isExplicitObjectParameter())
11543 NumParam--;
11544 }
11545
11546 if (NumParam != 0) {
11547 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11548 // Delete the parameters.
11549 FTI.freeParams();
11550 D.setInvalidType();
11551 } else if (Proto->isVariadic()) {
11552 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11553 D.setInvalidType();
11554 }
11555
11556 // Diagnose "&operator bool()" and other such nonsense. This
11557 // is actually a gcc extension which we don't support.
11558 if (Proto->getReturnType() != ConvType) {
11559 bool NeedsTypedef = false;
11560 SourceRange Before, After;
11561
11562 // Walk the chunks and extract information on them for our diagnostic.
11563 bool PastFunctionChunk = false;
11564 for (auto &Chunk : D.type_objects()) {
11565 switch (Chunk.Kind) {
11567 if (!PastFunctionChunk) {
11568 if (Chunk.Fun.HasTrailingReturnType) {
11569 TypeSourceInfo *TRT = nullptr;
11570 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11571 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11572 }
11573 PastFunctionChunk = true;
11574 break;
11575 }
11576 [[fallthrough]];
11578 NeedsTypedef = true;
11579 extendRight(After, Chunk.getSourceRange());
11580 break;
11581
11587 extendLeft(Before, Chunk.getSourceRange());
11588 break;
11589
11591 extendLeft(Before, Chunk.Loc);
11592 extendRight(After, Chunk.EndLoc);
11593 break;
11594 }
11595 }
11596
11597 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11598 After.isValid() ? After.getBegin() :
11599 D.getIdentifierLoc();
11600 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11601 DB << Before << After;
11602
11603 if (!NeedsTypedef) {
11604 DB << /*don't need a typedef*/0;
11605
11606 // If we can provide a correct fix-it hint, do so.
11607 if (After.isInvalid() && ConvTSI) {
11608 SourceLocation InsertLoc =
11610 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11612 InsertLoc, CharSourceRange::getTokenRange(Before))
11613 << FixItHint::CreateRemoval(Before);
11614 }
11615 } else if (!Proto->getReturnType()->isDependentType()) {
11616 DB << /*typedef*/1 << Proto->getReturnType();
11617 } else if (getLangOpts().CPlusPlus11) {
11618 DB << /*alias template*/2 << Proto->getReturnType();
11619 } else {
11620 DB << /*might not be fixable*/3;
11621 }
11622
11623 // Recover by incorporating the other type chunks into the result type.
11624 // Note, this does *not* change the name of the function. This is compatible
11625 // with the GCC extension:
11626 // struct S { &operator int(); } s;
11627 // int &r = s.operator int(); // ok in GCC
11628 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11629 ConvType = Proto->getReturnType();
11630 }
11631
11632 // C++ [class.conv.fct]p4:
11633 // The conversion-type-id shall not represent a function type nor
11634 // an array type.
11635 if (ConvType->isArrayType()) {
11636 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11637 ConvType = Context.getPointerType(ConvType);
11638 D.setInvalidType();
11639 } else if (ConvType->isFunctionType()) {
11640 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11641 ConvType = Context.getPointerType(ConvType);
11642 D.setInvalidType();
11643 }
11644
11645 // Rebuild the function type "R" without any parameters (in case any
11646 // of the errors above fired) and with the conversion type as the
11647 // return type.
11648 if (D.isInvalidType())
11649 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11650
11651 // C++0x explicit conversion operators.
11652 if (DS.hasExplicitSpecifier())
11654 diag_compat::explicit_conversion_functions)
11656}
11657
11659 assert(Conversion && "Expected to receive a conversion function declaration");
11660
11661 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11662
11663 // Make sure we aren't redeclaring the conversion function.
11664 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11665 // C++ [class.conv.fct]p1:
11666 // [...] A conversion function is never used to convert a
11667 // (possibly cv-qualified) object to the (possibly cv-qualified)
11668 // same object type (or a reference to it), to a (possibly
11669 // cv-qualified) base class of that type (or a reference to it),
11670 // or to (possibly cv-qualified) void.
11671 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11672 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11673 ConvType = ConvTypeRef->getPointeeType();
11674 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11676 /* Suppress diagnostics for instantiations. */;
11677 else if (Conversion->size_overridden_methods() != 0)
11678 /* Suppress diagnostics for overriding virtual function in a base class. */;
11679 else if (ConvType->isRecordType()) {
11680 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11681 if (ConvType == ClassType)
11682 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11683 << ClassType;
11684 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11685 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11686 << ClassType << ConvType;
11687 } else if (ConvType->isVoidType()) {
11688 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11689 << ClassType << ConvType;
11690 }
11691
11692 if (FunctionTemplateDecl *ConversionTemplate =
11693 Conversion->getDescribedFunctionTemplate()) {
11694 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11695 ConvType = ConvTypePtr->getPointeeType();
11696 }
11697 if (ConvType->isUndeducedAutoType()) {
11698 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11699 << getReturnTypeLoc(Conversion).getSourceRange()
11700 << ConvType->castAs<AutoType>()->getKeyword()
11701 << /* in declaration of conversion function template= */ 24;
11702 }
11703
11704 return ConversionTemplate;
11705 }
11706
11707 return Conversion;
11708}
11709
11714
11718
11720 DeclarationName Name, QualType R,
11721 bool IsLambda, DeclContext *DC) {
11722 if (!D.isFunctionDeclarator())
11723 return;
11724
11726 if (FTI.NumParams == 0)
11727 return;
11728 ParmVarDecl *ExplicitObjectParam = nullptr;
11729 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11730 const auto &ParamInfo = FTI.Params[Idx];
11731 if (!ParamInfo.Param)
11732 continue;
11733 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11734 if (!Param->isExplicitObjectParameter())
11735 continue;
11736 if (Idx == 0) {
11737 ExplicitObjectParam = Param;
11738 continue;
11739 } else {
11740 Diag(Param->getLocation(),
11741 diag::err_explicit_object_parameter_must_be_first)
11742 << IsLambda << Param->getSourceRange();
11743 }
11744 }
11745 if (!ExplicitObjectParam)
11746 return;
11747
11748 if (ExplicitObjectParam->hasDefaultArg()) {
11749 Diag(ExplicitObjectParam->getLocation(),
11750 diag::err_explicit_object_default_arg)
11751 << ExplicitObjectParam->getSourceRange();
11752 D.setInvalidType();
11753 }
11754
11757 D.isStaticMember())) {
11758 Diag(ExplicitObjectParam->getBeginLoc(),
11759 diag::err_explicit_object_parameter_nonmember)
11760 << D.getSourceRange() << /*static=*/0 << IsLambda;
11761 D.setInvalidType();
11762 }
11763
11764 if (D.getDeclSpec().isVirtualSpecified()) {
11765 Diag(ExplicitObjectParam->getBeginLoc(),
11766 diag::err_explicit_object_parameter_nonmember)
11767 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11768 D.setInvalidType();
11769 }
11770
11771 // Friend declarations require some care. Consider:
11772 //
11773 // namespace N {
11774 // struct A{};
11775 // int f(A);
11776 // }
11777 //
11778 // struct S {
11779 // struct T {
11780 // int f(this T);
11781 // };
11782 //
11783 // friend int T::f(this T); // Allow this.
11784 // friend int f(this S); // But disallow this.
11785 // friend int N::f(this A); // And disallow this.
11786 // };
11787 //
11788 // Here, it seems to suffice to check whether the scope
11789 // specifier designates a class type.
11790 if (D.getDeclSpec().isFriendSpecified() &&
11791 !isa_and_present<CXXRecordDecl>(
11793 Diag(ExplicitObjectParam->getBeginLoc(),
11794 diag::err_explicit_object_parameter_nonmember)
11795 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11796 D.setInvalidType();
11797 }
11798
11799 if (IsLambda && FTI.hasMutableQualifier()) {
11800 Diag(ExplicitObjectParam->getBeginLoc(),
11801 diag::err_explicit_object_parameter_mutable)
11802 << D.getSourceRange();
11803 }
11804
11805 if (IsLambda)
11806 return;
11807
11808 if (!DC || !DC->isRecord()) {
11809 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11810 "should have been diagnosed already");
11811 return;
11812 }
11813
11814 // CWG2674: constructors and destructors cannot have explicit parameters.
11817 Diag(ExplicitObjectParam->getBeginLoc(),
11818 diag::err_explicit_object_parameter_constructor)
11820 << D.getSourceRange();
11821 D.setInvalidType();
11822 }
11823}
11824
11825namespace {
11826/// Utility class to accumulate and print a diagnostic listing the invalid
11827/// specifier(s) on a declaration.
11828struct BadSpecifierDiagnoser {
11829 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11830 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11831 ~BadSpecifierDiagnoser() {
11832 Diagnostic << Specifiers;
11833 }
11834
11835 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11836 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11837 }
11838 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11839 return check(SpecLoc,
11841 }
11842 void check(SourceLocation SpecLoc, const char *Spec) {
11843 if (SpecLoc.isInvalid()) return;
11844 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11845 if (!Specifiers.empty()) Specifiers += " ";
11846 Specifiers += Spec;
11847 }
11848
11849 Sema &S;
11850 Sema::SemaDiagnosticBuilder Diagnostic;
11851 std::string Specifiers;
11852};
11853}
11854
11856 StorageClass &SC) {
11857 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11858 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11859 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11860
11861 // C++ [temp.deduct.guide]p3:
11862 // A deduction-gide shall be declared in the same scope as the
11863 // corresponding class template.
11864 if (!CurContext->getRedeclContext()->Equals(
11865 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11866 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11867 << GuidedTemplateDecl;
11868 NoteTemplateLocation(*GuidedTemplateDecl);
11869 }
11870
11871 auto &DS = D.getMutableDeclSpec();
11872 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11873 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11874 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11875 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11876 BadSpecifierDiagnoser Diagnoser(
11877 *this, D.getIdentifierLoc(),
11878 diag::err_deduction_guide_invalid_specifier);
11879
11880 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11881 DS.ClearStorageClassSpecs();
11882 SC = SC_None;
11883
11884 // 'explicit' is permitted.
11885 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11886 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11887 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11888 DS.ClearConstexprSpec();
11889
11890 Diagnoser.check(DS.getConstSpecLoc(), "const");
11891 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11892 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11893 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11894 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11895 DS.ClearTypeQualifiers();
11896
11897 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11898 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11899 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11900 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11901 DS.ClearTypeSpecType();
11902 }
11903
11904 if (D.isInvalidType())
11905 return true;
11906
11907 // Check the declarator is simple enough.
11908 bool FoundFunction = false;
11909 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11910 if (Chunk.Kind == DeclaratorChunk::Paren)
11911 continue;
11912 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11914 diag::err_deduction_guide_with_complex_decl)
11915 << D.getSourceRange();
11916 break;
11917 }
11918 if (!Chunk.Fun.hasTrailingReturnType())
11919 return Diag(D.getName().getBeginLoc(),
11920 diag::err_deduction_guide_no_trailing_return_type);
11921
11922 // Check that the return type is written as a specialization of
11923 // the template specified as the deduction-guide's name.
11924 // The template name may not be qualified. [temp.deduct.guide]
11925 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11926 TypeSourceInfo *TSI = nullptr;
11927 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11928 assert(TSI && "deduction guide has valid type but invalid return type?");
11929 bool AcceptableReturnType = false;
11930 bool MightInstantiateToSpecialization = false;
11931 if (auto RetTST =
11933 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11934 bool TemplateMatches = Context.hasSameTemplateName(
11935 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11936
11938 SpecifiedName.getAsQualifiedTemplateName();
11939 // A Template template parameter is never wrapped in a
11940 // QualifiedTemplateName, but it's always simply-written.
11941 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11942 !Qualifiers->getQualifier());
11943 if (SimplyWritten && TemplateMatches)
11944 AcceptableReturnType = true;
11945 else {
11946 // This could still instantiate to the right type, unless we know it
11947 // names the wrong class template.
11948 auto *TD = SpecifiedName.getAsTemplateDecl();
11949 MightInstantiateToSpecialization =
11950 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11951 }
11952 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11953 MightInstantiateToSpecialization = true;
11954 }
11955
11956 if (!AcceptableReturnType)
11957 return Diag(TSI->getTypeLoc().getBeginLoc(),
11958 diag::err_deduction_guide_bad_trailing_return_type)
11959 << GuidedTemplate << TSI->getType()
11960 << MightInstantiateToSpecialization
11961 << TSI->getTypeLoc().getSourceRange();
11962
11963 // Keep going to check that we don't have any inner declarator pieces (we
11964 // could still have a function returning a pointer to a function).
11965 FoundFunction = true;
11966 }
11967
11968 if (D.isFunctionDefinition())
11969 // we can still create a valid deduction guide here.
11970 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11971 return false;
11972}
11973
11974//===----------------------------------------------------------------------===//
11975// Namespace Handling
11976//===----------------------------------------------------------------------===//
11977
11978/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11979/// reopened.
11981 SourceLocation Loc,
11982 IdentifierInfo *II, bool *IsInline,
11983 NamespaceDecl *PrevNS) {
11984 assert(*IsInline != PrevNS->isInline());
11985
11986 // 'inline' must appear on the original definition, but not necessarily
11987 // on all extension definitions, so the note should point to the first
11988 // definition to avoid confusion.
11989 PrevNS = PrevNS->getFirstDecl();
11990
11991 if (PrevNS->isInline())
11992 // The user probably just forgot the 'inline', so suggest that it
11993 // be added back.
11994 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11995 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11996 else
11997 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11998
11999 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
12000 *IsInline = PrevNS->isInline();
12001}
12002
12003/// ActOnStartNamespaceDef - This is called at the start of a namespace
12004/// definition.
12006 SourceLocation InlineLoc,
12007 SourceLocation NamespaceLoc,
12008 SourceLocation IdentLoc, IdentifierInfo *II,
12009 SourceLocation LBrace,
12010 const ParsedAttributesView &AttrList,
12011 UsingDirectiveDecl *&UD, bool IsNested) {
12012 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
12013 // For anonymous namespace, take the location of the left brace.
12014 SourceLocation Loc = II ? IdentLoc : LBrace;
12015 bool IsInline = InlineLoc.isValid();
12016 bool IsInvalid = false;
12017 bool IsStd = false;
12018 bool AddToKnown = false;
12019 Scope *DeclRegionScope = NamespcScope->getParent();
12020
12021 NamespaceDecl *PrevNS = nullptr;
12022 if (II) {
12023 // C++ [namespace.std]p7:
12024 // A translation unit shall not declare namespace std to be an inline
12025 // namespace (9.8.2).
12026 //
12027 // Precondition: the std namespace is in the file scope and is declared to
12028 // be inline
12029 auto DiagnoseInlineStdNS = [&]() {
12030 assert(IsInline && II->isStr("std") &&
12031 CurContext->getRedeclContext()->isTranslationUnit() &&
12032 "Precondition of DiagnoseInlineStdNS not met");
12033 Diag(InlineLoc, diag::err_inline_namespace_std)
12034 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12035 IsInline = false;
12036 };
12037 // C++ [namespace.def]p2:
12038 // The identifier in an original-namespace-definition shall not
12039 // have been previously defined in the declarative region in
12040 // which the original-namespace-definition appears. The
12041 // identifier in an original-namespace-definition is the name of
12042 // the namespace. Subsequently in that declarative region, it is
12043 // treated as an original-namespace-name.
12044 //
12045 // Since namespace names are unique in their scope, and we don't
12046 // look through using directives, just look for any ordinary names
12047 // as if by qualified name lookup.
12048 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12050 LookupQualifiedName(R, CurContext->getRedeclContext());
12051 NamedDecl *PrevDecl =
12052 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12053 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12054
12055 if (PrevNS) {
12056 // This is an extended namespace definition.
12057 if (IsInline && II->isStr("std") &&
12058 CurContext->getRedeclContext()->isTranslationUnit())
12059 DiagnoseInlineStdNS();
12060 else if (IsInline != PrevNS->isInline())
12061 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12062 &IsInline, PrevNS);
12063 } else if (PrevDecl) {
12064 // This is an invalid name redefinition.
12065 Diag(Loc, diag::err_redefinition_different_kind)
12066 << II;
12067 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12068 IsInvalid = true;
12069 // Continue on to push Namespc as current DeclContext and return it.
12070 } else if (II->isStr("std") &&
12071 CurContext->getRedeclContext()->isTranslationUnit()) {
12072 if (IsInline)
12073 DiagnoseInlineStdNS();
12074 // This is the first "real" definition of the namespace "std", so update
12075 // our cache of the "std" namespace to point at this definition.
12076 PrevNS = getStdNamespace();
12077 IsStd = true;
12078 AddToKnown = !IsInline;
12079 } else {
12080 // We've seen this namespace for the first time.
12081 AddToKnown = !IsInline;
12082 }
12083 } else {
12084 // Anonymous namespaces.
12085
12086 // Determine whether the parent already has an anonymous namespace.
12087 DeclContext *Parent = CurContext->getRedeclContext();
12088 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12089 PrevNS = TU->getAnonymousNamespace();
12090 } else {
12091 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12092 PrevNS = ND->getAnonymousNamespace();
12093 }
12094
12095 if (PrevNS && IsInline != PrevNS->isInline())
12096 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12097 &IsInline, PrevNS);
12098 }
12099
12101 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12102 if (IsInvalid)
12103 Namespc->setInvalidDecl();
12104
12105 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12106 AddPragmaAttributes(DeclRegionScope, Namespc);
12107 ProcessAPINotes(Namespc);
12108
12109 // FIXME: Should we be merging attributes?
12110 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12112
12113 if (IsStd)
12114 StdNamespace = Namespc;
12115 if (AddToKnown)
12116 KnownNamespaces[Namespc] = false;
12117
12118 if (II) {
12119 PushOnScopeChains(Namespc, DeclRegionScope);
12120 } else {
12121 // Link the anonymous namespace into its parent.
12122 DeclContext *Parent = CurContext->getRedeclContext();
12123 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12124 TU->setAnonymousNamespace(Namespc);
12125 } else {
12126 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12127 }
12128
12129 CurContext->addDecl(Namespc);
12130
12131 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12132 // behaves as if it were replaced by
12133 // namespace unique { /* empty body */ }
12134 // using namespace unique;
12135 // namespace unique { namespace-body }
12136 // where all occurrences of 'unique' in a translation unit are
12137 // replaced by the same identifier and this identifier differs
12138 // from all other identifiers in the entire program.
12139
12140 // We just create the namespace with an empty name and then add an
12141 // implicit using declaration, just like the standard suggests.
12142 //
12143 // CodeGen enforces the "universally unique" aspect by giving all
12144 // declarations semantically contained within an anonymous
12145 // namespace internal linkage.
12146
12147 if (!PrevNS) {
12149 /* 'using' */ LBrace,
12150 /* 'namespace' */ SourceLocation(),
12151 /* qualifier */ NestedNameSpecifierLoc(),
12152 /* identifier */ SourceLocation(),
12153 Namespc,
12154 /* Ancestor */ Parent);
12155 UD->setImplicit();
12156 Parent->addDecl(UD);
12157 }
12158 }
12159
12160 ActOnDocumentableDecl(Namespc);
12161
12162 // Although we could have an invalid decl (i.e. the namespace name is a
12163 // redefinition), push it as current DeclContext and try to continue parsing.
12164 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12165 // for the namespace has the declarations that showed up in that particular
12166 // namespace definition.
12167 PushDeclContext(NamespcScope, Namespc);
12168 return Namespc;
12169}
12170
12171/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12172/// is a namespace alias, returns the namespace it points to.
12174 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12175 return AD->getNamespace();
12176 return dyn_cast_or_null<NamespaceDecl>(D);
12177}
12178
12180 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12181 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12182 Namespc->setRBraceLoc(RBrace);
12184 if (Namespc->hasAttr<VisibilityAttr>())
12185 PopPragmaVisibility(true, RBrace);
12186 // If this namespace contains an export-declaration, export it now.
12187 if (DeferredExportedNamespaces.erase(Namespc))
12189}
12190
12192 return cast_or_null<CXXRecordDecl>(
12193 StdBadAlloc.get(Context.getExternalSource()));
12194}
12195
12197 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12198}
12199
12201 return cast_or_null<NamespaceDecl>(
12202 StdNamespace.get(Context.getExternalSource()));
12203}
12204
12205namespace {
12206
12207enum UnsupportedSTLSelect {
12208 USS_InvalidMember,
12209 USS_MissingMember,
12210 USS_NonTrivial,
12211 USS_Other
12212};
12213
12214struct InvalidSTLDiagnoser {
12215 Sema &S;
12216 SourceLocation Loc;
12217 QualType TyForDiags;
12218
12219 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12220 const VarDecl *VD = nullptr) {
12221 {
12222 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12223 << TyForDiags << ((int)Sel);
12224 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12225 assert(!Name.empty());
12226 D << Name;
12227 }
12228 }
12229 if (Sel == USS_InvalidMember) {
12230 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12231 << VD << VD->getSourceRange();
12232 }
12233 return QualType();
12234 }
12235};
12236} // namespace
12237
12239 SourceLocation Loc,
12241 assert(getLangOpts().CPlusPlus &&
12242 "Looking for comparison category type outside of C++.");
12243
12244 // Use an elaborated type for diagnostics which has a name containing the
12245 // prepended 'std' namespace but not any inline namespace names.
12246 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12248 /*Prefix=*/std::nullopt);
12249 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12250 Info->Record,
12251 /*OwnsTag=*/false);
12252 };
12253
12254 // Check if we've already successfully checked the comparison category type
12255 // before. If so, skip checking it again.
12256 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12257 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12258 // The only thing we need to check is that the type has a reachable
12259 // definition in the current context.
12260 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12261 return QualType();
12262
12263 return Info->getType();
12264 }
12265
12266 // If lookup failed
12267 if (!Info) {
12268 std::string NameForDiags = "std::";
12269 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12270 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12271 << NameForDiags << (int)Usage;
12272 return QualType();
12273 }
12274
12275 assert(Info->Kind == Kind);
12276 assert(Info->Record);
12277
12278 // Update the Record decl in case we encountered a forward declaration on our
12279 // first pass. FIXME: This is a bit of a hack.
12280 if (Info->Record->hasDefinition())
12281 Info->Record = Info->Record->getDefinition();
12282
12283 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12284 return QualType();
12285
12286 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12287
12288 if (!Info->Record->isTriviallyCopyable())
12289 return UnsupportedSTLError(USS_NonTrivial);
12290
12291 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12292 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12293 // Tolerate empty base classes.
12294 if (Base->isEmpty())
12295 continue;
12296 // Reject STL implementations which have at least one non-empty base.
12297 return UnsupportedSTLError();
12298 }
12299
12300 // Check that the STL has implemented the types using a single integer field.
12301 // This expectation allows better codegen for builtin operators. We require:
12302 // (1) The class has exactly one field.
12303 // (2) The field is an integral or enumeration type.
12304 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12305 if (std::distance(FIt, FEnd) != 1 ||
12306 !FIt->getType()->isIntegralOrEnumerationType()) {
12307 return UnsupportedSTLError();
12308 }
12309
12310 // Build each of the require values and store them in Info.
12311 for (ComparisonCategoryResult CCR :
12313 StringRef MemName = ComparisonCategories::getResultString(CCR);
12314 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12315
12316 if (!ValInfo)
12317 return UnsupportedSTLError(USS_MissingMember, MemName);
12318
12319 VarDecl *VD = ValInfo->VD;
12320 assert(VD && "should not be null!");
12321
12322 // Attempt to diagnose reasons why the STL definition of this type
12323 // might be foobar, including it failing to be a constant expression.
12324 // TODO Handle more ways the lookup or result can be invalid.
12325 if (!VD->isStaticDataMember() ||
12327 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12328
12329 // Attempt to evaluate the var decl as a constant expression and extract
12330 // the value of its first field as a ICE. If this fails, the STL
12331 // implementation is not supported.
12332 if (!ValInfo->hasValidIntValue())
12333 return UnsupportedSTLError();
12334
12335 MarkVariableReferenced(Loc, VD);
12336 }
12337
12338 // We've successfully built the required types and expressions. Update
12339 // the cache and return the newly cached value.
12340 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12341 return Info->getType();
12342}
12343
12345 if (!StdNamespace) {
12346 // The "std" namespace has not yet been defined, so build one implicitly.
12348 Context, Context.getTranslationUnitDecl(),
12349 /*Inline=*/false, SourceLocation(), SourceLocation(),
12350 &PP.getIdentifierTable().get("std"),
12351 /*PrevDecl=*/nullptr, /*Nested=*/false);
12352 getStdNamespace()->setImplicit(true);
12353 // We want the created NamespaceDecl to be available for redeclaration
12354 // lookups, but not for regular name lookups.
12355 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12356 getStdNamespace()->clearIdentifierNamespace();
12357 }
12358
12359 return getStdNamespace();
12360}
12361
12362static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12363 const char *ClassName,
12364 ClassTemplateDecl **CachedDecl,
12365 const Decl **MalformedDecl) {
12366 // We're looking for implicit instantiations of
12367 // template <typename U> class std::{ClassName}.
12368
12369 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12370 // it.
12371 return false;
12372
12373 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12374 if (!MalformedDecl)
12375 return;
12376 if (!D)
12377 D = SugaredType->getAsTagDecl();
12378 if (!D || !D->isInStdNamespace())
12379 return;
12380 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12381 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12382 *MalformedDecl = D;
12383 };
12384
12385 ClassTemplateDecl *Template = nullptr;
12387 if (const TemplateSpecializationType *TST =
12389 Template = dyn_cast_or_null<ClassTemplateDecl>(
12390 TST->getTemplateName().getAsTemplateDecl());
12391 Arguments = TST->template_arguments();
12392 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12393 Template = TT->getTemplateDecl();
12394 Arguments = TT->getTemplateArgs(S.Context);
12395 }
12396
12397 if (!Template) {
12398 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12399 return false;
12400 }
12401
12402 if (!*CachedDecl) {
12403 // Haven't recognized std::{ClassName} yet, maybe this is it.
12404 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12405 // semantics of this are slightly different, most notably the existing
12406 // "lookup" semantics explicitly diagnose an invalid definition as an
12407 // error.
12408 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12409 if (TemplateClass->getIdentifier() !=
12410 &S.PP.getIdentifierTable().get(ClassName) ||
12412 TemplateClass->getNonTransparentDeclContext()))
12413 return false;
12414 // This is a template called std::{ClassName}, but is it the right
12415 // template?
12416 TemplateParameterList *Params = Template->getTemplateParameters();
12417 if (Params->getMinRequiredArguments() != 1 ||
12418 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12419 Params->getParam(0)->isTemplateParameterPack()) {
12420 if (MalformedDecl)
12421 *MalformedDecl = TemplateClass;
12422 return false;
12423 }
12424
12425 // It's the right template.
12426 *CachedDecl = Template;
12427 }
12428
12429 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12430 return false;
12431
12432 // This is an instance of std::{ClassName}. Find the argument type.
12433 if (TypeArg) {
12434 QualType ArgType = Arguments[0].getAsType();
12435 // FIXME: Since TST only has as-written arguments, we have to perform the
12436 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12437 // - If an explicitly-specified template argument type is a lifetime type
12438 // with no lifetime qualifier, the __strong lifetime qualifier is
12439 // inferred.
12440 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12441 !ArgType.getObjCLifetime()) {
12442 Qualifiers Qs;
12444 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12445 }
12446 *TypeArg = ArgType;
12447 }
12448
12449 return true;
12450}
12451
12453 assert(getLangOpts().CPlusPlus &&
12454 "Looking for std::initializer_list outside of C++.");
12455
12456 // We're looking for implicit instantiations of
12457 // template <typename E> class std::initializer_list.
12458
12459 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12460 &StdInitializerList, /*MalformedDecl=*/nullptr);
12461}
12462
12464 const Decl **MalformedDecl) {
12465 assert(getLangOpts().CPlusPlus &&
12466 "Looking for std::type_identity outside of C++.");
12467
12468 // We're looking for implicit instantiations of
12469 // template <typename T> struct std::type_identity.
12470
12471 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12472 &StdTypeIdentity, MalformedDecl);
12473}
12474
12476 const char *ClassName,
12477 bool *WasMalformed) {
12478 if (!S.StdNamespace)
12479 return nullptr;
12480
12481 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12484 return nullptr;
12485
12487 if (!Template) {
12488 Result.suppressDiagnostics();
12489 // We found something weird. Complain about the first thing we found.
12490 NamedDecl *Found = *Result.begin();
12491 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12492 << ClassName;
12493 if (WasMalformed)
12494 *WasMalformed = true;
12495 return nullptr;
12496 }
12497
12498 // We found some template with the correct name. Now verify that it's
12499 // correct.
12500 TemplateParameterList *Params = Template->getTemplateParameters();
12501 if (Params->getMinRequiredArguments() != 1 ||
12502 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12503 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12504 << ClassName;
12505 if (WasMalformed)
12506 *WasMalformed = true;
12507 return nullptr;
12508 }
12509
12510 return Template;
12511}
12512
12514 QualType TypeParam, SourceLocation Loc) {
12515 assert(S.getStdNamespace());
12516 TemplateArgumentListInfo Args(Loc, Loc);
12517 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12518 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12519
12521 Loc, Args, /*Scope=*/nullptr,
12522 /*ForNestedNameSpecifier=*/false);
12523}
12524
12526 if (!StdInitializerList) {
12527 bool WasMalformed = false;
12529 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12530 if (!StdInitializerList) {
12531 if (!WasMalformed)
12532 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12533 return QualType();
12534 }
12535 }
12536 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12537}
12538
12540 if (!StdTypeIdentity) {
12541 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12542 /*WasMalformed=*/nullptr);
12543 if (!StdTypeIdentity)
12544 return QualType();
12545 }
12546 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12547}
12548
12550 // C++ [dcl.init.list]p2:
12551 // A constructor is an initializer-list constructor if its first parameter
12552 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12553 // std::initializer_list<E> for some type E, and either there are no other
12554 // parameters or else all other parameters have default arguments.
12555 if (!Ctor->hasOneParamOrDefaultArgs())
12556 return false;
12557
12558 QualType ArgType = Ctor->getParamDecl(0)->getType();
12559 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12560 ArgType = RT->getPointeeType().getUnqualifiedType();
12561
12562 return isStdInitializerList(ArgType, nullptr);
12563}
12564
12565/// Determine whether a using statement is in a context where it will be
12566/// apply in all contexts.
12568 switch (CurContext->getDeclKind()) {
12569 case Decl::TranslationUnit:
12570 return true;
12571 case Decl::LinkageSpec:
12572 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12573 default:
12574 return false;
12575 }
12576}
12577
12578namespace {
12579
12580// Callback to only accept typo corrections that are namespaces.
12581class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12582public:
12583 bool ValidateCandidate(const TypoCorrection &candidate) override {
12584 if (NamedDecl *ND = candidate.getCorrectionDecl())
12586 return false;
12587 }
12588
12589 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12590 return std::make_unique<NamespaceValidatorCCC>(*this);
12591 }
12592};
12593
12594}
12595
12596static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12597 Sema &S) {
12598 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12599 Module *M = ND->getOwningModule();
12600 assert(M && "hidden namespace definition not in a module?");
12601
12602 if (M->isExplicitGlobalModule())
12603 S.Diag(Corrected.getCorrectionRange().getBegin(),
12604 diag::err_module_unimported_use_header)
12606 << /*Header Name*/ false;
12607 else
12608 S.Diag(Corrected.getCorrectionRange().getBegin(),
12609 diag::err_module_unimported_use)
12611 << M->getTopLevelModuleName();
12612}
12613
12615 CXXScopeSpec &SS,
12616 SourceLocation IdentLoc,
12617 IdentifierInfo *Ident) {
12618 R.clear();
12619 NamespaceValidatorCCC CCC{};
12620 if (TypoCorrection Corrected =
12621 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12623 // Generally we find it is confusing more than helpful to diagnose the
12624 // invisible namespace.
12625 // See https://github.com/llvm/llvm-project/issues/73893.
12626 //
12627 // However, we should diagnose when the users are trying to using an
12628 // invisible namespace. So we handle the case specially here.
12629 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12630 Corrected.requiresImport()) {
12631 DiagnoseInvisibleNamespace(Corrected, S);
12632 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12633 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12634 bool DroppedSpecifier =
12635 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12636 S.diagnoseTypo(Corrected,
12637 S.PDiag(diag::err_using_directive_member_suggest)
12638 << Ident << DC << DroppedSpecifier << SS.getRange(),
12639 S.PDiag(diag::note_namespace_defined_here));
12640 } else {
12641 S.diagnoseTypo(Corrected,
12642 S.PDiag(diag::err_using_directive_suggest) << Ident,
12643 S.PDiag(diag::note_namespace_defined_here));
12644 }
12645 R.addDecl(Corrected.getFoundDecl());
12646 return true;
12647 }
12648 return false;
12649}
12650
12652 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12653 SourceLocation IdentLoc,
12654 IdentifierInfo *NamespcName,
12655 const ParsedAttributesView &AttrList) {
12656 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12657 assert(NamespcName && "Invalid NamespcName.");
12658 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12659
12660 // Get the innermost enclosing declaration scope.
12661 S = S->getDeclParent();
12662
12663 UsingDirectiveDecl *UDir = nullptr;
12664 NestedNameSpecifier Qualifier = SS.getScopeRep();
12665
12666 // Lookup namespace name.
12667 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12668 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12669 if (R.isAmbiguous())
12670 return nullptr;
12671
12672 if (R.empty()) {
12673 R.clear();
12674 // Allow "using namespace std;" or "using namespace ::std;" even if
12675 // "std" hasn't been defined yet, for GCC compatibility.
12676 if ((!Qualifier ||
12677 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12678 NamespcName->isStr("std")) {
12679 Diag(IdentLoc, diag::ext_using_undefined_std);
12680 R.addDecl(getOrCreateStdNamespace());
12681 R.resolveKind();
12682 }
12683 // Otherwise, attempt typo correction.
12684 else
12685 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12686 }
12687
12688 if (!R.empty()) {
12689 NamedDecl *Named = R.getRepresentativeDecl();
12690 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12691 assert(NS && "expected namespace decl");
12692
12693 // The use of a nested name specifier may trigger deprecation warnings.
12694 DiagnoseUseOfDecl(Named, IdentLoc);
12695
12696 // C++ [namespace.udir]p1:
12697 // A using-directive specifies that the names in the nominated
12698 // namespace can be used in the scope in which the
12699 // using-directive appears after the using-directive. During
12700 // unqualified name lookup (3.4.1), the names appear as if they
12701 // were declared in the nearest enclosing namespace which
12702 // contains both the using-directive and the nominated
12703 // namespace. [Note: in this context, "contains" means "contains
12704 // directly or indirectly". ]
12705
12706 // Find enclosing context containing both using-directive and
12707 // nominated namespace.
12708 DeclContext *CommonAncestor = NS;
12709 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12710 CommonAncestor = CommonAncestor->getParent();
12711
12712 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12714 IdentLoc, Named, CommonAncestor);
12715
12717 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12718 Diag(IdentLoc, diag::warn_using_directive_in_header);
12719 }
12720
12721 PushUsingDirective(S, UDir);
12722 } else {
12723 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12724 }
12725
12726 if (UDir) {
12727 ProcessDeclAttributeList(S, UDir, AttrList);
12728 ProcessAPINotes(UDir);
12729 }
12730
12731 return UDir;
12732}
12733
12735 // If the scope has an associated entity and the using directive is at
12736 // namespace or translation unit scope, add the UsingDirectiveDecl into
12737 // its lookup structure so qualified name lookup can find it.
12738 DeclContext *Ctx = S->getEntity();
12739 if (Ctx && !Ctx->isFunctionOrMethod())
12740 Ctx->addDecl(UDir);
12741 else
12742 // Otherwise, it is at block scope. The using-directives will affect lookup
12743 // only to the end of the scope.
12744 S->PushUsingDirective(UDir);
12745}
12746
12748 SourceLocation UsingLoc,
12749 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12750 UnqualifiedId &Name,
12751 SourceLocation EllipsisLoc,
12752 const ParsedAttributesView &AttrList) {
12753 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12754
12755 if (SS.isEmpty()) {
12756 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12757 return nullptr;
12758 }
12759
12760 switch (Name.getKind()) {
12766 break;
12767
12770 // C++11 inheriting constructors.
12771 Diag(Name.getBeginLoc(),
12773 ? diag::warn_cxx98_compat_using_decl_constructor
12774 : diag::err_using_decl_constructor)
12775 << SS.getRange();
12776
12777 if (getLangOpts().CPlusPlus11) break;
12778
12779 return nullptr;
12780
12782 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12783 return nullptr;
12784
12786 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12788 return nullptr;
12789
12791 llvm_unreachable("cannot parse qualified deduction guide name");
12792 }
12793
12794 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12795 DeclarationName TargetName = TargetNameInfo.getName();
12796 if (!TargetName)
12797 return nullptr;
12798
12799 // Warn about access declarations.
12800 if (UsingLoc.isInvalid()) {
12802 ? diag::err_access_decl
12803 : diag::warn_access_decl_deprecated)
12804 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12805 }
12806
12807 if (EllipsisLoc.isInvalid()) {
12810 return nullptr;
12811 } else {
12813 !TargetNameInfo.containsUnexpandedParameterPack()) {
12814 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12815 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12816 EllipsisLoc = SourceLocation();
12817 }
12818 }
12819
12820 NamedDecl *UD =
12821 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12822 SS, TargetNameInfo, EllipsisLoc, AttrList,
12823 /*IsInstantiation*/ false,
12824 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12825 if (UD)
12826 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12827
12828 return UD;
12829}
12830
12832 SourceLocation UsingLoc,
12833 SourceLocation EnumLoc, SourceRange TyLoc,
12834 const IdentifierInfo &II, ParsedType Ty,
12835 const CXXScopeSpec &SS) {
12836 TypeSourceInfo *TSI = nullptr;
12837 SourceLocation IdentLoc = TyLoc.getBegin();
12838 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12839 if (EnumTy.isNull()) {
12840 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12841 ? diag::err_using_enum_is_dependent
12842 : diag::err_unknown_typename)
12843 << II.getName()
12844 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12845 TyLoc.getEnd());
12846 return nullptr;
12847 }
12848
12849 if (EnumTy->isDependentType()) {
12850 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12851 return nullptr;
12852 }
12853
12854 auto *Enum = EnumTy->getAsEnumDecl();
12855 if (!Enum) {
12856 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12857 return nullptr;
12858 }
12859
12860 if (TSI == nullptr)
12861 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12862
12863 auto *UD =
12864 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12865
12866 if (UD)
12867 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12868
12869 return UD;
12870}
12871
12872/// Determine whether a using declaration considers the given
12873/// declarations as "equivalent", e.g., if they are redeclarations of
12874/// the same entity or are both typedefs of the same type.
12875static bool
12877 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12878 return true;
12879
12880 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12881 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12882 return Context.hasSameType(TD1->getUnderlyingType(),
12883 TD2->getUnderlyingType());
12884
12885 // Two using_if_exists using-declarations are equivalent if both are
12886 // unresolved.
12889 return true;
12890
12891 return false;
12892}
12893
12895 const LookupResult &Previous,
12896 UsingShadowDecl *&PrevShadow) {
12897 // Diagnose finding a decl which is not from a base class of the
12898 // current class. We do this now because there are cases where this
12899 // function will silently decide not to build a shadow decl, which
12900 // will pre-empt further diagnostics.
12901 //
12902 // We don't need to do this in C++11 because we do the check once on
12903 // the qualifier.
12904 //
12905 // FIXME: diagnose the following if we care enough:
12906 // struct A { int foo; };
12907 // struct B : A { using A::foo; };
12908 // template <class T> struct C : A {};
12909 // template <class T> struct D : C<T> { using B::foo; } // <---
12910 // This is invalid (during instantiation) in C++03 because B::foo
12911 // resolves to the using decl in B, which is not a base class of D<T>.
12912 // We can't diagnose it immediately because C<T> is an unknown
12913 // specialization. The UsingShadowDecl in D<T> then points directly
12914 // to A::foo, which will look well-formed when we instantiate.
12915 // The right solution is to not collapse the shadow-decl chain.
12916 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12917 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12918 DeclContext *OrigDC = Orig->getDeclContext();
12919
12920 // Handle enums and anonymous structs.
12921 if (isa<EnumDecl>(OrigDC))
12922 OrigDC = OrigDC->getParent();
12923 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12924 while (OrigRec->isAnonymousStructOrUnion())
12925 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12926
12928 if (OrigDC == CurContext) {
12929 Diag(Using->getLocation(),
12930 diag::err_using_decl_nested_name_specifier_is_current_class)
12931 << Using->getQualifierLoc().getSourceRange();
12932 Diag(Orig->getLocation(), diag::note_using_decl_target);
12933 Using->setInvalidDecl();
12934 return true;
12935 }
12936
12937 Diag(Using->getQualifierLoc().getBeginLoc(),
12938 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12939 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12940 << Using->getQualifierLoc().getSourceRange();
12941 Diag(Orig->getLocation(), diag::note_using_decl_target);
12942 Using->setInvalidDecl();
12943 return true;
12944 }
12945 }
12946
12947 if (Previous.empty()) return false;
12948
12949 NamedDecl *Target = Orig;
12951 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12952
12953 // If the target happens to be one of the previous declarations, we
12954 // don't have a conflict.
12955 //
12956 // FIXME: but we might be increasing its access, in which case we
12957 // should redeclare it.
12958 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12959 bool FoundEquivalentDecl = false;
12960 for (NamedDecl *Element : Previous) {
12961 NamedDecl *D = Element->getUnderlyingDecl();
12962 // We can have UsingDecls in our Previous results because we use the same
12963 // LookupResult for checking whether the UsingDecl itself is a valid
12964 // redeclaration.
12966 continue;
12967
12968 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12969 // C++ [class.mem]p19:
12970 // If T is the name of a class, then [every named member other than
12971 // a non-static data member] shall have a name different from T
12972 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12976 CurContext,
12978 return true;
12979 }
12980
12982 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12983 PrevShadow = Shadow;
12984 FoundEquivalentDecl = true;
12986 // We don't conflict with an existing using shadow decl of an equivalent
12987 // declaration, but we're not a redeclaration of it.
12988 FoundEquivalentDecl = true;
12989 }
12990
12991 if (isVisible(D))
12992 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12993 }
12994
12995 if (FoundEquivalentDecl)
12996 return false;
12997
12998 // Always emit a diagnostic for a mismatch between an unresolved
12999 // using_if_exists and a resolved using declaration in either direction.
13001 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
13002 if (!NonTag && !Tag)
13003 return false;
13004 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13005 Diag(Target->getLocation(), diag::note_using_decl_target);
13006 Diag((NonTag ? NonTag : Tag)->getLocation(),
13007 diag::note_using_decl_conflict);
13008 BUD->setInvalidDecl();
13009 return true;
13010 }
13011
13012 if (FunctionDecl *FD = Target->getAsFunction()) {
13013 NamedDecl *OldDecl = nullptr;
13014 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
13015 /*IsForUsingDecl*/ true)) {
13017 return false;
13018
13020 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13021 break;
13022
13023 // We found a decl with the exact signature.
13025 // If we're in a record, we want to hide the target, so we
13026 // return true (without a diagnostic) to tell the caller not to
13027 // build a shadow decl.
13028 if (CurContext->isRecord())
13029 return true;
13030
13031 // If we're not in a record, this is an error.
13032 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13033 break;
13034 }
13035
13036 Diag(Target->getLocation(), diag::note_using_decl_target);
13037 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13038 BUD->setInvalidDecl();
13039 return true;
13040 }
13041
13042 // Target is not a function.
13043
13044 if (isa<TagDecl>(Target)) {
13045 // No conflict between a tag and a non-tag.
13046 if (!Tag) return false;
13047
13048 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13049 Diag(Target->getLocation(), diag::note_using_decl_target);
13050 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13051 BUD->setInvalidDecl();
13052 return true;
13053 }
13054
13055 // No conflict between a tag and a non-tag.
13056 if (!NonTag) return false;
13057
13058 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13059 Diag(Target->getLocation(), diag::note_using_decl_target);
13060 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13061 BUD->setInvalidDecl();
13062 return true;
13063}
13064
13065/// Determine whether a direct base class is a virtual base class.
13067 if (!Derived->getNumVBases())
13068 return false;
13069 for (auto &B : Derived->bases())
13070 if (B.getType()->getAsCXXRecordDecl() == Base)
13071 return B.isVirtual();
13072 llvm_unreachable("not a direct base class");
13073}
13074
13076 NamedDecl *Orig,
13077 UsingShadowDecl *PrevDecl) {
13078 // If we resolved to another shadow declaration, just coalesce them.
13079 NamedDecl *Target = Orig;
13081 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13082 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13083 }
13084
13085 NamedDecl *NonTemplateTarget = Target;
13086 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13087 NonTemplateTarget = TargetTD->getTemplatedDecl();
13088
13089 UsingShadowDecl *Shadow;
13090 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13091 UsingDecl *Using = cast<UsingDecl>(BUD);
13092 bool IsVirtualBase =
13094 Using->getQualifier().getAsRecordDecl());
13096 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13097 } else {
13099 Target->getDeclName(), BUD, Target);
13100 }
13101 BUD->addShadowDecl(Shadow);
13102
13103 Shadow->setAccess(BUD->getAccess());
13104 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13105 Shadow->setInvalidDecl();
13106
13107 Shadow->setPreviousDecl(PrevDecl);
13108
13109 if (S)
13110 PushOnScopeChains(Shadow, S);
13111 else
13112 CurContext->addDecl(Shadow);
13113
13114
13115 return Shadow;
13116}
13117
13119 if (Shadow->getDeclName().getNameKind() ==
13121 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13122
13123 // Remove it from the DeclContext...
13124 Shadow->getDeclContext()->removeDecl(Shadow);
13125
13126 // ...and the scope, if applicable...
13127 if (S) {
13128 S->RemoveDecl(Shadow);
13129 IdResolver.RemoveDecl(Shadow);
13130 }
13131
13132 // ...and the using decl.
13133 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13134
13135 // TODO: complain somehow if Shadow was used. It shouldn't
13136 // be possible for this to happen, because...?
13137}
13138
13139/// Find the base specifier for a base class with the given type.
13141 QualType DesiredBase,
13142 bool &AnyDependentBases) {
13143 // Check whether the named type is a direct base class.
13144 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13145 for (auto &Base : Derived->bases()) {
13146 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13147 if (CanonicalDesiredBase == BaseType)
13148 return &Base;
13149 if (BaseType->isDependentType())
13150 AnyDependentBases = true;
13151 }
13152 return nullptr;
13153}
13154
13155namespace {
13156class UsingValidatorCCC final : public CorrectionCandidateCallback {
13157public:
13158 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13159 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13160 : HasTypenameKeyword(HasTypenameKeyword),
13161 IsInstantiation(IsInstantiation), OldNNS(NNS),
13162 RequireMemberOf(RequireMemberOf) {}
13163
13164 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13165 NamedDecl *ND = Candidate.getCorrectionDecl();
13166
13167 // Keywords are not valid here.
13168 if (!ND || isa<NamespaceDecl>(ND))
13169 return false;
13170
13171 // Completely unqualified names are invalid for a 'using' declaration.
13172 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13173 return false;
13174
13175 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13176 // reject.
13177
13178 if (RequireMemberOf) {
13179 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13180 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13181 // No-one ever wants a using-declaration to name an injected-class-name
13182 // of a base class, unless they're declaring an inheriting constructor.
13183 ASTContext &Ctx = ND->getASTContext();
13184 if (!Ctx.getLangOpts().CPlusPlus11)
13185 return false;
13186 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13187
13188 // Check that the injected-class-name is named as a member of its own
13189 // type; we don't want to suggest 'using Derived::Base;', since that
13190 // means something else.
13191 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13192 ? Candidate.getCorrectionSpecifier()
13193 : OldNNS;
13194 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13195 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13196 return false;
13197
13198 // Check that this inheriting constructor declaration actually names a
13199 // direct base class of the current class.
13200 bool AnyDependentBases = false;
13201 if (!findDirectBaseWithType(RequireMemberOf,
13202 Ctx.getCanonicalTagType(FoundRecord),
13203 AnyDependentBases) &&
13204 !AnyDependentBases)
13205 return false;
13206 } else {
13207 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13208 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13209 return false;
13210
13211 // FIXME: Check that the base class member is accessible?
13212 }
13213 } else {
13214 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13215 if (FoundRecord && FoundRecord->isInjectedClassName())
13216 return false;
13217 }
13218
13219 if (isa<TypeDecl>(ND))
13220 return HasTypenameKeyword || !IsInstantiation;
13221
13222 return !HasTypenameKeyword;
13223 }
13224
13225 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13226 return std::make_unique<UsingValidatorCCC>(*this);
13227 }
13228
13229private:
13230 bool HasTypenameKeyword;
13231 bool IsInstantiation;
13232 NestedNameSpecifier OldNNS;
13233 CXXRecordDecl *RequireMemberOf;
13234};
13235} // end anonymous namespace
13236
13238 // It is really dumb that we have to do this.
13239 LookupResult::Filter F = Previous.makeFilter();
13240 while (F.hasNext()) {
13241 NamedDecl *D = F.next();
13242 if (!isDeclInScope(D, CurContext, S))
13243 F.erase();
13244 // If we found a local extern declaration that's not ordinarily visible,
13245 // and this declaration is being added to a non-block scope, ignore it.
13246 // We're only checking for scope conflicts here, not also for violations
13247 // of the linkage rules.
13248 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13250 F.erase();
13251 }
13252 F.done();
13253}
13254
13256 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13257 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13258 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13259 const ParsedAttributesView &AttrList, bool IsInstantiation,
13260 bool IsUsingIfExists) {
13261 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13262 SourceLocation IdentLoc = NameInfo.getLoc();
13263 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13264
13265 // FIXME: We ignore attributes for now.
13266
13267 // For an inheriting constructor declaration, the name of the using
13268 // declaration is the name of a constructor in this class, not in the
13269 // base class.
13270 DeclarationNameInfo UsingName = NameInfo;
13272 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13273 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13274 Context.getCanonicalTagType(RD)));
13275
13276 // Do the redeclaration lookup in the current scope.
13277 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13279 Previous.setHideTags(false);
13280 if (S) {
13281 LookupName(Previous, S);
13282
13284 } else {
13285 assert(IsInstantiation && "no scope in non-instantiation");
13286 if (CurContext->isRecord())
13288 else {
13289 // No redeclaration check is needed here; in non-member contexts we
13290 // diagnosed all possible conflicts with other using-declarations when
13291 // building the template:
13292 //
13293 // For a dependent non-type using declaration, the only valid case is
13294 // if we instantiate to a single enumerator. We check for conflicts
13295 // between shadow declarations we introduce, and we check in the template
13296 // definition for conflicts between a non-type using declaration and any
13297 // other declaration, which together covers all cases.
13298 //
13299 // A dependent typename using declaration will never successfully
13300 // instantiate, since it will always name a class member, so we reject
13301 // that in the template definition.
13302 }
13303 }
13304
13305 // Check for invalid redeclarations.
13306 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13307 SS, IdentLoc, Previous))
13308 return nullptr;
13309
13310 // 'using_if_exists' doesn't make sense on an inherited constructor.
13311 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13313 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13314 return nullptr;
13315 }
13316
13317 DeclContext *LookupContext = computeDeclContext(SS);
13319 if (!LookupContext || EllipsisLoc.isValid()) {
13320 NamedDecl *D;
13321 // Dependent scope, or an unexpanded pack
13322 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13323 SS, NameInfo, IdentLoc))
13324 return nullptr;
13325
13326 if (Previous.isSingleResult() &&
13327 Previous.getFoundDecl()->isTemplateParameter())
13328 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13329
13330 if (HasTypenameKeyword) {
13331 // FIXME: not all declaration name kinds are legal here
13333 UsingLoc, TypenameLoc,
13334 QualifierLoc,
13335 IdentLoc, NameInfo.getName(),
13336 EllipsisLoc);
13337 } else {
13339 QualifierLoc, NameInfo, EllipsisLoc);
13340 }
13341 D->setAccess(AS);
13342 CurContext->addDecl(D);
13343 ProcessDeclAttributeList(S, D, AttrList);
13344 return D;
13345 }
13346
13347 auto Build = [&](bool Invalid) {
13348 UsingDecl *UD =
13349 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13350 UsingName, HasTypenameKeyword);
13351 UD->setAccess(AS);
13352 CurContext->addDecl(UD);
13353 ProcessDeclAttributeList(S, UD, AttrList);
13355 return UD;
13356 };
13357 auto BuildInvalid = [&]{ return Build(true); };
13358 auto BuildValid = [&]{ return Build(false); };
13359
13360 if (RequireCompleteDeclContext(SS, LookupContext))
13361 return BuildInvalid();
13362
13363 // Look up the target name.
13364 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13365
13366 // Unlike most lookups, we don't always want to hide tag
13367 // declarations: tag names are visible through the using declaration
13368 // even if hidden by ordinary names, *except* in a dependent context
13369 // where they may be used by two-phase lookup.
13370 if (!IsInstantiation)
13371 R.setHideTags(false);
13372
13373 // For the purposes of this lookup, we have a base object type
13374 // equal to that of the current context.
13375 if (CurContext->isRecord()) {
13376 R.setBaseObjectType(
13377 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13378 }
13379
13380 LookupQualifiedName(R, LookupContext);
13381
13382 // Validate the context, now we have a lookup
13383 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13384 IdentLoc, &R))
13385 return nullptr;
13386
13387 if (R.empty() && IsUsingIfExists)
13389 UsingName.getName()),
13390 AS_public);
13391
13392 // Try to correct typos if possible. If constructor name lookup finds no
13393 // results, that means the named class has no explicit constructors, and we
13394 // suppressed declaring implicit ones (probably because it's dependent or
13395 // invalid).
13396 if (R.empty() &&
13398 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13399 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13400 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13401 auto *II = NameInfo.getName().getAsIdentifierInfo();
13402 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13403 CurContext->isStdNamespace() &&
13404 isa<TranslationUnitDecl>(LookupContext) &&
13405 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13406 getSourceManager().isInSystemHeader(UsingLoc))
13407 return nullptr;
13408 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13409 dyn_cast<CXXRecordDecl>(CurContext));
13410 if (TypoCorrection Corrected =
13411 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13413 // We reject candidates where DroppedSpecifier == true, hence the
13414 // literal '0' below.
13415 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13416 << NameInfo.getName() << LookupContext << 0
13417 << SS.getRange());
13418
13419 // If we picked a correction with no attached Decl we can't do anything
13420 // useful with it, bail out.
13421 NamedDecl *ND = Corrected.getCorrectionDecl();
13422 if (!ND)
13423 return BuildInvalid();
13424
13425 // If we corrected to an inheriting constructor, handle it as one.
13426 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13427 if (RD && RD->isInjectedClassName()) {
13428 // The parent of the injected class name is the class itself.
13429 RD = cast<CXXRecordDecl>(RD->getParent());
13430
13431 // Fix up the information we'll use to build the using declaration.
13432 if (Corrected.WillReplaceSpecifier()) {
13434 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13435 QualifierLoc.getSourceRange());
13436 QualifierLoc = Builder.getWithLocInContext(Context);
13437 }
13438
13439 // In this case, the name we introduce is the name of a derived class
13440 // constructor.
13441 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13442 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13443 Context.getCanonicalTagType(CurClass)));
13444 UsingName.setNamedTypeInfo(nullptr);
13445 for (auto *Ctor : LookupConstructors(RD))
13446 R.addDecl(Ctor);
13447 R.resolveKind();
13448 } else {
13449 // FIXME: Pick up all the declarations if we found an overloaded
13450 // function.
13451 UsingName.setName(ND->getDeclName());
13452 R.addDecl(ND);
13453 }
13454 } else {
13455 Diag(IdentLoc, diag::err_no_member)
13456 << NameInfo.getName() << LookupContext << SS.getRange();
13457 return BuildInvalid();
13458 }
13459 }
13460
13461 if (R.isAmbiguous())
13462 return BuildInvalid();
13463
13464 if (HasTypenameKeyword) {
13465 // If we asked for a typename and got a non-type decl, error out.
13466 if (!R.getAsSingle<TypeDecl>() &&
13467 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13468 Diag(IdentLoc, diag::err_using_typename_non_type);
13469 for (const NamedDecl *D : R)
13470 Diag(D->getUnderlyingDecl()->getLocation(),
13471 diag::note_using_decl_target);
13472 return BuildInvalid();
13473 }
13474 } else {
13475 // If we asked for a non-typename and we got a type, error out,
13476 // but only if this is an instantiation of an unresolved using
13477 // decl. Otherwise just silently find the type name.
13478 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13479 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13480 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13481 return BuildInvalid();
13482 }
13483 }
13484
13485 // C++14 [namespace.udecl]p6:
13486 // A using-declaration shall not name a namespace.
13487 if (R.getAsSingle<NamespaceDecl>()) {
13488 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13489 << SS.getRange();
13490 // Suggest using 'using namespace ...' instead.
13491 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13492 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13493 return BuildInvalid();
13494 }
13495
13496 UsingDecl *UD = BuildValid();
13497
13498 // Some additional rules apply to inheriting constructors.
13499 if (UsingName.getName().getNameKind() ==
13501 // Suppress access diagnostics; the access check is instead performed at the
13502 // point of use for an inheriting constructor.
13503 R.suppressDiagnostics();
13505 return UD;
13506 }
13507
13508 for (NamedDecl *D : R) {
13509 UsingShadowDecl *PrevDecl = nullptr;
13510 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13511 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13512 }
13513
13514 return UD;
13515}
13516
13518 SourceLocation UsingLoc,
13519 SourceLocation EnumLoc,
13520 SourceLocation NameLoc,
13521 TypeSourceInfo *EnumType,
13522 EnumDecl *ED) {
13523 bool Invalid = false;
13524
13525 if (CurContext->getRedeclContext()->isRecord()) {
13526 /// In class scope, check if this is a duplicate, for better a diagnostic.
13527 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13528 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13530
13532
13533 for (NamedDecl *D : Previous)
13534 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13535 if (UED->getEnumDecl() == ED) {
13536 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13537 << SourceRange(EnumLoc, NameLoc);
13538 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13539 Invalid = true;
13540 break;
13541 }
13542 }
13543
13544 if (RequireCompleteEnumDecl(ED, NameLoc))
13545 Invalid = true;
13546
13548 EnumLoc, NameLoc, EnumType);
13549 UD->setAccess(AS);
13550 CurContext->addDecl(UD);
13551
13552 if (Invalid) {
13553 UD->setInvalidDecl();
13554 return UD;
13555 }
13556
13557 // Create the shadow decls for each enumerator
13558 for (EnumConstantDecl *EC : ED->enumerators()) {
13559 UsingShadowDecl *PrevDecl = nullptr;
13560 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13563 LookupName(Previous, S);
13565
13566 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13567 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13568 }
13569
13570 return UD;
13571}
13572
13574 ArrayRef<NamedDecl *> Expansions) {
13575 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13576 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13577 isa<UsingPackDecl>(InstantiatedFrom));
13578
13579 auto *UPD =
13580 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13581 UPD->setAccess(InstantiatedFrom->getAccess());
13582 CurContext->addDecl(UPD);
13583 return UPD;
13584}
13585
13587 assert(!UD->hasTypename() && "expecting a constructor name");
13588
13589 QualType SourceType(UD->getQualifier().getAsType(), 0);
13591
13592 // Check whether the named type is a direct base class.
13593 bool AnyDependentBases = false;
13594 auto *Base =
13595 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13596 if (!Base && !AnyDependentBases) {
13597 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13598 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13599 UD->setInvalidDecl();
13600 return true;
13601 }
13602
13603 if (Base)
13604 Base->setInheritConstructors();
13605
13606 return false;
13607}
13608
13610 bool HasTypenameKeyword,
13611 const CXXScopeSpec &SS,
13612 SourceLocation NameLoc,
13613 const LookupResult &Prev) {
13614 NestedNameSpecifier Qual = SS.getScopeRep();
13615
13616 // C++03 [namespace.udecl]p8:
13617 // C++0x [namespace.udecl]p10:
13618 // A using-declaration is a declaration and can therefore be used
13619 // repeatedly where (and only where) multiple declarations are
13620 // allowed.
13621 //
13622 // That's in non-member contexts.
13623 if (!CurContext->getRedeclContext()->isRecord()) {
13624 // A dependent qualifier outside a class can only ever resolve to an
13625 // enumeration type. Therefore it conflicts with any other non-type
13626 // declaration in the same scope.
13627 // FIXME: How should we check for dependent type-type conflicts at block
13628 // scope?
13629 if (Qual.isDependent() && !HasTypenameKeyword) {
13630 for (auto *D : Prev) {
13631 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13632 bool OldCouldBeEnumerator =
13634 Diag(NameLoc,
13635 OldCouldBeEnumerator ? diag::err_redefinition
13636 : diag::err_redefinition_different_kind)
13637 << Prev.getLookupName();
13638 Diag(D->getLocation(), diag::note_previous_definition);
13639 return true;
13640 }
13641 }
13642 }
13643 return false;
13644 }
13645
13646 NestedNameSpecifier CNNS = Qual.getCanonical();
13647 for (const NamedDecl *D : Prev) {
13648 bool DTypename;
13649 NestedNameSpecifier DQual = std::nullopt;
13650 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13651 DTypename = UD->hasTypename();
13652 DQual = UD->getQualifier();
13653 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13654 DTypename = false;
13655 DQual = UD->getQualifier();
13656 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13657 DTypename = true;
13658 DQual = UD->getQualifier();
13659 } else
13660 continue;
13661
13662 // using decls differ if one says 'typename' and the other doesn't.
13663 // FIXME: non-dependent using decls?
13664 if (HasTypenameKeyword != DTypename) continue;
13665
13666 // using decls differ if they name different scopes (but note that
13667 // template instantiation can cause this check to trigger when it
13668 // didn't before instantiation).
13669 if (CNNS != DQual.getCanonical())
13670 continue;
13671
13672 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13673 Diag(D->getLocation(), diag::note_using_decl) << 1;
13674 return true;
13675 }
13676
13677 return false;
13678}
13679
13680bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13681 const CXXScopeSpec &SS,
13682 const DeclarationNameInfo &NameInfo,
13683 SourceLocation NameLoc,
13684 const LookupResult *R, const UsingDecl *UD) {
13685 DeclContext *NamedContext = computeDeclContext(SS);
13686 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13687 "resolvable context must have exactly one set of decls");
13688
13689 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13690 // relationship.
13691 bool Cxx20Enumerator = false;
13692 if (NamedContext) {
13693 EnumConstantDecl *EC = nullptr;
13694 if (R)
13695 EC = R->getAsSingle<EnumConstantDecl>();
13696 else if (UD && UD->shadow_size() == 1)
13697 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13698 if (EC)
13699 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13700
13701 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13702 // C++14 [namespace.udecl]p7:
13703 // A using-declaration shall not name a scoped enumerator.
13704 // C++20 p1099 permits enumerators.
13705 if (EC && R && ED->isScoped())
13706 DiagCompat(SS.getBeginLoc(), diag_compat::using_decl_scoped_enumerator)
13707 << SS.getRange();
13708
13709 // We want to consider the scope of the enumerator
13710 NamedContext = ED->getDeclContext();
13711 }
13712 }
13713
13714 if (!CurContext->isRecord()) {
13715 // C++03 [namespace.udecl]p3:
13716 // C++0x [namespace.udecl]p8:
13717 // A using-declaration for a class member shall be a member-declaration.
13718 // C++20 [namespace.udecl]p7
13719 // ... other than an enumerator ...
13720
13721 // If we weren't able to compute a valid scope, it might validly be a
13722 // dependent class or enumeration scope. If we have a 'typename' keyword,
13723 // the scope must resolve to a class type.
13724 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13725 : !HasTypename)
13726 return false; // OK
13727
13728 Diag(NameLoc,
13729 Cxx20Enumerator
13730 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13731 : diag::err_using_decl_can_not_refer_to_class_member)
13732 << SS.getRange();
13733
13734 if (Cxx20Enumerator)
13735 return false; // OK
13736
13737 auto *RD = NamedContext
13738 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13739 : nullptr;
13740 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13741 // See if there's a helpful fixit
13742
13743 if (!R) {
13744 // We will have already diagnosed the problem on the template
13745 // definition, Maybe we should do so again?
13746 } else if (R->getAsSingle<TypeDecl>()) {
13747 if (getLangOpts().CPlusPlus11) {
13748 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13749 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13750 << diag::MemClassWorkaround::AliasDecl
13752 NameInfo.getName().getAsString() +
13753 " = ");
13754 } else {
13755 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13756 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13757 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13758 << diag::MemClassWorkaround::TypedefDecl
13759 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13761 InsertLoc, " " + NameInfo.getName().getAsString());
13762 }
13763 } else if (R->getAsSingle<VarDecl>()) {
13764 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13765 // repeating the type of the static data member here.
13766 FixItHint FixIt;
13767 if (getLangOpts().CPlusPlus11) {
13768 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13770 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13771 }
13772
13773 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13774 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13775 } else if (R->getAsSingle<EnumConstantDecl>()) {
13776 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13777 // repeating the type of the enumeration here, and we can't do so if
13778 // the type is anonymous.
13779 FixItHint FixIt;
13780 if (getLangOpts().CPlusPlus11) {
13781 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13783 UsingLoc,
13784 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13785 }
13786
13787 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13788 << (getLangOpts().CPlusPlus11
13789 ? diag::MemClassWorkaround::ConstexprVar
13790 : diag::MemClassWorkaround::ConstVar)
13791 << FixIt;
13792 }
13793 }
13794
13795 return true; // Fail
13796 }
13797
13798 // If the named context is dependent, we can't decide much.
13799 if (!NamedContext) {
13800 // FIXME: in C++0x, we can diagnose if we can prove that the
13801 // nested-name-specifier does not refer to a base class, which is
13802 // still possible in some cases.
13803
13804 // Otherwise we have to conservatively report that things might be
13805 // okay.
13806 return false;
13807 }
13808
13809 // The current scope is a record.
13810 if (!NamedContext->isRecord()) {
13811 // Ideally this would point at the last name in the specifier,
13812 // but we don't have that level of source info.
13813 Diag(SS.getBeginLoc(),
13814 Cxx20Enumerator
13815 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13816 : diag::err_using_decl_nested_name_specifier_is_not_class)
13817 << SS.getScopeRep() << SS.getRange();
13818
13819 if (Cxx20Enumerator)
13820 return false; // OK
13821
13822 return true;
13823 }
13824
13825 if (!NamedContext->isDependentContext() &&
13826 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13827 return true;
13828
13829 // C++26 [namespace.udecl]p3:
13830 // In a using-declaration used as a member-declaration, each
13831 // using-declarator shall either name an enumerator or have a
13832 // nested-name-specifier naming a base class of the current class
13833 // ([expr.prim.this]). ...
13834 // "have a nested-name-specifier naming a base class of the current class"
13835 // was introduced by CWG400.
13836
13839
13840 if (Cxx20Enumerator) {
13841 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13842 << SS.getScopeRep() << SS.getRange();
13843 return false;
13844 }
13845
13846 if (CurContext == NamedContext) {
13847 Diag(SS.getBeginLoc(),
13848 diag::err_using_decl_nested_name_specifier_is_current_class)
13849 << SS.getRange();
13850 return true;
13851 }
13852
13853 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13854 Diag(SS.getBeginLoc(),
13855 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13857 << SS.getRange();
13858 }
13859 return true;
13860 }
13861
13862 return false;
13863}
13864
13866 MultiTemplateParamsArg TemplateParamLists,
13867 SourceLocation UsingLoc, UnqualifiedId &Name,
13868 const ParsedAttributesView &AttrList,
13869 TypeResult Type, Decl *DeclFromDeclSpec) {
13870
13871 if (Type.isInvalid())
13872 return nullptr;
13873
13874 bool Invalid = false;
13876 TypeSourceInfo *TInfo = nullptr;
13877 GetTypeFromParser(Type.get(), &TInfo);
13878
13879 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13880 return nullptr;
13881
13884 Invalid = true;
13885 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13886 TInfo->getTypeLoc().getBeginLoc());
13887 }
13888
13889 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13890 TemplateParamLists.size()
13893 LookupName(Previous, S);
13894
13895 // Warn about shadowing the name of a template parameter.
13896 if (Previous.isSingleResult() &&
13897 Previous.getFoundDecl()->isTemplateParameter()) {
13899 Previous.clear();
13900 }
13901
13902 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13903 "name in alias declaration must be an identifier");
13905 Name.StartLocation,
13906 Name.Identifier, TInfo);
13907
13908 NewTD->setAccess(AS);
13909
13910 if (Invalid)
13911 NewTD->setInvalidDecl();
13912
13913 ProcessDeclAttributeList(S, NewTD, AttrList);
13914 AddPragmaAttributes(S, NewTD);
13915 ProcessAPINotes(NewTD);
13916
13918 Invalid |= NewTD->isInvalidDecl();
13919
13920 // Get the innermost enclosing declaration scope.
13921 S = S->getDeclParent();
13922
13923 bool Redeclaration = false;
13924
13925 NamedDecl *NewND;
13926 if (TemplateParamLists.size()) {
13927 TypeAliasTemplateDecl *OldDecl = nullptr;
13928 TemplateParameterList *OldTemplateParams = nullptr;
13929
13930 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13931 if (TemplateParamLists.size() != 1) {
13932 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13933 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13934 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13935 Invalid = true;
13936
13937 // Recover by picking the last non-empty template parameter list.
13938 auto It = llvm::find_if(
13939 llvm::reverse(TemplateParamLists),
13940 [](TemplateParameterList *TPL) { return !TPL->empty(); });
13941 assert(It != TemplateParamLists.rend() &&
13942 "if all template parameter lists were empty, this should have "
13943 "been rejected as an explicit specialization");
13944 TemplateParams = *It;
13945 }
13946
13947 // Check that we can declare a template here.
13948 if (CheckTemplateDeclScope(S, TemplateParams))
13949 return nullptr;
13950
13951 // Only consider previous declarations in the same scope.
13952 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13953 /*ExplicitInstantiationOrSpecialization*/false);
13954 if (!Previous.empty()) {
13955 Redeclaration = true;
13956
13957 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13958 if (!OldDecl && !Invalid) {
13959 Diag(UsingLoc, diag::err_redefinition_different_kind)
13960 << Name.Identifier;
13961
13962 NamedDecl *OldD = Previous.getRepresentativeDecl();
13963 if (OldD->getLocation().isValid())
13964 Diag(OldD->getLocation(), diag::note_previous_definition);
13965
13966 Invalid = true;
13967 }
13968
13969 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13970 if (TemplateParameterListsAreEqual(TemplateParams,
13971 OldDecl->getTemplateParameters(),
13972 /*Complain=*/true,
13974 OldTemplateParams =
13976 else
13977 Invalid = true;
13978
13979 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13980 if (!Invalid &&
13981 !Context.hasSameType(OldTD->getUnderlyingType(),
13982 NewTD->getUnderlyingType())) {
13983 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13984 // but we can't reasonably accept it.
13985 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13986 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13987 if (OldTD->getLocation().isValid())
13988 Diag(OldTD->getLocation(), diag::note_previous_definition);
13989 Invalid = true;
13990 }
13991 }
13992 }
13993
13994 // Merge any previous default template arguments into our parameters,
13995 // and check the parameter list.
13996 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13997 TPC_Other))
13998 return nullptr;
13999
14000 TypeAliasTemplateDecl *NewDecl =
14002 Name.Identifier, TemplateParams,
14003 NewTD);
14004 NewTD->setDescribedAliasTemplate(NewDecl);
14005
14006 NewDecl->setAccess(AS);
14007
14008 if (Invalid)
14009 NewDecl->setInvalidDecl();
14010 else if (OldDecl) {
14011 NewDecl->setPreviousDecl(OldDecl);
14012 CheckRedeclarationInModule(NewDecl, OldDecl);
14013 }
14014
14015 NewND = NewDecl;
14016 } else {
14017 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
14019 handleTagNumbering(TD, S);
14020 }
14022 NewND = NewTD;
14023 }
14024
14025 PushOnScopeChains(NewND, S);
14026 ActOnDocumentableDecl(NewND);
14027 return NewND;
14028}
14029
14031 SourceLocation AliasLoc,
14032 IdentifierInfo *Alias, CXXScopeSpec &SS,
14033 SourceLocation IdentLoc,
14034 IdentifierInfo *Ident) {
14035
14036 // Lookup the namespace name.
14037 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14038 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14039
14040 if (R.isAmbiguous())
14041 return nullptr;
14042
14043 if (R.empty()) {
14044 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14045 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14046 return nullptr;
14047 }
14048 }
14049 assert(!R.isAmbiguous() && !R.empty());
14050 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14051
14052 // Check if we have a previous declaration with the same name.
14053 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14055 LookupName(PrevR, S);
14056
14057 // Check we're not shadowing a template parameter.
14058 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14060 PrevR.clear();
14061 }
14062
14063 // Filter out any other lookup result from an enclosing scope.
14064 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14065 /*AllowInlineNamespace*/false);
14066
14067 // Find the previous declaration and check that we can redeclare it.
14068 NamespaceAliasDecl *Prev = nullptr;
14069 if (PrevR.isSingleResult()) {
14070 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14071 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14072 // We already have an alias with the same name that points to the same
14073 // namespace; check that it matches.
14074 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14075 Prev = AD;
14076 } else if (isVisible(PrevDecl)) {
14077 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14078 << Alias;
14079 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14080 << AD->getNamespace();
14081 return nullptr;
14082 }
14083 } else if (isVisible(PrevDecl)) {
14084 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14085 ? diag::err_redefinition
14086 : diag::err_redefinition_different_kind;
14087 Diag(AliasLoc, DiagID) << Alias;
14088 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14089 return nullptr;
14090 }
14091 }
14092
14093 // The use of a nested name specifier may trigger deprecation warnings.
14094 DiagnoseUseOfDecl(ND, IdentLoc);
14095
14097 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14098 Alias, SS.getWithLocInContext(Context),
14099 IdentLoc, ND);
14100 if (Prev)
14101 AliasDecl->setPreviousDecl(Prev);
14102
14104 return AliasDecl;
14105}
14106
14107namespace {
14108struct SpecialMemberExceptionSpecInfo
14109 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14110 SourceLocation Loc;
14112
14113 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14116 SourceLocation Loc)
14117 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14118
14119 bool visitBase(CXXBaseSpecifier *Base);
14120 bool visitField(FieldDecl *FD);
14121
14122 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14123 unsigned Quals);
14124
14125 void visitSubobjectCall(Subobject Subobj,
14127};
14128}
14129
14130bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14131 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14132 if (!BaseClass)
14133 return false;
14134
14135 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14136 if (auto *BaseCtor = SMOR.getMethod()) {
14137 visitSubobjectCall(Base, BaseCtor);
14138 return false;
14139 }
14140
14141 visitClassSubobject(BaseClass, Base, 0);
14142 return false;
14143}
14144
14145bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14146 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14147 FD->hasInClassInitializer()) {
14148 Expr *E = FD->getInClassInitializer();
14149 if (!E)
14150 // FIXME: It's a little wasteful to build and throw away a
14151 // CXXDefaultInitExpr here.
14152 // FIXME: We should have a single context note pointing at Loc, and
14153 // this location should be MD->getLocation() instead, since that's
14154 // the location where we actually use the default init expression.
14155 E = S.BuildCXXCtorDefaultInitExpr(Loc, FD).get();
14156 if (E)
14157 ExceptSpec.CalledExpr(E);
14158 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14159 ->getAsCXXRecordDecl()) {
14160 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14161 }
14162 return false;
14163}
14164
14165void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14166 Subobject Subobj,
14167 unsigned Quals) {
14168 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14169 bool IsMutable = Field && Field->isMutable();
14170 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14171}
14172
14173void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14174 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14175 // Note, if lookup fails, it doesn't matter what exception specification we
14176 // choose because the special member will be deleted.
14177 if (CXXMethodDecl *MD = SMOR.getMethod())
14178 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14179}
14180
14182 llvm::APSInt Result;
14184 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14185 ExplicitSpec.setExpr(Converted.get());
14186 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14187 ExplicitSpec.setKind(Result.getBoolValue()
14190 return true;
14191 }
14193 return false;
14194}
14195
14198 if (!ExplicitExpr->isTypeDependent())
14200 return ES;
14201}
14202
14207 ComputingExceptionSpec CES(S, MD, Loc);
14208
14209 CXXRecordDecl *ClassDecl = MD->getParent();
14210
14211 // C++ [except.spec]p14:
14212 // An implicitly declared special member function (Clause 12) shall have an
14213 // exception-specification. [...]
14214 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14215 if (ClassDecl->isInvalidDecl())
14216 return Info.ExceptSpec;
14217
14218 // FIXME: If this diagnostic fires, we're probably missing a check for
14219 // attempting to resolve an exception specification before it's known
14220 // at a higher level.
14221 if (S.RequireCompleteType(MD->getLocation(),
14222 S.Context.getCanonicalTagType(ClassDecl),
14223 diag::err_exception_spec_incomplete_type))
14224 return Info.ExceptSpec;
14225
14226 // C++1z [except.spec]p7:
14227 // [Look for exceptions thrown by] a constructor selected [...] to
14228 // initialize a potentially constructed subobject,
14229 // C++1z [except.spec]p8:
14230 // The exception specification for an implicitly-declared destructor, or a
14231 // destructor without a noexcept-specifier, is potentially-throwing if and
14232 // only if any of the destructors for any of its potentially constructed
14233 // subojects is potentially throwing.
14234 // FIXME: We respect the first rule but ignore the "potentially constructed"
14235 // in the second rule to resolve a core issue (no number yet) that would have
14236 // us reject:
14237 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14238 // struct B : A {};
14239 // struct C : B { void f(); };
14240 // ... due to giving B::~B() a non-throwing exception specification.
14241 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14242 : Info.VisitAllBases);
14243
14244 return Info.ExceptSpec;
14245}
14246
14247namespace {
14248/// RAII object to register a special member as being currently declared.
14249struct DeclaringSpecialMember {
14250 Sema &S;
14252 Sema::ContextRAII SavedContext;
14253 bool WasAlreadyBeingDeclared;
14254
14255 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14256 : S(S), D(RD, CSM), SavedContext(S, RD) {
14257 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14258 if (WasAlreadyBeingDeclared)
14259 // This almost never happens, but if it does, ensure that our cache
14260 // doesn't contain a stale result.
14261 S.SpecialMemberCache.clear();
14262 else {
14263 // Register a note to be produced if we encounter an error while
14264 // declaring the special member.
14265 Sema::CodeSynthesisContext Ctx;
14266 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14267 // FIXME: We don't have a location to use here. Using the class's
14268 // location maintains the fiction that we declare all special members
14269 // with the class, but (1) it's not clear that lying about that helps our
14270 // users understand what's going on, and (2) there may be outer contexts
14271 // on the stack (some of which are relevant) and printing them exposes
14272 // our lies.
14273 Ctx.PointOfInstantiation = RD->getLocation();
14274 Ctx.Entity = RD;
14275 Ctx.SpecialMember = CSM;
14276 S.pushCodeSynthesisContext(Ctx);
14277 }
14278 }
14279 ~DeclaringSpecialMember() {
14280 if (!WasAlreadyBeingDeclared) {
14281 S.SpecialMembersBeingDeclared.erase(D);
14283 }
14284 }
14285
14286 /// Are we already trying to declare this special member?
14287 bool isAlreadyBeingDeclared() const {
14288 return WasAlreadyBeingDeclared;
14289 }
14290};
14291}
14292
14294 // Look up any existing declarations, but don't trigger declaration of all
14295 // implicit special members with this name.
14296 DeclarationName Name = FD->getDeclName();
14299 for (auto *D : FD->getParent()->lookup(Name))
14300 if (auto *Acceptable = R.getAcceptableDecl(D))
14301 R.addDecl(Acceptable);
14302 R.resolveKind();
14303 R.suppressDiagnostics();
14304
14305 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14307}
14308
14309void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14310 QualType ResultTy,
14311 ArrayRef<QualType> Args) {
14312 // Build an exception specification pointing back at this constructor.
14314
14315 LangAS AS = getDefaultCXXMethodAddrSpace();
14316 if (AS != LangAS::Default) {
14317 EPI.TypeQuals.addAddressSpace(AS);
14318 }
14319
14320 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14321 SpecialMem->setType(QT);
14322
14323 // During template instantiation of implicit special member functions we need
14324 // a reliable TypeSourceInfo for the function prototype in order to allow
14325 // functions to be substituted.
14326 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14327 TypeSourceInfo *TSI =
14328 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14329 SpecialMem->setTypeSourceInfo(TSI);
14330 }
14331}
14332
14334 CXXRecordDecl *ClassDecl) {
14335 // C++ [class.ctor]p5:
14336 // A default constructor for a class X is a constructor of class X
14337 // that can be called without an argument. If there is no
14338 // user-declared constructor for class X, a default constructor is
14339 // implicitly declared. An implicitly-declared default constructor
14340 // is an inline public member of its class.
14341 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14342 "Should not build implicit default constructor!");
14343
14344 DeclaringSpecialMember DSM(*this, ClassDecl,
14346 if (DSM.isAlreadyBeingDeclared())
14347 return nullptr;
14348
14350 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14351
14352 // Create the actual constructor declaration.
14353 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14354 SourceLocation ClassLoc = ClassDecl->getLocation();
14355 DeclarationName Name
14356 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14357 DeclarationNameInfo NameInfo(Name, ClassLoc);
14359 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14360 /*TInfo=*/nullptr, ExplicitSpecifier(),
14361 getCurFPFeatures().isFPConstrained(),
14362 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14365 DefaultCon->setAccess(AS_public);
14366 DefaultCon->setDefaulted();
14367
14368 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14369
14370 if (getLangOpts().CUDA)
14371 CUDA().inferTargetForImplicitSpecialMember(
14372 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14373 /* ConstRHS */ false,
14374 /* Diagnose */ false);
14375
14376 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14377 // constructors is easy to compute.
14378 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14379
14380 // Note that we have declared this constructor.
14381 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14382
14383 Scope *S = getScopeForContext(ClassDecl);
14385
14386 if (ShouldDeleteSpecialMember(DefaultCon,
14388 SetDeclDeleted(DefaultCon, ClassLoc);
14389
14390 if (S)
14391 PushOnScopeChains(DefaultCon, S, false);
14392 ClassDecl->addDecl(DefaultCon);
14393
14394 return DefaultCon;
14395}
14396
14399 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14400 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14401 !Constructor->doesThisDeclarationHaveABody() &&
14402 !Constructor->isDeleted()) &&
14403 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14404 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14405 return;
14406
14407 CXXRecordDecl *ClassDecl = Constructor->getParent();
14408 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14409 if (ClassDecl->isInvalidDecl()) {
14410 return;
14411 }
14412
14414
14415 // The exception specification is needed because we are defining the
14416 // function.
14417 ResolveExceptionSpec(CurrentLocation,
14418 Constructor->getType()->castAs<FunctionProtoType>());
14419 MarkVTableUsed(CurrentLocation, ClassDecl);
14420
14421 // Add a context note for diagnostics produced after this point.
14422 Scope.addContextNote(CurrentLocation);
14423
14424 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14425 Constructor->setInvalidDecl();
14426 return;
14427 }
14428
14429 SourceLocation Loc = Constructor->getEndLoc().isValid()
14430 ? Constructor->getEndLoc()
14431 : Constructor->getLocation();
14432 Constructor->setBody(new (Context) CompoundStmt(Loc));
14433 Constructor->markUsed(Context);
14434
14436 L->CompletedImplicitDefinition(Constructor);
14437 }
14438
14439 DiagnoseUninitializedFields(*this, Constructor);
14440
14441 // The synthesized body applies the class's NSDMIs and never reaches the
14442 // normal IssueWarnings path, so run lifetime safety on it here.
14443 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14444}
14445
14447 // Perform any delayed checks on exception specifications.
14449}
14450
14451/// Find or create the fake constructor we synthesize to model constructing an
14452/// object of a derived class via a constructor of a base class.
14455 CXXConstructorDecl *BaseCtor,
14457 CXXRecordDecl *Derived = Shadow->getParent();
14458 SourceLocation UsingLoc = Shadow->getLocation();
14459
14460 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14461 // For now we use the name of the base class constructor as a member of the
14462 // derived class to indicate a (fake) inherited constructor name.
14463 DeclarationName Name = BaseCtor->getDeclName();
14464
14465 // Check to see if we already have a fake constructor for this inherited
14466 // constructor call.
14467 for (NamedDecl *Ctor : Derived->lookup(Name))
14469 ->getInheritedConstructor()
14470 .getConstructor(),
14471 BaseCtor))
14472 return cast<CXXConstructorDecl>(Ctor);
14473
14474 DeclarationNameInfo NameInfo(Name, UsingLoc);
14475 TypeSourceInfo *TInfo =
14476 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14477 FunctionProtoTypeLoc ProtoLoc =
14479
14480 // Check the inherited constructor is valid and find the list of base classes
14481 // from which it was inherited.
14482 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14483
14484 bool Constexpr = BaseCtor->isConstexpr() &&
14487 false, BaseCtor, &ICI);
14488
14490 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14491 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14492 /*isInline=*/true,
14493 /*isImplicitlyDeclared=*/true,
14495 InheritedConstructor(Shadow, BaseCtor),
14496 BaseCtor->getTrailingRequiresClause());
14497 if (Shadow->isInvalidDecl())
14498 DerivedCtor->setInvalidDecl();
14499
14500 // Build an unevaluated exception specification for this fake constructor.
14501 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14504 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14505 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14506 FPT->getParamTypes(), EPI));
14507
14508 // Build the parameter declarations.
14510 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14511 TypeSourceInfo *TInfo =
14512 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14514 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14515 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14516 PD->setScopeInfo(0, I);
14517 PD->setImplicit();
14518 // Ensure attributes are propagated onto parameters (this matters for
14519 // format, pass_object_size, ...).
14520 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14521 ParamDecls.push_back(PD);
14522 ProtoLoc.setParam(I, PD);
14523 }
14524
14525 // Set up the new constructor.
14526 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14527 DerivedCtor->setAccess(BaseCtor->getAccess());
14528 DerivedCtor->setParams(ParamDecls);
14529 Derived->addDecl(DerivedCtor);
14530
14531 if (ShouldDeleteSpecialMember(DerivedCtor,
14533 SetDeclDeleted(DerivedCtor, UsingLoc);
14534
14535 return DerivedCtor;
14536}
14537
14545
14548 CXXRecordDecl *ClassDecl = Constructor->getParent();
14549 assert(Constructor->getInheritedConstructor() &&
14550 !Constructor->doesThisDeclarationHaveABody() &&
14551 !Constructor->isDeleted());
14552 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14553 return;
14554
14555 // Initializations are performed "as if by a defaulted default constructor",
14556 // so enter the appropriate scope.
14558
14559 // The exception specification is needed because we are defining the
14560 // function.
14561 ResolveExceptionSpec(CurrentLocation,
14562 Constructor->getType()->castAs<FunctionProtoType>());
14563 MarkVTableUsed(CurrentLocation, ClassDecl);
14564
14565 // Add a context note for diagnostics produced after this point.
14566 Scope.addContextNote(CurrentLocation);
14567
14569 Constructor->getInheritedConstructor().getShadowDecl();
14570 CXXConstructorDecl *InheritedCtor =
14571 Constructor->getInheritedConstructor().getConstructor();
14572
14573 // [class.inhctor.init]p1:
14574 // initialization proceeds as if a defaulted default constructor is used to
14575 // initialize the D object and each base class subobject from which the
14576 // constructor was inherited
14577
14578 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14579 CXXRecordDecl *RD = Shadow->getParent();
14580 SourceLocation InitLoc = Shadow->getLocation();
14581
14582 // Build explicit initializers for all base classes from which the
14583 // constructor was inherited.
14585 for (bool VBase : {false, true}) {
14586 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14587 if (B.isVirtual() != VBase)
14588 continue;
14589
14590 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14591 if (!BaseRD)
14592 continue;
14593
14594 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14595 if (!BaseCtor.first)
14596 continue;
14597
14598 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14600 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14601
14602 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14603 Inits.push_back(new (Context) CXXCtorInitializer(
14604 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14605 SourceLocation()));
14606 }
14607 }
14608
14609 // We now proceed as if for a defaulted default constructor, with the relevant
14610 // initializers replaced.
14611
14612 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14613 Constructor->setInvalidDecl();
14614 return;
14615 }
14616
14617 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14618 Constructor->markUsed(Context);
14619
14621 L->CompletedImplicitDefinition(Constructor);
14622 }
14623
14624 DiagnoseUninitializedFields(*this, Constructor);
14625
14626 // The synthesized body applies the class's NSDMIs and never reaches the
14627 // normal IssueWarnings path, so run lifetime safety on it here.
14628 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14629}
14630
14632 // C++ [class.dtor]p2:
14633 // If a class has no user-declared destructor, a destructor is
14634 // declared implicitly. An implicitly-declared destructor is an
14635 // inline public member of its class.
14636 assert(ClassDecl->needsImplicitDestructor());
14637
14638 DeclaringSpecialMember DSM(*this, ClassDecl,
14640 if (DSM.isAlreadyBeingDeclared())
14641 return nullptr;
14642
14644 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14645
14646 // Create the actual destructor declaration.
14647 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14648 SourceLocation ClassLoc = ClassDecl->getLocation();
14649 DeclarationName Name
14650 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14651 DeclarationNameInfo NameInfo(Name, ClassLoc);
14653 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14654 getCurFPFeatures().isFPConstrained(),
14655 /*isInline=*/true,
14656 /*isImplicitlyDeclared=*/true,
14659 Destructor->setAccess(AS_public);
14660 Destructor->setDefaulted();
14661
14662 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14663
14664 if (getLangOpts().CUDA)
14665 CUDA().inferTargetForImplicitSpecialMember(
14667 /* ConstRHS */ false,
14668 /* Diagnose */ false);
14669
14670 // We don't need to use SpecialMemberIsTrivial here; triviality for
14671 // destructors is easy to compute.
14672 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14673 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14674 ClassDecl->hasTrivialDestructorForCall());
14675
14676 // Note that we have declared this destructor.
14677 ++getASTContext().NumImplicitDestructorsDeclared;
14678
14679 Scope *S = getScopeForContext(ClassDecl);
14681
14682 // We can't check whether an implicit destructor is deleted before we complete
14683 // the definition of the class, because its validity depends on the alignment
14684 // of the class. We'll check this from ActOnFields once the class is complete.
14685 if (ClassDecl->isCompleteDefinition() &&
14687 SetDeclDeleted(Destructor, ClassLoc);
14688
14689 // Introduce this destructor into its scope.
14690 if (S)
14691 PushOnScopeChains(Destructor, S, false);
14692 ClassDecl->addDecl(Destructor);
14693
14694 return Destructor;
14695}
14696
14699 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14700 assert((Destructor->isDefaulted() &&
14701 !Destructor->doesThisDeclarationHaveABody() &&
14702 !Destructor->isDeleted()) &&
14703 "DefineImplicitDestructor - call it for implicit default dtor");
14704 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14705 return;
14706
14707 CXXRecordDecl *ClassDecl = Destructor->getParent();
14708 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14709
14711
14712 // The exception specification is needed because we are defining the
14713 // function.
14714 ResolveExceptionSpec(CurrentLocation,
14715 Destructor->getType()->castAs<FunctionProtoType>());
14716 MarkVTableUsed(CurrentLocation, ClassDecl);
14717
14718 // Add a context note for diagnostics produced after this point.
14719 Scope.addContextNote(CurrentLocation);
14720
14722 Destructor->getParent());
14723
14725 Destructor->setInvalidDecl();
14726 return;
14727 }
14728
14729 SourceLocation Loc = Destructor->getEndLoc().isValid()
14730 ? Destructor->getEndLoc()
14731 : Destructor->getLocation();
14732 Destructor->setBody(new (Context) CompoundStmt(Loc));
14733 Destructor->markUsed(Context);
14734
14736 L->CompletedImplicitDefinition(Destructor);
14737 }
14738}
14739
14742 if (Destructor->isInvalidDecl())
14743 return;
14744
14745 CXXRecordDecl *ClassDecl = Destructor->getParent();
14746 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14747 "implicit complete dtors unneeded outside MS ABI");
14748 assert(ClassDecl->getNumVBases() > 0 &&
14749 "complete dtor only exists for classes with vbases");
14750
14752
14753 // Add a context note for diagnostics produced after this point.
14754 Scope.addContextNote(CurrentLocation);
14755
14756 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14757}
14758
14760 // If the context is an invalid C++ class, just suppress these checks.
14761 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14762 if (Record->isInvalidDecl()) {
14765 return;
14766 }
14768 }
14769}
14770
14773
14774 if (!DelayedDllExportMemberFunctions.empty()) {
14776 std::swap(DelayedDllExportMemberFunctions, WorkList);
14777 for (CXXMethodDecl *M : WorkList) {
14778 DefineDefaultedFunction(*this, M, M->getLocation());
14779
14780 // Pass the method to the consumer to get emitted. This is not necessary
14781 // for explicit instantiation definitions, as they will get emitted
14782 // anyway.
14783 if (M->getParent()->getTemplateSpecializationKind() !=
14786 }
14787 }
14788}
14789
14791 if (!DelayedDllExportClasses.empty()) {
14792 // Calling ReferenceDllExportedMembers might cause the current function to
14793 // be called again, so use a local copy of DelayedDllExportClasses.
14795 std::swap(DelayedDllExportClasses, WorkList);
14796 for (CXXRecordDecl *Class : WorkList)
14798 }
14799}
14800
14802 assert(getLangOpts().CPlusPlus11 &&
14803 "adjusting dtor exception specs was introduced in c++11");
14804
14805 if (Destructor->isDependentContext())
14806 return;
14807
14808 // C++11 [class.dtor]p3:
14809 // A declaration of a destructor that does not have an exception-
14810 // specification is implicitly considered to have the same exception-
14811 // specification as an implicit declaration.
14812 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14813 if (DtorType->hasExceptionSpec())
14814 return;
14815
14816 // Replace the destructor's type, building off the existing one. Fortunately,
14817 // the only thing of interest in the destructor type is its extended info.
14818 // The return and arguments are fixed.
14819 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14822 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14823
14824 // FIXME: If the destructor has a body that could throw, and the newly created
14825 // spec doesn't allow exceptions, we should emit a warning, because this
14826 // change in behavior can break conforming C++03 programs at runtime.
14827 // However, we don't have a body or an exception specification yet, so it
14828 // needs to be done somewhere else.
14829}
14830
14831namespace {
14832/// An abstract base class for all helper classes used in building the
14833// copy/move operators. These classes serve as factory functions and help us
14834// avoid using the same Expr* in the AST twice.
14835class ExprBuilder {
14836 ExprBuilder(const ExprBuilder&) = delete;
14837 ExprBuilder &operator=(const ExprBuilder&) = delete;
14838
14839protected:
14840 static Expr *assertNotNull(Expr *E) {
14841 assert(E && "Expression construction must not fail.");
14842 return E;
14843 }
14844
14845public:
14846 ExprBuilder() {}
14847 virtual ~ExprBuilder() {}
14848
14849 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14850};
14851
14852class RefBuilder: public ExprBuilder {
14853 VarDecl *Var;
14854 QualType VarType;
14855
14856public:
14857 Expr *build(Sema &S, SourceLocation Loc) const override {
14858 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14859 }
14860
14861 RefBuilder(VarDecl *Var, QualType VarType)
14862 : Var(Var), VarType(VarType) {}
14863};
14864
14865class ThisBuilder: public ExprBuilder {
14866public:
14867 Expr *build(Sema &S, SourceLocation Loc) const override {
14868 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14869 }
14870};
14871
14872class CastBuilder: public ExprBuilder {
14873 const ExprBuilder &Builder;
14874 QualType Type;
14876 const CXXCastPath &Path;
14877
14878public:
14879 Expr *build(Sema &S, SourceLocation Loc) const override {
14880 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14881 CK_UncheckedDerivedToBase, Kind,
14882 &Path).get());
14883 }
14884
14885 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14886 const CXXCastPath &Path)
14887 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14888};
14889
14890class DerefBuilder: public ExprBuilder {
14891 const ExprBuilder &Builder;
14892
14893public:
14894 Expr *build(Sema &S, SourceLocation Loc) const override {
14895 return assertNotNull(
14896 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14897 }
14898
14899 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14900};
14901
14902class MemberBuilder: public ExprBuilder {
14903 const ExprBuilder &Builder;
14904 QualType Type;
14905 CXXScopeSpec SS;
14906 bool IsArrow;
14907 LookupResult &MemberLookup;
14908
14909public:
14910 Expr *build(Sema &S, SourceLocation Loc) const override {
14911 return assertNotNull(S.BuildMemberReferenceExpr(
14912 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14913 nullptr, MemberLookup, nullptr, nullptr).get());
14914 }
14915
14916 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14917 LookupResult &MemberLookup)
14918 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14919 MemberLookup(MemberLookup) {}
14920};
14921
14922class MoveCastBuilder: public ExprBuilder {
14923 const ExprBuilder &Builder;
14924
14925public:
14926 Expr *build(Sema &S, SourceLocation Loc) const override {
14927 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14928 }
14929
14930 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14931};
14932
14933class LvalueConvBuilder: public ExprBuilder {
14934 const ExprBuilder &Builder;
14935
14936public:
14937 Expr *build(Sema &S, SourceLocation Loc) const override {
14938 return assertNotNull(
14939 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14940 }
14941
14942 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14943};
14944
14945class SubscriptBuilder: public ExprBuilder {
14946 const ExprBuilder &Base;
14947 const ExprBuilder &Index;
14948
14949public:
14950 Expr *build(Sema &S, SourceLocation Loc) const override {
14951 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14952 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14953 }
14954
14955 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14956 : Base(Base), Index(Index) {}
14957};
14958
14959} // end anonymous namespace
14960
14961/// When generating a defaulted copy or move assignment operator, if a field
14962/// should be copied with __builtin_memcpy rather than via explicit assignments,
14963/// do so. This optimization only applies for arrays of scalars, and for arrays
14964/// of class type where the selected copy/move-assignment operator is trivial.
14965static StmtResult
14967 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14968 // Compute the size of the memory buffer to be copied.
14969 QualType SizeType = S.Context.getSizeType();
14970 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14972
14973 // Take the address of the field references for "from" and "to". We
14974 // directly construct UnaryOperators here because semantic analysis
14975 // does not permit us to take the address of an xvalue.
14976 Expr *From = FromB.build(S, Loc);
14977 From = UnaryOperator::Create(
14978 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14979 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14980 Expr *To = ToB.build(S, Loc);
14982 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14983 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14984
14985 bool NeedsCollectableMemCpy = false;
14986 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14987 NeedsCollectableMemCpy = RD->hasObjectMember();
14988
14989 // Create a reference to the __builtin_objc_memmove_collectable function
14990 StringRef MemCpyName = NeedsCollectableMemCpy ?
14991 "__builtin_objc_memmove_collectable" :
14992 "__builtin_memcpy";
14993 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14995 S.LookupName(R, S.TUScope, true);
14996
14997 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14998 if (!MemCpy)
14999 // Something went horribly wrong earlier, and we will have complained
15000 // about it.
15001 return StmtError();
15002
15003 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
15004 VK_PRValue, Loc, nullptr);
15005 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
15006
15007 Expr *CallArgs[] = {
15008 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
15009 };
15010 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
15011 Loc, CallArgs, Loc);
15012
15013 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15014 return Call.getAs<Stmt>();
15015}
15016
15017/// Builds a statement that copies/moves the given entity from \p From to
15018/// \c To.
15019///
15020/// This routine is used to copy/move the members of a class with an
15021/// implicitly-declared copy/move assignment operator. When the entities being
15022/// copied are arrays, this routine builds for loops to copy them.
15023///
15024/// \param S The Sema object used for type-checking.
15025///
15026/// \param Loc The location where the implicit copy/move is being generated.
15027///
15028/// \param T The type of the expressions being copied/moved. Both expressions
15029/// must have this type.
15030///
15031/// \param To The expression we are copying/moving to.
15032///
15033/// \param From The expression we are copying/moving from.
15034///
15035/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15036/// Otherwise, it's a non-static member subobject.
15037///
15038/// \param Copying Whether we're copying or moving.
15039///
15040/// \param Depth Internal parameter recording the depth of the recursion.
15041///
15042/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15043/// if a memcpy should be used instead.
15044static StmtResult
15046 const ExprBuilder &To, const ExprBuilder &From,
15047 bool CopyingBaseSubobject, bool Copying,
15048 unsigned Depth = 0) {
15049 // C++11 [class.copy]p28:
15050 // Each subobject is assigned in the manner appropriate to its type:
15051 //
15052 // - if the subobject is of class type, as if by a call to operator= with
15053 // the subobject as the object expression and the corresponding
15054 // subobject of x as a single function argument (as if by explicit
15055 // qualification; that is, ignoring any possible virtual overriding
15056 // functions in more derived classes);
15057 //
15058 // C++03 [class.copy]p13:
15059 // - if the subobject is of class type, the copy assignment operator for
15060 // the class is used (as if by explicit qualification; that is,
15061 // ignoring any possible virtual overriding functions in more derived
15062 // classes);
15063 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15064 // Look for operator=.
15065 DeclarationName Name
15067 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15068 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15069
15070 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15071 // operator.
15072 if (!S.getLangOpts().CPlusPlus11) {
15073 LookupResult::Filter F = OpLookup.makeFilter();
15074 while (F.hasNext()) {
15075 NamedDecl *D = F.next();
15076 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15077 if (Method->isCopyAssignmentOperator() ||
15078 (!Copying && Method->isMoveAssignmentOperator()))
15079 continue;
15080
15081 F.erase();
15082 }
15083 F.done();
15084 }
15085
15086 // Suppress the protected check (C++ [class.protected]) for each of the
15087 // assignment operators we found. This strange dance is required when
15088 // we're assigning via a base classes's copy-assignment operator. To
15089 // ensure that we're getting the right base class subobject (without
15090 // ambiguities), we need to cast "this" to that subobject type; to
15091 // ensure that we don't go through the virtual call mechanism, we need
15092 // to qualify the operator= name with the base class (see below). However,
15093 // this means that if the base class has a protected copy assignment
15094 // operator, the protected member access check will fail. So, we
15095 // rewrite "protected" access to "public" access in this case, since we
15096 // know by construction that we're calling from a derived class.
15097 if (CopyingBaseSubobject) {
15098 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15099 L != LEnd; ++L) {
15100 if (L.getAccess() == AS_protected)
15101 L.setAccess(AS_public);
15102 }
15103 }
15104
15105 // Create the nested-name-specifier that will be used to qualify the
15106 // reference to operator=; this is required to suppress the virtual
15107 // call mechanism.
15108 CXXScopeSpec SS;
15109 // FIXME: Don't canonicalize this.
15110 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15111 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15112
15113 // Create the reference to operator=.
15114 ExprResult OpEqualRef
15115 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15116 SS, /*TemplateKWLoc=*/SourceLocation(),
15117 /*FirstQualifierInScope=*/nullptr,
15118 OpLookup,
15119 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15120 /*SuppressQualifierCheck=*/true);
15121 if (OpEqualRef.isInvalid())
15122 return StmtError();
15123
15124 // Build the call to the assignment operator.
15125
15126 Expr *FromInst = From.build(S, Loc);
15127 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15128 OpEqualRef.getAs<Expr>(),
15129 Loc, FromInst, Loc);
15130 if (Call.isInvalid())
15131 return StmtError();
15132
15133 // If we built a call to a trivial 'operator=' while copying an array,
15134 // bail out. We'll replace the whole shebang with a memcpy.
15135 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15136 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15137 return StmtResult((Stmt*)nullptr);
15138
15139 // Convert to an expression-statement, and clean up any produced
15140 // temporaries.
15141 return S.ActOnExprStmt(Call);
15142 }
15143
15144 // - if the subobject is of scalar type, the built-in assignment
15145 // operator is used.
15147 if (!ArrayTy) {
15149 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15150 if (Assignment.isInvalid())
15151 return StmtError();
15152 return S.ActOnExprStmt(Assignment);
15153 }
15154
15155 // - if the subobject is an array, each element is assigned, in the
15156 // manner appropriate to the element type;
15157
15158 // Construct a loop over the array bounds, e.g.,
15159 //
15160 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15161 //
15162 // that will copy each of the array elements.
15163 QualType SizeType = S.Context.getSizeType();
15164
15165 // Create the iteration variable.
15166 IdentifierInfo *IterationVarName = nullptr;
15167 {
15168 SmallString<8> Str;
15169 llvm::raw_svector_ostream OS(Str);
15170 OS << "__i" << Depth;
15171 IterationVarName = &S.Context.Idents.get(OS.str());
15172 }
15173 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15174 IterationVarName, SizeType,
15175 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15176 SC_None);
15177
15178 // Initialize the iteration variable to zero.
15179 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15180 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15181
15182 // Creates a reference to the iteration variable.
15183 RefBuilder IterationVarRef(IterationVar, SizeType);
15184 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15185
15186 // Create the DeclStmt that holds the iteration variable.
15187 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15188
15189 // Subscript the "from" and "to" expressions with the iteration variable.
15190 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15191 MoveCastBuilder FromIndexMove(FromIndexCopy);
15192 const ExprBuilder *FromIndex;
15193 if (Copying)
15194 FromIndex = &FromIndexCopy;
15195 else
15196 FromIndex = &FromIndexMove;
15197
15198 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15199
15200 // Build the copy/move for an individual element of the array.
15201 StmtResult Copy =
15203 ToIndex, *FromIndex, CopyingBaseSubobject,
15204 Copying, Depth + 1);
15205 // Bail out if copying fails or if we determined that we should use memcpy.
15206 if (Copy.isInvalid() || !Copy.get())
15207 return Copy;
15208
15209 // Create the comparison against the array bound.
15210 llvm::APInt Upper
15211 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15213 S.Context, IterationVarRefRVal.build(S, Loc),
15214 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15217
15218 // Create the pre-increment of the iteration variable. We can determine
15219 // whether the increment will overflow based on the value of the array
15220 // bound.
15221 Expr *Increment = UnaryOperator::Create(
15222 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15223 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15224
15225 // Construct the loop that copies all elements of this array.
15226 return S.ActOnForStmt(
15227 Loc, Loc, InitStmt,
15229 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15230}
15231
15232static StmtResult
15234 const ExprBuilder &To, const ExprBuilder &From,
15235 bool CopyingBaseSubobject, bool Copying) {
15236 // Maybe we should use a memcpy?
15237 if (T->isArrayType() && !T.hasQualifiers() &&
15238 T.isTriviallyCopyableType(S.Context))
15239 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15240
15241 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15242 CopyingBaseSubobject,
15243 Copying, 0));
15244
15245 // If we ended up picking a trivial assignment operator for an array of a
15246 // non-trivially-copyable class type, just emit a memcpy.
15247 if (!Result.isInvalid() && !Result.get())
15248 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15249
15250 return Result;
15251}
15252
15254 // Note: The following rules are largely analoguous to the copy
15255 // constructor rules. Note that virtual bases are not taken into account
15256 // for determining the argument type of the operator. Note also that
15257 // operators taking an object instead of a reference are allowed.
15258 assert(ClassDecl->needsImplicitCopyAssignment());
15259
15260 DeclaringSpecialMember DSM(*this, ClassDecl,
15262 if (DSM.isAlreadyBeingDeclared())
15263 return nullptr;
15264
15266 /*Qualifier=*/std::nullopt, ClassDecl,
15267 /*OwnsTag=*/false);
15269 if (AS != LangAS::Default)
15270 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15271 QualType RetType = Context.getLValueReferenceType(ArgType);
15272 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15273 if (Const)
15274 ArgType = ArgType.withConst();
15275
15276 ArgType = Context.getLValueReferenceType(ArgType);
15277
15279 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15280
15281 // An implicitly-declared copy assignment operator is an inline public
15282 // member of its class.
15283 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15284 SourceLocation ClassLoc = ClassDecl->getLocation();
15285 DeclarationNameInfo NameInfo(Name, ClassLoc);
15287 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15288 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15289 getCurFPFeatures().isFPConstrained(),
15290 /*isInline=*/true,
15292 SourceLocation());
15293 CopyAssignment->setAccess(AS_public);
15294 CopyAssignment->setDefaulted();
15295 CopyAssignment->setImplicit();
15296
15297 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15298
15299 if (getLangOpts().CUDA)
15300 CUDA().inferTargetForImplicitSpecialMember(
15302 /* ConstRHS */ Const,
15303 /* Diagnose */ false);
15304
15305 // Add the parameter to the operator.
15307 ClassLoc, ClassLoc,
15308 /*Id=*/nullptr, ArgType,
15309 /*TInfo=*/nullptr, SC_None,
15310 nullptr);
15311 CopyAssignment->setParams(FromParam);
15312
15313 CopyAssignment->setTrivial(
15317 : ClassDecl->hasTrivialCopyAssignment());
15318
15319 // Note that we have added this copy-assignment operator.
15320 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15321
15322 Scope *S = getScopeForContext(ClassDecl);
15324
15328 SetDeclDeleted(CopyAssignment, ClassLoc);
15329 }
15330
15331 if (S)
15333 ClassDecl->addDecl(CopyAssignment);
15334
15335 return CopyAssignment;
15336}
15337
15338/// Diagnose an implicit copy operation for a class which is odr-used, but
15339/// which is deprecated because the class has a user-declared copy constructor,
15340/// copy assignment operator, or destructor.
15342 assert(CopyOp->isImplicit());
15343
15344 CXXRecordDecl *RD = CopyOp->getParent();
15345 CXXMethodDecl *UserDeclaredOperation = nullptr;
15346
15347 if (RD->hasUserDeclaredDestructor()) {
15348 UserDeclaredOperation = RD->getDestructor();
15349 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15351 // Find any user-declared copy constructor.
15352 for (auto *I : RD->ctors()) {
15353 if (I->isCopyConstructor()) {
15354 UserDeclaredOperation = I;
15355 break;
15356 }
15357 }
15358 assert(UserDeclaredOperation);
15359 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15361 // Find any user-declared move assignment operator.
15362 for (auto *I : RD->methods()) {
15363 if (I->isCopyAssignmentOperator()) {
15364 UserDeclaredOperation = I;
15365 break;
15366 }
15367 }
15368 assert(UserDeclaredOperation);
15369 }
15370
15371 if (UserDeclaredOperation) {
15372 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15373 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15374 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15375 unsigned DiagID =
15376 (UDOIsUserProvided && UDOIsDestructor)
15377 ? diag::warn_deprecated_copy_with_user_provided_dtor
15378 : (UDOIsUserProvided && !UDOIsDestructor)
15379 ? diag::warn_deprecated_copy_with_user_provided_copy
15380 : (!UDOIsUserProvided && UDOIsDestructor)
15381 ? diag::warn_deprecated_copy_with_dtor
15382 : diag::warn_deprecated_copy;
15383 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15384 << RD << IsCopyAssignment;
15385 }
15386}
15387
15389 CXXMethodDecl *CopyAssignOperator) {
15390 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15391 assert((CopyAssignOperator->isDefaulted() &&
15392 CopyAssignOperator->isOverloadedOperator() &&
15393 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15394 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15395 !CopyAssignOperator->isDeleted()) &&
15396 "DefineImplicitCopyAssignment called for wrong function");
15397 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15398 return;
15399
15400 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15401 if (ClassDecl->isInvalidDecl()) {
15402 CopyAssignOperator->setInvalidDecl();
15403 return;
15404 }
15405
15406 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15407
15408 // The exception specification is needed because we are defining the
15409 // function.
15410 ResolveExceptionSpec(CurrentLocation,
15411 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15412
15413 // Add a context note for diagnostics produced after this point.
15414 Scope.addContextNote(CurrentLocation);
15415
15416 // C++11 [class.copy]p18:
15417 // The [definition of an implicitly declared copy assignment operator] is
15418 // deprecated if the class has a user-declared copy constructor or a
15419 // user-declared destructor.
15420 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15421 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15422
15423 // C++0x [class.copy]p30:
15424 // The implicitly-defined or explicitly-defaulted copy assignment operator
15425 // for a non-union class X performs memberwise copy assignment of its
15426 // subobjects. The direct base classes of X are assigned first, in the
15427 // order of their declaration in the base-specifier-list, and then the
15428 // immediate non-static data members of X are assigned, in the order in
15429 // which they were declared in the class definition.
15430
15431 // The statements that form the synthesized function body.
15432 SmallVector<Stmt*, 8> Statements;
15433
15434 // The parameter for the "other" object, which we are copying from.
15435 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15436 Qualifiers OtherQuals = Other->getType().getQualifiers();
15437 QualType OtherRefType = Other->getType();
15438 if (OtherRefType->isLValueReferenceType()) {
15439 OtherRefType = OtherRefType->getPointeeType();
15440 OtherQuals = OtherRefType.getQualifiers();
15441 }
15442
15443 // Our location for everything implicitly-generated.
15444 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15445 ? CopyAssignOperator->getEndLoc()
15446 : CopyAssignOperator->getLocation();
15447
15448 // Builds a DeclRefExpr for the "other" object.
15449 RefBuilder OtherRef(Other, OtherRefType);
15450
15451 // Builds the function object parameter.
15452 std::optional<ThisBuilder> This;
15453 std::optional<DerefBuilder> DerefThis;
15454 std::optional<RefBuilder> ExplicitObject;
15455 bool IsArrow = false;
15456 QualType ObjectType;
15457 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15458 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15459 if (ObjectType->isReferenceType())
15460 ObjectType = ObjectType->getPointeeType();
15461 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15462 } else {
15463 ObjectType = getCurrentThisType();
15464 This.emplace();
15465 DerefThis.emplace(*This);
15466 IsArrow = !LangOpts.HLSL;
15467 }
15468 ExprBuilder &ObjectParameter =
15469 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15470 : static_cast<ExprBuilder &>(*This);
15471
15472 // Assign base classes.
15473 bool Invalid = false;
15474 for (auto &Base : ClassDecl->bases()) {
15475 // Form the assignment:
15476 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15477 QualType BaseType = Base.getType().getUnqualifiedType();
15478 if (!BaseType->isRecordType()) {
15479 Invalid = true;
15480 continue;
15481 }
15482
15483 CXXCastPath BasePath;
15484 BasePath.push_back(&Base);
15485
15486 // Construct the "from" expression, which is an implicit cast to the
15487 // appropriately-qualified base type.
15488 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15489 VK_LValue, BasePath);
15490
15491 // Dereference "this".
15492 CastBuilder To(
15493 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15494 : static_cast<ExprBuilder &>(*DerefThis),
15495 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15496 VK_LValue, BasePath);
15497
15498 // Build the copy.
15499 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15500 To, From,
15501 /*CopyingBaseSubobject=*/true,
15502 /*Copying=*/true);
15503 if (Copy.isInvalid()) {
15504 CopyAssignOperator->setInvalidDecl();
15505 return;
15506 }
15507
15508 // Success! Record the copy.
15509 Statements.push_back(Copy.getAs<Expr>());
15510 }
15511
15512 // A defaulted copy assignment operator for a union copies the object
15513 // representation as if by a memcpy, the same way the defaulted union copy
15514 // constructor does. The memberwise loop below skips union members.
15515 if (ClassDecl->isUnion()) {
15516 ExprBuilder &To = ExplicitObject
15517 ? static_cast<ExprBuilder &>(*ExplicitObject)
15518 : static_cast<ExprBuilder &>(*DerefThis);
15519 // Copying the object representation is correct even for a union that is
15520 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15521 // here. Ignoring warnings rather than casting the arguments to void*
15522 // keeps them typed, which preserves their address space.
15523 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15525 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15526 if (Copy.isInvalid()) {
15527 CopyAssignOperator->setInvalidDecl();
15528 return;
15529 }
15530 Statements.push_back(Copy.getAs<Stmt>());
15531 }
15532
15533 // Assign non-static members.
15534 for (auto *Field : ClassDecl->fields()) {
15535 // Union members are copied by the whole-object memcpy emitted above.
15536 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15537 continue;
15538
15539 if (Field->isInvalidDecl()) {
15540 Invalid = true;
15541 continue;
15542 }
15543
15544 // Check for members of reference type; we can't copy those.
15545 if (Field->getType()->isReferenceType()) {
15546 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15547 << Context.getCanonicalTagType(ClassDecl) << 0
15548 << Field->getDeclName();
15549 Diag(Field->getLocation(), diag::note_declared_at);
15550 Invalid = true;
15551 continue;
15552 }
15553
15554 // Check for members of const-qualified, non-class type.
15555 QualType BaseType = Context.getBaseElementType(Field->getType());
15556 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15557 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15558 << Context.getCanonicalTagType(ClassDecl) << 1
15559 << Field->getDeclName();
15560 Diag(Field->getLocation(), diag::note_declared_at);
15561 Invalid = true;
15562 continue;
15563 }
15564
15565 // Suppress assigning zero-width bitfields.
15566 if (Field->isZeroLengthBitField())
15567 continue;
15568
15569 QualType FieldType = Field->getType().getNonReferenceType();
15570 if (FieldType->isIncompleteArrayType()) {
15571 assert(ClassDecl->hasFlexibleArrayMember() &&
15572 "Incomplete array type is not valid");
15573 continue;
15574 }
15575
15576 // Build references to the field in the object we're copying from and to.
15577 CXXScopeSpec SS; // Intentionally empty
15578 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15580 MemberLookup.addDecl(Field);
15581 MemberLookup.resolveKind();
15582
15583 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15584 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15585 // Build the copy of this field.
15586 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15587 To, From,
15588 /*CopyingBaseSubobject=*/false,
15589 /*Copying=*/true);
15590 if (Copy.isInvalid()) {
15591 CopyAssignOperator->setInvalidDecl();
15592 return;
15593 }
15594
15595 // Success! Record the copy.
15596 Statements.push_back(Copy.getAs<Stmt>());
15597 }
15598
15599 if (!Invalid) {
15600 // Add a "return *this;"
15601 Expr *ThisExpr =
15602 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15603 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15604 : static_cast<ExprBuilder &>(*DerefThis))
15605 .build(*this, Loc);
15606 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15607 if (Return.isInvalid())
15608 Invalid = true;
15609 else
15610 Statements.push_back(Return.getAs<Stmt>());
15611 }
15612
15613 if (Invalid) {
15614 CopyAssignOperator->setInvalidDecl();
15615 return;
15616 }
15617
15618 StmtResult Body;
15619 {
15620 CompoundScopeRAII CompoundScope(*this);
15621 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15622 /*isStmtExpr=*/false);
15623 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15624 }
15625 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15626 CopyAssignOperator->markUsed(Context);
15627
15629 L->CompletedImplicitDefinition(CopyAssignOperator);
15630 }
15631}
15632
15634 assert(ClassDecl->needsImplicitMoveAssignment());
15635
15636 DeclaringSpecialMember DSM(*this, ClassDecl,
15638 if (DSM.isAlreadyBeingDeclared())
15639 return nullptr;
15640
15641 // Note: The following rules are largely analoguous to the move
15642 // constructor rules.
15643
15645 /*Qualifier=*/std::nullopt, ClassDecl,
15646 /*OwnsTag=*/false);
15648 if (AS != LangAS::Default)
15649 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15650 QualType RetType = Context.getLValueReferenceType(ArgType);
15651 ArgType = Context.getRValueReferenceType(ArgType);
15652
15654 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15655
15656 // An implicitly-declared move assignment operator is an inline public
15657 // member of its class.
15658 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15659 SourceLocation ClassLoc = ClassDecl->getLocation();
15660 DeclarationNameInfo NameInfo(Name, ClassLoc);
15662 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15663 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15664 getCurFPFeatures().isFPConstrained(),
15665 /*isInline=*/true,
15667 SourceLocation());
15668 MoveAssignment->setAccess(AS_public);
15669 MoveAssignment->setDefaulted();
15670 MoveAssignment->setImplicit();
15671
15672 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15673
15674 if (getLangOpts().CUDA)
15675 CUDA().inferTargetForImplicitSpecialMember(
15677 /* ConstRHS */ false,
15678 /* Diagnose */ false);
15679
15680 // Add the parameter to the operator.
15682 ClassLoc, ClassLoc,
15683 /*Id=*/nullptr, ArgType,
15684 /*TInfo=*/nullptr, SC_None,
15685 nullptr);
15686 MoveAssignment->setParams(FromParam);
15687
15688 MoveAssignment->setTrivial(
15692 : ClassDecl->hasTrivialMoveAssignment());
15693
15694 // Note that we have added this copy-assignment operator.
15695 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15696
15697 Scope *S = getScopeForContext(ClassDecl);
15699
15703 SetDeclDeleted(MoveAssignment, ClassLoc);
15704 }
15705
15706 if (S)
15708 ClassDecl->addDecl(MoveAssignment);
15709
15710 return MoveAssignment;
15711}
15712
15713/// Check if we're implicitly defining a move assignment operator for a class
15714/// with virtual bases. Such a move assignment might move-assign the virtual
15715/// base multiple times.
15717 SourceLocation CurrentLocation) {
15718 assert(!Class->isDependentContext() && "should not define dependent move");
15719
15720 // Only a virtual base could get implicitly move-assigned multiple times.
15721 // Only a non-trivial move assignment can observe this. We only want to
15722 // diagnose if we implicitly define an assignment operator that assigns
15723 // two base classes, both of which move-assign the same virtual base.
15724 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15725 Class->getNumBases() < 2)
15726 return;
15727
15729 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15730 VBaseMap VBases;
15731
15732 for (auto &BI : Class->bases()) {
15733 Worklist.push_back(&BI);
15734 while (!Worklist.empty()) {
15735 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15736 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15737
15738 // If the base has no non-trivial move assignment operators,
15739 // we don't care about moves from it.
15740 if (!Base->hasNonTrivialMoveAssignment())
15741 continue;
15742
15743 // If there's nothing virtual here, skip it.
15744 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15745 continue;
15746
15747 // If we're not actually going to call a move assignment for this base,
15748 // or the selected move assignment is trivial, skip it.
15751 /*ConstArg*/ false, /*VolatileArg*/ false,
15752 /*RValueThis*/ true, /*ConstThis*/ false,
15753 /*VolatileThis*/ false);
15754 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15756 continue;
15757
15758 if (BaseSpec->isVirtual()) {
15759 // We're going to move-assign this virtual base, and its move
15760 // assignment operator is not trivial. If this can happen for
15761 // multiple distinct direct bases of Class, diagnose it. (If it
15762 // only happens in one base, we'll diagnose it when synthesizing
15763 // that base class's move assignment operator.)
15764 CXXBaseSpecifier *&Existing =
15765 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15766 .first->second;
15767 if (Existing && Existing != &BI) {
15768 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15769 << Class << Base;
15770 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15771 << (Base->getCanonicalDecl() ==
15773 << Base << Existing->getType() << Existing->getSourceRange();
15774 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15775 << (Base->getCanonicalDecl() ==
15776 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15777 << Base << BI.getType() << BaseSpec->getSourceRange();
15778
15779 // Only diagnose each vbase once.
15780 Existing = nullptr;
15781 }
15782 } else {
15783 // Only walk over bases that have defaulted move assignment operators.
15784 // We assume that any user-provided move assignment operator handles
15785 // the multiple-moves-of-vbase case itself somehow.
15786 if (!SMOR.getMethod()->isDefaulted())
15787 continue;
15788
15789 // We're going to move the base classes of Base. Add them to the list.
15790 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15791 }
15792 }
15793 }
15794}
15795
15797 CXXMethodDecl *MoveAssignOperator) {
15798 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15799 assert((MoveAssignOperator->isDefaulted() &&
15800 MoveAssignOperator->isOverloadedOperator() &&
15801 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15802 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15803 !MoveAssignOperator->isDeleted()) &&
15804 "DefineImplicitMoveAssignment called for wrong function");
15805 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15806 return;
15807
15808 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15809 if (ClassDecl->isInvalidDecl()) {
15810 MoveAssignOperator->setInvalidDecl();
15811 return;
15812 }
15813
15814 // C++0x [class.copy]p28:
15815 // The implicitly-defined or move assignment operator for a non-union class
15816 // X performs memberwise move assignment of its subobjects. The direct base
15817 // classes of X are assigned first, in the order of their declaration in the
15818 // base-specifier-list, and then the immediate non-static data members of X
15819 // are assigned, in the order in which they were declared in the class
15820 // definition.
15821
15822 // Issue a warning if our implicit move assignment operator will move
15823 // from a virtual base more than once.
15824 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15825
15826 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15827
15828 // The exception specification is needed because we are defining the
15829 // function.
15830 ResolveExceptionSpec(CurrentLocation,
15831 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15832
15833 // Add a context note for diagnostics produced after this point.
15834 Scope.addContextNote(CurrentLocation);
15835
15836 // The statements that form the synthesized function body.
15837 SmallVector<Stmt*, 8> Statements;
15838
15839 // The parameter for the "other" object, which we are move from.
15840 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15841 QualType OtherRefType =
15842 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15843
15844 // Our location for everything implicitly-generated.
15845 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15846 ? MoveAssignOperator->getEndLoc()
15847 : MoveAssignOperator->getLocation();
15848
15849 // Builds a reference to the "other" object.
15850 RefBuilder OtherRef(Other, OtherRefType);
15851 // Cast to rvalue.
15852 MoveCastBuilder MoveOther(OtherRef);
15853
15854 // Builds the function object parameter.
15855 std::optional<ThisBuilder> This;
15856 std::optional<DerefBuilder> DerefThis;
15857 std::optional<RefBuilder> ExplicitObject;
15858 QualType ObjectType;
15859 bool IsArrow = false;
15860 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15861 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15862 if (ObjectType->isReferenceType())
15863 ObjectType = ObjectType->getPointeeType();
15864 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15865 } else {
15866 ObjectType = getCurrentThisType();
15867 This.emplace();
15868 DerefThis.emplace(*This);
15869 IsArrow = !getLangOpts().HLSL;
15870 }
15871 ExprBuilder &ObjectParameter =
15872 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15873
15874 // Assign base classes.
15875 bool Invalid = false;
15876 for (auto &Base : ClassDecl->bases()) {
15877 // C++11 [class.copy]p28:
15878 // It is unspecified whether subobjects representing virtual base classes
15879 // are assigned more than once by the implicitly-defined copy assignment
15880 // operator.
15881 // FIXME: Do not assign to a vbase that will be assigned by some other base
15882 // class. For a move-assignment, this can result in the vbase being moved
15883 // multiple times.
15884
15885 // Form the assignment:
15886 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15887 QualType BaseType = Base.getType().getUnqualifiedType();
15888 if (!BaseType->isRecordType()) {
15889 Invalid = true;
15890 continue;
15891 }
15892
15893 CXXCastPath BasePath;
15894 BasePath.push_back(&Base);
15895
15896 // Construct the "from" expression, which is an implicit cast to the
15897 // appropriately-qualified base type.
15898 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15899
15900 // Implicitly cast "this" to the appropriately-qualified base type.
15901 // Dereference "this".
15902 CastBuilder To(
15903 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15904 : static_cast<ExprBuilder &>(*DerefThis),
15905 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15906 VK_LValue, BasePath);
15907
15908 // Build the move.
15909 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15910 To, From,
15911 /*CopyingBaseSubobject=*/true,
15912 /*Copying=*/false);
15913 if (Move.isInvalid()) {
15914 MoveAssignOperator->setInvalidDecl();
15915 return;
15916 }
15917
15918 // Success! Record the move.
15919 Statements.push_back(Move.getAs<Expr>());
15920 }
15921
15922 // A defaulted move assignment operator for a union copies the object
15923 // representation as if by a memcpy, the same way the defaulted union copy
15924 // constructor does. The memberwise loop below skips union members.
15925 if (ClassDecl->isUnion()) {
15926 ExprBuilder &To = ExplicitObject
15927 ? static_cast<ExprBuilder &>(*ExplicitObject)
15928 : static_cast<ExprBuilder &>(*DerefThis);
15929 // Copying the object representation is correct even for a union that is
15930 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15931 // here. Ignoring warnings rather than casting the arguments to void*
15932 // keeps them typed, which preserves their address space.
15933 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15935 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15936 if (Copy.isInvalid()) {
15937 MoveAssignOperator->setInvalidDecl();
15938 return;
15939 }
15940 Statements.push_back(Copy.getAs<Stmt>());
15941 }
15942
15943 // Assign non-static members.
15944 for (auto *Field : ClassDecl->fields()) {
15945 // Union members are copied by the whole-object memcpy emitted above.
15946 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15947 continue;
15948
15949 if (Field->isInvalidDecl()) {
15950 Invalid = true;
15951 continue;
15952 }
15953
15954 // Check for members of reference type; we can't move those.
15955 if (Field->getType()->isReferenceType()) {
15956 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15957 << Context.getCanonicalTagType(ClassDecl) << 0
15958 << Field->getDeclName();
15959 Diag(Field->getLocation(), diag::note_declared_at);
15960 Invalid = true;
15961 continue;
15962 }
15963
15964 // Check for members of const-qualified, non-class type.
15965 QualType BaseType = Context.getBaseElementType(Field->getType());
15966 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15967 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15968 << Context.getCanonicalTagType(ClassDecl) << 1
15969 << Field->getDeclName();
15970 Diag(Field->getLocation(), diag::note_declared_at);
15971 Invalid = true;
15972 continue;
15973 }
15974
15975 // Suppress assigning zero-width bitfields.
15976 if (Field->isZeroLengthBitField())
15977 continue;
15978
15979 QualType FieldType = Field->getType().getNonReferenceType();
15980 if (FieldType->isIncompleteArrayType()) {
15981 assert(ClassDecl->hasFlexibleArrayMember() &&
15982 "Incomplete array type is not valid");
15983 continue;
15984 }
15985
15986 // Build references to the field in the object we're copying from and to.
15987 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15989 MemberLookup.addDecl(Field);
15990 MemberLookup.resolveKind();
15991 MemberBuilder From(MoveOther, OtherRefType,
15992 /*IsArrow=*/false, MemberLookup);
15993 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15994
15995 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15996 "Member reference with rvalue base must be rvalue except for reference "
15997 "members, which aren't allowed for move assignment.");
15998
15999 // Build the move of this field.
16000 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
16001 To, From,
16002 /*CopyingBaseSubobject=*/false,
16003 /*Copying=*/false);
16004 if (Move.isInvalid()) {
16005 MoveAssignOperator->setInvalidDecl();
16006 return;
16007 }
16008
16009 // Success! Record the copy.
16010 Statements.push_back(Move.getAs<Stmt>());
16011 }
16012
16013 if (!Invalid) {
16014 // Add a "return *this;"
16015 Expr *ThisExpr =
16016 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16017 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16018 : static_cast<ExprBuilder &>(*DerefThis))
16019 .build(*this, Loc);
16020
16021 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
16022 if (Return.isInvalid())
16023 Invalid = true;
16024 else
16025 Statements.push_back(Return.getAs<Stmt>());
16026 }
16027
16028 if (Invalid) {
16029 MoveAssignOperator->setInvalidDecl();
16030 return;
16031 }
16032
16033 StmtResult Body;
16034 {
16035 CompoundScopeRAII CompoundScope(*this);
16036 Body = ActOnCompoundStmt(Loc, Loc, Statements,
16037 /*isStmtExpr=*/false);
16038 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16039 }
16040 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16041 MoveAssignOperator->markUsed(Context);
16042
16044 L->CompletedImplicitDefinition(MoveAssignOperator);
16045 }
16046}
16047
16049 CXXRecordDecl *ClassDecl) {
16050 // C++ [class.copy]p4:
16051 // If the class definition does not explicitly declare a copy
16052 // constructor, one is declared implicitly.
16053 assert(ClassDecl->needsImplicitCopyConstructor());
16054
16055 DeclaringSpecialMember DSM(*this, ClassDecl,
16057 if (DSM.isAlreadyBeingDeclared())
16058 return nullptr;
16059
16060 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16061 /*Qualifier=*/std::nullopt, ClassDecl,
16062 /*OwnsTag=*/false);
16063 QualType ArgType = ClassType;
16064 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16065 if (Const)
16066 ArgType = ArgType.withConst();
16067
16069 if (AS != LangAS::Default)
16070 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
16071
16072 ArgType = Context.getLValueReferenceType(ArgType);
16073
16075 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
16076
16077 DeclarationName Name
16078 = Context.DeclarationNames.getCXXConstructorName(
16079 Context.getCanonicalType(ClassType));
16080 SourceLocation ClassLoc = ClassDecl->getLocation();
16081 DeclarationNameInfo NameInfo(Name, ClassLoc);
16082
16083 // An implicitly-declared copy constructor is an inline public
16084 // member of its class.
16086 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16087 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16088 /*isInline=*/true,
16089 /*isImplicitlyDeclared=*/true,
16092 CopyConstructor->setAccess(AS_public);
16093 CopyConstructor->setDefaulted();
16094
16095 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16096
16097 if (getLangOpts().CUDA)
16098 CUDA().inferTargetForImplicitSpecialMember(
16100 /* ConstRHS */ Const,
16101 /* Diagnose */ false);
16102
16103 // During template instantiation of special member functions we need a
16104 // reliable TypeSourceInfo for the parameter types in order to allow functions
16105 // to be substituted.
16106 TypeSourceInfo *TSI = nullptr;
16107 if (inTemplateInstantiation() && ClassDecl->isLambda())
16108 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16109
16110 // Add the parameter to the constructor.
16111 ParmVarDecl *FromParam =
16112 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16113 /*IdentifierInfo=*/nullptr, ArgType,
16114 /*TInfo=*/TSI, SC_None, nullptr);
16115 CopyConstructor->setParams(FromParam);
16116
16117 CopyConstructor->setTrivial(
16121 : ClassDecl->hasTrivialCopyConstructor());
16122
16123 CopyConstructor->setTrivialForCall(
16124 ClassDecl->hasAttr<TrivialABIAttr>() ||
16129 : ClassDecl->hasTrivialCopyConstructorForCall()));
16130
16131 // Note that we have declared this constructor.
16132 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16133
16134 Scope *S = getScopeForContext(ClassDecl);
16136
16141 }
16142
16143 if (S)
16145 ClassDecl->addDecl(CopyConstructor);
16146
16147 return CopyConstructor;
16148}
16149
16152 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16153 assert((CopyConstructor->isDefaulted() &&
16154 CopyConstructor->isCopyConstructor() &&
16155 !CopyConstructor->doesThisDeclarationHaveABody() &&
16156 !CopyConstructor->isDeleted()) &&
16157 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16158 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16159 return;
16160
16161 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16162 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16163
16165
16166 // The exception specification is needed because we are defining the
16167 // function.
16168 ResolveExceptionSpec(CurrentLocation,
16169 CopyConstructor->getType()->castAs<FunctionProtoType>());
16170 MarkVTableUsed(CurrentLocation, ClassDecl);
16171
16172 // Add a context note for diagnostics produced after this point.
16173 Scope.addContextNote(CurrentLocation);
16174
16175 // C++11 [class.copy]p7:
16176 // The [definition of an implicitly declared copy constructor] is
16177 // deprecated if the class has a user-declared copy assignment operator
16178 // or a user-declared destructor.
16179 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16181
16182 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16183 CopyConstructor->setInvalidDecl();
16184 } else {
16185 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16186 ? CopyConstructor->getEndLoc()
16187 : CopyConstructor->getLocation();
16188 Sema::CompoundScopeRAII CompoundScope(*this);
16189 CopyConstructor->setBody(
16190 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16191 CopyConstructor->markUsed(Context);
16192 }
16193
16195 L->CompletedImplicitDefinition(CopyConstructor);
16196 }
16197}
16198
16200 CXXRecordDecl *ClassDecl) {
16201 assert(ClassDecl->needsImplicitMoveConstructor());
16202
16203 DeclaringSpecialMember DSM(*this, ClassDecl,
16205 if (DSM.isAlreadyBeingDeclared())
16206 return nullptr;
16207
16208 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16209 /*Qualifier=*/std::nullopt, ClassDecl,
16210 /*OwnsTag=*/false);
16211
16212 QualType ArgType = ClassType;
16214 if (AS != LangAS::Default)
16215 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16216 ArgType = Context.getRValueReferenceType(ArgType);
16217
16219 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16220
16221 DeclarationName Name
16222 = Context.DeclarationNames.getCXXConstructorName(
16223 Context.getCanonicalType(ClassType));
16224 SourceLocation ClassLoc = ClassDecl->getLocation();
16225 DeclarationNameInfo NameInfo(Name, ClassLoc);
16226
16227 // C++11 [class.copy]p11:
16228 // An implicitly-declared copy/move constructor is an inline public
16229 // member of its class.
16231 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16232 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16233 /*isInline=*/true,
16234 /*isImplicitlyDeclared=*/true,
16237 MoveConstructor->setAccess(AS_public);
16238 MoveConstructor->setDefaulted();
16239
16240 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16241
16242 if (getLangOpts().CUDA)
16243 CUDA().inferTargetForImplicitSpecialMember(
16245 /* ConstRHS */ false,
16246 /* Diagnose */ false);
16247
16248 // Add the parameter to the constructor.
16250 ClassLoc, ClassLoc,
16251 /*IdentifierInfo=*/nullptr,
16252 ArgType, /*TInfo=*/nullptr,
16253 SC_None, nullptr);
16254 MoveConstructor->setParams(FromParam);
16255
16256 MoveConstructor->setTrivial(
16260 : ClassDecl->hasTrivialMoveConstructor());
16261
16262 MoveConstructor->setTrivialForCall(
16263 ClassDecl->hasAttr<TrivialABIAttr>() ||
16268 : ClassDecl->hasTrivialMoveConstructorForCall()));
16269
16270 // Note that we have declared this constructor.
16271 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16272
16273 Scope *S = getScopeForContext(ClassDecl);
16275
16280 }
16281
16282 if (S)
16284 ClassDecl->addDecl(MoveConstructor);
16285
16286 return MoveConstructor;
16287}
16288
16291 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16292 assert((MoveConstructor->isDefaulted() &&
16293 MoveConstructor->isMoveConstructor() &&
16294 !MoveConstructor->doesThisDeclarationHaveABody() &&
16295 !MoveConstructor->isDeleted()) &&
16296 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16297 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16298 return;
16299
16300 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16301 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16302
16304
16305 // The exception specification is needed because we are defining the
16306 // function.
16307 ResolveExceptionSpec(CurrentLocation,
16308 MoveConstructor->getType()->castAs<FunctionProtoType>());
16309 MarkVTableUsed(CurrentLocation, ClassDecl);
16310
16311 // Add a context note for diagnostics produced after this point.
16312 Scope.addContextNote(CurrentLocation);
16313
16314 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16315 MoveConstructor->setInvalidDecl();
16316 } else {
16317 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16318 ? MoveConstructor->getEndLoc()
16319 : MoveConstructor->getLocation();
16320 Sema::CompoundScopeRAII CompoundScope(*this);
16321 MoveConstructor->setBody(
16322 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16323 MoveConstructor->markUsed(Context);
16324 }
16325
16327 L->CompletedImplicitDefinition(MoveConstructor);
16328 }
16329}
16330
16332 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16333}
16334
16336 SourceLocation CurrentLocation,
16337 CXXConversionDecl *Conv) {
16338 SynthesizedFunctionScope Scope(*this, Conv);
16339 assert(!Conv->getReturnType()->isUndeducedType());
16340
16341 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16342 CallingConv CC =
16343 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16344
16345 CXXRecordDecl *Lambda = Conv->getParent();
16346 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16347 FunctionDecl *Invoker =
16348 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16349 ? CallOp
16350 : Lambda->getLambdaStaticInvoker(CC);
16351
16352 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16354 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16355 if (!CallOp)
16356 return;
16357
16358 if (CallOp != Invoker) {
16360 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16361 CurrentLocation);
16362 if (!Invoker)
16363 return;
16364 }
16365 }
16366
16367 if (CallOp->isInvalidDecl())
16368 return;
16369
16370 // Mark the call operator referenced (and add to pending instantiations
16371 // if necessary).
16372 // For both the conversion and static-invoker template specializations
16373 // we construct their body's in this function, so no need to add them
16374 // to the PendingInstantiations.
16375 MarkFunctionReferenced(CurrentLocation, CallOp);
16376
16377 if (Invoker != CallOp) {
16378 // Fill in the __invoke function with a dummy implementation. IR generation
16379 // will fill in the actual details. Update its type in case it contained
16380 // an 'auto'.
16381 Invoker->markUsed(Context);
16382 Invoker->setReferenced();
16383 Invoker->setType(Conv->getReturnType()->getPointeeType());
16384 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16385 }
16386
16387 // Construct the body of the conversion function { return __invoke; }.
16388 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16389 Conv->getLocation());
16390 assert(FunctionRef && "Can't refer to __invoke function?");
16391 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16393 Conv->getLocation(), Conv->getLocation()));
16394 Conv->markUsed(Context);
16395 Conv->setReferenced();
16396
16398 L->CompletedImplicitDefinition(Conv);
16399 if (Invoker != CallOp)
16400 L->CompletedImplicitDefinition(Invoker);
16401 }
16402}
16403
16405 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16406 assert(!Conv->getParent()->isGenericLambda());
16407
16408 SynthesizedFunctionScope Scope(*this, Conv);
16409
16410 // Copy-initialize the lambda object as needed to capture it.
16411 Expr *This = ActOnCXXThis(CurrentLocation).get();
16412 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16413
16414 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16415 Conv->getLocation(),
16416 Conv, DerefThis);
16417
16418 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16419 // behavior. Note that only the general conversion function does this
16420 // (since it's unusable otherwise); in the case where we inline the
16421 // block literal, it has block literal lifetime semantics.
16422 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16423 BuildBlock = ImplicitCastExpr::Create(
16424 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16425 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16426
16427 if (BuildBlock.isInvalid()) {
16428 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16429 Conv->setInvalidDecl();
16430 return;
16431 }
16432
16433 // Create the return statement that returns the block from the conversion
16434 // function.
16435 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16436 if (Return.isInvalid()) {
16437 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16438 Conv->setInvalidDecl();
16439 return;
16440 }
16441
16442 // Set the body of the conversion function.
16443 Stmt *ReturnS = Return.get();
16445 Conv->getLocation(), Conv->getLocation()));
16446 Conv->markUsed(Context);
16447
16448 // We're done; notify the mutation listener, if any.
16450 L->CompletedImplicitDefinition(Conv);
16451 }
16452}
16453
16454/// Determine whether the given list arguments contains exactly one
16455/// "real" (non-default) argument.
16457 switch (Args.size()) {
16458 case 0:
16459 return false;
16460
16461 default:
16462 if (!Args[1]->isDefaultArgument())
16463 return false;
16464
16465 [[fallthrough]];
16466 case 1:
16467 return !Args[0]->isDefaultArgument();
16468 }
16469
16470 return false;
16471}
16472
16474 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16476 bool HadMultipleCandidates, bool IsListInitialization,
16477 bool IsStdInitListInitialization, bool RequiresZeroInit,
16478 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16479 bool Elidable = false;
16480
16481 // C++0x [class.copy]p34:
16482 // When certain criteria are met, an implementation is allowed to
16483 // omit the copy/move construction of a class object, even if the
16484 // copy/move constructor and/or destructor for the object have
16485 // side effects. [...]
16486 // - when a temporary class object that has not been bound to a
16487 // reference (12.2) would be copied/moved to a class object
16488 // with the same cv-unqualified type, the copy/move operation
16489 // can be omitted by constructing the temporary object
16490 // directly into the target of the omitted copy/move
16491 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16492 // FIXME: Converting constructors should also be accepted.
16493 // But to fix this, the logic that digs down into a CXXConstructExpr
16494 // to find the source object needs to handle it.
16495 // Right now it assumes the source object is passed directly as the
16496 // first argument.
16497 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16498 Expr *SubExpr = ExprArgs[0];
16499 // FIXME: Per above, this is also incorrect if we want to accept
16500 // converting constructors, as isTemporaryObject will
16501 // reject temporaries with different type from the
16502 // CXXRecord itself.
16503 Elidable = SubExpr->isTemporaryObject(
16505 }
16506
16507 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16508 FoundDecl, Constructor,
16509 Elidable, ExprArgs, HadMultipleCandidates,
16510 IsListInitialization,
16511 IsStdInitListInitialization, RequiresZeroInit,
16512 ConstructKind, ParenRange);
16513}
16514
16516 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16517 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16518 bool HadMultipleCandidates, bool IsListInitialization,
16519 bool IsStdInitListInitialization, bool RequiresZeroInit,
16520 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16521 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16522 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16523 // The only way to get here is if we did overload resolution to find the
16524 // shadow decl, so we don't need to worry about re-checking the trailing
16525 // requires clause.
16526 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16527 return ExprError();
16528 }
16529
16530 return BuildCXXConstructExpr(
16531 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16532 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16533 RequiresZeroInit, ConstructKind, ParenRange);
16534}
16535
16536/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16537/// including handling of its default argument expressions.
16539 SourceLocation ConstructLoc, QualType DeclInitType,
16540 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16541 bool HadMultipleCandidates, bool IsListInitialization,
16542 bool IsStdInitListInitialization, bool RequiresZeroInit,
16543 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16544 assert(declaresSameEntity(
16545 Constructor->getParent(),
16546 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16547 "given constructor for wrong type");
16548 MarkFunctionReferenced(ConstructLoc, Constructor);
16549 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16550 return ExprError();
16551
16554 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16555 HadMultipleCandidates, IsListInitialization,
16556 IsStdInitListInitialization, RequiresZeroInit,
16557 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16558 Constructor);
16559}
16560
16562 if (VD->isInvalidDecl()) return;
16563 // If initializing the variable failed, don't also diagnose problems with
16564 // the destructor, they're likely related.
16565 if (VD->getInit() && VD->getInit()->containsErrors())
16566 return;
16567
16568 ClassDecl = ClassDecl->getDefinitionOrSelf();
16569 if (ClassDecl->isInvalidDecl()) return;
16570 if (ClassDecl->hasIrrelevantDestructor()) return;
16571 if (ClassDecl->isDependentContext()) return;
16572
16573 if (VD->isNoDestroy(getASTContext()))
16574 return;
16575
16577 // The result of `LookupDestructor` might be nullptr if the destructor is
16578 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16579 // will not be selected by `CXXRecordDecl::getDestructor()`.
16580 if (!Destructor)
16581 return;
16582 // If this is an array, we'll require the destructor during initialization, so
16583 // we can skip over this. We still want to emit exit-time destructor warnings
16584 // though.
16585 if (!VD->getType()->isArrayType()) {
16588 PDiag(diag::err_access_dtor_var)
16589 << VD->getDeclName() << VD->getType());
16591 }
16592
16593 if (Destructor->isTrivial()) return;
16594
16595 // If the destructor is constexpr, check whether the variable has constant
16596 // destruction now.
16597 if (Destructor->isConstexpr()) {
16598 bool HasConstantInit = false;
16599 if (VD->getInit() && !VD->getInit()->isValueDependent())
16600 HasConstantInit = VD->evaluateValue();
16602 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16603 HasConstantInit) {
16604 Diag(VD->getLocation(),
16605 diag::err_constexpr_var_requires_const_destruction) << VD;
16606 for (const PartialDiagnosticAt &Note : Notes)
16607 Diag(Note.first, Note.second);
16608 }
16609 }
16610
16611 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16612 return;
16613
16614 // Emit warning for non-trivial dtor in global scope (a real global,
16615 // class-static, function-static).
16616 if (!VD->hasAttr<AlwaysDestroyAttr>())
16617 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16618
16619 // TODO: this should be re-enabled for static locals by !CXAAtExit
16620 if (!VD->isStaticLocal())
16621 Diag(VD->getLocation(), diag::warn_global_destructor);
16622}
16623
16625 QualType DeclInitType, MultiExprArg ArgsPtr,
16626 SourceLocation Loc,
16627 SmallVectorImpl<Expr *> &ConvertedArgs,
16628 bool AllowExplicit,
16629 bool IsListInitialization) {
16630 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16631 unsigned NumArgs = ArgsPtr.size();
16632 Expr **Args = ArgsPtr.data();
16633
16634 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16635 unsigned NumParams = Proto->getNumParams();
16636
16637 // If too few arguments are available, we'll fill in the rest with defaults.
16638 if (NumArgs < NumParams)
16639 ConvertedArgs.reserve(NumParams);
16640 else
16641 ConvertedArgs.reserve(NumArgs);
16642
16643 VariadicCallType CallType = Proto->isVariadic()
16646 SmallVector<Expr *, 8> AllArgs;
16648 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16649 CallType, AllowExplicit, IsListInitialization);
16650 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16651
16652 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16653
16654 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16655 Proto, Loc);
16656
16657 return Invalid;
16658}
16659
16661 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16662 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16663}
16664
16667 QualType DeallocType, SourceLocation Loc) {
16668 if (DeallocType.isNull())
16669 return nullptr;
16670
16671 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16672 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16673 return nullptr;
16674
16675 if (FnDecl->isVariadic())
16676 return nullptr;
16677
16678 unsigned NumParams = FnDecl->getNumParams();
16679 constexpr unsigned RequiredParameterCount =
16681 // A usual deallocation function has no placement parameters
16682 if (NumParams != RequiredParameterCount)
16683 return nullptr;
16684
16685 // A type aware allocation is only usual if the only dependent parameter is
16686 // the first parameter.
16687 if (llvm::any_of(FnDecl->parameters().drop_front(),
16688 [](const ParmVarDecl *ParamDecl) {
16689 return ParamDecl->getType()->isDependentType();
16690 }))
16691 return nullptr;
16692
16693 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16694 if (SpecializedTypeIdentity.isNull())
16695 return nullptr;
16696
16698 ArgTypes.reserve(NumParams);
16699
16700 // The first parameter to a type aware operator delete is by definition the
16701 // type-identity argument, so we explicitly set this to the target
16702 // type-identity type, the remaining usual parameters should then simply match
16703 // the type declared in the function template.
16704 ArgTypes.push_back(SpecializedTypeIdentity);
16705 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16706 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16707
16709 QualType ExpectedFunctionType =
16710 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16713 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16715 return nullptr;
16716 return Result;
16717}
16718
16719static inline bool
16721 const FunctionDecl *FnDecl) {
16722 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16723 if (isa<NamespaceDecl>(DC)) {
16724 return SemaRef.Diag(FnDecl->getLocation(),
16725 diag::err_operator_new_delete_declared_in_namespace)
16726 << FnDecl->getDeclName();
16727 }
16728
16729 if (isa<TranslationUnitDecl>(DC) &&
16730 FnDecl->getStorageClass() == SC_Static) {
16731 return SemaRef.Diag(FnDecl->getLocation(),
16732 diag::err_operator_new_delete_declared_static)
16733 << FnDecl->getDeclName();
16734 }
16735
16736 return false;
16737}
16738
16740 const PointerType *PtrTy) {
16741 auto &Ctx = SemaRef.Context;
16742 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16743 PtrQuals.removeAddressSpace();
16745 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16746}
16747
16749
16751 const FunctionDecl *FD,
16752 bool *WasMalformed) {
16753 const Decl *MalformedDecl = nullptr;
16754 if (FD->getNumParams() > 0 &&
16755 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16756 /*TypeArgument=*/nullptr, &MalformedDecl))
16757 return true;
16758
16759 if (!MalformedDecl)
16760 return false;
16761
16762 if (WasMalformed)
16763 *WasMalformed = true;
16764
16765 return true;
16766}
16767
16769 auto *RD = Type->getAsCXXRecordDecl();
16770 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16771 RD->getIdentifier()->isStr("destroying_delete_t");
16772}
16773
16775 const FunctionDecl *FD) {
16776 // C++ P0722:
16777 // Within a class C, a single object deallocation function with signature
16778 // (T, std::destroying_delete_t, <more params>)
16779 // is a destroying operator delete.
16780 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16781 SemaRef, FD, /*WasMalformed=*/nullptr);
16782 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16783 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16784 FD->getNumParams() > DestroyingDeleteIdx &&
16785 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16786}
16787
16789 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16790 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16791 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16792 auto NormalizeType = [&SemaRef](QualType T) {
16793 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16794 // The operator is valid on any address space for OpenCL.
16795 // Drop address space from actual and expected result types.
16796 if (const auto PtrTy = T->template getAs<PointerType>())
16797 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16798 }
16799 return SemaRef.Context.getCanonicalType(T);
16800 };
16801
16802 const unsigned NumParams = FnDecl->getNumParams();
16803 unsigned FirstNonTypeParam = 0;
16804 bool MalformedTypeIdentity = false;
16805 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16806 SemaRef, FnDecl, &MalformedTypeIdentity);
16807 unsigned MinimumMandatoryArgumentCount = 1;
16808 unsigned SizeParameterIndex = 0;
16809 if (IsPotentiallyTypeAware) {
16810 // We don't emit this diagnosis for template instantiations as we will
16811 // have already emitted it for the original template declaration.
16812 if (!FnDecl->isTemplateInstantiation())
16813 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16814
16815 if (OperatorKind == AllocationOperatorKind::New) {
16816 SizeParameterIndex = 1;
16817 MinimumMandatoryArgumentCount =
16819 } else {
16820 SizeParameterIndex = 2;
16821 MinimumMandatoryArgumentCount =
16823 }
16824 FirstNonTypeParam = 1;
16825 }
16826
16827 bool IsPotentiallyDestroyingDelete =
16829
16830 if (IsPotentiallyDestroyingDelete) {
16831 ++MinimumMandatoryArgumentCount;
16832 ++SizeParameterIndex;
16833 }
16834
16835 if (NumParams < MinimumMandatoryArgumentCount)
16836 return SemaRef.Diag(FnDecl->getLocation(),
16837 diag::err_operator_new_delete_too_few_parameters)
16838 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16839 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16840
16841 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16842 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16843 if (ParamDecl->hasDefaultArg())
16844 return SemaRef.Diag(FnDecl->getLocation(),
16845 diag::err_operator_new_default_arg)
16846 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16847 }
16848
16849 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16850 QualType CanResultType = NormalizeType(FnType->getReturnType());
16851 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16852 QualType CanExpectedSizeOrAddressParamType =
16853 NormalizeType(ExpectedSizeOrAddressParamType);
16854
16855 // Check that the result type is what we expect.
16856 if (CanResultType != CanExpectedResultType) {
16857 // Reject even if the type is dependent; an operator delete function is
16858 // required to have a non-dependent result type.
16859 return SemaRef.Diag(
16860 FnDecl->getLocation(),
16861 CanResultType->isDependentType()
16862 ? diag::err_operator_new_delete_dependent_result_type
16863 : diag::err_operator_new_delete_invalid_result_type)
16864 << FnDecl->getDeclName() << ExpectedResultType;
16865 }
16866
16867 // A function template must have at least 2 parameters.
16868 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16869 return SemaRef.Diag(FnDecl->getLocation(),
16870 diag::err_operator_new_delete_template_too_few_parameters)
16871 << FnDecl->getDeclName();
16872
16873 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16874 auto FallbackType) -> bool {
16875 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16876 if (ExpectedType.isNull()) {
16877 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16878 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16879 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16880 << ParamDecl->getSourceRange();
16881 }
16882 CanQualType CanExpectedTy =
16883 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16884 auto ActualParamType =
16885 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16886 if (ActualParamType == CanExpectedTy)
16887 return false;
16888 unsigned Diagnostic = ActualParamType->isDependentType()
16889 ? DependentParamTypeDiag
16890 : InvalidParamTypeDiag;
16891 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16892 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16893 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16894 << FallbackType << ParamDecl->getSourceRange();
16895 };
16896
16897 // Check that the first parameter type is what we expect.
16898 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16899 return true;
16900
16901 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16902
16903 // If the first parameter type is not a type-identity we're done, otherwise
16904 // we need to ensure the size and alignment parameters have the correct type
16905 if (!IsPotentiallyTypeAware)
16906 return false;
16907
16908 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16909 return true;
16910 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16911 CanQualType StdAlignValT =
16912 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16913 : CanQualType();
16914 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16915 return true;
16916
16918 return MalformedTypeIdentity;
16919}
16920
16921static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16922 // C++ [basic.stc.dynamic.allocation]p1:
16923 // A program is ill-formed if an allocation function is declared in a
16924 // namespace scope other than global scope or declared static in global
16925 // scope.
16926 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16927 return true;
16928
16929 CanQualType SizeTy =
16930 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16931
16932 // C++ [basic.stc.dynamic.allocation]p1:
16933 // The return type shall be void*. The first parameter shall have type
16934 // std::size_t.
16936 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16937 SizeTy, diag::err_operator_new_dependent_param_type,
16938 diag::err_operator_new_param_type);
16939}
16940
16941static bool
16943 // C++ [basic.stc.dynamic.deallocation]p1:
16944 // A program is ill-formed if deallocation functions are declared in a
16945 // namespace scope other than global scope or declared static in global
16946 // scope.
16947 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16948 return true;
16949
16950 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16951 auto ConstructDestroyingDeleteAddressType = [&]() {
16952 assert(MD);
16953 return SemaRef.Context.getPointerType(
16954 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16955 };
16956
16957 // C++ P2719: A destroying operator delete cannot be type aware
16958 // so for QoL we actually check for this explicitly by considering
16959 // an destroying-delete appropriate address type and the presence of
16960 // any parameter of type destroying_delete_t as an erroneous attempt
16961 // to declare a type aware destroying delete, rather than emitting a
16962 // pile of incorrect parameter type errors.
16964 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16965 QualType AddressParamType =
16966 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16967 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16968 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16969 // The address parameter type implies an author trying to construct a
16970 // type aware destroying delete, so we'll see if we can find a parameter
16971 // of type `std::destroying_delete_t`, and if we find it we'll report
16972 // this as being an attempt at a type aware destroying delete just stop
16973 // here. If we don't do this, the resulting incorrect parameter ordering
16974 // results in a pile mismatched argument type errors that don't explain
16975 // the core problem.
16976 for (auto Param : MD->parameters()) {
16977 if (isDestroyingDeleteT(Param->getType())) {
16978 SemaRef.Diag(MD->getLocation(),
16979 diag::err_type_aware_destroying_operator_delete)
16980 << Param->getSourceRange();
16981 return true;
16982 }
16983 }
16984 }
16985 }
16986
16987 // C++ P0722:
16988 // Within a class C, the first parameter of a destroying operator delete
16989 // shall be of type C *. The first parameter of any other deallocation
16990 // function shall be of type void *.
16991 CanQualType ExpectedAddressParamType =
16992 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16993 ? SemaRef.Context.getPointerType(
16994 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16995 : SemaRef.Context.VoidPtrTy;
16996
16997 // C++ [basic.stc.dynamic.deallocation]p2:
16998 // Each deallocation function shall return void
17000 SemaRef, FnDecl, AllocationOperatorKind::Delete,
17001 SemaRef.Context.VoidTy, ExpectedAddressParamType,
17002 diag::err_operator_delete_dependent_param_type,
17003 diag::err_operator_delete_param_type))
17004 return true;
17005
17006 // C++ P0722:
17007 // A destroying operator delete shall be a usual deallocation function.
17008 if (MD && !MD->getParent()->isDependentContext() &&
17010 if (!SemaRef.isUsualDeallocationFunction(MD)) {
17011 SemaRef.Diag(MD->getLocation(),
17012 diag::err_destroying_operator_delete_not_usual);
17013 return true;
17014 }
17015 }
17016
17017 return false;
17018}
17019
17021 assert(FnDecl && FnDecl->isOverloadedOperator() &&
17022 "Expected an overloaded operator declaration");
17023
17025
17026 // C++ [over.oper]p5:
17027 // The allocation and deallocation functions, operator new,
17028 // operator new[], operator delete and operator delete[], are
17029 // described completely in 3.7.3. The attributes and restrictions
17030 // found in the rest of this subclause do not apply to them unless
17031 // explicitly stated in 3.7.3.
17032 if (Op == OO_Delete || Op == OO_Array_Delete)
17033 return CheckOperatorDeleteDeclaration(*this, FnDecl);
17034
17035 if (Op == OO_New || Op == OO_Array_New)
17036 return CheckOperatorNewDeclaration(*this, FnDecl);
17037
17038 // C++ [over.oper]p7:
17039 // An operator function shall either be a member function or
17040 // be a non-member function and have at least one parameter
17041 // whose type is a class, a reference to a class, an enumeration,
17042 // or a reference to an enumeration.
17043 // Note: Before C++23, a member function could not be static. The only member
17044 // function allowed to be static is the call operator function.
17045 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
17046 if (MethodDecl->isStatic()) {
17047 if (Op == OO_Call || Op == OO_Subscript)
17048 DiagCompat(FnDecl->getLocation(), diag_compat::operator_overload_static)
17049 << FnDecl;
17050 else
17051 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
17052 << FnDecl;
17053 }
17054 } else {
17055 bool ClassOrEnumParam = false;
17056 for (auto *Param : FnDecl->parameters()) {
17057 QualType ParamType = Param->getType().getNonReferenceType();
17058 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17059 ParamType->isEnumeralType()) {
17060 ClassOrEnumParam = true;
17061 break;
17062 }
17063 }
17064
17065 if (!ClassOrEnumParam)
17066 return Diag(FnDecl->getLocation(),
17067 diag::err_operator_overload_needs_class_or_enum)
17068 << FnDecl->getDeclName();
17069 }
17070
17071 // C++ [over.oper]p8:
17072 // An operator function cannot have default arguments (8.3.6),
17073 // except where explicitly stated below.
17074 //
17075 // Only the function-call operator (C++ [over.call]p1) and the subscript
17076 // operator (CWG2507) allow default arguments.
17077 if (Op != OO_Call) {
17078 ParmVarDecl *FirstDefaultedParam = nullptr;
17079 for (auto *Param : FnDecl->parameters()) {
17080 if (Param->hasDefaultArg()) {
17081 FirstDefaultedParam = Param;
17082 break;
17083 }
17084 }
17085 if (FirstDefaultedParam) {
17086 if (Op == OO_Subscript) {
17087 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17088 ? diag::ext_subscript_overload
17089 : diag::error_subscript_overload)
17090 << FnDecl->getDeclName() << 1
17091 << FirstDefaultedParam->getDefaultArgRange();
17092 } else {
17093 return Diag(FirstDefaultedParam->getLocation(),
17094 diag::err_operator_overload_default_arg)
17095 << FnDecl->getDeclName()
17096 << FirstDefaultedParam->getDefaultArgRange();
17097 }
17098 }
17099 }
17100
17101 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17102 { false, false, false }
17103#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17104 , { Unary, Binary, MemberOnly }
17105#include "clang/Basic/OperatorKinds.def"
17106 };
17107
17108 bool CanBeUnaryOperator = OperatorUses[Op][0];
17109 bool CanBeBinaryOperator = OperatorUses[Op][1];
17110 bool MustBeMemberOperator = OperatorUses[Op][2];
17111
17112 // C++ [over.oper]p8:
17113 // [...] Operator functions cannot have more or fewer parameters
17114 // than the number required for the corresponding operator, as
17115 // described in the rest of this subclause.
17116 unsigned NumParams = FnDecl->getNumParams() +
17117 (isa<CXXMethodDecl>(FnDecl) &&
17119 ? 1
17120 : 0);
17121 if (Op != OO_Call && Op != OO_Subscript &&
17122 ((NumParams == 1 && !CanBeUnaryOperator) ||
17123 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17124 (NumParams > 2))) {
17125 // We have the wrong number of parameters.
17126 unsigned ErrorKind;
17127 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17128 ErrorKind = 2; // 2 -> unary or binary.
17129 } else if (CanBeUnaryOperator) {
17130 ErrorKind = 0; // 0 -> unary
17131 } else {
17132 assert(CanBeBinaryOperator &&
17133 "All non-call overloaded operators are unary or binary!");
17134 ErrorKind = 1; // 1 -> binary
17135 }
17136 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17137 << FnDecl->getDeclName() << NumParams << ErrorKind;
17138 }
17139
17140 if (Op == OO_Subscript && NumParams != 2) {
17141 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17142 ? diag::ext_subscript_overload
17143 : diag::error_subscript_overload)
17144 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17145 }
17146
17147 // Overloaded operators other than operator() and operator[] cannot be
17148 // variadic.
17149 if (Op != OO_Call &&
17150 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17151 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17152 << FnDecl->getDeclName();
17153 }
17154
17155 // Some operators must be member functions.
17156 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17157 return Diag(FnDecl->getLocation(),
17158 diag::err_operator_overload_must_be_member)
17159 << FnDecl->getDeclName();
17160 }
17161
17162 // C++ [over.inc]p1:
17163 // The user-defined function called operator++ implements the
17164 // prefix and postfix ++ operator. If this function is a member
17165 // function with no parameters, or a non-member function with one
17166 // parameter of class or enumeration type, it defines the prefix
17167 // increment operator ++ for objects of that type. If the function
17168 // is a member function with one parameter (which shall be of type
17169 // int) or a non-member function with two parameters (the second
17170 // of which shall be of type int), it defines the postfix
17171 // increment operator ++ for objects of that type.
17172 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17173 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17174 QualType ParamType = LastParam->getType();
17175
17176 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17177 !ParamType->isDependentType())
17178 return Diag(LastParam->getLocation(),
17179 diag::err_operator_overload_post_incdec_must_be_int)
17180 << LastParam->getType() << (Op == OO_MinusMinus);
17181 }
17182
17183 return false;
17184}
17185
17186static bool
17188 FunctionTemplateDecl *TpDecl) {
17189 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17190
17191 // Must have one or two template parameters.
17192 if (TemplateParams->size() == 1) {
17193 NonTypeTemplateParmDecl *PmDecl =
17194 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17195
17196 // The template parameter must be a char parameter pack.
17197 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17198 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17199 return false;
17200
17201 // C++20 [over.literal]p5:
17202 // A string literal operator template is a literal operator template
17203 // whose template-parameter-list comprises a single non-type
17204 // template-parameter of class type.
17205 //
17206 // As a DR resolution, we also allow placeholders for deduced class
17207 // template specializations.
17208 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17209 !PmDecl->isTemplateParameterPack() &&
17210 (PmDecl->getType()->isRecordType() ||
17211 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17212 return false;
17213 } else if (TemplateParams->size() == 2) {
17214 TemplateTypeParmDecl *PmType =
17215 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17216 NonTypeTemplateParmDecl *PmArgs =
17217 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17218
17219 // The second template parameter must be a parameter pack with the
17220 // first template parameter as its type.
17221 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17222 PmArgs->isTemplateParameterPack()) {
17223 if (const auto *TArgs =
17224 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17225 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17226 TArgs->getIndex() == PmType->getIndex()) {
17227 if (!SemaRef.inTemplateInstantiation())
17228 SemaRef.Diag(TpDecl->getLocation(),
17229 diag::ext_string_literal_operator_template);
17230 return false;
17231 }
17232 }
17233 }
17234
17235 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17236 diag::err_literal_operator_template)
17237 << TpDecl->getTemplateParameters()->getSourceRange();
17238 return true;
17239}
17240
17242 if (isa<CXXMethodDecl>(FnDecl)) {
17243 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17244 << FnDecl->getDeclName();
17245 return true;
17246 }
17247
17248 if (FnDecl->isExternC()) {
17249 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17250 if (const LinkageSpecDecl *LSD =
17251 FnDecl->getDeclContext()->getExternCContext())
17252 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17253 return true;
17254 }
17255
17256 // This might be the definition of a literal operator template.
17258
17259 // This might be a specialization of a literal operator template.
17260 if (!TpDecl)
17261 TpDecl = FnDecl->getPrimaryTemplate();
17262
17263 // template <char...> type operator "" name() and
17264 // template <class T, T...> type operator "" name() are the only valid
17265 // template signatures, and the only valid signatures with no parameters.
17266 //
17267 // C++20 also allows template <SomeClass T> type operator "" name().
17268 if (TpDecl) {
17269 if (FnDecl->param_size() != 0) {
17270 Diag(FnDecl->getLocation(),
17271 diag::err_literal_operator_template_with_params);
17272 return true;
17273 }
17274
17276 return true;
17277
17278 } else if (FnDecl->param_size() == 1) {
17279 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17280
17281 QualType ParamType = Param->getType().getUnqualifiedType();
17282
17283 // Only unsigned long long int, long double, any character type, and const
17284 // char * are allowed as the only parameters.
17285 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17286 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17287 Context.hasSameType(ParamType, Context.CharTy) ||
17288 Context.hasSameType(ParamType, Context.WideCharTy) ||
17289 Context.hasSameType(ParamType, Context.Char8Ty) ||
17290 Context.hasSameType(ParamType, Context.Char16Ty) ||
17291 Context.hasSameType(ParamType, Context.Char32Ty)) {
17292 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17293 QualType InnerType = Ptr->getPointeeType();
17294
17295 // Pointer parameter must be a const char *.
17296 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17297 Context.CharTy) &&
17298 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17299 Diag(Param->getSourceRange().getBegin(),
17300 diag::err_literal_operator_param)
17301 << ParamType << "'const char *'" << Param->getSourceRange();
17302 return true;
17303 }
17304
17305 } else if (ParamType->isRealFloatingType()) {
17306 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17307 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17308 return true;
17309
17310 } else if (ParamType->isIntegerType()) {
17311 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17312 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17313 return true;
17314
17315 } else {
17316 Diag(Param->getSourceRange().getBegin(),
17317 diag::err_literal_operator_invalid_param)
17318 << ParamType << Param->getSourceRange();
17319 return true;
17320 }
17321
17322 } else if (FnDecl->param_size() == 2) {
17323 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17324
17325 // First, verify that the first parameter is correct.
17326
17327 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17328
17329 // Two parameter function must have a pointer to const as a
17330 // first parameter; let's strip those qualifiers.
17331 const PointerType *PT = FirstParamType->getAs<PointerType>();
17332
17333 if (!PT) {
17334 Diag((*Param)->getSourceRange().getBegin(),
17335 diag::err_literal_operator_param)
17336 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17337 return true;
17338 }
17339
17340 QualType PointeeType = PT->getPointeeType();
17341 // First parameter must be const
17342 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17343 Diag((*Param)->getSourceRange().getBegin(),
17344 diag::err_literal_operator_param)
17345 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17346 return true;
17347 }
17348
17349 QualType InnerType = PointeeType.getUnqualifiedType();
17350 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17351 // const char32_t* are allowed as the first parameter to a two-parameter
17352 // function
17353 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17354 Context.hasSameType(InnerType, Context.WideCharTy) ||
17355 Context.hasSameType(InnerType, Context.Char8Ty) ||
17356 Context.hasSameType(InnerType, Context.Char16Ty) ||
17357 Context.hasSameType(InnerType, Context.Char32Ty))) {
17358 Diag((*Param)->getSourceRange().getBegin(),
17359 diag::err_literal_operator_param)
17360 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17361 return true;
17362 }
17363
17364 // Move on to the second and final parameter.
17365 ++Param;
17366
17367 // The second parameter must be a std::size_t.
17368 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17369 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17370 Diag((*Param)->getSourceRange().getBegin(),
17371 diag::err_literal_operator_param)
17372 << SecondParamType << Context.getSizeType()
17373 << (*Param)->getSourceRange();
17374 return true;
17375 }
17376 } else {
17377 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17378 return true;
17379 }
17380
17381 // Parameters are good.
17382
17383 // A parameter-declaration-clause containing a default argument is not
17384 // equivalent to any of the permitted forms.
17385 for (auto *Param : FnDecl->parameters()) {
17386 if (Param->hasDefaultArg()) {
17387 Diag(Param->getDefaultArgRange().getBegin(),
17388 diag::err_literal_operator_default_argument)
17389 << Param->getDefaultArgRange();
17390 break;
17391 }
17392 }
17393
17394 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17397 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17398 // C++23 [usrlit.suffix]p1:
17399 // Literal suffix identifiers that do not start with an underscore are
17400 // reserved for future standardization. Literal suffix identifiers that
17401 // contain a double underscore __ are reserved for use by C++
17402 // implementations.
17403 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17404 << static_cast<int>(Status)
17406 }
17407
17408 return false;
17409}
17410
17412 Expr *LangStr,
17413 SourceLocation LBraceLoc) {
17414 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17415 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17416
17417 StringRef Lang = Lit->getString();
17419 if (Lang == "C")
17421 else if (Lang == "C++")
17423 else {
17424 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17425 << LangStr->getSourceRange();
17426 return nullptr;
17427 }
17428
17429 // FIXME: Add all the various semantics of linkage specifications
17430
17432 LangStr->getExprLoc(), Language,
17433 LBraceLoc.isValid());
17434
17435 /// C++ [module.unit]p7.2.3
17436 /// - Otherwise, if the declaration
17437 /// - ...
17438 /// - ...
17439 /// - appears within a linkage-specification,
17440 /// it is attached to the global module.
17441 ///
17442 /// If the declaration is already in global module fragment, we don't
17443 /// need to attach it again.
17444 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17445 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17446 D->setLocalOwningModule(GlobalModule);
17447 }
17448
17449 CurContext->addDecl(D);
17450 PushDeclContext(S, D);
17451 return D;
17452}
17453
17455 Decl *LinkageSpec,
17456 SourceLocation RBraceLoc) {
17457 if (RBraceLoc.isValid()) {
17458 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17459 LSDecl->setRBraceLoc(RBraceLoc);
17460 }
17461
17462 // If the current module doesn't has Parent, it implies that the
17463 // LinkageSpec isn't in the module created by itself. So we don't
17464 // need to pop it.
17465 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17466 getCurrentModule()->isImplicitGlobalModule() &&
17467 getCurrentModule()->Parent)
17468 PopImplicitGlobalModuleFragment();
17469
17471 return LinkageSpec;
17472}
17473
17475 const ParsedAttributesView &AttrList,
17476 SourceLocation SemiLoc) {
17477 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17478 // Attribute declarations appertain to empty declaration so we handle
17479 // them here.
17480 ProcessDeclAttributeList(S, ED, AttrList);
17481
17482 CurContext->addDecl(ED);
17483 return ED;
17484}
17485
17487 SourceLocation StartLoc,
17488 SourceLocation Loc,
17489 const IdentifierInfo *Name) {
17490 bool Invalid = false;
17491 QualType ExDeclType = TInfo->getType();
17492
17493 // Arrays and functions decay.
17494 if (ExDeclType->isArrayType())
17495 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17496 else if (ExDeclType->isFunctionType())
17497 ExDeclType = Context.getPointerType(ExDeclType);
17498
17499 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17500 // The exception-declaration shall not denote a pointer or reference to an
17501 // incomplete type, other than [cv] void*.
17502 // N2844 forbids rvalue references.
17503 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17504 Diag(Loc, diag::err_catch_rvalue_ref);
17505 Invalid = true;
17506 }
17507
17508 if (ExDeclType->isVariablyModifiedType()) {
17509 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17510 Invalid = true;
17511 }
17512
17513 QualType BaseType = ExDeclType;
17514 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17515 unsigned DK = diag::err_catch_incomplete;
17516 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17517 BaseType = Ptr->getPointeeType();
17518 Mode = 1;
17519 DK = diag::err_catch_incomplete_ptr;
17520 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17521 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17522 BaseType = Ref->getPointeeType();
17523 Mode = 2;
17524 DK = diag::err_catch_incomplete_ref;
17525 }
17526 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17527 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17528 Invalid = true;
17529
17530 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17531 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17532 Invalid = true;
17533 }
17534
17535 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17536 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17537 Invalid = true;
17538 }
17539
17540 if (!Invalid && !ExDeclType->isDependentType() &&
17541 RequireNonAbstractType(Loc, ExDeclType,
17542 diag::err_abstract_type_in_decl,
17544 Invalid = true;
17545
17546 // Only the non-fragile NeXT runtime currently supports C++ catches
17547 // of ObjC types, and no runtime supports catching ObjC types by value.
17548 if (!Invalid && getLangOpts().ObjC) {
17549 QualType T = ExDeclType;
17550 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17551 T = RT->getPointeeType();
17552
17553 if (T->isObjCObjectType()) {
17554 Diag(Loc, diag::err_objc_object_catch);
17555 Invalid = true;
17556 } else if (T->isObjCObjectPointerType()) {
17557 // FIXME: should this be a test for macosx-fragile specifically?
17559 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17560 }
17561 }
17562
17563 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17564 ExDeclType, TInfo, SC_None);
17565 ExDecl->setExceptionVariable(true);
17566
17567 // In ARC, infer 'retaining' for variables of retainable type.
17568 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17569 Invalid = true;
17570
17571 if (!Invalid && !ExDeclType->isDependentType()) {
17572 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17573 // Insulate this from anything else we might currently be parsing.
17576
17577 // C++ [except.handle]p16:
17578 // The object declared in an exception-declaration or, if the
17579 // exception-declaration does not specify a name, a temporary (12.2) is
17580 // copy-initialized (8.5) from the exception object. [...]
17581 // The object is destroyed when the handler exits, after the destruction
17582 // of any automatic objects initialized within the handler.
17583 //
17584 // We just pretend to initialize the object with itself, then make sure
17585 // it can be destroyed later.
17586 QualType initType = Context.getExceptionObjectType(ExDeclType);
17587
17588 InitializedEntity entity =
17590 InitializationKind initKind =
17592
17593 Expr *opaqueValue =
17594 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17595 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17596 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17597 if (result.isInvalid())
17598 Invalid = true;
17599 else {
17600 // If the constructor used was non-trivial, set this as the
17601 // "initializer".
17602 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17603 if (!construct->getConstructor()->isTrivial()) {
17604 Expr *init = MaybeCreateExprWithCleanups(construct);
17605 ExDecl->setInit(init);
17606 }
17607
17608 // And make sure it's destructable.
17609 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17610 }
17611 }
17612 }
17613
17614 if (Invalid)
17615 ExDecl->setInvalidDecl();
17616
17617 return ExDecl;
17618}
17619
17622 bool Invalid = D.isInvalidType();
17623
17624 // Check for unexpanded parameter packs.
17627 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17628 D.getIdentifierLoc());
17629 Invalid = true;
17630 }
17631
17632 const IdentifierInfo *II = D.getIdentifier();
17633 if (NamedDecl *PrevDecl =
17636 // The scope should be freshly made just for us. There is just no way
17637 // it contains any previous declaration, except for function parameters in
17638 // a function-try-block's catch statement.
17639 assert(!S->isDeclScope(PrevDecl));
17640 if (isDeclInScope(PrevDecl, CurContext, S)) {
17641 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17642 << D.getIdentifier();
17643 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17644 Invalid = true;
17645 } else if (PrevDecl->isTemplateParameter())
17646 // Maybe we will complain about the shadowed template parameter.
17648 }
17649
17650 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17651 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17652 << D.getCXXScopeSpec().getRange();
17653 Invalid = true;
17654 }
17655
17657 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17658 if (Invalid)
17659 ExDecl->setInvalidDecl();
17660
17661 // Add the exception declaration into this scope.
17662 if (II)
17663 PushOnScopeChains(ExDecl, S);
17664 else
17665 CurContext->addDecl(ExDecl);
17666
17667 ProcessDeclAttributes(S, ExDecl, D);
17668 return ExDecl;
17669}
17670
17672 Expr *AssertExpr,
17673 Expr *AssertMessageExpr,
17674 SourceLocation RParenLoc) {
17676 return nullptr;
17677
17678 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17679 AssertMessageExpr, RParenLoc, false);
17680}
17681
17682static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17683 switch (BTK) {
17684 case BuiltinType::Char_S:
17685 case BuiltinType::Char_U:
17686 break;
17687 case BuiltinType::Char8:
17688 OS << "u8";
17689 break;
17690 case BuiltinType::Char16:
17691 OS << 'u';
17692 break;
17693 case BuiltinType::Char32:
17694 OS << 'U';
17695 break;
17696 case BuiltinType::WChar_S:
17697 case BuiltinType::WChar_U:
17698 OS << 'L';
17699 break;
17700 default:
17701 llvm_unreachable("Non-character type");
17702 }
17703}
17704
17705/// Convert character's value, interpreted as a code unit, to a string.
17706/// The value needs to be zero-extended to 32-bits.
17707/// FIXME: This assumes Unicode literal encodings
17709 unsigned TyWidth,
17710 SmallVectorImpl<char> &Str) {
17711 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17712 char *Ptr = Arr;
17713 BuiltinType::Kind K = BTy->getKind();
17714 llvm::raw_svector_ostream OS(Str);
17715
17716 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17717 // other types.
17718 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17719 K == BuiltinType::Char8 || Value <= 0x7F) {
17720 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17721 if (!Escaped.empty())
17722 EscapeStringForDiagnostic(Escaped, Str);
17723 else
17724 OS << static_cast<char>(Value);
17725 return;
17726 }
17727
17728 switch (K) {
17729 case BuiltinType::Char16:
17730 case BuiltinType::Char32:
17731 case BuiltinType::WChar_S:
17732 case BuiltinType::WChar_U: {
17733 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17734 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17735 else
17736 OS << "\\x"
17737 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17738 break;
17739 }
17740 default:
17741 llvm_unreachable("Non-character type is passed");
17742 }
17743}
17744
17745/// Convert \V to a string we can present to the user in a diagnostic
17746/// \T is the type of the expression that has been evaluated into \V
17749 ASTContext &Context) {
17750 if (!V.hasValue())
17751 return false;
17752
17753 switch (V.getKind()) {
17755 if (T->isBooleanType()) {
17756 // Bools are reduced to ints during evaluation, but for
17757 // diagnostic purposes we want to print them as
17758 // true or false.
17759 int64_t BoolValue = V.getInt().getExtValue();
17760 assert((BoolValue == 0 || BoolValue == 1) &&
17761 "Bool type, but value is not 0 or 1");
17762 llvm::raw_svector_ostream OS(Str);
17763 OS << (BoolValue ? "true" : "false");
17764 } else {
17765 llvm::raw_svector_ostream OS(Str);
17766 // Same is true for chars.
17767 // We want to print the character representation for textual types
17768 const auto *BTy = T->getAs<BuiltinType>();
17769 if (BTy) {
17770 switch (BTy->getKind()) {
17771 case BuiltinType::Char_S:
17772 case BuiltinType::Char_U:
17773 case BuiltinType::Char8:
17774 case BuiltinType::Char16:
17775 case BuiltinType::Char32:
17776 case BuiltinType::WChar_S:
17777 case BuiltinType::WChar_U: {
17778 unsigned TyWidth = Context.getIntWidth(T);
17779 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17780 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17781 WriteCharTypePrefix(BTy->getKind(), OS);
17782 OS << '\'';
17783 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17784 OS << "' (0x"
17785 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17786 /*Upper=*/true)
17787 << ", " << V.getInt() << ')';
17788 return true;
17789 }
17790 default:
17791 break;
17792 }
17793 }
17794 V.getInt().toString(Str);
17795 }
17796
17797 break;
17798
17800 V.getFloat().toString(Str);
17801 break;
17802
17804 if (V.isNullPointer()) {
17805 llvm::raw_svector_ostream OS(Str);
17806 OS << "nullptr";
17807 } else
17808 return false;
17809 break;
17810
17812 llvm::raw_svector_ostream OS(Str);
17813 OS << '(';
17814 V.getComplexFloatReal().toString(Str);
17815 OS << " + ";
17816 V.getComplexFloatImag().toString(Str);
17817 OS << "i)";
17818 } break;
17819
17821 llvm::raw_svector_ostream OS(Str);
17822 OS << '(';
17823 V.getComplexIntReal().toString(Str);
17824 OS << " + ";
17825 V.getComplexIntImag().toString(Str);
17826 OS << "i)";
17827 } break;
17828
17829 default:
17830 return false;
17831 }
17832
17833 return true;
17834}
17835
17836/// Some Expression types are not useful to print notes about,
17837/// e.g. literals and values that have already been expanded
17838/// before such as int-valued template parameters.
17839static bool UsefulToPrintExpr(const Expr *E) {
17840 E = E->IgnoreParenImpCasts();
17841 // Literals are pretty easy for humans to understand.
17844 return false;
17845
17846 // These have been substituted from template parameters
17847 // and appear as literals in the static assert error.
17849 return false;
17850
17851 // -5 is also simple to understand.
17852 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17853 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17854
17855 // Only print nested arithmetic operators.
17856 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17857 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17858 BO->isBitwiseOp());
17859
17860 return true;
17861}
17862
17864 // FIXME: Should we also ignore explicit casts?
17865 E = E->IgnoreParenImpCasts();
17866 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17867 Op && Op->getOpcode() != BO_LOr) {
17868 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17869 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17870
17871 // Ignore comparisons of boolean expressions with a boolean literal.
17872 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17873 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17874 return;
17875
17876 // Don't print obvious expressions.
17877 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17878 return;
17879
17880 struct {
17881 const clang::Expr *Cond;
17883 SmallString<12> ValueString;
17884 bool Print;
17885 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17886 {RHS, Expr::EvalResult(), {}, false}};
17887 for (auto &DiagSide : DiagSides) {
17888 const Expr *Side = DiagSide.Cond;
17889
17890 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17891
17892 DiagSide.Print = ConvertAPValueToString(
17893 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17894 }
17895 if (DiagSides[0].Print && DiagSides[1].Print) {
17896 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17897 << DiagSides[0].ValueString << Op->getOpcodeStr()
17898 << DiagSides[1].ValueString << Op->getSourceRange();
17899 }
17900 } else if (const auto *RE = dyn_cast<RequiresExpr>(E)) {
17902 } else {
17904 }
17905}
17906
17907template <typename ResultType>
17908static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17909 ResultType &Result, ASTContext &Ctx,
17911 bool ErrorOnInvalidMessage) {
17912
17913 assert(Message);
17914 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17915 "can't evaluate a dependant static assert message");
17916
17917 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17918 assert(SL->isUnevaluated() && "expected an unevaluated string");
17919 if constexpr (std::is_same_v<APValue, ResultType>) {
17920 Result =
17921 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17922 const ConstantArrayType *CAT =
17923 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17924 assert(CAT && "string literal isn't an array");
17925 QualType CharType = CAT->getElementType();
17926 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17927 CharType->isUnsignedIntegerType());
17928 for (unsigned I = 0; I < SL->getLength(); I++) {
17929 Value = SL->getCodeUnit(I);
17930 Result.getArrayInitializedElt(I) = APValue(Value);
17931 }
17932 } else {
17933 Result.assign(SL->getString().begin(), SL->getString().end());
17934 }
17935 return true;
17936 }
17937
17938 SourceLocation Loc = Message->getBeginLoc();
17939 QualType T = Message->getType().getNonReferenceType();
17940 auto *RD = T->getAsCXXRecordDecl();
17941 if (!RD) {
17942 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17943 return false;
17944 }
17945
17946 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17948 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17949 SemaRef.LookupQualifiedName(MemberLookup, RD);
17950 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17952 if (MemberLookup.empty())
17953 return std::nullopt;
17954 return std::move(MemberLookup);
17955 };
17956
17957 std::optional<LookupResult> SizeMember = FindMember("size");
17958 std::optional<LookupResult> DataMember = FindMember("data");
17959 if (!SizeMember || !DataMember) {
17960 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17961 << EvalContext
17962 << ((!SizeMember && !DataMember) ? 2
17963 : !SizeMember ? 0
17964 : 1);
17965 return false;
17966 }
17967
17968 auto BuildExpr = [&](LookupResult &LR) {
17970 Message, Message->getType(), Message->getBeginLoc(), false,
17971 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17972 if (Res.isInvalid())
17973 return ExprError();
17974 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17975 false, true);
17976 if (Res.isInvalid())
17977 return ExprError();
17978 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17979 return ExprError();
17980 return SemaRef.TemporaryMaterializationConversion(Res.get());
17981 };
17982
17983 ExprResult SizeE = BuildExpr(*SizeMember);
17984 ExprResult DataE = BuildExpr(*DataMember);
17985
17986 QualType SizeT = SemaRef.Context.getSizeType();
17987 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17988 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17989
17990 ExprResult EvaluatedSize =
17991 SizeE.isInvalid()
17992 ? ExprError()
17995 if (EvaluatedSize.isInvalid()) {
17996 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17997 << EvalContext << /*size*/ 0;
17998 return false;
17999 }
18000
18001 ExprResult EvaluatedData =
18002 DataE.isInvalid()
18003 ? ExprError()
18005 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
18006 if (EvaluatedData.isInvalid()) {
18007 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18008 << EvalContext << /*data*/ 1;
18009 return false;
18010 }
18011
18012 if (!ErrorOnInvalidMessage &&
18013 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
18014 return true;
18015
18016 Expr::EvalResult Status;
18018 Status.Diag = &Notes;
18019 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
18020 EvaluatedData.get(), Ctx, Status) ||
18021 !Notes.empty()) {
18022 SemaRef.Diag(Message->getBeginLoc(),
18023 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
18024 : diag::warn_user_defined_msg_constexpr)
18025 << EvalContext;
18026 for (const auto &Note : Notes)
18027 SemaRef.Diag(Note.first, Note.second);
18028 return !ErrorOnInvalidMessage;
18029 }
18030 return true;
18031}
18032
18034 StringEvaluationContext EvalContext,
18035 bool ErrorOnInvalidMessage) {
18036 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18037 ErrorOnInvalidMessage);
18038}
18039
18040bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18041 StringEvaluationContext EvalContext,
18042 bool ErrorOnInvalidMessage) {
18043 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18044 ErrorOnInvalidMessage);
18045}
18046
18048 Expr *AssertExpr, Expr *AssertMessage,
18049 SourceLocation RParenLoc,
18050 bool Failed) {
18051 assert(AssertExpr != nullptr && "Expected non-null condition");
18052 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18053 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18054 !AssertMessage->isValueDependent())) &&
18055 !Failed) {
18056 // In a static_assert-declaration, the constant-expression shall be a
18057 // constant expression that can be contextually converted to bool.
18058 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
18059 if (Converted.isInvalid())
18060 Failed = true;
18061
18062 ExprResult FullAssertExpr =
18063 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
18064 /*DiscardedValue*/ false,
18065 /*IsConstexpr*/ true);
18066 if (FullAssertExpr.isInvalid())
18067 Failed = true;
18068 else
18069 AssertExpr = FullAssertExpr.get();
18070
18071 llvm::APSInt Cond;
18072 Expr *BaseExpr = AssertExpr;
18074
18075 if (!getLangOpts().CPlusPlus) {
18076 // In C mode, allow folding as an extension for better compatibility with
18077 // C++ in terms of expressions like static_assert("test") or
18078 // static_assert(nullptr).
18079 FoldKind = AllowFoldKind::Allow;
18080 }
18081
18082 if (!Failed && VerifyIntegerConstantExpression(
18083 BaseExpr, &Cond,
18084 diag::err_static_assert_expression_is_not_constant,
18085 FoldKind).isInvalid())
18086 Failed = true;
18087
18088 // If the static_assert passes, only verify that
18089 // the message is grammatically valid without evaluating it.
18090 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18091 std::string Str;
18092 EvaluateAsString(AssertMessage, Str, Context,
18094 /*ErrorOnInvalidMessage=*/false);
18095 }
18096
18097 // CWG2518
18098 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18099 // template definition, the declaration has no effect.
18100 bool InTemplateDefinition =
18101 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18102
18103 if (!Failed && !Cond && !InTemplateDefinition) {
18104 SmallString<256> MsgBuffer;
18105 llvm::raw_svector_ostream Msg(MsgBuffer);
18106 bool HasMessage = AssertMessage;
18107 if (AssertMessage) {
18108 std::string Str;
18109 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18111 /*ErrorOnInvalidMessage=*/true) ||
18112 !Str.empty();
18113 Msg << Str;
18114 }
18115 Expr *InnerCond = nullptr;
18116 std::string InnerCondDescription;
18117 std::tie(InnerCond, InnerCondDescription) =
18118 findFailedBooleanCondition(Converted.get());
18119 if (const auto *ConceptIDExpr =
18120 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18121 const ASTConstraintSatisfaction &Satisfaction =
18122 ConceptIDExpr->getSatisfaction();
18123 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18124 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18125 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18126 // Drill down into concept specialization expressions to see why they
18127 // weren't satisfied.
18128 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18129 }
18130 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18131 !isa<IntegerLiteral>(InnerCond)) {
18132 Diag(InnerCond->getBeginLoc(),
18133 diag::err_static_assert_requirement_failed)
18134 << InnerCondDescription << !HasMessage << Msg.str()
18135 << InnerCond->getSourceRange();
18136 DiagnoseStaticAssertDetails(InnerCond);
18137 } else {
18138 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18139 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18141 }
18142 Failed = true;
18143 }
18144 } else {
18145 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18146 /*DiscardedValue*/false,
18147 /*IsConstexpr*/true);
18148 if (FullAssertExpr.isInvalid())
18149 Failed = true;
18150 else
18151 AssertExpr = FullAssertExpr.get();
18152 }
18153
18155 AssertExpr, AssertMessage, RParenLoc,
18156 Failed);
18157
18158 CurContext->addDecl(Decl);
18159 return Decl;
18160}
18161
18163 if (const auto *PIT = dyn_cast<PackIndexingType>(T))
18164 return PIT->getPattern();
18165 return T;
18166}
18167
18168static const TemplateSpecializationType *
18171 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(T))
18172 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Context);
18173
18174 const auto *TST = dyn_cast<TemplateSpecializationType>(T);
18175 if (!TST)
18176 return nullptr;
18177
18178 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18179 if (!TD || isa<ClassTemplateDecl>(TD))
18180 return TST;
18181 return nullptr;
18182}
18183
18185 NestedNameSpecifierLoc NNSLoc) {
18186 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18187 TL = TL.getPrefix().getAsTypeLoc()) {
18188 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18189 continue;
18190
18191 Diag(Loc, diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18192 return true;
18193 }
18194 return false;
18195}
18196
18198 NestedNameSpecifier NNS) {
18199 QualType T(NNS.getAsType(), 0);
18200 if (const auto *TST =
18201 dyn_cast<TemplateSpecializationType>(IgnorePackIndexing(T))) {
18202 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18203 TST->getTemplateName().getAsTemplateDecl())) {
18204 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec)
18205 << NNS;
18206 return;
18207 }
18208 }
18209
18210 if (NNS.getAsRecordDecl()) {
18211 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18212 } else {
18213 S.Diag(Loc, diag::err_dependent_friend_not_member);
18214 }
18215}
18216
18220 bool IsInstantiation) {
18222 if (!NNS.isDependent() && !IsInstantiation)
18223 return false;
18224
18225 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18226 "nested-name-specifier of dependent friend must be a type");
18227
18228 QualType T(NNS.getAsType(), 0);
18229 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18230 return true;
18231
18232 const TemplateSpecializationType *TST =
18234 if (!TST) {
18235 DiagnoseDependentFriendNotMember(*this, Loc, NNS);
18236 return true;
18237 }
18238
18239 if (TPLs.empty())
18240 return false;
18241
18242 SmallVector<NamedDecl *, 4> UndeducedParameters;
18243 for (TemplateParameterList *Params : TPLs) {
18244 llvm::SmallBitVector UsedParameters(Params->size());
18245 MarkUsedTemplateParameters(TST->template_arguments(),
18246 /*OnlyDeduced=*/true, Params->getDepth(),
18247 UsedParameters);
18248
18249 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18250 if (!UsedParameters[I])
18251 UndeducedParameters.push_back(Params->getParam(I));
18252 }
18253
18254 if (UndeducedParameters.empty())
18255 return false;
18256
18257 Diag(Loc, diag::err_dependent_friend_undeduced_params)
18258 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18259
18260 for (NamedDecl *Param : UndeducedParameters) {
18261 if (Param->getDeclName())
18262 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18263 << Param->getDeclName();
18264 else
18265 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18266 << "(anonymous)";
18267 }
18268
18269 return true;
18270}
18271
18273 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18274 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18275 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18276 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18278
18279 bool IsMemberSpecialization = false;
18280 bool Invalid = false;
18281
18282 TemplateParameterList *TemplateParams =
18283 MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, TemplateId,
18284 TempParamLists, /*friend*/ true,
18285 IsMemberSpecialization, Invalid);
18286 if (TemplateId) {
18287 if (Invalid)
18288 return true;
18289
18290 if (TemplateParams) {
18291 Diag(NameLoc, diag::err_not_class_template_specialization) << 0;
18292 return true;
18293 }
18294 }
18295
18296 if (TemplateParams) {
18297 if (TemplateParams->size() > 0) {
18298 if (Invalid)
18299 return true;
18300
18301 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18303 S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc, Attr,
18304 TemplateParams, AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18305 FriendLoc, TempParamLists.size() - 1, TempParamLists.data(),
18306 IsMemberSpecialization);
18307 return Result.get();
18308 }
18309 } else {
18310 // The "template<>" header is extraneous.
18311 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18312 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18313 }
18314 }
18315
18316 if (Invalid)
18317 return true;
18318
18319 bool IsAllExplicitSpecializations =
18320 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18321 return List->size() == 0;
18322 });
18323
18324 // FIXME: don't ignore attributes.
18325
18326 // If it's explicit specializations all the way down, just forget
18327 // about the template header and build an appropriate non-templated
18328 // friend. TODO: for source fidelity, remember the headers.
18330 if (!TemplateId && IsAllExplicitSpecializations) {
18331 if (SS.isEmpty()) {
18332 bool Owned = false;
18333 bool IsDependent = false;
18334 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18335 Attr, AS_public,
18336 /*ModulePrivateLoc=*/SourceLocation(),
18337 MultiTemplateParamsArg(), Owned, IsDependent,
18338 /*ScopedEnumKWLoc=*/SourceLocation(),
18339 /*ScopedEnumUsesClassTag=*/false,
18340 /*UnderlyingType=*/TypeResult(),
18341 /*IsTypeSpecifier=*/false,
18342 /*IsTemplateParamOrArg=*/false,
18343 /*OOK=*/OffsetOfKind::Outside);
18344 }
18345
18346 TypeSourceInfo *TSI = nullptr;
18349 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18350 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18351 if (T.isNull())
18352 return true;
18353
18355 FriendLoc, EllipsisLoc);
18356 Friend->setAccess(AS_public);
18357 CurContext->addDecl(Friend);
18358 return Friend;
18359 }
18360
18361 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18362
18363 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18364 if (TemplateParams)
18365 TPLs = TPLs.drop_back();
18366 if (CheckDependentFriend(TagLoc, QualifierLoc, TPLs,
18367 /*IsInstantiation=*/false))
18368 return true;
18369
18370 TypeSourceInfo *TSI = nullptr;
18371 if (TemplateId) {
18372 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18373 TemplateId->NumArgs);
18375 TagUseKind::Friend, static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18376 TemplateId->TemplateKWLoc, TemplateId->Template, NameLoc,
18377 TemplateId->LAngleLoc, ParsedArgs, TemplateId->RAngleLoc);
18378 if (ParsedType.isInvalid())
18379 return true;
18380
18381 GetTypeFromParser(ParsedType.get(), &TSI);
18382 } else {
18384 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18385 TSI = Context.CreateTypeSourceInfo(T);
18386
18388 TL.setElaboratedKeywordLoc(TagLoc);
18389 TL.setQualifierLoc(QualifierLoc);
18390 TL.setNameLoc(NameLoc);
18391 }
18392
18394 collectUnexpandedParameterPacks(TSI->getTypeLoc(), Unexpanded);
18395 if (EllipsisLoc.isInvalid()) {
18397 return true;
18398 } else if (Unexpanded.empty()) {
18399 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18400 << TSI->getTypeLoc().getSourceRange();
18401 return true;
18402 } else {
18403 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18404 // introduced by the template-declaration containing that specifier.
18405 if (!TempParamLists.empty()) {
18406 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18407 for (UnexpandedParameterPack &U : Unexpanded) {
18408 if (std::optional<std::pair<unsigned, unsigned>> DI =
18410 DI && DI->first >= FriendDeclDepth) {
18411 auto *ND = dyn_cast<NamedDecl *>(U.first);
18412 if (!ND)
18413 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18414 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18415 << ND->getDeclName()
18416 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18417 return true;
18418 }
18419 }
18420 }
18421 }
18422
18424 if (TempParamLists.empty())
18425 Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18426 EllipsisLoc);
18427 else {
18428 if (CheckTemplateDeclScope(S, TempParamLists.back()))
18429 return true;
18430
18432 if (TemplateParams)
18433 FriendTemplate = Context.getDependentTemplateName(
18434 {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
18435 Friend =
18436 FriendTemplateDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18437 TempParamLists, EllipsisLoc, FriendTemplate);
18438 }
18439
18440 Friend->setAccess(AS_public);
18441 CurContext->addDecl(Friend);
18442
18443 return Friend;
18444}
18445
18447 MultiTemplateParamsArg TempParams,
18448 SourceLocation EllipsisLoc) {
18449 SourceLocation Loc = DS.getBeginLoc();
18450 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18451
18452 assert(DS.isFriendSpecified());
18454
18455 // C++ [class.friend]p3:
18456 // A friend declaration that does not declare a function shall have one of
18457 // the following forms:
18458 // friend elaborated-type-specifier ;
18459 // friend simple-type-specifier ;
18460 // friend typename-specifier ;
18461 //
18462 // If the friend keyword isn't first, or if the declarations has any type
18463 // qualifiers, then the declaration doesn't have that form.
18465 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18466 if (DS.getTypeQualifiers()) {
18468 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18470 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18472 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18474 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18476 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18477 }
18478
18479 // Try to convert the decl specifier to a type. This works for
18480 // friend templates because ActOnTag never produces a ClassTemplateDecl
18481 // for a TagUseKind::Friend.
18482 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18484 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18485 QualType T = TSI->getType();
18486 if (TheDeclarator.isInvalidType())
18487 return nullptr;
18488
18489 // If '...' is present, the type must contain an unexpanded parameter
18490 // pack, and vice versa.
18491 bool Invalid = false;
18492 if (EllipsisLoc.isInvalid() &&
18494 return nullptr;
18495 if (EllipsisLoc.isValid() &&
18497 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18498 << TSI->getTypeLoc().getSourceRange();
18499 Invalid = true;
18500 }
18501
18502 if (!T->isElaboratedTypeSpecifier()) {
18503 if (TempParams.size()) {
18504 // C++23 [dcl.pre]p5:
18505 // In a simple-declaration, the optional init-declarator-list can be
18506 // omitted only when declaring a class or enumeration, that is, when
18507 // the decl-specifier-seq contains either a class-specifier, an
18508 // elaborated-type-specifier with a class-key, or an enum-specifier.
18509 //
18510 // The declaration of a template-declaration or explicit-specialization
18511 // is never a member-declaration, so this must be a simple-declaration
18512 // with no init-declarator-list. Therefore, this is ill-formed.
18513 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18514 return nullptr;
18515 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18516 SmallString<16> InsertionText(" ");
18517 InsertionText += RD->getKindName();
18518
18520 ? diag::warn_cxx98_compat_unelaborated_friend_type
18521 : diag::ext_unelaborated_friend_type)
18522 << (unsigned)RD->getTagKind() << T
18524 InsertionText);
18525 } else {
18526 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18527 << T << DS.getSourceRange();
18528 }
18529 }
18530
18531 // C++98 [class.friend]p1: A friend of a class is a function
18532 // or class that is not a member of the class . . .
18533 // This is fixed in DR77, which just barely didn't make the C++03
18534 // deadline. It's also a very silly restriction that seriously
18535 // affects inner classes and which nobody else seems to implement;
18536 // thus we never diagnose it, not even in -pedantic.
18537 //
18538 // But note that we could warn about it: it's always useless to
18539 // friend one of your own members (it's not, however, worthless to
18540 // friend a member of an arbitrary specialization of your template).
18541
18542 Decl *D;
18543 if (!TempParams.empty()) {
18544 if (CheckTemplateDeclScope(S, TempParams.back()))
18545 return nullptr;
18546
18547 // TODO: Support variadic friend template decls?
18548 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TSI, FriendLoc,
18549 TempParams, EllipsisLoc);
18550 } else
18552 TSI, FriendLoc, EllipsisLoc);
18553
18554 if (!D)
18555 return nullptr;
18556
18557 D->setAccess(AS_public);
18558 CurContext->addDecl(D);
18559
18560 if (Invalid)
18561 D->setInvalidDecl();
18562
18563 return D;
18564}
18565
18567 MultiTemplateParamsArg TemplateParams) {
18568 const DeclSpec &DS = D.getDeclSpec();
18569
18570 assert(DS.isFriendSpecified());
18572
18575
18576 // C++ [class.friend]p1
18577 // A friend of a class is a function or class....
18578 // Note that this sees through typedefs, which is intended.
18579 // It *doesn't* see through dependent types, which is correct
18580 // according to [temp.arg.type]p3:
18581 // If a declaration acquires a function type through a
18582 // type dependent on a template-parameter and this causes
18583 // a declaration that does not use the syntactic form of a
18584 // function declarator to have a function type, the program
18585 // is ill-formed.
18586 if (!TInfo->getType()->isFunctionType()) {
18587 Diag(Loc, diag::err_unexpected_friend);
18588
18589 // It might be worthwhile to try to recover by creating an
18590 // appropriate declaration.
18591 return nullptr;
18592 }
18593
18594 // C++ [namespace.memdef]p3
18595 // - If a friend declaration in a non-local class first declares a
18596 // class or function, the friend class or function is a member
18597 // of the innermost enclosing namespace.
18598 // - The name of the friend is not found by simple name lookup
18599 // until a matching declaration is provided in that namespace
18600 // scope (either before or after the class declaration granting
18601 // friendship).
18602 // - If a friend function is called, its name may be found by the
18603 // name lookup that considers functions from namespaces and
18604 // classes associated with the types of the function arguments.
18605 // - When looking for a prior declaration of a class or a function
18606 // declared as a friend, scopes outside the innermost enclosing
18607 // namespace scope are not considered.
18608
18609 CXXScopeSpec &SS = D.getCXXScopeSpec();
18611 assert(NameInfo.getName());
18612
18614 NameInfo.getLoc(), SS.getWithLocInContext(Context)))
18615 return nullptr;
18616
18617 // Check for unexpanded parameter packs.
18621 return nullptr;
18622
18623 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18624
18625 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18626 auto Kind = SS.getScopeRep().getKind();
18627 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18629 if (IsNamespaceOrGlobal) {
18630 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
18631 << SS.getScopeRep();
18632 SS.clear();
18633 }
18634 }
18635
18636 // The context we found the declaration in, or in which we should
18637 // create the declaration.
18638 DeclContext *DC;
18639 Scope *DCScope = S;
18640 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18642
18643 // There are five cases here.
18644 // - There's no scope specifier and we're in a local class. Only look
18645 // for functions declared in the immediately-enclosing block scope.
18646 // We recover from invalid scope qualifiers as if they just weren't there.
18647 FunctionDecl *FunctionContainingLocalClass = nullptr;
18648 if ((SS.isInvalid() || !SS.isSet()) &&
18649 (FunctionContainingLocalClass =
18650 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18651 // C++11 [class.friend]p11:
18652 // If a friend declaration appears in a local class and the name
18653 // specified is an unqualified name, a prior declaration is
18654 // looked up without considering scopes that are outside the
18655 // innermost enclosing non-class scope. For a friend function
18656 // declaration, if there is no prior declaration, the program is
18657 // ill-formed.
18658
18659 // Find the innermost enclosing non-class scope. This is the block
18660 // scope containing the local class definition (or for a nested class,
18661 // the outer local class).
18662 DCScope = S->getFnParent();
18663
18664 // Look up the function name in the scope.
18666 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18667
18668 if (!Previous.empty()) {
18669 // All possible previous declarations must have the same context:
18670 // either they were declared at block scope or they are members of
18671 // one of the enclosing local classes.
18672 DC = Previous.getRepresentativeDecl()->getDeclContext();
18673 } else {
18674 // This is ill-formed, but provide the context that we would have
18675 // declared the function in, if we were permitted to, for error recovery.
18676 DC = FunctionContainingLocalClass;
18677 }
18679
18680 // - There's no scope specifier, in which case we just go to the
18681 // appropriate scope and look for a function or function template
18682 // there as appropriate.
18683 } else if (SS.isInvalid() || !SS.isSet()) {
18684 // C++11 [namespace.memdef]p3:
18685 // If the name in a friend declaration is neither qualified nor
18686 // a template-id and the declaration is a function or an
18687 // elaborated-type-specifier, the lookup to determine whether
18688 // the entity has been previously declared shall not consider
18689 // any scopes outside the innermost enclosing namespace.
18690
18691 // Find the appropriate context according to the above.
18692 DC = CurContext;
18693
18694 // Skip class contexts. If someone can cite chapter and verse
18695 // for this behavior, that would be nice --- it's what GCC and
18696 // EDG do, and it seems like a reasonable intent, but the spec
18697 // really only says that checks for unqualified existing
18698 // declarations should stop at the nearest enclosing namespace,
18699 // not that they should only consider the nearest enclosing
18700 // namespace.
18701 while (DC->isRecord())
18702 DC = DC->getParent();
18703
18704 DeclContext *LookupDC = DC->getNonTransparentContext();
18705 while (true) {
18706 LookupQualifiedName(Previous, LookupDC);
18707
18708 if (!Previous.empty()) {
18709 DC = LookupDC;
18710 break;
18711 }
18712
18713 if (isTemplateId) {
18714 if (isa<TranslationUnitDecl>(LookupDC)) break;
18715 } else {
18716 if (LookupDC->isFileContext()) break;
18717 }
18718 LookupDC = LookupDC->getParent();
18719 }
18720
18721 DCScope = getScopeForDeclContext(S, DC);
18722
18723 // - There's a non-dependent scope specifier, in which case we
18724 // compute it and do a previous lookup there for a function
18725 // or function template.
18726 } else if (!SS.getScopeRep().isDependent()) {
18727 DC = computeDeclContext(SS);
18728 if (!DC) return nullptr;
18729
18730 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18731
18733
18734 // C++ [class.friend]p1: A friend of a class is a function or
18735 // class that is not a member of the class . . .
18736 if (DC->Equals(CurContext))
18739 diag::warn_cxx98_compat_friend_is_member :
18740 diag::err_friend_is_member);
18741
18742 // - There's a dependent scope specifier, in which case we use an
18743 // arbitrary context and wait for instantiation.
18744 } else {
18745 DC = CurContext;
18746 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18747 }
18748
18749 if (!DC->isRecord()) {
18750 int DiagArg = -1;
18751 switch (D.getName().getKind()) {
18754 DiagArg = 0;
18755 break;
18757 DiagArg = 1;
18758 break;
18760 DiagArg = 2;
18761 break;
18763 DiagArg = 3;
18764 break;
18770 break;
18771 }
18772 // This implies that it has to be an operator or function.
18773 if (DiagArg >= 0) {
18774 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18775 return nullptr;
18776 }
18777 } else {
18778 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
18779 if (RC->isLambda()) {
18780 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
18781 }
18782 }
18783
18784 // FIXME: This is an egregious hack to cope with cases where the scope stack
18785 // does not contain the declaration context, i.e., in an out-of-line
18786 // definition of a class.
18787 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18788 if (!DCScope) {
18789 FakeDCScope.setEntity(DC);
18790 DCScope = &FakeDCScope;
18791 }
18792
18793 bool AddToScope = true;
18794 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18795 TemplateParams, AddToScope);
18796 if (!ND) return nullptr;
18797
18798 assert(ND->getLexicalDeclContext() == CurContext);
18799
18800 // If we performed typo correction, we might have added a scope specifier
18801 // and changed the decl context.
18802 DC = ND->getDeclContext();
18803
18804 // Add the function declaration to the appropriate lookup tables,
18805 // adjusting the redeclarations list as necessary. We don't
18806 // want to do this yet if the friending class is dependent.
18807 //
18808 // Also update the scope-based lookup if the target context's
18809 // lookup context is in lexical scope.
18810 if (!CurContext->isDependentContext()) {
18811 DC = DC->getRedeclContext();
18813 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18814 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18815 }
18816
18818
18819 if (ND->isInvalidDecl()) {
18822 Friend->setAccess(AS_public);
18824 Friend->setInvalidDecl();
18825 CurContext->addDecl(Friend);
18826 return ND;
18827 }
18828
18829 FunctionDecl *FD = ND->getAsFunction();
18830 assert(FD && "Expected a function declaration!");
18831
18833 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TPLs.back()))
18834 return nullptr;
18835
18837 if (!TPLs.empty() && SS.isValid())
18838 Friend =
18840 ND, DS.getFriendSpecLoc(), TPLs);
18841 else
18843 DS.getFriendSpecLoc());
18844
18845 Friend->setAccess(AS_public);
18846 CurContext->addDecl(Friend);
18847
18848 if (DC->isRecord())
18850
18851 if (!TemplateParams.empty() && SS.isValid() &&
18854 /*IsInstantiation=*/false))
18855 return ND;
18856
18857 // C++ [class.friend]p6:
18858 // A function may be defined in a friend declaration of a class if and
18859 // only if the class is a non-local class, and the function name is
18860 // unqualified.
18861 if (D.isFunctionDefinition()) {
18862 // Qualified friend function definition.
18863 if (SS.isNotEmpty()) {
18865 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18866
18867 DB << SS.getScopeRep();
18868
18869 // Friend function defined in a local class.
18870 } else if (FunctionContainingLocalClass) {
18871 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18872
18873 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18874 // a template-id, the function name is not unqualified because these is
18875 // no name. While the wording requires some reading in-between the
18876 // lines, GCC, MSVC, and EDG all consider a friend function
18877 // specialization definitions to be de facto explicit specialization
18878 // and diagnose them as such.
18879 } else if (isTemplateId) {
18880 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18881 }
18882 }
18883
18884 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18885 // default argument expression, that declaration shall be a definition
18886 // and shall be the only declaration of the function or function
18887 // template in the translation unit.
18889 // We can't look at FD->getPreviousDecl() because it may not have been set
18890 // if we're in a dependent context. If the function is known to be a
18891 // redeclaration, we will have narrowed Previous down to the right decl.
18892 if (D.isRedeclaration()) {
18893 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18894 Diag(Previous.getRepresentativeDecl()->getLocation(),
18895 diag::note_previous_declaration);
18896 } else if (!D.isFunctionDefinition())
18897 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18898 }
18899
18900 return ND;
18901}
18902
18904 StringLiteral *Message) {
18906
18907 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18908 if (!Fn) {
18909 Diag(DelLoc, diag::err_deleted_non_function);
18910 return;
18911 }
18912
18913 // Deleted function does not have a body.
18914 Fn->setWillHaveBody(false);
18915
18916 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18917 // Don't consider the implicit declaration we generate for explicit
18918 // specializations. FIXME: Do not generate these implicit declarations.
18919 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18920 Prev->getPreviousDecl()) &&
18921 !Prev->isDefined()) {
18922 Diag(DelLoc, diag::err_deleted_decl_not_first);
18923 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18924 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18925 : diag::note_previous_declaration);
18926 // We can't recover from this; the declaration might have already
18927 // been used.
18928 Fn->setInvalidDecl();
18929 return;
18930 }
18931
18932 // To maintain the invariant that functions are only deleted on their first
18933 // declaration, mark the implicitly-instantiated declaration of the
18934 // explicitly-specialized function as deleted instead of marking the
18935 // instantiated redeclaration.
18936 Fn = Fn->getCanonicalDecl();
18937 }
18938
18939 // dllimport/dllexport cannot be deleted.
18940 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18941 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18942 Fn->setInvalidDecl();
18943 }
18944
18945 // C++11 [basic.start.main]p3:
18946 // A program that defines main as deleted [...] is ill-formed.
18947 if (Fn->isMain())
18948 Diag(DelLoc, diag::err_deleted_main);
18949
18950 // C++11 [dcl.fct.def.delete]p4:
18951 // A deleted function is implicitly inline.
18952 Fn->setImplicitlyInline();
18953 Fn->setDeletedAsWritten(true, Message);
18954}
18955
18957 if (!Dcl || Dcl->isInvalidDecl())
18958 return;
18959
18960 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18961 if (!FD) {
18962 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18963 if (FTD->getTemplatedDecl()->getDefaultedFunctionKind().isComparison()) {
18964 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18965 return;
18966 }
18967 }
18968
18969 Diag(DefaultLoc, diag::err_default_special_members)
18970 << getLangOpts().CPlusPlus20;
18971 return;
18972 }
18973
18974 // Reject if this can't possibly be a defaultable function.
18975 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
18976 if (!DefKind &&
18977 // A dependent function that doesn't locally look defaultable can
18978 // still instantiate to a defaultable function if it's a constructor
18979 // or assignment operator.
18980 (!FD->isDependentContext() ||
18982 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18983 Diag(DefaultLoc, diag::err_default_special_members)
18984 << getLangOpts().CPlusPlus20;
18985 return;
18986 }
18987
18988 // Issue compatibility warning. We already warned if the operator is
18989 // 'operator<=>' when parsing the '<=>' token.
18990 if (DefKind.isComparison() &&
18992 DiagCompat(DefaultLoc, diag_compat::defaulted_comparison);
18993 }
18994
18995 FD->setDefaulted();
18996 FD->setExplicitlyDefaulted();
18997 FD->setDefaultLoc(DefaultLoc);
18998
18999 // Defer checking functions that are defaulted in a dependent context.
19000 if (FD->isDependentContext())
19001 return;
19002
19003 // Unset that we will have a body for this function. We might not,
19004 // if it turns out to be trivial, and we don't need this marking now
19005 // that we've marked it as defaulted.
19006 FD->setWillHaveBody(false);
19007
19008 if (DefKind.isComparison()) {
19009 // If this comparison's defaulting occurs within the definition of its
19010 // lexical class context, we have to do the checking when complete.
19011 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
19012 if (!RD->isCompleteDefinition())
19013 return;
19014 }
19015
19016 // If this member fn was defaulted on its first declaration, we will have
19017 // already performed the checking in CheckCompletedCXXClass. Such a
19018 // declaration doesn't trigger an implicit definition.
19019 if (isa<CXXMethodDecl>(FD)) {
19020 const FunctionDecl *Primary = FD;
19021 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
19022 // Ask the template instantiation pattern that actually had the
19023 // '= default' on it.
19024 Primary = Pattern;
19025 if (Primary->getCanonicalDecl()->isDefaulted())
19026 return;
19027 }
19028
19029 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19030 // non-default FP features to stash. This avoids memory overhead for
19031 // the vast majority of defaulted functions.
19032 if (!FD->getDefaultedOrDeletedInfo() &&
19033 CurFPFeatureOverrides().requiresTrailingStorage()) {
19034 FD->setDefaultedOrDeletedInfo(
19036 Context, /*Lookups=*/{}, CurFPFeatureOverrides()));
19037 }
19038
19039 if (DefKind.isComparison()) {
19040 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
19041 FD->setInvalidDecl();
19042 else
19043 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
19044 } else {
19045 auto *MD = cast<CXXMethodDecl>(FD);
19046
19048 DefaultLoc))
19049 MD->setInvalidDecl();
19050 else
19051 DefineDefaultedFunction(*this, MD, DefaultLoc);
19052 }
19053}
19054
19056 for (Stmt *SubStmt : S->children()) {
19057 if (!SubStmt)
19058 continue;
19059 if (isa<ReturnStmt>(SubStmt))
19060 Self.Diag(SubStmt->getBeginLoc(),
19061 diag::err_return_in_constructor_handler);
19062 if (!isa<Expr>(SubStmt))
19063 SearchForReturnInStmt(Self, SubStmt);
19064 }
19065}
19066
19068 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19069 CXXCatchStmt *Handler = TryBlock->getHandler(I);
19070 SearchForReturnInStmt(*this, Handler);
19071 }
19072}
19073
19075 StringLiteral *DeletedMessage) {
19076 switch (BodyKind) {
19077 case FnBodyKind::Delete:
19078 SetDeclDeleted(D, Loc, DeletedMessage);
19079 break;
19081 SetDeclDefaulted(D, Loc);
19082 break;
19083 case FnBodyKind::Other:
19084 llvm_unreachable(
19085 "Parsed function body should be '= delete;' or '= default;'");
19086 }
19087}
19088
19090 const CXXMethodDecl *Old) {
19091 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19092 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19093
19094 if (OldFT->hasExtParameterInfos()) {
19095 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19096 // A parameter of the overriding method should be annotated with noescape
19097 // if the corresponding parameter of the overridden method is annotated.
19098 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19099 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19100 Diag(New->getParamDecl(I)->getLocation(),
19101 diag::warn_overriding_method_missing_noescape);
19102 Diag(Old->getParamDecl(I)->getLocation(),
19103 diag::note_overridden_marked_noescape);
19104 }
19105 }
19106
19107 // SME attributes must match when overriding a function declaration.
19108 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
19109 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
19110 << New << New->getType() << Old->getType();
19111 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19112 return true;
19113 }
19114
19115 // Virtual overrides must have the same code_seg.
19116 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19117 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19118 if ((NewCSA || OldCSA) &&
19119 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19120 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
19121 Diag(Old->getLocation(), diag::note_previous_declaration);
19122 return true;
19123 }
19124
19125 // Virtual overrides: check for matching effects.
19126 if (Context.hasAnyFunctionEffects()) {
19127 const auto OldFX = Old->getFunctionEffects();
19128 const auto NewFXOrig = New->getFunctionEffects();
19129
19130 if (OldFX != NewFXOrig) {
19131 FunctionEffectSet NewFX(NewFXOrig);
19132 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19134 for (const auto &Diff : Diffs) {
19135 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
19137 break;
19139 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
19140 << Diff.effectName();
19141 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19142 << Old->getReturnTypeSourceRange();
19143 break;
19145 NewFX.insert(Diff.Old.value(), Errs);
19146 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19147 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19149 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
19150 NewFT->getParamTypes(), EPI);
19151 New->setType(ModQT);
19152 if (Errs.empty()) {
19153 // A warning here is somewhat pedantic. Skip this if there was
19154 // already a merge conflict, which is more serious.
19155 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
19156 << Diff.effectName();
19157 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19158 << Old->getReturnTypeSourceRange();
19159 }
19160 break;
19161 }
19162 }
19163 }
19164 if (!Errs.empty())
19165 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
19166 Old->getLocation());
19167 }
19168 }
19169
19170 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19171
19172 // If the calling conventions match, everything is fine
19173 if (NewCC == OldCC)
19174 return false;
19175
19176 // If the calling conventions mismatch because the new function is static,
19177 // suppress the calling convention mismatch error; the error about static
19178 // function override (err_static_overrides_virtual from
19179 // Sema::CheckFunctionDeclaration) is more clear.
19180 if (New->getStorageClass() == SC_Static)
19181 return false;
19182
19183 Diag(New->getLocation(),
19184 diag::err_conflicting_overriding_cc_attributes)
19185 << New->getDeclName() << New->getType() << Old->getType();
19186 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19187 return true;
19188}
19189
19191 const CXXMethodDecl *Old) {
19192 // CWG2553
19193 // A virtual function shall not be an explicit object member function.
19194 if (!New->isExplicitObjectMemberFunction())
19195 return true;
19196 Diag(New->getParamDecl(0)->getBeginLoc(),
19197 diag::err_explicit_object_parameter_nonmember)
19198 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19199 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19200 New->setInvalidDecl();
19201 return false;
19202}
19203
19205 const CXXMethodDecl *Old) {
19206 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19207 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19208
19209 if (Context.hasSameType(NewTy, OldTy) ||
19210 NewTy->isDependentType() || OldTy->isDependentType())
19211 return false;
19212
19213 // Check if the return types are covariant
19214 QualType NewClassTy, OldClassTy;
19215
19216 /// Both types must be pointers or references to classes.
19217 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19218 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19219 NewClassTy = NewPT->getPointeeType();
19220 OldClassTy = OldPT->getPointeeType();
19221 }
19222 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19223 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19224 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19225 NewClassTy = NewRT->getPointeeType();
19226 OldClassTy = OldRT->getPointeeType();
19227 }
19228 }
19229 }
19230
19231 // The return types aren't either both pointers or references to a class type.
19232 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19233 Diag(New->getLocation(),
19234 diag::err_different_return_type_for_overriding_virtual_function)
19235 << New->getDeclName() << NewTy << OldTy
19236 << New->getReturnTypeSourceRange();
19237 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19238 << Old->getReturnTypeSourceRange();
19239
19240 return true;
19241 }
19242
19243 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
19244 // C++14 [class.virtual]p8:
19245 // If the class type in the covariant return type of D::f differs from
19246 // that of B::f, the class type in the return type of D::f shall be
19247 // complete at the point of declaration of D::f or shall be the class
19248 // type D.
19249 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19250 if (!RD->isBeingDefined() &&
19251 RequireCompleteType(New->getLocation(), NewClassTy,
19252 diag::err_covariant_return_incomplete,
19253 New->getDeclName()))
19254 return true;
19255 }
19256
19257 // Check if the new class derives from the old class.
19258 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
19259 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
19260 << New->getDeclName() << NewTy << OldTy
19261 << New->getReturnTypeSourceRange();
19262 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19263 << Old->getReturnTypeSourceRange();
19264 return true;
19265 }
19266
19267 // Check if we the conversion from derived to base is valid.
19269 NewClassTy, OldClassTy,
19270 diag::err_covariant_return_inaccessible_base,
19271 diag::err_covariant_return_ambiguous_derived_to_base_conv,
19272 New->getLocation(), New->getReturnTypeSourceRange(),
19273 New->getDeclName(), nullptr)) {
19274 // FIXME: this note won't trigger for delayed access control
19275 // diagnostics, and it's impossible to get an undelayed error
19276 // here from access control during the original parse because
19277 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19278 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19279 << Old->getReturnTypeSourceRange();
19280 return true;
19281 }
19282 }
19283
19284 // The qualifiers of the return types must be the same.
19285 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19286 Diag(New->getLocation(),
19287 diag::err_covariant_return_type_different_qualifications)
19288 << New->getDeclName() << NewTy << OldTy
19289 << New->getReturnTypeSourceRange();
19290 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19291 << Old->getReturnTypeSourceRange();
19292 return true;
19293 }
19294
19295
19296 // The new class type must have the same or less qualifiers as the old type.
19297 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
19298 Diag(New->getLocation(),
19299 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19300 << New->getDeclName() << NewTy << OldTy
19301 << New->getReturnTypeSourceRange();
19302 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19303 << Old->getReturnTypeSourceRange();
19304 return true;
19305 }
19306
19307 return false;
19308}
19309
19311 SourceLocation EndLoc = InitRange.getEnd();
19312 if (EndLoc.isValid())
19313 Method->setRangeEnd(EndLoc);
19314
19315 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19316 Method->setIsPureVirtual();
19317 return false;
19318 }
19319
19320 if (!Method->isInvalidDecl())
19321 Diag(Method->getLocation(), diag::err_non_virtual_pure)
19322 << Method->getDeclName() << InitRange;
19323 return true;
19324}
19325
19327 if (D->getFriendObjectKind())
19328 Diag(D->getLocation(), diag::err_pure_friend);
19329 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19330 CheckPureMethod(M, ZeroLoc);
19331 else
19332 Diag(D->getLocation(), diag::err_illegal_initializer);
19333}
19334
19335/// Invoked when we are about to parse an initializer for the declaration
19336/// 'Dcl'.
19337///
19338/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19339/// static data member of class X, names should be looked up in the scope of
19340/// class X. If the declaration had a scope specifier, a scope will have
19341/// been created and passed in for this purpose. Otherwise, S will be null.
19343 assert(D && !D->isInvalidDecl());
19344
19345 // We will always have a nested name specifier here, but this declaration
19346 // might not be out of line if the specifier names the current namespace:
19347 // extern int n;
19348 // int ::n = 0;
19349 if (S && D->isOutOfLine())
19351
19355}
19356
19358 assert(D);
19359
19360 if (S && D->isOutOfLine())
19362
19364}
19365
19367 // C++ 6.4p2:
19368 // The declarator shall not specify a function or an array.
19369 // The type-specifier-seq shall not contain typedef and shall not declare a
19370 // new class or enumeration.
19372 "Parser allowed 'typedef' as storage class of condition decl.");
19373
19374 Decl *Dcl = ActOnDeclarator(S, D);
19375 if (!Dcl)
19376 return true;
19377
19378 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19379 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19380 << D.getSourceRange();
19381 return true;
19382 }
19383
19384 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19385 VD->setCXXCondDecl();
19386
19387 return Dcl;
19388}
19389
19391 if (!ExternalSource)
19392 return;
19393
19395 ExternalSource->ReadUsedVTables(VTables);
19397 for (const ExternalVTableUse &VTable : VTables) {
19398 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19399 VTablesUsed.find(VTable.Record);
19400 // Even if a definition wasn't required before, it may be required now.
19401 if (Pos != VTablesUsed.end()) {
19402 if (!Pos->second && VTable.DefinitionRequired)
19403 Pos->second = true;
19404 continue;
19405 }
19406
19407 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19408 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
19409 }
19410
19411 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19412}
19413
19415 bool DefinitionRequired) {
19416 // Ignore any vtable uses in unevaluated operands or for classes that do
19417 // not have a vtable.
19418 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19419 CurContext->isDependentContext() || isUnevaluatedContext())
19420 return;
19421 // Do not mark as used if compiling for the device outside of the target
19422 // region.
19423 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19424 !OpenMP().isInOpenMPDeclareTargetContext() &&
19425 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19426 if (!DefinitionRequired)
19428 return;
19429 }
19430
19431 // Try to insert this class into the map.
19433 Class = Class->getCanonicalDecl();
19434 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19435 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19436 if (!Pos.second) {
19437 // If we already had an entry, check to see if we are promoting this vtable
19438 // to require a definition. If so, we need to reappend to the VTableUses
19439 // list, since we may have already processed the first entry.
19440 if (DefinitionRequired && !Pos.first->second) {
19441 Pos.first->second = true;
19442 } else {
19443 // Otherwise, we can early exit.
19444 return;
19445 }
19446 } else {
19447 // The Microsoft ABI requires that we perform the destructor body
19448 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19449 // the deleting destructor is emitted with the vtable, not with the
19450 // destructor definition as in the Itanium ABI.
19451 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19452 CXXDestructorDecl *DD = Class->getDestructor();
19453 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19454 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19455 // If this is an out-of-line declaration, marking it referenced will
19456 // not do anything. Manually call CheckDestructor to look up operator
19457 // delete().
19458 ContextRAII SavedContext(*this, DD);
19459 CheckDestructor(DD);
19460 if (!DD->getOperatorDelete())
19461 DD->setInvalidDecl();
19462 } else {
19463 MarkFunctionReferenced(Loc, Class->getDestructor());
19464 }
19465 }
19466 }
19467 }
19468
19469 // Local classes need to have their virtual members marked
19470 // immediately. For all other classes, we mark their virtual members
19471 // at the end of the translation unit.
19472 if (Class->isLocalClass())
19473 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19474 else
19475 VTableUses.push_back(std::make_pair(Class, Loc));
19476}
19477
19480 if (VTableUses.empty())
19481 return false;
19482
19483 // Note: The VTableUses vector could grow as a result of marking
19484 // the members of a class as "used", so we check the size each
19485 // time through the loop and prefer indices (which are stable) to
19486 // iterators (which are not).
19487 bool DefinedAnything = false;
19488 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19489 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19490 if (!Class)
19491 continue;
19493 Class->getTemplateSpecializationKind();
19494
19495 SourceLocation Loc = VTableUses[I].second;
19496
19497 bool DefineVTable = true;
19498
19499 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19500 // V-tables for non-template classes with an owning module are always
19501 // uniquely emitted in that module.
19502 if (Class->isInCurrentModuleUnit()) {
19503 DefineVTable = true;
19504 } else if (KeyFunction && !KeyFunction->hasBody()) {
19505 // If this class has a key function, but that key function is
19506 // defined in another translation unit, we don't need to emit the
19507 // vtable even though we're using it.
19508 // The key function is in another translation unit.
19509 DefineVTable = false;
19511 KeyFunction->getTemplateSpecializationKind();
19514 "Instantiations don't have key functions");
19515 (void)TSK;
19516 } else if (!KeyFunction) {
19517 // If we have a class with no key function that is the subject
19518 // of an explicit instantiation declaration, suppress the
19519 // vtable; it will live with the explicit instantiation
19520 // definition.
19521 bool IsExplicitInstantiationDeclaration =
19523 for (auto *R : Class->redecls()) {
19525 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19527 IsExplicitInstantiationDeclaration = true;
19528 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19529 IsExplicitInstantiationDeclaration = false;
19530 break;
19531 }
19532 }
19533
19534 if (IsExplicitInstantiationDeclaration) {
19535 const bool HasExcludeFromExplicitInstantiation =
19536 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
19537 // If the class has a member function declared with
19538 // `__attribute__((exclude_from_explicit_instantiation))`, the
19539 // explicit instantiation declaration should not suppress emitting
19540 // the vtable, since the corresponding explicit instantiation
19541 // definition might not emit the vtable if a triggering method is
19542 // excluded.
19543 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19544 });
19545 if (!HasExcludeFromExplicitInstantiation)
19546 DefineVTable = false;
19547 }
19548 }
19549
19550 // The exception specifications for all virtual members may be needed even
19551 // if we are not providing an authoritative form of the vtable in this TU.
19552 // We may choose to emit it available_externally anyway.
19553 if (!DefineVTable) {
19555 continue;
19556 }
19557
19558 // Mark all of the virtual members of this class as referenced, so
19559 // that we can build a vtable. Then, tell the AST consumer that a
19560 // vtable for this class is required.
19561 DefinedAnything = true;
19563 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19564 // The vtable is assumed to be emitted in an external source only for
19565 // classes attached to a named module, which is guaranteed to have an object
19566 // file. This isn't true for -fmodules-debuginfo, which still has
19567 // shouldEmitInExternalSource as true so that debug info gets supressed.
19568 if (VTablesUsed[Canonical] &&
19569 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19570 Consumer.HandleVTable(Class);
19571
19572 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19573 // no key function or the key function is inlined. Don't warn in C++ ABIs
19574 // that lack key functions, since the user won't be able to make one.
19575 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19576 Class->isExternallyVisible() &&
19577 !(Class->getOwningModule() &&
19578 Class->getOwningModule()->isInterfaceOrPartition()) &&
19579 ClassTSK != TSK_ImplicitInstantiation &&
19582 const FunctionDecl *KeyFunctionDef = nullptr;
19583 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19584 KeyFunctionDef->isInlined()))
19585 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19586 }
19587 }
19588 VTableUses.clear();
19589
19590 return DefinedAnything;
19591}
19592
19594 const CXXRecordDecl *RD) {
19595 for (const auto *I : RD->methods())
19596 if (I->isVirtual() && !I->isPureVirtual())
19597 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19598}
19599
19601 const CXXRecordDecl *RD,
19602 bool ConstexprOnly) {
19603 // Mark all functions which will appear in RD's vtable as used.
19604 CXXFinalOverriderMap FinalOverriders;
19605 RD->getFinalOverriders(FinalOverriders);
19606 for (const auto &FinalOverrider : FinalOverriders) {
19607 for (const auto &OverridingMethod : FinalOverrider.second) {
19608 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19609 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19610
19611 // C++ [basic.def.odr]p2:
19612 // [...] A virtual member function is used if it is not pure. [...]
19613 if (!Overrider->isPureVirtual() &&
19614 (!ConstexprOnly || Overrider->isConstexpr()))
19615 MarkFunctionReferenced(Loc, Overrider);
19616 }
19617 }
19618
19619 // Only classes that have virtual bases need a VTT.
19620 if (RD->getNumVBases() == 0)
19621 return;
19622
19623 for (const auto &I : RD->bases()) {
19624 const auto *Base = I.getType()->castAsCXXRecordDecl();
19625 if (Base->getNumVBases() == 0)
19626 continue;
19628 }
19629}
19630
19631static
19636 Sema &S) {
19637 if (Ctor->isInvalidDecl())
19638 return;
19639
19641
19642 // Target may not be determinable yet, for instance if this is a dependent
19643 // call in an uninstantiated template.
19644 if (Target) {
19645 const FunctionDecl *FNTarget = nullptr;
19646 (void)Target->hasBody(FNTarget);
19647 Target = const_cast<CXXConstructorDecl*>(
19648 cast_or_null<CXXConstructorDecl>(FNTarget));
19649 }
19650
19651 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19652 // Avoid dereferencing a null pointer here.
19653 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19654
19655 if (!Current.insert(Canonical).second)
19656 return;
19657
19658 // We know that beyond here, we aren't chaining into a cycle.
19659 if (!Target || !Target->isDelegatingConstructor() ||
19660 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19661 Valid.insert_range(Current);
19662 Current.clear();
19663 // We've hit a cycle.
19664 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19665 Current.count(TCanonical)) {
19666 // If we haven't diagnosed this cycle yet, do so now.
19667 if (!Invalid.count(TCanonical)) {
19668 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19669 diag::warn_delegating_ctor_cycle)
19670 << Ctor;
19671
19672 // Don't add a note for a function delegating directly to itself.
19673 if (TCanonical != Canonical)
19674 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19675
19677 while (C->getCanonicalDecl() != Canonical) {
19678 const FunctionDecl *FNTarget = nullptr;
19679 (void)C->getTargetConstructor()->hasBody(FNTarget);
19680 assert(FNTarget && "Ctor cycle through bodiless function");
19681
19682 C = const_cast<CXXConstructorDecl*>(
19683 cast<CXXConstructorDecl>(FNTarget));
19684 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19685 }
19686 }
19687
19688 Invalid.insert_range(Current);
19689 Current.clear();
19690 } else {
19692 }
19693}
19694
19695
19698
19699 for (DelegatingCtorDeclsType::iterator
19700 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19701 E = DelegatingCtorDecls.end();
19702 I != E; ++I)
19703 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19704
19705 for (CXXConstructorDecl *CI : Invalid)
19706 CI->setInvalidDecl();
19707}
19708
19709namespace {
19710 /// AST visitor that finds references to the 'this' expression.
19711class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19712 Sema &S;
19713
19714public:
19715 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19716
19717 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19718 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19719 << E->isImplicit();
19720 return false;
19721 }
19722};
19723}
19724
19726 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19727 if (!TSInfo)
19728 return false;
19729
19730 TypeLoc TL = TSInfo->getTypeLoc();
19732 if (!ProtoTL)
19733 return false;
19734
19735 // C++11 [expr.prim.general]p3:
19736 // [The expression this] shall not appear before the optional
19737 // cv-qualifier-seq and it shall not appear within the declaration of a
19738 // static member function (although its type and value category are defined
19739 // within a static member function as they are within a non-static member
19740 // function). [ Note: this is because declaration matching does not occur
19741 // until the complete declarator is known. - end note ]
19742 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19743 FindCXXThisExpr Finder(*this);
19744
19745 // If the return type came after the cv-qualifier-seq, check it now.
19746 if (Proto->hasTrailingReturn() &&
19747 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19748 return true;
19749
19750 // Check the exception specification.
19752 return true;
19753
19754 // Check the trailing requires clause
19755 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19756 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19757 return true;
19758
19760}
19761
19763 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19764 if (!TSInfo)
19765 return false;
19766
19767 TypeLoc TL = TSInfo->getTypeLoc();
19769 if (!ProtoTL)
19770 return false;
19771
19772 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19773 FindCXXThisExpr Finder(*this);
19774
19775 switch (Proto->getExceptionSpecType()) {
19776 case EST_Unparsed:
19777 case EST_Uninstantiated:
19778 case EST_Unevaluated:
19779 case EST_BasicNoexcept:
19780 case EST_NoThrow:
19781 case EST_DynamicNone:
19782 case EST_MSAny:
19783 case EST_None:
19784 break;
19785
19787 case EST_NoexceptFalse:
19788 case EST_NoexceptTrue:
19789 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19790 return true;
19791 [[fallthrough]];
19792
19793 case EST_Dynamic:
19794 for (const auto &E : Proto->exceptions()) {
19795 if (!Finder.TraverseType(E))
19796 return true;
19797 }
19798 break;
19799 }
19800
19801 return false;
19802}
19803
19805 FindCXXThisExpr Finder(*this);
19806
19807 // Check attributes.
19808 for (const auto *A : Method->attrs()) {
19809 // FIXME: This should be emitted by tblgen.
19810 Expr *Arg = nullptr;
19811 ArrayRef<Expr *> Args;
19812 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19813 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19814 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19815 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19816 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19817 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19818 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19819 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19820 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19821 Arg = LR->getArg();
19822 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19823 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19824 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19825 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19826 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19827 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19828 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19829 Arg = AC->getSuccessValue();
19830 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19831 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19832 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19833
19834 if (Arg && !Finder.TraverseStmt(Arg))
19835 return true;
19836
19837 for (Expr *A : Args) {
19838 if (!Finder.TraverseStmt(A))
19839 return true;
19840 }
19841 }
19842
19843 return false;
19844}
19845
19847 bool IsTopLevel, ExceptionSpecificationType EST,
19848 ArrayRef<ParsedType> DynamicExceptions,
19849 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19850 SmallVectorImpl<QualType> &Exceptions,
19852 Exceptions.clear();
19853 ESI.Type = EST;
19854 if (EST == EST_Dynamic) {
19855 Exceptions.reserve(DynamicExceptions.size());
19856 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19857 // FIXME: Preserve type source info.
19858 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19859
19860 if (IsTopLevel) {
19862 collectUnexpandedParameterPacks(ET, Unexpanded);
19863 if (!Unexpanded.empty()) {
19865 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19866 Unexpanded);
19867 continue;
19868 }
19869 }
19870
19871 // Check that the type is valid for an exception spec, and
19872 // drop it if not.
19873 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19874 Exceptions.push_back(ET);
19875 }
19876 ESI.Exceptions = Exceptions;
19877 return;
19878 }
19879
19880 if (isComputedNoexcept(EST)) {
19881 assert((NoexceptExpr->isTypeDependent() ||
19882 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19883 Context.BoolTy) &&
19884 "Parser should have made sure that the expression is boolean");
19885 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19886 ESI.Type = EST_BasicNoexcept;
19887 return;
19888 }
19889
19890 ESI.NoexceptExpr = NoexceptExpr;
19891 return;
19892 }
19893}
19894
19896 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19897 ArrayRef<ParsedType> DynamicExceptions,
19898 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19899 if (!D)
19900 return;
19901
19902 // Dig out the function we're referring to.
19903 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19904 D = FTD->getTemplatedDecl();
19905
19906 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19907 if (!FD)
19908 return;
19909
19910 // Check the exception specification.
19913 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19914 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19915 ESI);
19916
19917 // Update the exception specification on the function type.
19918 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19919
19920 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19921 if (MD->isStatic())
19923
19924 if (MD->isVirtual()) {
19925 // Check overrides, which we previously had to delay.
19926 for (const CXXMethodDecl *O : MD->overridden_methods())
19928 }
19929 }
19930}
19931
19932/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19933///
19935 SourceLocation DeclStart, Declarator &D,
19936 Expr *BitWidth,
19937 InClassInitStyle InitStyle,
19938 AccessSpecifier AS,
19939 const ParsedAttr &MSPropertyAttr) {
19940 const IdentifierInfo *II = D.getIdentifier();
19941 if (!II) {
19942 Diag(DeclStart, diag::err_anonymous_property);
19943 return nullptr;
19944 }
19946
19948 QualType T = TInfo->getType();
19949 if (getLangOpts().CPlusPlus) {
19951
19954 D.setInvalidType();
19955 T = Context.IntTy;
19956 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19957 }
19958 }
19959
19961
19963 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19964 << getLangOpts().CPlusPlus17;
19967 diag::err_invalid_thread)
19969
19970 // Check to see if this name was declared as a member previously
19971 NamedDecl *PrevDecl = nullptr;
19972 LookupResult Previous(*this, II, Loc, LookupMemberName,
19974 LookupName(Previous, S);
19975 switch (Previous.getResultKind()) {
19978 PrevDecl = Previous.getAsSingle<NamedDecl>();
19979 break;
19980
19982 PrevDecl = Previous.getRepresentativeDecl();
19983 break;
19984
19988 break;
19989 }
19990
19991 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19992 // Maybe we will complain about the shadowed template parameter.
19994 // Just pretend that we didn't see the previous declaration.
19995 PrevDecl = nullptr;
19996 }
19997
19998 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19999 PrevDecl = nullptr;
20000
20001 SourceLocation TSSL = D.getBeginLoc();
20002 MSPropertyDecl *NewPD =
20003 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
20004 MSPropertyAttr.getPropertyDataGetter(),
20005 MSPropertyAttr.getPropertyDataSetter());
20006 ProcessDeclAttributes(TUScope, NewPD, D);
20007 NewPD->setAccess(AS);
20008
20009 if (NewPD->isInvalidDecl())
20010 Record->setInvalidDecl();
20011
20013 NewPD->setModulePrivate();
20014
20015 if (NewPD->isInvalidDecl() && PrevDecl) {
20016 // Don't introduce NewFD into scope; there's already something
20017 // with the same name in the same scope.
20018 } else if (II) {
20019 PushOnScopeChains(NewPD, S);
20020 } else
20021 Record->addDecl(NewPD);
20022
20023 return NewPD;
20024}
20025
20027 Declarator &Declarator, unsigned TemplateParameterDepth) {
20028 auto &Info = InventedParameterInfos.emplace_back();
20029 TemplateParameterList *ExplicitParams = nullptr;
20030 ArrayRef<TemplateParameterList *> ExplicitLists =
20032 if (!ExplicitLists.empty()) {
20033 bool IsMemberSpecialization, IsInvalid;
20036 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20037 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
20038 /*SuppressDiagnostic=*/true);
20039 }
20040 // C++23 [dcl.fct]p23:
20041 // An abbreviated function template can have a template-head. The invented
20042 // template-parameters are appended to the template-parameter-list after
20043 // the explicitly declared template-parameters.
20044 //
20045 // A template-head must have one or more template-parameters (read:
20046 // 'template<>' is *not* a template-head). Only append the invented
20047 // template parameters if we matched the nested-name-specifier to a non-empty
20048 // TemplateParameterList.
20049 if (ExplicitParams && !ExplicitParams->empty()) {
20050 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20051 llvm::append_range(Info.TemplateParams, *ExplicitParams);
20052 Info.NumExplicitTemplateParams = ExplicitParams->size();
20053 } else {
20054 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20055 Info.NumExplicitTemplateParams = 0;
20056 }
20057}
20058
20060 auto &FSI = InventedParameterInfos.back();
20061 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20062 if (FSI.NumExplicitTemplateParams != 0) {
20063 TemplateParameterList *ExplicitParams =
20067 Context, ExplicitParams->getTemplateLoc(),
20068 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
20069 ExplicitParams->getRAngleLoc(),
20070 ExplicitParams->getRequiresClause()));
20071 } else {
20074 FSI.TemplateParams, Declarator.getEndLoc(),
20075 /*RequiresClause=*/nullptr));
20076 }
20077 }
20078 InventedParameterInfos.pop_back();
20079}
20080
20082 CXXConstructorDecl *Ctor, bool IsCopy) {
20083 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20084
20085 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20086 // If we build args for default constructor closures, those will have
20087 // been generated *before* building args for any copy constructor closures.
20088 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20089 return false;
20090 }
20091
20092 unsigned NumParams = Ctor->getNumParams();
20093 if (NumParams == 0)
20094 return false;
20095
20096 CXXDefaultArgExpr **Args =
20097 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20098
20099 if (IsCopy)
20100 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20101
20102 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20103 ExprResult R = BuildCXXDefaultArgExpr(Loc, Ctor, Ctor->getParamDecl(I));
20105 if (R.isInvalid())
20106 return true;
20107 Args[I] = cast<CXXDefaultArgExpr>(R.get());
20108 }
20109
20110 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20111 return false;
20112}
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 AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
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 Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
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 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 const TemplateSpecializationType * GetClassTemplateSpecializationType(ASTContext &Context, QualType T)
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 QualType IgnorePackIndexing(QualType T)
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 void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc, NestedNameSpecifier NNS)
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 MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
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:239
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:850
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:846
const LangOptions & getLangOpts() const
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:899
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:965
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:1838
QualType getElementType() const
Definition TypeBase.h:3825
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:3526
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3604
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3516
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3596
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3525
Expr * getLHS() const
Definition Expr.h:4132
Expr * getRHS() const
Definition Expr.h:4134
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:5138
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
Opcode getOpcode() const
Definition Expr.h:4127
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2173
A binding in a decomposition declaration.
Definition DeclCXX.h:4215
void setDecomposedDecl(DecompositionDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4259
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3707
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:4253
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
Wrapper for source info for block pointers.
Definition TypeLoc.h:1557
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3292
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:29
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:1213
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:2642
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2882
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:3063
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2736
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:3040
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:3058
void setCtorClosureDefaultArgs(ArrayRef< CXXDefaultArgExpr * > Args)
Definition DeclCXX.cpp:3143
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2877
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:3018
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs() const
Definition DeclCXX.cpp:3139
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclCXX.h:2714
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3013
Represents a C++ base or member initializer.
Definition DeclCXX.h:2407
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2579
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2966
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2953
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2487
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2541
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2553
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
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:3158
const FunctionDecl * getOperatorDelete() const
Definition DeclCXX.cpp:3230
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:774
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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:2719
bool isVirtual() const
Definition DeclCXX.h:2205
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2229
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:2504
unsigned getNumExplicitParams() const
Definition DeclCXX.h:2321
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2270
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2828
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2822
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2812
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
bool isInstance() const
Definition DeclCXX.h:2177
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2317
bool isStatic() const
Definition DeclCXX.cpp:2417
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2263
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:1286
friend_range friends() const
Definition DeclFriend.h:183
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1357
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:613
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1256
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1011
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:827
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:719
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1436
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1407
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1386
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:711
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.cpp:1508
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:970
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1372
base_class_range bases()
Definition DeclCXX.h:609
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:606
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1317
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:771
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:899
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:918
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:651
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:940
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1745
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1279
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1294
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:982
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:601
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:702
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1298
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:732
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1344
base_class_range vbases()
Definition DeclCXX.h:626
base_class_iterator vbases_begin()
Definition DeclCXX.h:633
ctor_range ctors() const
Definition DeclCXX.h:671
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:874
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1231
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1246
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:865
bool isDynamicClass() const
Definition DeclCXX.h:575
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1158
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:805
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1418
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1309
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1210
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:799
bool hasDefinition() const
Definition DeclCXX.h:562
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:924
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1017
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
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:910
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:1004
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1396
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1023
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1430
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1756
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:812
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:556
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:853
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:992
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:933
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1322
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
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:955
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:70
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:109
unsigned getNumHandlers() const
Definition StmtCXX.h:108
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
bool isCallToStdMove() const
Definition Expr.cpp:3676
Expr * getCallee()
Definition Expr.h:3134
arg_range arguments()
Definition Expr.h:3239
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3764
Expr * getSubExpr()
Definition Expr.h:3770
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:3355
QualType getElementType() const
Definition TypeBase.h:3365
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
body_range body()
Definition Stmt.h:1815
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:3851
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3907
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:3707
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3771
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3498
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:5401
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:2443
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:2279
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2628
bool isFileContext() const
Definition DeclBase.h:2217
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:2222
bool isRecord() const
Definition DeclBase.h:2226
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:2425
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2423
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2181
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:1290
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:1358
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1488
SourceLocation getBeginLoc() const
Definition Expr.h:1369
bool isImmediateEscalating() const
Definition Expr.h:1498
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:1643
decl_range decls()
Definition Stmt.h:1691
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1669
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:453
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:550
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:100
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:594
@ 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:2843
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:781
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2004
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:815
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:863
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
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:4279
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4319
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:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
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:970
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5962
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:3558
Represents an enum.
Definition Decl.h:4146
enumerator_range enumerators() const
Definition Decl.h:4292
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
const Expr * getExpr() const
Definition DeclCXX.h:1958
void setExpr(Expr *E)
Definition DeclCXX.h:1983
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1982
This represents one expression.
Definition Expr.h:113
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:178
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
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:3286
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:145
Represents difference between two FPOptions values.
FPOptions applyOverrides(FPOptions Base)
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3395
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4790
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3475
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4780
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3469
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4800
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3542
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3401
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:116
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
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 * > FriendTPLists, SourceLocation EllipsisLoc={}, TemplateName Template={})
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2123
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2152
DefaultedComparisonKind asComparison() const
Definition Decl.h:2155
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3126
Represents a function declaration or definition.
Definition Decl.h:2059
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2773
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3266
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:3000
bool isTrivialForCall() const
Definition Decl.h:2507
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2603
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3181
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3889
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4232
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2428
bool isImmediateFunction() const
Definition Decl.cpp:3382
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3147
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4066
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3593
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3907
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3052
SourceLocation getDefaultLoc() const
Definition Decl.h:2525
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2516
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4352
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2913
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3789
param_iterator param_begin()
Definition Decl.h:2917
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2954
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3119
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2440
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2613
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4368
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3269
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4296
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3019
bool isStatic() const
Definition Decl.h:3060
void setTrivial(bool IT)
Definition Decl.h:2505
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4183
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2769
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2480
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3660
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3353
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3597
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3601
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3605
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4608
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3064
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4169
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2600
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4456
void setDefaulted(bool D=true)
Definition Decl.h:2513
bool isConsteval() const
Definition Decl.h:2609
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2537
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3286
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:2993
void setBody(Stmt *B)
Definition Decl.cpp:3278
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2471
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3921
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3868
size_t param_size() const
Definition Decl.h:2921
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2325
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3186
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:3233
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:2936
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2816
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5334
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5988
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5366
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5198
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1834
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5398
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5902
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5705
unsigned getNumParams() const
Definition TypeBase.h:5676
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5818
const QualType * param_type_iterator
Definition TypeBase.h:5836
QualType getParamType(unsigned i) const
Definition TypeBase.h:5678
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5802
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5687
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5763
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5683
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5852
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5867
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:1675
unsigned getNumParams() const
Definition TypeLoc.h:1747
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1753
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1756
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4817
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4594
CallingConv getCallConv() const
Definition TypeBase.h:4949
QualType getReturnType() const
Definition TypeBase.h:4934
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:2271
RAII class that temporarily sets the "ignore all warnings" state on a DiagnosticsEngine and restores ...
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1751
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2103
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6107
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3623
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2613
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2625
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5352
unsigned getNumInits() const
Definition Expr.h:5385
const Expr * getInit(unsigned Init) const
Definition Expr.h:5407
child_range children()
Definition Expr.h:5548
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:3708
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1391
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1404
@ 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:1075
Represents a linkage specification.
Definition DeclCXX.h:3045
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3313
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:3087
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:4397
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3839
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3603
Wrapper for source info for member pointers.
Definition TypeLoc.h:1575
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3744
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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:3231
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3414
Represents C++ namespaces and their aliases.
Definition Decl.h:574
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3351
Represent a C++ namespace.
Definition Decl.h:593
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:649
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3374
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition Decl.h:676
void setRBraceLoc(SourceLocation L)
Definition Decl.h:695
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.
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
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...
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
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:1198
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1161
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1172
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
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:5010
Represents a parameter to a function.
Definition Decl.h:1820
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3008
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1961
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1949
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3013
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3033
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1853
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1953
bool hasInheritedDefaultArg() const
Definition Decl.h:1965
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:2943
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3038
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3044
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1969
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2966
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:830
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:916
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:910
bool isAddressDiscriminated() const
Definition TypeBase.h:266
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6926
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1473
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8512
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8517
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8428
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8468
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
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:8613
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8522
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8501
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8474
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2912
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:8593
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
void removeAddressSpace()
Definition TypeBase.h:597
void removeVolatile()
Definition TypeBase.h:470
LangAS getAddressSpace() const
Definition TypeBase.h:572
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3726
Represents a struct/union/class.
Definition Decl.h:4460
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
bool hasObjectMember() const
Definition Decl.h:4520
field_iterator field_end() const
Definition Decl.h:4666
field_range fields() const
Definition Decl.h:4663
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4648
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4512
bool field_empty() const
Definition Decl.h:4671
field_iterator field_begin() const
Definition Decl.cpp:5340
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:5468
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3671
QualType getPointeeType() const
Definition TypeBase.h:3693
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:395
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:348
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:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
Scope * getDeclParent()
Definition Scope.h:321
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:639
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:1313
A RAII object to temporarily push a declaration context.
Definition Sema.h:3534
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14179
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5566
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:5608
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:9356
CXXMethodDecl * getMethod() const
Definition Sema.h:9368
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13664
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7769
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:13182
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2701
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:6586
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
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.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9394
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9421
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9429
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9417
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9402
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:418
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:13801
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:1531
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6376
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:1258
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:6559
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:6540
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:1471
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:7890
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:1690
@ AR_accessible
Definition Sema.h:1688
@ AR_inaccessible
Definition Sema.h:1689
@ AR_delayed
Definition Sema.h:1691
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2473
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.
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2078
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:4215
@ Default
= default ;
Definition Sema.h:4217
@ Delete
deleted-function-body
Definition Sema.h:4223
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:2079
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:1304
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:228
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1516
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:935
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6566
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:6650
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:777
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...
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:6581
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:1208
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:12271
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1787
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8413
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2492
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:930
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
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
void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr, bool First=true)
@ UPPC_RequiresClause
Definition Sema.h:14599
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14554
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14572
@ UPPC_Initializer
An initializer.
Definition Sema.h:14563
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14533
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14557
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14566
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14536
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14539
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14545
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:928
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:5968
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:2604
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:1303
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:1302
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:6544
SemaHLSL & HLSL()
Definition Sema.h:1481
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:5974
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5342
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5349
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6537
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:6642
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6574
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 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.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
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:13194
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:5964
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:648
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:15668
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:9922
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:7019
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6551
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1444
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:6570
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:8232
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:14079
SourceManager & getSourceManager() const
Definition Sema.h:933
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,...
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:6084
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:15623
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:6562
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:1582
ASTConsumer & Consumer
Definition Sema.h:1305
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:4722
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:127
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1344
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:6772
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6782
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6751
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:1263
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc, ArrayRef< TemplateParameterList * > TPLs, bool IsInstantiation)
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:1307
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)
ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition Sema.h:1306
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7839
FPOptions CurFPFeatures
Definition Sema.h:1300
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:6546
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)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1586
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:6578
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:6375
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:6321
@ AbstractVariableType
Definition Sema.h:6325
@ AbstractReturnType
Definition Sema.h:6323
@ AbstractNone
Definition Sema.h:6322
@ AbstractFieldType
Definition Sema.h:6326
@ AbstractArrayType
Definition Sema.h:6329
@ AbstractParamType
Definition Sema.h:6324
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:8417
llvm::DenseMap< SpecialMemberCacheKey, SpecialMemberOverloadResult > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9380
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId)
Handle a friend tag declaration where the scope specifier was templated.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6457
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6462
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6459
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:3527
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
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:672
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8712
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:3680
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1505
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:1819
bool isUnevaluated() const
Definition Expr.h:1957
StringRef getString() const
Definition Expr.h:1887
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3973
StringRef getKindName() const
Definition Decl.h:4048
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4964
bool isUnion() const
Definition Decl.h:4063
TagKind getTagKind() const
Definition Decl.h:4052
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3998
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:1948
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:106
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3823
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5882
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3842
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:3648
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
NestedNameSpecifierLoc getPrefix() const
If this type represents a qualified-id, this returns it's nested name specifier.
Definition TypeLoc.cpp:475
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1468
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:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8399
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:8410
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9037
bool isBooleanType() const
Definition TypeBase.h:9174
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:2088
bool isIncompleteArrayType() const
Definition TypeBase.h:8772
bool isUndeducedAutoType() const
Definition TypeBase.h:8861
bool isRValueReferenceType() const
Definition TypeBase.h:8697
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:8764
bool isPointerType() const
Definition TypeBase.h:8665
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9081
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9331
bool isReferenceType() const
Definition TypeBase.h:8689
bool isEnumeralType() const
Definition TypeBase.h:8796
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
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:8693
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9006
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3196
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9217
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9187
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2877
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9180
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8661
bool isStructureOrClassType() const
Definition Type.cpp:835
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2529
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
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:2456
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
bool isRecordType() const
Definition TypeBase.h:8792
bool isUnionType() const
Definition Type.cpp:847
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
QualType getUnderlyingType() const
Definition Decl.h:3752
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:2329
Opcode getOpcode() const
Definition Expr.h:2324
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2384
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:5195
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
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:463
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:4148
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3659
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:3638
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3610
Represents a C++ using-declaration.
Definition DeclCXX.h:3621
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3670
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3658
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3662
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3547
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3648
Represents C++ using-directive.
Definition DeclCXX.h:3126
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3330
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3822
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3568
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3590
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3465
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3493
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:3487
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5658
Represents a variable declaration or definition.
Definition Decl.h:933
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2780
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2131
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1594
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2240
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2170
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2806
void setCXXCondDecl()
Definition Decl.h:1640
bool isInlineSpecified() const
Definition Decl.h:1579
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1248
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:1215
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2821
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1184
const Expr * getInit() const
Definition Decl.h:1392
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2555
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:959
void setInit(Expr *I)
Definition Decl.cpp:2457
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1175
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:2508
void setExceptionVariable(bool EV)
Definition Decl.h:1522
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4266
unsigned getNumElements() const
Definition TypeBase.h:4281
QualType getElementType() const
Definition TypeBase.h:4280
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:1188
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:972
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.
Top level wrappers for InstallAPI frontend operations.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
@ 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:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
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:507
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3037
@ 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:661
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:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
@ 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:627
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:243
@ 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.
@ 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:906
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
const FunctionProtoType * T
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:6021
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6026
@ Struct
The "struct" keyword.
Definition TypeBase.h:6023
@ Class
The "class" keyword.
Definition TypeBase.h:6032
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
@ Type
The name was classified as a type.
Definition Sema.h:558
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2030
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Decl.h:2044
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Decl.h:2041
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Decl.h:2038
@ None
This is not a defaultable comparison operator.
Definition Decl.h:2032
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Decl.h:2035
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:4439
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4453
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4448
AllowFoldKind
Definition Sema.h:649
@ 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.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2019
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:639
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:644
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:641
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
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:843
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:841
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:839
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:5996
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6017
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6007
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6010
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
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __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:666
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:5455
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5467
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5457
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5460
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5463
Extra information about a function prototype.
Definition TypeBase.h:5483
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6060
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3509
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3491
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:13233
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13364
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13324
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13321
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13277
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13295
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13367
Abstract class used to diagnose incomplete types.
Definition Sema.h:8309
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.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105