Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
clang 20.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
17#include "clang/AST/CharUnits.h"
19#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
27#include "clang/AST/TypeLoc.h"
36#include "clang/Sema/DeclSpec.h"
39#include "clang/Sema/Lookup.h"
42#include "clang/Sema/Scope.h"
44#include "clang/Sema/SemaCUDA.h"
46#include "clang/Sema/SemaObjC.h"
48#include "clang/Sema/Template.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/STLForwardCompat.h"
52#include "llvm/ADT/StringExtras.h"
53#include "llvm/Support/ConvertUTF.h"
54#include "llvm/Support/SaveAndRestore.h"
55#include <map>
56#include <optional>
57#include <set>
58
59using namespace clang;
60
61//===----------------------------------------------------------------------===//
62// CheckDefaultArgumentVisitor
63//===----------------------------------------------------------------------===//
64
65namespace {
66/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
67/// the default argument of a parameter to determine whether it
68/// contains any ill-formed subexpressions. For example, this will
69/// diagnose the use of local variables or parameters within the
70/// default argument expression.
71class CheckDefaultArgumentVisitor
72 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
73 Sema &S;
74 const Expr *DefaultArg;
75
76public:
77 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
78 : S(S), DefaultArg(DefaultArg) {}
79
80 bool VisitExpr(const Expr *Node);
81 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
82 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
83 bool VisitLambdaExpr(const LambdaExpr *Lambda);
84 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
85};
86
87/// VisitExpr - Visit all of the children of this expression.
88bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
89 bool IsInvalid = false;
90 for (const Stmt *SubStmt : Node->children())
91 if (SubStmt)
92 IsInvalid |= Visit(SubStmt);
93 return IsInvalid;
94}
95
96/// VisitDeclRefExpr - Visit a reference to a declaration, to
97/// determine whether this declaration can be used in the default
98/// argument expression.
99bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
100 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
101
102 if (!isa<VarDecl, BindingDecl>(Decl))
103 return false;
104
105 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
106 // C++ [dcl.fct.default]p9:
107 // [...] parameters of a function shall not be used in default
108 // argument expressions, even if they are not evaluated. [...]
109 //
110 // C++17 [dcl.fct.default]p9 (by CWG 2082):
111 // [...] A parameter shall not appear as a potentially-evaluated
112 // expression in a default argument. [...]
113 //
114 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_param)
117 << Param->getDeclName() << DefaultArg->getSourceRange();
118 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
119 // C++ [dcl.fct.default]p7:
120 // Local variables shall not be used in default argument
121 // expressions.
122 //
123 // C++17 [dcl.fct.default]p7 (by CWG 2082):
124 // A local variable shall not appear as a potentially-evaluated
125 // expression in a default argument.
126 //
127 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
128 // Note: A local variable cannot be odr-used (6.3) in a default
129 // argument.
130 //
131 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
132 return S.Diag(DRE->getBeginLoc(),
133 diag::err_param_default_argument_references_local)
134 << Decl << DefaultArg->getSourceRange();
135 }
136 return false;
137}
138
139/// VisitCXXThisExpr - Visit a C++ "this" expression.
140bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
141 // C++ [dcl.fct.default]p8:
142 // The keyword this shall not be used in a default argument of a
143 // member function.
144 return S.Diag(ThisE->getBeginLoc(),
145 diag::err_param_default_argument_references_this)
146 << ThisE->getSourceRange();
147}
148
149bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
150 const PseudoObjectExpr *POE) {
151 bool Invalid = false;
152 for (const Expr *E : POE->semantics()) {
153 // Look through bindings.
154 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
155 E = OVE->getSourceExpr();
156 assert(E && "pseudo-object binding without source expression?");
157 }
158
159 Invalid |= Visit(E);
160 }
161 return Invalid;
162}
163
164bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
165 // [expr.prim.lambda.capture]p9
166 // a lambda-expression appearing in a default argument cannot implicitly or
167 // explicitly capture any local entity. Such a lambda-expression can still
168 // have an init-capture if any full-expression in its initializer satisfies
169 // the constraints of an expression appearing in a default argument.
170 bool Invalid = false;
171 for (const LambdaCapture &LC : Lambda->captures()) {
172 if (!Lambda->isInitCapture(&LC))
173 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
174 // Init captures are always VarDecl.
175 auto *D = cast<VarDecl>(LC.getCapturedVar());
176 Invalid |= Visit(D->getInit());
177 }
178 return Invalid;
179}
180} // namespace
181
182void
184 const CXXMethodDecl *Method) {
185 // If we have an MSAny spec already, don't bother.
186 if (!Method || ComputedEST == EST_MSAny)
187 return;
188
189 const FunctionProtoType *Proto
190 = Method->getType()->getAs<FunctionProtoType>();
191 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
192 if (!Proto)
193 return;
194
196
197 // If we have a throw-all spec at this point, ignore the function.
198 if (ComputedEST == EST_None)
199 return;
200
201 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
202 EST = EST_BasicNoexcept;
203
204 switch (EST) {
205 case EST_Unparsed:
207 case EST_Unevaluated:
208 llvm_unreachable("should not see unresolved exception specs here");
209
210 // If this function can throw any exceptions, make a note of that.
211 case EST_MSAny:
212 case EST_None:
213 // FIXME: Whichever we see last of MSAny and None determines our result.
214 // We should make a consistent, order-independent choice here.
215 ClearExceptions();
216 ComputedEST = EST;
217 return;
219 ClearExceptions();
220 ComputedEST = EST_None;
221 return;
222 // FIXME: If the call to this decl is using any of its default arguments, we
223 // need to search them for potentially-throwing calls.
224 // If this function has a basic noexcept, it doesn't affect the outcome.
226 case EST_NoexceptTrue:
227 case EST_NoThrow:
228 return;
229 // If we're still at noexcept(true) and there's a throw() callee,
230 // change to that specification.
231 case EST_DynamicNone:
232 if (ComputedEST == EST_BasicNoexcept)
233 ComputedEST = EST_DynamicNone;
234 return;
236 llvm_unreachable(
237 "should not generate implicit declarations for dependent cases");
238 case EST_Dynamic:
239 break;
240 }
241 assert(EST == EST_Dynamic && "EST case not considered earlier.");
242 assert(ComputedEST != EST_None &&
243 "Shouldn't collect exceptions when throw-all is guaranteed.");
244 ComputedEST = EST_Dynamic;
245 // Record the exceptions in this function's exception specification.
246 for (const auto &E : Proto->exceptions())
247 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
248 Exceptions.push_back(E);
249}
250
252 if (!S || ComputedEST == EST_MSAny)
253 return;
254
255 // FIXME:
256 //
257 // C++0x [except.spec]p14:
258 // [An] implicit exception-specification specifies the type-id T if and
259 // only if T is allowed by the exception-specification of a function directly
260 // invoked by f's implicit definition; f shall allow all exceptions if any
261 // function it directly invokes allows all exceptions, and f shall allow no
262 // exceptions if every function it directly invokes allows no exceptions.
263 //
264 // Note in particular that if an implicit exception-specification is generated
265 // for a function containing a throw-expression, that specification can still
266 // be noexcept(true).
267 //
268 // Note also that 'directly invoked' is not defined in the standard, and there
269 // is no indication that we should only consider potentially-evaluated calls.
270 //
271 // Ultimately we should implement the intent of the standard: the exception
272 // specification should be the set of exceptions which can be thrown by the
273 // implicit definition. For now, we assume that any non-nothrow expression can
274 // throw any exception.
275
276 if (Self->canThrow(S))
277 ComputedEST = EST_None;
278}
279
281 SourceLocation EqualLoc) {
282 if (RequireCompleteType(Param->getLocation(), Param->getType(),
283 diag::err_typecheck_decl_incomplete_type))
284 return true;
285
286 // C++ [dcl.fct.default]p5
287 // A default argument expression is implicitly converted (clause
288 // 4) to the parameter type. The default argument expression has
289 // the same semantic constraints as the initializer expression in
290 // a declaration of a variable of the parameter type, using the
291 // copy-initialization semantics (8.5).
293 Param);
295 EqualLoc);
296 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
297 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
298 if (Result.isInvalid())
299 return true;
300 Arg = Result.getAs<Expr>();
301
302 CheckCompletedExpr(Arg, EqualLoc);
304
305 return Arg;
306}
307
309 SourceLocation EqualLoc) {
310 // Add the default argument to the parameter
311 Param->setDefaultArg(Arg);
312
313 // We have already instantiated this parameter; provide each of the
314 // instantiations with the uninstantiated default argument.
315 UnparsedDefaultArgInstantiationsMap::iterator InstPos
317 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
318 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
319 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
320
321 // We're done tracking this parameter's instantiations.
323 }
324}
325
326void
328 Expr *DefaultArg) {
329 if (!param || !DefaultArg)
330 return;
331
332 ParmVarDecl *Param = cast<ParmVarDecl>(param);
333 UnparsedDefaultArgLocs.erase(Param);
334
335 // Default arguments are only permitted in C++
336 if (!getLangOpts().CPlusPlus) {
337 Diag(EqualLoc, diag::err_param_default_argument)
338 << DefaultArg->getSourceRange();
339 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
340 }
341
342 // Check for unexpanded parameter packs.
344 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
345
346 // C++11 [dcl.fct.default]p3
347 // A default argument expression [...] shall not be specified for a
348 // parameter pack.
349 if (Param->isParameterPack()) {
350 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
351 << DefaultArg->getSourceRange();
352 // Recover by discarding the default argument.
353 Param->setDefaultArg(nullptr);
354 return;
355 }
356
357 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
358 if (Result.isInvalid())
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360
361 DefaultArg = Result.getAs<Expr>();
362
363 // Check that the default argument is well-formed
364 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
365 if (DefaultArgChecker.Visit(DefaultArg))
366 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
367
368 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
369}
370
372 SourceLocation EqualLoc,
373 SourceLocation ArgLoc) {
374 if (!param)
375 return;
376
377 ParmVarDecl *Param = cast<ParmVarDecl>(param);
378 Param->setUnparsedDefaultArg();
379 UnparsedDefaultArgLocs[Param] = ArgLoc;
380}
381
383 Expr *DefaultArg) {
384 if (!param)
385 return;
386
387 ParmVarDecl *Param = cast<ParmVarDecl>(param);
388 Param->setInvalidDecl();
389 UnparsedDefaultArgLocs.erase(Param);
390 ExprResult RE;
391 if (DefaultArg) {
392 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
393 Param->getType().getNonReferenceType());
394 } else {
395 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
396 Param->getType().getNonReferenceType());
397 }
398 Param->setDefaultArg(RE.get());
399}
400
402 // C++ [dcl.fct.default]p3
403 // A default argument expression shall be specified only in the
404 // parameter-declaration-clause of a function declaration or in a
405 // template-parameter (14.1). It shall not be specified for a
406 // parameter pack. If it is specified in a
407 // parameter-declaration-clause, it shall not occur within a
408 // declarator or abstract-declarator of a parameter-declaration.
409 bool MightBeFunction = D.isFunctionDeclarationContext();
410 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
411 DeclaratorChunk &chunk = D.getTypeObject(i);
412 if (chunk.Kind == DeclaratorChunk::Function) {
413 if (MightBeFunction) {
414 // This is a function declaration. It can have default arguments, but
415 // keep looking in case its return type is a function type with default
416 // arguments.
417 MightBeFunction = false;
418 continue;
419 }
420 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
421 ++argIdx) {
422 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
423 if (Param->hasUnparsedDefaultArg()) {
424 std::unique_ptr<CachedTokens> Toks =
425 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
426 SourceRange SR;
427 if (Toks->size() > 1)
428 SR = SourceRange((*Toks)[1].getLocation(),
429 Toks->back().getLocation());
430 else
431 SR = UnparsedDefaultArgLocs[Param];
432 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
433 << SR;
434 } else if (Param->getDefaultArg()) {
435 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
436 << Param->getDefaultArg()->getSourceRange();
437 Param->setDefaultArg(nullptr);
438 }
439 }
440 } else if (chunk.Kind != DeclaratorChunk::Paren) {
441 MightBeFunction = false;
442 }
443 }
444}
445
447 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
448 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
449 });
450}
451
453 Scope *S) {
454 bool Invalid = false;
455
456 // The declaration context corresponding to the scope is the semantic
457 // parent, unless this is a local function declaration, in which case
458 // it is that surrounding function.
459 DeclContext *ScopeDC = New->isLocalExternDecl()
460 ? New->getLexicalDeclContext()
461 : New->getDeclContext();
462
463 // Find the previous declaration for the purpose of default arguments.
464 FunctionDecl *PrevForDefaultArgs = Old;
465 for (/**/; PrevForDefaultArgs;
466 // Don't bother looking back past the latest decl if this is a local
467 // extern declaration; nothing else could work.
468 PrevForDefaultArgs = New->isLocalExternDecl()
469 ? nullptr
470 : PrevForDefaultArgs->getPreviousDecl()) {
471 // Ignore hidden declarations.
472 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
473 continue;
474
475 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
476 !New->isCXXClassMember()) {
477 // Ignore default arguments of old decl if they are not in
478 // the same scope and this is not an out-of-line definition of
479 // a member function.
480 continue;
481 }
482
483 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
484 // If only one of these is a local function declaration, then they are
485 // declared in different scopes, even though isDeclInScope may think
486 // they're in the same scope. (If both are local, the scope check is
487 // sufficient, and if neither is local, then they are in the same scope.)
488 continue;
489 }
490
491 // We found the right previous declaration.
492 break;
493 }
494
495 // C++ [dcl.fct.default]p4:
496 // For non-template functions, default arguments can be added in
497 // later declarations of a function in the same
498 // scope. Declarations in different scopes have completely
499 // distinct sets of default arguments. That is, declarations in
500 // inner scopes do not acquire default arguments from
501 // declarations in outer scopes, and vice versa. In a given
502 // function declaration, all parameters subsequent to a
503 // parameter with a default argument shall have default
504 // arguments supplied in this or previous declarations. A
505 // default argument shall not be redefined by a later
506 // declaration (not even to the same value).
507 //
508 // C++ [dcl.fct.default]p6:
509 // Except for member functions of class templates, the default arguments
510 // in a member function definition that appears outside of the class
511 // definition are added to the set of default arguments provided by the
512 // member function declaration in the class definition.
513 for (unsigned p = 0, NumParams = PrevForDefaultArgs
514 ? PrevForDefaultArgs->getNumParams()
515 : 0;
516 p < NumParams; ++p) {
517 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
518 ParmVarDecl *NewParam = New->getParamDecl(p);
519
520 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
521 bool NewParamHasDfl = NewParam->hasDefaultArg();
522
523 if (OldParamHasDfl && NewParamHasDfl) {
524 unsigned DiagDefaultParamID =
525 diag::err_param_default_argument_redefinition;
526
527 // MSVC accepts that default parameters be redefined for member functions
528 // of template class. The new default parameter's value is ignored.
529 Invalid = true;
530 if (getLangOpts().MicrosoftExt) {
531 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
532 if (MD && MD->getParent()->getDescribedClassTemplate()) {
533 // Merge the old default argument into the new parameter.
534 NewParam->setHasInheritedDefaultArg();
535 if (OldParam->hasUninstantiatedDefaultArg())
537 OldParam->getUninstantiatedDefaultArg());
538 else
539 NewParam->setDefaultArg(OldParam->getInit());
540 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
541 Invalid = false;
542 }
543 }
544
545 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
546 // hint here. Alternatively, we could walk the type-source information
547 // for NewParam to find the last source location in the type... but it
548 // isn't worth the effort right now. This is the kind of test case that
549 // is hard to get right:
550 // int f(int);
551 // void g(int (*fp)(int) = f);
552 // void g(int (*fp)(int) = &f);
553 Diag(NewParam->getLocation(), DiagDefaultParamID)
554 << NewParam->getDefaultArgRange();
555
556 // Look for the function declaration where the default argument was
557 // actually written, which may be a declaration prior to Old.
558 for (auto Older = PrevForDefaultArgs;
559 OldParam->hasInheritedDefaultArg(); /**/) {
560 Older = Older->getPreviousDecl();
561 OldParam = Older->getParamDecl(p);
562 }
563
564 Diag(OldParam->getLocation(), diag::note_previous_definition)
565 << OldParam->getDefaultArgRange();
566 } else if (OldParamHasDfl) {
567 // Merge the old default argument into the new parameter unless the new
568 // function is a friend declaration in a template class. In the latter
569 // case the default arguments will be inherited when the friend
570 // declaration will be instantiated.
571 if (New->getFriendObjectKind() == Decl::FOK_None ||
573 // It's important to use getInit() here; getDefaultArg()
574 // strips off any top-level ExprWithCleanups.
575 NewParam->setHasInheritedDefaultArg();
576 if (OldParam->hasUnparsedDefaultArg())
577 NewParam->setUnparsedDefaultArg();
578 else if (OldParam->hasUninstantiatedDefaultArg())
580 OldParam->getUninstantiatedDefaultArg());
581 else
582 NewParam->setDefaultArg(OldParam->getInit());
583 }
584 } else if (NewParamHasDfl) {
585 if (New->getDescribedFunctionTemplate()) {
586 // Paragraph 4, quoted above, only applies to non-template functions.
587 Diag(NewParam->getLocation(),
588 diag::err_param_default_argument_template_redecl)
589 << NewParam->getDefaultArgRange();
590 Diag(PrevForDefaultArgs->getLocation(),
591 diag::note_template_prev_declaration)
592 << false;
593 } else if (New->getTemplateSpecializationKind()
596 // C++ [temp.expr.spec]p21:
597 // Default function arguments shall not be specified in a declaration
598 // or a definition for one of the following explicit specializations:
599 // - the explicit specialization of a function template;
600 // - the explicit specialization of a member function template;
601 // - the explicit specialization of a member function of a class
602 // template where the class template specialization to which the
603 // member function specialization belongs is implicitly
604 // instantiated.
605 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
607 << New->getDeclName()
608 << NewParam->getDefaultArgRange();
609 } else if (New->getDeclContext()->isDependentContext()) {
610 // C++ [dcl.fct.default]p6 (DR217):
611 // Default arguments for a member function of a class template shall
612 // be specified on the initial declaration of the member function
613 // within the class template.
614 //
615 // Reading the tea leaves a bit in DR217 and its reference to DR205
616 // leads me to the conclusion that one cannot add default function
617 // arguments for an out-of-line definition of a member function of a
618 // dependent type.
619 int WhichKind = 2;
621 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
622 if (Record->getDescribedClassTemplate())
623 WhichKind = 0;
624 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
625 WhichKind = 1;
626 else
627 WhichKind = 2;
628 }
629
630 Diag(NewParam->getLocation(),
631 diag::err_param_default_argument_member_template_redecl)
632 << WhichKind
633 << NewParam->getDefaultArgRange();
634 }
635 }
636 }
637
638 // DR1344: If a default argument is added outside a class definition and that
639 // default argument makes the function a special member function, the program
640 // is ill-formed. This can only happen for constructors.
641 if (isa<CXXConstructorDecl>(New) &&
643 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
644 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
645 if (NewSM != OldSM) {
646 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
647 assert(NewParam->hasDefaultArg());
648 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
649 << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
650 Diag(Old->getLocation(), diag::note_previous_declaration);
651 }
652 }
653
654 const FunctionDecl *Def;
655 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
656 // template has a constexpr specifier then all its declarations shall
657 // contain the constexpr specifier.
658 if (New->getConstexprKind() != Old->getConstexprKind()) {
659 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
660 << New << static_cast<int>(New->getConstexprKind())
661 << static_cast<int>(Old->getConstexprKind());
662 Diag(Old->getLocation(), diag::note_previous_declaration);
663 Invalid = true;
664 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
665 Old->isDefined(Def) &&
666 // If a friend function is inlined but does not have 'inline'
667 // specifier, it is a definition. Do not report attribute conflict
668 // in this case, redefinition will be diagnosed later.
669 (New->isInlineSpecified() ||
671 // C++11 [dcl.fcn.spec]p4:
672 // If the definition of a function appears in a translation unit before its
673 // first declaration as inline, the program is ill-formed.
674 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
675 Diag(Def->getLocation(), diag::note_previous_definition);
676 Invalid = true;
677 }
678
679 // C++17 [temp.deduct.guide]p3:
680 // Two deduction guide declarations in the same translation unit
681 // for the same class template shall not have equivalent
682 // parameter-declaration-clauses.
683 if (isa<CXXDeductionGuideDecl>(New) &&
685 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
686 Diag(Old->getLocation(), diag::note_previous_declaration);
687 }
688
689 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
690 // argument expression, that declaration shall be a definition and shall be
691 // the only declaration of the function or function template in the
692 // translation unit.
695 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
696 Diag(Old->getLocation(), diag::note_previous_declaration);
697 Invalid = true;
698 }
699
700 // C++11 [temp.friend]p4 (DR329):
701 // When a function is defined in a friend function declaration in a class
702 // template, the function is instantiated when the function is odr-used.
703 // The same restrictions on multiple declarations and definitions that
704 // apply to non-template function declarations and definitions also apply
705 // to these implicit definitions.
706 const FunctionDecl *OldDefinition = nullptr;
708 Old->isDefined(OldDefinition, true))
709 CheckForFunctionRedefinition(New, OldDefinition);
710
711 return Invalid;
712}
713
716 ? diag::warn_cxx23_placeholder_var_definition
717 : diag::ext_placeholder_var_definition);
718}
719
720NamedDecl *
722 MultiTemplateParamsArg TemplateParamLists) {
723 assert(D.isDecompositionDeclarator());
724 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
725
726 // The syntax only allows a decomposition declarator as a simple-declaration,
727 // a for-range-declaration, or a condition in Clang, but we parse it in more
728 // cases than that.
729 if (!D.mayHaveDecompositionDeclarator()) {
730 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
731 << Decomp.getSourceRange();
732 return nullptr;
733 }
734
735 if (!TemplateParamLists.empty()) {
736 // FIXME: There's no rule against this, but there are also no rules that
737 // would actually make it usable, so we reject it for now.
738 Diag(TemplateParamLists.front()->getTemplateLoc(),
739 diag::err_decomp_decl_template);
740 return nullptr;
741 }
742
743 Diag(Decomp.getLSquareLoc(),
745 ? diag::ext_decomp_decl
746 : D.getContext() == DeclaratorContext::Condition
747 ? diag::ext_decomp_decl_cond
748 : diag::warn_cxx14_compat_decomp_decl)
749 << Decomp.getSourceRange();
750
751 // The semantic context is always just the current context.
752 DeclContext *const DC = CurContext;
753
754 // C++17 [dcl.dcl]/8:
755 // The decl-specifier-seq shall contain only the type-specifier auto
756 // and cv-qualifiers.
757 // C++20 [dcl.dcl]/8:
758 // If decl-specifier-seq contains any decl-specifier other than static,
759 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
760 // C++23 [dcl.pre]/6:
761 // Each decl-specifier in the decl-specifier-seq shall be static,
762 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
763 auto &DS = D.getDeclSpec();
764 {
765 // Note: While constrained-auto needs to be checked, we do so separately so
766 // we can emit a better diagnostic.
767 SmallVector<StringRef, 8> BadSpecifiers;
768 SmallVector<SourceLocation, 8> BadSpecifierLocs;
769 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
770 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
771 if (auto SCS = DS.getStorageClassSpec()) {
772 if (SCS == DeclSpec::SCS_static) {
773 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
774 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
775 } else {
776 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
777 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
778 }
779 }
780 if (auto TSCS = DS.getThreadStorageClassSpec()) {
781 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
782 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
783 }
784 if (DS.hasConstexprSpecifier()) {
785 BadSpecifiers.push_back(
786 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
787 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
788 }
789 if (DS.isInlineSpecified()) {
790 BadSpecifiers.push_back("inline");
791 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
792 }
793
794 if (!BadSpecifiers.empty()) {
795 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
796 Err << (int)BadSpecifiers.size()
797 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
798 // Don't add FixItHints to remove the specifiers; we do still respect
799 // them when building the underlying variable.
800 for (auto Loc : BadSpecifierLocs)
801 Err << SourceRange(Loc, Loc);
802 } else if (!CPlusPlus20Specifiers.empty()) {
803 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
805 ? diag::warn_cxx17_compat_decomp_decl_spec
806 : diag::ext_decomp_decl_spec);
807 Warn << (int)CPlusPlus20Specifiers.size()
808 << llvm::join(CPlusPlus20Specifiers.begin(),
809 CPlusPlus20Specifiers.end(), " ");
810 for (auto Loc : CPlusPlus20SpecifierLocs)
811 Warn << SourceRange(Loc, Loc);
812 }
813 // We can't recover from it being declared as a typedef.
814 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
815 return nullptr;
816 }
817
818 // C++2a [dcl.struct.bind]p1:
819 // A cv that includes volatile is deprecated
820 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
822 Diag(DS.getVolatileSpecLoc(),
823 diag::warn_deprecated_volatile_structured_binding);
824
826 QualType R = TInfo->getType();
827
828 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
830 D.setInvalidType();
831
832 // The syntax only allows a single ref-qualifier prior to the decomposition
833 // declarator. No other declarator chunks are permitted. Also check the type
834 // specifier here.
835 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
836 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
837 (D.getNumTypeObjects() == 1 &&
838 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
839 Diag(Decomp.getLSquareLoc(),
840 (D.hasGroupingParens() ||
841 (D.getNumTypeObjects() &&
842 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
843 ? diag::err_decomp_decl_parens
844 : diag::err_decomp_decl_type)
845 << R;
846
847 // In most cases, there's no actual problem with an explicitly-specified
848 // type, but a function type won't work here, and ActOnVariableDeclarator
849 // shouldn't be called for such a type.
850 if (R->isFunctionType())
851 D.setInvalidType();
852 }
853
854 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
855 if (DS.isConstrainedAuto()) {
856 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
857 assert(TemplRep->Kind == TNK_Concept_template &&
858 "No other template kind should be possible for a constrained auto");
859
860 SourceRange TemplRange{TemplRep->TemplateNameLoc,
861 TemplRep->RAngleLoc.isValid()
862 ? TemplRep->RAngleLoc
863 : TemplRep->TemplateNameLoc};
864 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
865 << TemplRange << FixItHint::CreateRemoval(TemplRange);
866 }
867
868 // Build the BindingDecls.
870
871 // Build the BindingDecls.
872 for (auto &B : D.getDecompositionDeclarator().bindings()) {
873 // Check for name conflicts.
874 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
875 IdentifierInfo *VarName = B.Name;
876 assert(VarName && "Cannot have an unnamed binding declaration");
877
879 RedeclarationKind::ForVisibleRedeclaration);
881 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
882
883 // It's not permitted to shadow a template parameter name.
884 if (Previous.isSingleResult() &&
885 Previous.getFoundDecl()->isTemplateParameter()) {
886 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
887 Previous.getFoundDecl());
888 Previous.clear();
889 }
890
891 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
892
893 ProcessDeclAttributeList(S, BD, *B.Attrs);
894
895 // Find the shadowed declaration before filtering for scope.
896 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
898 : nullptr;
899
900 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
901 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
902 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
903 /*AllowInlineNamespace*/false);
904
905 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
906 DC->isFunctionOrMethod() && VarName->isPlaceholder();
907 if (!Previous.empty()) {
908 if (IsPlaceholder) {
909 bool sameDC = (Previous.end() - 1)
910 ->getDeclContext()
911 ->getRedeclContext()
912 ->Equals(DC->getRedeclContext());
913 if (sameDC &&
914 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
915 Previous.clear();
917 }
918 } else {
919 auto *Old = Previous.getRepresentativeDecl();
920 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
921 Diag(Old->getLocation(), diag::note_previous_definition);
922 }
923 } else if (ShadowedDecl && !D.isRedeclaration()) {
924 CheckShadow(BD, ShadowedDecl, Previous);
925 }
926 PushOnScopeChains(BD, S, true);
927 Bindings.push_back(BD);
928 ParsingInitForAutoVars.insert(BD);
929 }
930
931 // There are no prior lookup results for the variable itself, because it
932 // is unnamed.
933 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
934 Decomp.getLSquareLoc());
936 RedeclarationKind::ForVisibleRedeclaration);
937
938 // Build the variable that holds the non-decomposed object.
939 bool AddToScope = true;
940 NamedDecl *New =
941 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
942 MultiTemplateParamsArg(), AddToScope, Bindings);
943 if (AddToScope) {
944 S->AddDecl(New);
946 }
947
948 if (OpenMP().isInOpenMPDeclareTargetContext())
950
951 return New;
952}
953
956 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
957 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
958 if ((int64_t)Bindings.size() != NumElems) {
959 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
960 << DecompType << (unsigned)Bindings.size()
961 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
962 << toString(NumElems, 10) << (NumElems < Bindings.size());
963 return true;
964 }
965
966 unsigned I = 0;
967 for (auto *B : Bindings) {
968 SourceLocation Loc = B->getLocation();
969 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
970 if (E.isInvalid())
971 return true;
972 E = GetInit(Loc, E.get(), I++);
973 if (E.isInvalid())
974 return true;
975 B->setBinding(ElemType, E.get());
976 }
977
978 return false;
979}
980
983 ValueDecl *Src, QualType DecompType,
984 const llvm::APSInt &NumElems,
985 QualType ElemType) {
987 S, Bindings, Src, DecompType, NumElems, ElemType,
988 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
990 if (E.isInvalid())
991 return ExprError();
992 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
993 });
994}
995
997 ValueDecl *Src, QualType DecompType,
998 const ConstantArrayType *CAT) {
999 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1000 llvm::APSInt(CAT->getSize()),
1001 CAT->getElementType());
1002}
1003
1005 ValueDecl *Src, QualType DecompType,
1006 const VectorType *VT) {
1008 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1010 DecompType.getQualifiers()));
1011}
1012
1015 ValueDecl *Src, QualType DecompType,
1016 const ComplexType *CT) {
1018 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1020 DecompType.getQualifiers()),
1021 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1022 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1023 });
1024}
1025
1028 const TemplateParameterList *Params) {
1030 llvm::raw_svector_ostream OS(SS);
1031 bool First = true;
1032 unsigned I = 0;
1033 for (auto &Arg : Args.arguments()) {
1034 if (!First)
1035 OS << ", ";
1036 Arg.getArgument().print(PrintingPolicy, OS,
1038 PrintingPolicy, Params, I));
1039 First = false;
1040 I++;
1041 }
1042 return std::string(OS.str());
1043}
1044
1045static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1046 SourceLocation Loc, StringRef Trait,
1048 unsigned DiagID) {
1049 auto DiagnoseMissing = [&] {
1050 if (DiagID)
1052 Args, /*Params*/ nullptr);
1053 return true;
1054 };
1055
1056 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1058 if (!Std)
1059 return DiagnoseMissing();
1060
1061 // Look up the trait itself, within namespace std. We can diagnose various
1062 // problems with this lookup even if we've been asked to not diagnose a
1063 // missing specialization, because this can only fail if the user has been
1064 // declaring their own names in namespace std or we don't support the
1065 // standard library implementation in use.
1069 return DiagnoseMissing();
1070 if (Result.isAmbiguous())
1071 return true;
1072
1073 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1074 if (!TraitTD) {
1075 Result.suppressDiagnostics();
1076 NamedDecl *Found = *Result.begin();
1077 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1078 S.Diag(Found->getLocation(), diag::note_declared_at);
1079 return true;
1080 }
1081
1082 // Build the template-id.
1083 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1084 if (TraitTy.isNull())
1085 return true;
1086 if (!S.isCompleteType(Loc, TraitTy)) {
1087 if (DiagID)
1089 Loc, TraitTy, DiagID,
1091 TraitTD->getTemplateParameters()));
1092 return true;
1093 }
1094
1095 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1096 assert(RD && "specialization of class template is not a class?");
1097
1098 // Look up the member of the trait type.
1099 S.LookupQualifiedName(TraitMemberLookup, RD);
1100 return TraitMemberLookup.isAmbiguous();
1101}
1102
1105 uint64_t I) {
1107 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1108}
1109
1113}
1114
1115namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1116
1118 llvm::APSInt &Size) {
1121
1124
1125 // Form template argument list for tuple_size<T>.
1128
1129 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1130 // it's not tuple-like.
1131 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1132 R.empty())
1133 return IsTupleLike::NotTupleLike;
1134
1135 // If we get this far, we've committed to the tuple interpretation, but
1136 // we can still fail if there actually isn't a usable ::value.
1137
1138 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1139 LookupResult &R;
1141 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1142 : R(R), Args(Args) {}
1143 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1144 SourceLocation Loc) override {
1145 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1147 /*Params*/ nullptr);
1148 }
1149 } Diagnoser(R, Args);
1150
1151 ExprResult E =
1152 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1153 if (E.isInvalid())
1154 return IsTupleLike::Error;
1155
1156 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1157 if (E.isInvalid())
1158 return IsTupleLike::Error;
1159
1160 return IsTupleLike::TupleLike;
1161}
1162
1163/// \return std::tuple_element<I, T>::type.
1165 unsigned I, QualType T) {
1166 // Form template argument list for tuple_element<I, T>.
1168 Args.addArgument(
1171
1172 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1175 S, R, Loc, "tuple_element", Args,
1176 diag::err_decomp_decl_std_tuple_element_not_specialized))
1177 return QualType();
1178
1179 auto *TD = R.getAsSingle<TypeDecl>();
1180 if (!TD) {
1182 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1184 /*Params*/ nullptr);
1185 if (!R.empty())
1186 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1187 return QualType();
1188 }
1189
1190 return S.Context.getTypeDeclType(TD);
1191}
1192
1193namespace {
1194struct InitializingBinding {
1195 Sema &S;
1196 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1199 Ctx.PointOfInstantiation = BD->getLocation();
1200 Ctx.Entity = BD;
1202 }
1203 ~InitializingBinding() {
1205 }
1206};
1207}
1208
1211 VarDecl *Src, QualType DecompType,
1212 const llvm::APSInt &TupleSize) {
1213 if ((int64_t)Bindings.size() != TupleSize) {
1214 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1215 << DecompType << (unsigned)Bindings.size()
1216 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1217 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1218 return true;
1219 }
1220
1221 if (Bindings.empty())
1222 return false;
1223
1224 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1225
1226 // [dcl.decomp]p3:
1227 // The unqualified-id get is looked up in the scope of E by class member
1228 // access lookup ...
1229 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1230 bool UseMemberGet = false;
1231 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1232 if (auto *RD = DecompType->getAsCXXRecordDecl())
1233 S.LookupQualifiedName(MemberGet, RD);
1234 if (MemberGet.isAmbiguous())
1235 return true;
1236 // ... and if that finds at least one declaration that is a function
1237 // template whose first template parameter is a non-type parameter ...
1238 for (NamedDecl *D : MemberGet) {
1239 if (FunctionTemplateDecl *FTD =
1240 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1241 TemplateParameterList *TPL = FTD->getTemplateParameters();
1242 if (TPL->size() != 0 &&
1243 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1244 // ... the initializer is e.get<i>().
1245 UseMemberGet = true;
1246 break;
1247 }
1248 }
1249 }
1250 }
1251
1252 unsigned I = 0;
1253 for (auto *B : Bindings) {
1254 InitializingBinding InitContext(S, B);
1255 SourceLocation Loc = B->getLocation();
1256
1257 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1258 if (E.isInvalid())
1259 return true;
1260
1261 // e is an lvalue if the type of the entity is an lvalue reference and
1262 // an xvalue otherwise
1263 if (!Src->getType()->isLValueReferenceType())
1264 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1265 E.get(), nullptr, VK_XValue,
1267
1269 Args.addArgument(
1271
1272 if (UseMemberGet) {
1273 // if [lookup of member get] finds at least one declaration, the
1274 // initializer is e.get<i-1>().
1275 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1276 CXXScopeSpec(), SourceLocation(), nullptr,
1277 MemberGet, &Args, nullptr);
1278 if (E.isInvalid())
1279 return true;
1280
1281 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1282 } else {
1283 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1284 // in the associated namespaces.
1287 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1289 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1290
1291 Expr *Arg = E.get();
1292 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1293 }
1294 if (E.isInvalid())
1295 return true;
1296 Expr *Init = E.get();
1297
1298 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1299 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1300 if (T.isNull())
1301 return true;
1302
1303 // each vi is a variable of type "reference to T" initialized with the
1304 // initializer, where the reference is an lvalue reference if the
1305 // initializer is an lvalue and an rvalue reference otherwise
1306 QualType RefType =
1307 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1308 if (RefType.isNull())
1309 return true;
1310 auto *RefVD = VarDecl::Create(
1311 S.Context, Src->getDeclContext(), Loc, Loc,
1312 B->getDeclName().getAsIdentifierInfo(), RefType,
1314 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1315 RefVD->setTSCSpec(Src->getTSCSpec());
1316 RefVD->setImplicit();
1317 if (Src->isInlineSpecified())
1318 RefVD->setInlineSpecified();
1319 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1320
1323 InitializationSequence Seq(S, Entity, Kind, Init);
1324 E = Seq.Perform(S, Entity, Kind, Init);
1325 if (E.isInvalid())
1326 return true;
1327 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1328 if (E.isInvalid())
1329 return true;
1330 RefVD->setInit(E.get());
1332
1334 DeclarationNameInfo(B->getDeclName(), Loc),
1335 RefVD);
1336 if (E.isInvalid())
1337 return true;
1338
1339 B->setBinding(T, E.get());
1340 I++;
1341 }
1342
1343 return false;
1344}
1345
1346/// Find the base class to decompose in a built-in decomposition of a class type.
1347/// This base class search is, unfortunately, not quite like any other that we
1348/// perform anywhere else in C++.
1350 const CXXRecordDecl *RD,
1351 CXXCastPath &BasePath) {
1352 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1353 CXXBasePath &Path) {
1354 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1355 };
1356
1357 const CXXRecordDecl *ClassWithFields = nullptr;
1359 if (RD->hasDirectFields())
1360 // [dcl.decomp]p4:
1361 // Otherwise, all of E's non-static data members shall be public direct
1362 // members of E ...
1363 ClassWithFields = RD;
1364 else {
1365 // ... or of ...
1366 CXXBasePaths Paths;
1367 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1368 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1369 // If no classes have fields, just decompose RD itself. (This will work
1370 // if and only if zero bindings were provided.)
1371 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1372 }
1373
1374 CXXBasePath *BestPath = nullptr;
1375 for (auto &P : Paths) {
1376 if (!BestPath)
1377 BestPath = &P;
1378 else if (!S.Context.hasSameType(P.back().Base->getType(),
1379 BestPath->back().Base->getType())) {
1380 // ... the same ...
1381 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1382 << false << RD << BestPath->back().Base->getType()
1383 << P.back().Base->getType();
1384 return DeclAccessPair();
1385 } else if (P.Access < BestPath->Access) {
1386 BestPath = &P;
1387 }
1388 }
1389
1390 // ... unambiguous ...
1391 QualType BaseType = BestPath->back().Base->getType();
1392 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1393 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1394 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1395 return DeclAccessPair();
1396 }
1397
1398 // ... [accessible, implied by other rules] base class of E.
1399 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1400 *BestPath, diag::err_decomp_decl_inaccessible_base);
1401 AS = BestPath->Access;
1402
1403 ClassWithFields = BaseType->getAsCXXRecordDecl();
1404 S.BuildBasePathArray(Paths, BasePath);
1405 }
1406
1407 // The above search did not check whether the selected class itself has base
1408 // classes with fields, so check that now.
1409 CXXBasePaths Paths;
1410 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1411 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1412 << (ClassWithFields == RD) << RD << ClassWithFields
1413 << Paths.front().back().Base->getType();
1414 return DeclAccessPair();
1415 }
1416
1417 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1418}
1419
1421 ValueDecl *Src, QualType DecompType,
1422 const CXXRecordDecl *OrigRD) {
1423 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1424 diag::err_incomplete_type))
1425 return true;
1426
1427 CXXCastPath BasePath;
1428 DeclAccessPair BasePair =
1429 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1430 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1431 if (!RD)
1432 return true;
1434 DecompType.getQualifiers());
1435
1436 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1437 unsigned NumFields = llvm::count_if(
1438 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1439 assert(Bindings.size() != NumFields);
1440 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1441 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1442 << (NumFields < Bindings.size());
1443 return true;
1444 };
1445
1446 // all of E's non-static data members shall be [...] well-formed
1447 // when named as e.name in the context of the structured binding,
1448 // E shall not have an anonymous union member, ...
1449 unsigned I = 0;
1450 for (auto *FD : RD->fields()) {
1451 if (FD->isUnnamedBitField())
1452 continue;
1453
1454 // All the non-static data members are required to be nameable, so they
1455 // must all have names.
1456 if (!FD->getDeclName()) {
1457 if (RD->isLambda()) {
1458 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1459 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1460 return true;
1461 }
1462
1463 if (FD->isAnonymousStructOrUnion()) {
1464 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1465 << DecompType << FD->getType()->isUnionType();
1466 S.Diag(FD->getLocation(), diag::note_declared_at);
1467 return true;
1468 }
1469
1470 // FIXME: Are there any other ways we could have an anonymous member?
1471 }
1472
1473 // We have a real field to bind.
1474 if (I >= Bindings.size())
1475 return DiagnoseBadNumberOfBindings();
1476 auto *B = Bindings[I++];
1477 SourceLocation Loc = B->getLocation();
1478
1479 // The field must be accessible in the context of the structured binding.
1480 // We already checked that the base class is accessible.
1481 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1482 // const_cast here.
1484 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1486 BasePair.getAccess(), FD->getAccess())));
1487
1488 // Initialize the binding to Src.FD.
1489 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1490 if (E.isInvalid())
1491 return true;
1492 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1493 VK_LValue, &BasePath);
1494 if (E.isInvalid())
1495 return true;
1496 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1497 CXXScopeSpec(), FD,
1498 DeclAccessPair::make(FD, FD->getAccess()),
1499 DeclarationNameInfo(FD->getDeclName(), Loc));
1500 if (E.isInvalid())
1501 return true;
1502
1503 // If the type of the member is T, the referenced type is cv T, where cv is
1504 // the cv-qualification of the decomposition expression.
1505 //
1506 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1507 // 'const' to the type of the field.
1508 Qualifiers Q = DecompType.getQualifiers();
1509 if (FD->isMutable())
1510 Q.removeConst();
1511 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1512 }
1513
1514 if (I != Bindings.size())
1515 return DiagnoseBadNumberOfBindings();
1516
1517 return false;
1518}
1519
1521 QualType DecompType = DD->getType();
1522
1523 // If the type of the decomposition is dependent, then so is the type of
1524 // each binding.
1525 if (DecompType->isDependentType()) {
1526 for (auto *B : DD->bindings())
1527 B->setType(Context.DependentTy);
1528 return;
1529 }
1530
1531 DecompType = DecompType.getNonReferenceType();
1533
1534 // C++1z [dcl.decomp]/2:
1535 // If E is an array type [...]
1536 // As an extension, we also support decomposition of built-in complex and
1537 // vector types.
1538 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1539 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1540 DD->setInvalidDecl();
1541 return;
1542 }
1543 if (auto *VT = DecompType->getAs<VectorType>()) {
1544 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1545 DD->setInvalidDecl();
1546 return;
1547 }
1548 if (auto *CT = DecompType->getAs<ComplexType>()) {
1549 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1550 DD->setInvalidDecl();
1551 return;
1552 }
1553
1554 // C++1z [dcl.decomp]/3:
1555 // if the expression std::tuple_size<E>::value is a well-formed integral
1556 // constant expression, [...]
1557 llvm::APSInt TupleSize(32);
1558 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1559 case IsTupleLike::Error:
1560 DD->setInvalidDecl();
1561 return;
1562
1563 case IsTupleLike::TupleLike:
1564 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1565 DD->setInvalidDecl();
1566 return;
1567
1568 case IsTupleLike::NotTupleLike:
1569 break;
1570 }
1571
1572 // C++1z [dcl.dcl]/8:
1573 // [E shall be of array or non-union class type]
1574 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1575 if (!RD || RD->isUnion()) {
1576 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1577 << DD << !RD << DecompType;
1578 DD->setInvalidDecl();
1579 return;
1580 }
1581
1582 // C++1z [dcl.decomp]/4:
1583 // all of E's non-static data members shall be [...] direct members of
1584 // E or of the same unambiguous public base class of E, ...
1585 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1586 DD->setInvalidDecl();
1587}
1588
1590 // Shortcut if exceptions are disabled.
1591 if (!getLangOpts().CXXExceptions)
1592 return;
1593
1594 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1595 "Should only be called if types are otherwise the same.");
1596
1597 QualType NewType = New->getType();
1598 QualType OldType = Old->getType();
1599
1600 // We're only interested in pointers and references to functions, as well
1601 // as pointers to member functions.
1602 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1603 NewType = R->getPointeeType();
1604 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1605 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1606 NewType = P->getPointeeType();
1607 OldType = OldType->castAs<PointerType>()->getPointeeType();
1608 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1609 NewType = M->getPointeeType();
1610 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1611 }
1612
1613 if (!NewType->isFunctionProtoType())
1614 return;
1615
1616 // There's lots of special cases for functions. For function pointers, system
1617 // libraries are hopefully not as broken so that we don't need these
1618 // workarounds.
1620 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1621 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1622 New->setInvalidDecl();
1623 }
1624}
1625
1626/// CheckCXXDefaultArguments - Verify that the default arguments for a
1627/// function declaration are well-formed according to C++
1628/// [dcl.fct.default].
1630 // This checking doesn't make sense for explicit specializations; their
1631 // default arguments are determined by the declaration we're specializing,
1632 // not by FD.
1634 return;
1635 if (auto *FTD = FD->getDescribedFunctionTemplate())
1636 if (FTD->isMemberSpecialization())
1637 return;
1638
1639 unsigned NumParams = FD->getNumParams();
1640 unsigned ParamIdx = 0;
1641
1642 // Find first parameter with a default argument
1643 for (; ParamIdx < NumParams; ++ParamIdx) {
1644 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1645 if (Param->hasDefaultArg())
1646 break;
1647 }
1648
1649 // C++20 [dcl.fct.default]p4:
1650 // In a given function declaration, each parameter subsequent to a parameter
1651 // with a default argument shall have a default argument supplied in this or
1652 // a previous declaration, unless the parameter was expanded from a
1653 // parameter pack, or shall be a function parameter pack.
1654 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1655 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1656 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1659 continue;
1660 if (Param->isInvalidDecl())
1661 /* We already complained about this parameter. */;
1662 else if (Param->getIdentifier())
1663 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1664 << Param->getIdentifier();
1665 else
1666 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1667 }
1668}
1669
1670/// Check that the given type is a literal type. Issue a diagnostic if not,
1671/// if Kind is Diagnose.
1672/// \return \c true if a problem has been found (and optionally diagnosed).
1673template <typename... Ts>
1675 SourceLocation Loc, QualType T, unsigned DiagID,
1676 Ts &&...DiagArgs) {
1677 if (T->isDependentType())
1678 return false;
1679
1680 switch (Kind) {
1682 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1683 std::forward<Ts>(DiagArgs)...);
1684
1686 return !T->isLiteralType(SemaRef.Context);
1687 }
1688
1689 llvm_unreachable("unknown CheckConstexprKind");
1690}
1691
1692/// Determine whether a destructor cannot be constexpr due to
1694 const CXXDestructorDecl *DD,
1696 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1697 "this check is obsolete for C++23");
1698 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1699 const CXXRecordDecl *RD =
1701 if (!RD || RD->hasConstexprDestructor())
1702 return true;
1703
1705 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1706 << static_cast<int>(DD->getConstexprKind()) << !FD
1707 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1708 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1709 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1710 }
1711 return false;
1712 };
1713
1714 const CXXRecordDecl *RD = DD->getParent();
1715 for (const CXXBaseSpecifier &B : RD->bases())
1716 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1717 return false;
1718 for (const FieldDecl *FD : RD->fields())
1719 if (!Check(FD->getLocation(), FD->getType(), FD))
1720 return false;
1721 return true;
1722}
1723
1724/// Check whether a function's parameter types are all literal types. If so,
1725/// return true. If not, produce a suitable diagnostic and return false.
1727 const FunctionDecl *FD,
1729 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1730 "this check is obsolete for C++23");
1731 unsigned ArgIndex = 0;
1732 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1733 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1734 e = FT->param_type_end();
1735 i != e; ++i, ++ArgIndex) {
1736 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1737 assert(PD && "null in a parameter list");
1738 SourceLocation ParamLoc = PD->getLocation();
1739 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1740 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1741 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1742 FD->isConsteval()))
1743 return false;
1744 }
1745 return true;
1746}
1747
1748/// Check whether a function's return type is a literal type. If so, return
1749/// true. If not, produce a suitable diagnostic and return false.
1752 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1753 "this check is obsolete for C++23");
1754 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1755 diag::err_constexpr_non_literal_return,
1756 FD->isConsteval()))
1757 return false;
1758 return true;
1759}
1760
1761/// Get diagnostic %select index for tag kind for
1762/// record diagnostic message.
1763/// WARNING: Indexes apply to particular diagnostics only!
1764///
1765/// \returns diagnostic %select index.
1767 switch (Tag) {
1769 return 0;
1771 return 1;
1772 case TagTypeKind::Class:
1773 return 2;
1774 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1775 }
1776}
1777
1778static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1779 Stmt *Body,
1781static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1782
1784 CheckConstexprKind Kind) {
1785 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1786 if (MD && MD->isInstance()) {
1787 // C++11 [dcl.constexpr]p4:
1788 // The definition of a constexpr constructor shall satisfy the following
1789 // constraints:
1790 // - the class shall not have any virtual base classes;
1791 //
1792 // FIXME: This only applies to constructors and destructors, not arbitrary
1793 // member functions.
1794 const CXXRecordDecl *RD = MD->getParent();
1795 if (RD->getNumVBases()) {
1797 return false;
1798
1799 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1800 << isa<CXXConstructorDecl>(NewFD)
1802 for (const auto &I : RD->vbases())
1803 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1804 << I.getSourceRange();
1805 return false;
1806 }
1807 }
1808
1809 if (!isa<CXXConstructorDecl>(NewFD)) {
1810 // C++11 [dcl.constexpr]p3:
1811 // The definition of a constexpr function shall satisfy the following
1812 // constraints:
1813 // - it shall not be virtual; (removed in C++20)
1814 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1815 if (Method && Method->isVirtual()) {
1816 if (getLangOpts().CPlusPlus20) {
1817 if (Kind == CheckConstexprKind::Diagnose)
1818 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1819 } else {
1821 return false;
1822
1823 Method = Method->getCanonicalDecl();
1824 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1825
1826 // If it's not obvious why this function is virtual, find an overridden
1827 // function which uses the 'virtual' keyword.
1828 const CXXMethodDecl *WrittenVirtual = Method;
1829 while (!WrittenVirtual->isVirtualAsWritten())
1830 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1831 if (WrittenVirtual != Method)
1832 Diag(WrittenVirtual->getLocation(),
1833 diag::note_overridden_virtual_function);
1834 return false;
1835 }
1836 }
1837
1838 // - its return type shall be a literal type; (removed in C++23)
1839 if (!getLangOpts().CPlusPlus23 &&
1840 !CheckConstexprReturnType(*this, NewFD, Kind))
1841 return false;
1842 }
1843
1844 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1845 // A destructor can be constexpr only if the defaulted destructor could be;
1846 // we don't need to check the members and bases if we already know they all
1847 // have constexpr destructors. (removed in C++23)
1848 if (!getLangOpts().CPlusPlus23 &&
1849 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1851 return false;
1852 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1853 return false;
1854 }
1855 }
1856
1857 // - each of its parameter types shall be a literal type; (removed in C++23)
1858 if (!getLangOpts().CPlusPlus23 &&
1859 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1860 return false;
1861
1862 Stmt *Body = NewFD->getBody();
1863 assert(Body &&
1864 "CheckConstexprFunctionDefinition called on function with no body");
1865 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1866}
1867
1868/// Check the given declaration statement is legal within a constexpr function
1869/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1870///
1871/// \return true if the body is OK (maybe only as an extension), false if we
1872/// have diagnosed a problem.
1874 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1876 // C++11 [dcl.constexpr]p3 and p4:
1877 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1878 // contain only
1879 for (const auto *DclIt : DS->decls()) {
1880 switch (DclIt->getKind()) {
1881 case Decl::StaticAssert:
1882 case Decl::Using:
1883 case Decl::UsingShadow:
1884 case Decl::UsingDirective:
1885 case Decl::UnresolvedUsingTypename:
1886 case Decl::UnresolvedUsingValue:
1887 case Decl::UsingEnum:
1888 // - static_assert-declarations
1889 // - using-declarations,
1890 // - using-directives,
1891 // - using-enum-declaration
1892 continue;
1893
1894 case Decl::Typedef:
1895 case Decl::TypeAlias: {
1896 // - typedef declarations and alias-declarations that do not define
1897 // classes or enumerations,
1898 const auto *TN = cast<TypedefNameDecl>(DclIt);
1899 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1900 // Don't allow variably-modified types in constexpr functions.
1902 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1903 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1904 << TL.getSourceRange() << TL.getType()
1905 << isa<CXXConstructorDecl>(Dcl);
1906 }
1907 return false;
1908 }
1909 continue;
1910 }
1911
1912 case Decl::Enum:
1913 case Decl::CXXRecord:
1914 // C++1y allows types to be defined, not just declared.
1915 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1917 SemaRef.Diag(DS->getBeginLoc(),
1918 SemaRef.getLangOpts().CPlusPlus14
1919 ? diag::warn_cxx11_compat_constexpr_type_definition
1920 : diag::ext_constexpr_type_definition)
1921 << isa<CXXConstructorDecl>(Dcl);
1922 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1923 return false;
1924 }
1925 }
1926 continue;
1927
1928 case Decl::EnumConstant:
1929 case Decl::IndirectField:
1930 case Decl::ParmVar:
1931 // These can only appear with other declarations which are banned in
1932 // C++11 and permitted in C++1y, so ignore them.
1933 continue;
1934
1935 case Decl::Var:
1936 case Decl::Decomposition: {
1937 // C++1y [dcl.constexpr]p3 allows anything except:
1938 // a definition of a variable of non-literal type or of static or
1939 // thread storage duration or [before C++2a] for which no
1940 // initialization is performed.
1941 const auto *VD = cast<VarDecl>(DclIt);
1942 if (VD->isThisDeclarationADefinition()) {
1943 if (VD->isStaticLocal()) {
1945 SemaRef.Diag(VD->getLocation(),
1946 SemaRef.getLangOpts().CPlusPlus23
1947 ? diag::warn_cxx20_compat_constexpr_var
1948 : diag::ext_constexpr_static_var)
1949 << isa<CXXConstructorDecl>(Dcl)
1950 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1951 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1952 return false;
1953 }
1954 }
1955 if (SemaRef.LangOpts.CPlusPlus23) {
1956 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1957 diag::warn_cxx20_compat_constexpr_var,
1958 isa<CXXConstructorDecl>(Dcl),
1959 /*variable of non-literal type*/ 2);
1960 } else if (CheckLiteralType(
1961 SemaRef, Kind, VD->getLocation(), VD->getType(),
1962 diag::err_constexpr_local_var_non_literal_type,
1963 isa<CXXConstructorDecl>(Dcl))) {
1964 return false;
1965 }
1966 if (!VD->getType()->isDependentType() &&
1967 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1969 SemaRef.Diag(
1970 VD->getLocation(),
1971 SemaRef.getLangOpts().CPlusPlus20
1972 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1973 : diag::ext_constexpr_local_var_no_init)
1974 << isa<CXXConstructorDecl>(Dcl);
1975 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1976 return false;
1977 }
1978 continue;
1979 }
1980 }
1982 SemaRef.Diag(VD->getLocation(),
1983 SemaRef.getLangOpts().CPlusPlus14
1984 ? diag::warn_cxx11_compat_constexpr_local_var
1985 : diag::ext_constexpr_local_var)
1986 << isa<CXXConstructorDecl>(Dcl);
1987 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1988 return false;
1989 }
1990 continue;
1991 }
1992
1993 case Decl::NamespaceAlias:
1994 case Decl::Function:
1995 // These are disallowed in C++11 and permitted in C++1y. Allow them
1996 // everywhere as an extension.
1997 if (!Cxx1yLoc.isValid())
1998 Cxx1yLoc = DS->getBeginLoc();
1999 continue;
2000
2001 default:
2003 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2004 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2005 }
2006 return false;
2007 }
2008 }
2009
2010 return true;
2011}
2012
2013/// Check that the given field is initialized within a constexpr constructor.
2014///
2015/// \param Dcl The constexpr constructor being checked.
2016/// \param Field The field being checked. This may be a member of an anonymous
2017/// struct or union nested within the class being checked.
2018/// \param Inits All declarations, including anonymous struct/union members and
2019/// indirect members, for which any initialization was provided.
2020/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2021/// multiple notes for different members to the same error.
2022/// \param Kind Whether we're diagnosing a constructor as written or determining
2023/// whether the formal requirements are satisfied.
2024/// \return \c false if we're checking for validity and the constructor does
2025/// not satisfy the requirements on a constexpr constructor.
2027 const FunctionDecl *Dcl,
2028 FieldDecl *Field,
2029 llvm::SmallSet<Decl*, 16> &Inits,
2030 bool &Diagnosed,
2032 // In C++20 onwards, there's nothing to check for validity.
2034 SemaRef.getLangOpts().CPlusPlus20)
2035 return true;
2036
2037 if (Field->isInvalidDecl())
2038 return true;
2039
2040 if (Field->isUnnamedBitField())
2041 return true;
2042
2043 // Anonymous unions with no variant members and empty anonymous structs do not
2044 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2045 // indirect fields don't need initializing.
2046 if (Field->isAnonymousStructOrUnion() &&
2047 (Field->getType()->isUnionType()
2048 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2049 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2050 return true;
2051
2052 if (!Inits.count(Field)) {
2054 if (!Diagnosed) {
2055 SemaRef.Diag(Dcl->getLocation(),
2056 SemaRef.getLangOpts().CPlusPlus20
2057 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2058 : diag::ext_constexpr_ctor_missing_init);
2059 Diagnosed = true;
2060 }
2061 SemaRef.Diag(Field->getLocation(),
2062 diag::note_constexpr_ctor_missing_init);
2063 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2064 return false;
2065 }
2066 } else if (Field->isAnonymousStructOrUnion()) {
2067 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2068 for (auto *I : RD->fields())
2069 // If an anonymous union contains an anonymous struct of which any member
2070 // is initialized, all members must be initialized.
2071 if (!RD->isUnion() || Inits.count(I))
2072 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2073 Kind))
2074 return false;
2075 }
2076 return true;
2077}
2078
2079/// Check the provided statement is allowed in a constexpr function
2080/// definition.
2081static bool
2084 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2085 SourceLocation &Cxx2bLoc,
2087 // - its function-body shall be [...] a compound-statement that contains only
2088 switch (S->getStmtClass()) {
2089 case Stmt::NullStmtClass:
2090 // - null statements,
2091 return true;
2092
2093 case Stmt::DeclStmtClass:
2094 // - static_assert-declarations
2095 // - using-declarations,
2096 // - using-directives,
2097 // - typedef declarations and alias-declarations that do not define
2098 // classes or enumerations,
2099 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2100 return false;
2101 return true;
2102
2103 case Stmt::ReturnStmtClass:
2104 // - and exactly one return statement;
2105 if (isa<CXXConstructorDecl>(Dcl)) {
2106 // C++1y allows return statements in constexpr constructors.
2107 if (!Cxx1yLoc.isValid())
2108 Cxx1yLoc = S->getBeginLoc();
2109 return true;
2110 }
2111
2112 ReturnStmts.push_back(S->getBeginLoc());
2113 return true;
2114
2115 case Stmt::AttributedStmtClass:
2116 // Attributes on a statement don't affect its formal kind and hence don't
2117 // affect its validity in a constexpr function.
2119 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2120 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2121
2122 case Stmt::CompoundStmtClass: {
2123 // C++1y allows compound-statements.
2124 if (!Cxx1yLoc.isValid())
2125 Cxx1yLoc = S->getBeginLoc();
2126
2127 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2128 for (auto *BodyIt : CompStmt->body()) {
2129 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2130 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2131 return false;
2132 }
2133 return true;
2134 }
2135
2136 case Stmt::IfStmtClass: {
2137 // C++1y allows if-statements.
2138 if (!Cxx1yLoc.isValid())
2139 Cxx1yLoc = S->getBeginLoc();
2140
2141 IfStmt *If = cast<IfStmt>(S);
2142 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2143 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2144 return false;
2145 if (If->getElse() &&
2146 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2147 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2148 return false;
2149 return true;
2150 }
2151
2152 case Stmt::WhileStmtClass:
2153 case Stmt::DoStmtClass:
2154 case Stmt::ForStmtClass:
2155 case Stmt::CXXForRangeStmtClass:
2156 case Stmt::ContinueStmtClass:
2157 // C++1y allows all of these. We don't allow them as extensions in C++11,
2158 // because they don't make sense without variable mutation.
2159 if (!SemaRef.getLangOpts().CPlusPlus14)
2160 break;
2161 if (!Cxx1yLoc.isValid())
2162 Cxx1yLoc = S->getBeginLoc();
2163 for (Stmt *SubStmt : S->children()) {
2164 if (SubStmt &&
2165 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2166 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2167 return false;
2168 }
2169 return true;
2170
2171 case Stmt::SwitchStmtClass:
2172 case Stmt::CaseStmtClass:
2173 case Stmt::DefaultStmtClass:
2174 case Stmt::BreakStmtClass:
2175 // C++1y allows switch-statements, and since they don't need variable
2176 // mutation, we can reasonably allow them in C++11 as an extension.
2177 if (!Cxx1yLoc.isValid())
2178 Cxx1yLoc = S->getBeginLoc();
2179 for (Stmt *SubStmt : S->children()) {
2180 if (SubStmt &&
2181 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2182 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2183 return false;
2184 }
2185 return true;
2186
2187 case Stmt::LabelStmtClass:
2188 case Stmt::GotoStmtClass:
2189 if (Cxx2bLoc.isInvalid())
2190 Cxx2bLoc = S->getBeginLoc();
2191 for (Stmt *SubStmt : S->children()) {
2192 if (SubStmt &&
2193 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2194 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2195 return false;
2196 }
2197 return true;
2198
2199 case Stmt::GCCAsmStmtClass:
2200 case Stmt::MSAsmStmtClass:
2201 // C++2a allows inline assembly statements.
2202 case Stmt::CXXTryStmtClass:
2203 if (Cxx2aLoc.isInvalid())
2204 Cxx2aLoc = S->getBeginLoc();
2205 for (Stmt *SubStmt : S->children()) {
2206 if (SubStmt &&
2207 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2208 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2209 return false;
2210 }
2211 return true;
2212
2213 case Stmt::CXXCatchStmtClass:
2214 // Do not bother checking the language mode (already covered by the
2215 // try block check).
2217 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2218 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2219 return false;
2220 return true;
2221
2222 default:
2223 if (!isa<Expr>(S))
2224 break;
2225
2226 // C++1y allows expression-statements.
2227 if (!Cxx1yLoc.isValid())
2228 Cxx1yLoc = S->getBeginLoc();
2229 return true;
2230 }
2231
2233 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2234 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2235 }
2236 return false;
2237}
2238
2239/// Check the body for the given constexpr function declaration only contains
2240/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2241///
2242/// \return true if the body is OK, false if we have found or diagnosed a
2243/// problem.
2245 Stmt *Body,
2248
2249 if (isa<CXXTryStmt>(Body)) {
2250 // C++11 [dcl.constexpr]p3:
2251 // The definition of a constexpr function shall satisfy the following
2252 // constraints: [...]
2253 // - its function-body shall be = delete, = default, or a
2254 // compound-statement
2255 //
2256 // C++11 [dcl.constexpr]p4:
2257 // In the definition of a constexpr constructor, [...]
2258 // - its function-body shall not be a function-try-block;
2259 //
2260 // This restriction is lifted in C++2a, as long as inner statements also
2261 // apply the general constexpr rules.
2262 switch (Kind) {
2264 if (!SemaRef.getLangOpts().CPlusPlus20)
2265 return false;
2266 break;
2267
2269 SemaRef.Diag(Body->getBeginLoc(),
2270 !SemaRef.getLangOpts().CPlusPlus20
2271 ? diag::ext_constexpr_function_try_block_cxx20
2272 : diag::warn_cxx17_compat_constexpr_function_try_block)
2273 << isa<CXXConstructorDecl>(Dcl);
2274 break;
2275 }
2276 }
2277
2278 // - its function-body shall be [...] a compound-statement that contains only
2279 // [... list of cases ...]
2280 //
2281 // Note that walking the children here is enough to properly check for
2282 // CompoundStmt and CXXTryStmt body.
2283 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2284 for (Stmt *SubStmt : Body->children()) {
2285 if (SubStmt &&
2286 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2287 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2288 return false;
2289 }
2290
2292 // If this is only valid as an extension, report that we don't satisfy the
2293 // constraints of the current language.
2294 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2295 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2296 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2297 return false;
2298 } else if (Cxx2bLoc.isValid()) {
2299 SemaRef.Diag(Cxx2bLoc,
2300 SemaRef.getLangOpts().CPlusPlus23
2301 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2302 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2303 << isa<CXXConstructorDecl>(Dcl);
2304 } else if (Cxx2aLoc.isValid()) {
2305 SemaRef.Diag(Cxx2aLoc,
2306 SemaRef.getLangOpts().CPlusPlus20
2307 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2308 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2309 << isa<CXXConstructorDecl>(Dcl);
2310 } else if (Cxx1yLoc.isValid()) {
2311 SemaRef.Diag(Cxx1yLoc,
2312 SemaRef.getLangOpts().CPlusPlus14
2313 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2314 : diag::ext_constexpr_body_invalid_stmt)
2315 << isa<CXXConstructorDecl>(Dcl);
2316 }
2317
2318 if (const CXXConstructorDecl *Constructor
2319 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2320 const CXXRecordDecl *RD = Constructor->getParent();
2321 // DR1359:
2322 // - every non-variant non-static data member and base class sub-object
2323 // shall be initialized;
2324 // DR1460:
2325 // - if the class is a union having variant members, exactly one of them
2326 // shall be initialized;
2327 if (RD->isUnion()) {
2328 if (Constructor->getNumCtorInitializers() == 0 &&
2329 RD->hasVariantMembers()) {
2331 SemaRef.Diag(
2332 Dcl->getLocation(),
2333 SemaRef.getLangOpts().CPlusPlus20
2334 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2335 : diag::ext_constexpr_union_ctor_no_init);
2336 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2337 return false;
2338 }
2339 }
2340 } else if (!Constructor->isDependentContext() &&
2341 !Constructor->isDelegatingConstructor()) {
2342 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2343
2344 // Skip detailed checking if we have enough initializers, and we would
2345 // allow at most one initializer per member.
2346 bool AnyAnonStructUnionMembers = false;
2347 unsigned Fields = 0;
2349 E = RD->field_end(); I != E; ++I, ++Fields) {
2350 if (I->isAnonymousStructOrUnion()) {
2351 AnyAnonStructUnionMembers = true;
2352 break;
2353 }
2354 }
2355 // DR1460:
2356 // - if the class is a union-like class, but is not a union, for each of
2357 // its anonymous union members having variant members, exactly one of
2358 // them shall be initialized;
2359 if (AnyAnonStructUnionMembers ||
2360 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2361 // Check initialization of non-static data members. Base classes are
2362 // always initialized so do not need to be checked. Dependent bases
2363 // might not have initializers in the member initializer list.
2364 llvm::SmallSet<Decl*, 16> Inits;
2365 for (const auto *I: Constructor->inits()) {
2366 if (FieldDecl *FD = I->getMember())
2367 Inits.insert(FD);
2368 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2369 Inits.insert(ID->chain_begin(), ID->chain_end());
2370 }
2371
2372 bool Diagnosed = false;
2373 for (auto *I : RD->fields())
2374 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2375 Kind))
2376 return false;
2377 }
2378 }
2379 } else {
2380 if (ReturnStmts.empty()) {
2381 switch (Kind) {
2384 return false;
2385 break;
2386
2388 // The formal requirements don't include this rule in C++14, even
2389 // though the "must be able to produce a constant expression" rules
2390 // still imply it in some cases.
2391 if (!SemaRef.getLangOpts().CPlusPlus14)
2392 return false;
2393 break;
2394 }
2395 } else if (ReturnStmts.size() > 1) {
2396 switch (Kind) {
2398 SemaRef.Diag(
2399 ReturnStmts.back(),
2400 SemaRef.getLangOpts().CPlusPlus14
2401 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2402 : diag::ext_constexpr_body_multiple_return);
2403 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2404 SemaRef.Diag(ReturnStmts[I],
2405 diag::note_constexpr_body_previous_return);
2406 break;
2407
2409 if (!SemaRef.getLangOpts().CPlusPlus14)
2410 return false;
2411 break;
2412 }
2413 }
2414 }
2415
2416 // C++11 [dcl.constexpr]p5:
2417 // if no function argument values exist such that the function invocation
2418 // substitution would produce a constant expression, the program is
2419 // ill-formed; no diagnostic required.
2420 // C++11 [dcl.constexpr]p3:
2421 // - every constructor call and implicit conversion used in initializing the
2422 // return value shall be one of those allowed in a constant expression.
2423 // C++11 [dcl.constexpr]p4:
2424 // - every constructor involved in initializing non-static data members and
2425 // base class sub-objects shall be a constexpr constructor.
2426 //
2427 // Note that this rule is distinct from the "requirements for a constexpr
2428 // function", so is not checked in CheckValid mode. Because the check for
2429 // constexpr potential is expensive, skip the check if the diagnostic is
2430 // disabled, the function is declared in a system header, or we're in C++23
2431 // or later mode (see https://wg21.link/P2448).
2432 bool SkipCheck =
2433 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2436 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2438 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2440 SemaRef.Diag(Dcl->getLocation(),
2441 diag::ext_constexpr_function_never_constant_expr)
2442 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2443 << Dcl->getNameInfo().getSourceRange();
2444 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2445 SemaRef.Diag(Diags[I].first, Diags[I].second);
2446 // Don't return false here: we allow this for compatibility in
2447 // system headers.
2448 }
2449
2450 return true;
2451}
2452
2454 const FunctionDecl *Dcl) {
2455 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2457 // Skip emitting a missing return error diagnostic for non-void functions
2458 // since C++23 no longer mandates constexpr functions to yield constant
2459 // expressions.
2460 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2461 return true;
2462
2463 // C++14 doesn't require constexpr functions to contain a 'return'
2464 // statement. We still do, unless the return type might be void, because
2465 // otherwise if there's no return statement, the function cannot
2466 // be used in a core constant expression.
2467 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2468 SemaRef.Diag(Dcl->getLocation(),
2469 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2470 : diag::err_constexpr_body_no_return)
2471 << Dcl->isConsteval();
2472 return OK;
2473}
2474
2476 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2478 return true;
2482 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2483 if (it != UndefinedButUsed.end()) {
2484 Diag(it->second, diag::err_immediate_function_used_before_definition)
2485 << it->first;
2486 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2487 if (FD->isImmediateFunction() && !FD->isConsteval())
2489 return false;
2490 }
2491 }
2492 return true;
2493}
2494
2496 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2497 "expected an immediate function");
2498 assert(FD->hasBody() && "expected the function to have a body");
2499 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2500 Sema &SemaRef;
2501
2502 const FunctionDecl *ImmediateFn;
2503 bool ImmediateFnIsConstructor;
2504 CXXConstructorDecl *CurrentConstructor = nullptr;
2505 CXXCtorInitializer *CurrentInit = nullptr;
2506
2507 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2508 : SemaRef(SemaRef), ImmediateFn(FD),
2509 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2510 ShouldVisitImplicitCode = true;
2511 ShouldVisitLambdaBody = false;
2512 }
2513
2514 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2517 if (CurrentConstructor && CurrentInit) {
2518 Loc = CurrentConstructor->getLocation();
2519 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2520 : SourceRange();
2521 }
2522
2523 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2524
2525 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2526 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2527 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2528 << (InitializedField != nullptr)
2529 << (CurrentInit && !CurrentInit->isWritten())
2530 << InitializedField << Range;
2531 }
2532 bool TraverseCallExpr(CallExpr *E) override {
2533 if (const auto *DR =
2534 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2535 DR && DR->isImmediateEscalating()) {
2536 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2537 return false;
2538 }
2539
2540 for (Expr *A : E->arguments())
2541 if (!TraverseStmt(A))
2542 return false;
2543
2544 return true;
2545 }
2546
2547 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2548 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2549 ReferencedFn && E->isImmediateEscalating()) {
2550 Diag(E, ReferencedFn, /*IsCall=*/false);
2551 return false;
2552 }
2553
2554 return true;
2555 }
2556
2557 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2558 CXXConstructorDecl *D = E->getConstructor();
2559 if (E->isImmediateEscalating()) {
2560 Diag(E, D, /*IsCall=*/true);
2561 return false;
2562 }
2563 return true;
2564 }
2565
2566 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2567 llvm::SaveAndRestore RAII(CurrentInit, Init);
2569 }
2570
2571 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2572 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2573 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2574 }
2575
2576 bool TraverseType(QualType T) override { return true; }
2577 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2578
2579 } Visitor(*this, FD);
2580 Visitor.TraverseDecl(FD);
2581}
2582
2584 assert(getLangOpts().CPlusPlus && "No class names in C!");
2585
2586 if (SS && SS->isInvalid())
2587 return nullptr;
2588
2589 if (SS && SS->isNotEmpty()) {
2590 DeclContext *DC = computeDeclContext(*SS, true);
2591 return dyn_cast_or_null<CXXRecordDecl>(DC);
2592 }
2593
2594 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2595}
2596
2598 const CXXScopeSpec *SS) {
2599 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2600 return CurDecl && &II == CurDecl->getIdentifier();
2601}
2602
2604 assert(getLangOpts().CPlusPlus && "No class names in C!");
2605
2606 if (!getLangOpts().SpellChecking)
2607 return false;
2608
2609 CXXRecordDecl *CurDecl;
2610 if (SS && SS->isSet() && !SS->isInvalid()) {
2611 DeclContext *DC = computeDeclContext(*SS, true);
2612 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2613 } else
2614 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2615
2616 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2617 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2618 < II->getLength()) {
2619 II = CurDecl->getIdentifier();
2620 return true;
2621 }
2622
2623 return false;
2624}
2625
2627 SourceRange SpecifierRange,
2628 bool Virtual, AccessSpecifier Access,
2629 TypeSourceInfo *TInfo,
2630 SourceLocation EllipsisLoc) {
2631 QualType BaseType = TInfo->getType();
2632 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2633 if (BaseType->containsErrors()) {
2634 // Already emitted a diagnostic when parsing the error type.
2635 return nullptr;
2636 }
2637
2638 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2639 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2640 << TInfo->getTypeLoc().getSourceRange();
2641 EllipsisLoc = SourceLocation();
2642 }
2643
2644 auto *BaseDecl =
2645 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2646 // C++ [class.derived.general]p2:
2647 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2648 // that is not an incompletely defined class; any cv-qualifiers are
2649 // ignored.
2650 if (BaseDecl) {
2651 // C++ [class.union.general]p4:
2652 // [...] A union shall not be used as a base class.
2653 if (BaseDecl->isUnion()) {
2654 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2655 return nullptr;
2656 }
2657
2658 if (BaseType.hasQualifiers()) {
2659 std::string Quals =
2661 Diag(BaseLoc, diag::warn_qual_base_type)
2662 << Quals << std::count(Quals.begin(), Quals.end(), ' ') + 1
2663 << BaseType;
2664 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2665 }
2666
2667 // For the MS ABI, propagate DLL attributes to base class templates.
2669 Context.getTargetInfo().getTriple().isPS()) {
2670 if (Attr *ClassAttr = getDLLAttr(Class)) {
2671 if (auto *BaseSpec =
2672 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2673 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2674 BaseLoc);
2675 }
2676 }
2677 }
2678
2679 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2680 SpecifierRange)) {
2681 Class->setInvalidDecl();
2682 return nullptr;
2683 }
2684
2685 BaseDecl = BaseDecl->getDefinition();
2686 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2687
2688 // Microsoft docs say:
2689 // "If a base-class has a code_seg attribute, derived classes must have the
2690 // same attribute."
2691 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2692 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2693 if ((DerivedCSA || BaseCSA) &&
2694 (!BaseCSA || !DerivedCSA ||
2695 BaseCSA->getName() != DerivedCSA->getName())) {
2696 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2697 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2698 << BaseDecl;
2699 return nullptr;
2700 }
2701
2702 // A class which contains a flexible array member is not suitable for use as
2703 // a base class:
2704 // - If the layout determines that a base comes before another base,
2705 // the flexible array member would index into the subsequent base.
2706 // - If the layout determines that base comes before the derived class,
2707 // the flexible array member would index into the derived class.
2708 if (BaseDecl->hasFlexibleArrayMember()) {
2709 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2710 << BaseDecl->getDeclName();
2711 return nullptr;
2712 }
2713
2714 // C++ [class]p3:
2715 // If a class is marked final and it appears as a base-type-specifier in
2716 // base-clause, the program is ill-formed.
2717 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2718 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2719 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2720 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2721 << BaseDecl->getDeclName() << FA->getRange();
2722 return nullptr;
2723 }
2724
2725 // If the base class is invalid the derived class is as well.
2726 if (BaseDecl->isInvalidDecl())
2727 Class->setInvalidDecl();
2728 } else if (BaseType->isDependentType()) {
2729 // Make sure that we don't make an ill-formed AST where the type of the
2730 // Class is non-dependent and its attached base class specifier is an
2731 // dependent type, which violates invariants in many clang code paths (e.g.
2732 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2733 // explicitly mark the Class decl invalid. The diagnostic was already
2734 // emitted.
2735 if (!Class->isDependentContext())
2736 Class->setInvalidDecl();
2737 } else {
2738 // The base class is some non-dependent non-class type.
2739 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2740 return nullptr;
2741 }
2742
2743 // In HLSL, unspecified class access is public rather than private.
2744 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2745 Access == AS_none)
2746 Access = AS_public;
2747
2748 // Create the base specifier.
2749 return new (Context) CXXBaseSpecifier(
2750 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2751 Access, TInfo, EllipsisLoc);
2752}
2753
2755 const ParsedAttributesView &Attributes,
2756 bool Virtual, AccessSpecifier Access,
2757 ParsedType basetype, SourceLocation BaseLoc,
2758 SourceLocation EllipsisLoc) {
2759 if (!classdecl)
2760 return true;
2761
2762 AdjustDeclIfTemplate(classdecl);
2763 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2764 if (!Class)
2765 return true;
2766
2767 // We haven't yet attached the base specifiers.
2768 Class->setIsParsingBaseSpecifiers();
2769
2770 // We do not support any C++11 attributes on base-specifiers yet.
2771 // Diagnose any attributes we see.
2772 for (const ParsedAttr &AL : Attributes) {
2773 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2774 continue;
2775 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2776 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2777 << AL << AL.getRange();
2778 else
2779 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2780 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2781 }
2782
2783 TypeSourceInfo *TInfo = nullptr;
2784 GetTypeFromParser(basetype, &TInfo);
2785
2786 if (EllipsisLoc.isInvalid() &&
2787 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2789 return true;
2790
2791 // C++ [class.union.general]p4:
2792 // [...] A union shall not have base classes.
2793 if (Class->isUnion()) {
2794 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2795 << SpecifierRange;
2796 return true;
2797 }
2798
2799 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2800 Virtual, Access, TInfo,
2801 EllipsisLoc))
2802 return BaseSpec;
2803
2804 Class->setInvalidDecl();
2805 return true;
2806}
2807
2808/// Use small set to collect indirect bases. As this is only used
2809/// locally, there's no need to abstract the small size parameter.
2811
2812/// Recursively add the bases of Type. Don't add Type itself.
2813static void
2815 const QualType &Type)
2816{
2817 // Even though the incoming type is a base, it might not be
2818 // a class -- it could be a template parm, for instance.
2819 if (auto Rec = Type->getAs<RecordType>()) {
2820 auto Decl = Rec->getAsCXXRecordDecl();
2821
2822 // Iterate over its bases.
2823 for (const auto &BaseSpec : Decl->bases()) {
2824 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2826 if (Set.insert(Base).second)
2827 // If we've not already seen it, recurse.
2829 }
2830 }
2831}
2832
2835 if (Bases.empty())
2836 return false;
2837
2838 // Used to keep track of which base types we have already seen, so
2839 // that we can properly diagnose redundant direct base types. Note
2840 // that the key is always the unqualified canonical type of the base
2841 // class.
2842 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2843
2844 // Used to track indirect bases so we can see if a direct base is
2845 // ambiguous.
2846 IndirectBaseSet IndirectBaseTypes;
2847
2848 // Copy non-redundant base specifiers into permanent storage.
2849 unsigned NumGoodBases = 0;
2850 bool Invalid = false;
2851 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2852 QualType NewBaseType
2853 = Context.getCanonicalType(Bases[idx]->getType());
2854 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2855
2856 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2857 if (KnownBase) {
2858 // C++ [class.mi]p3:
2859 // A class shall not be specified as a direct base class of a
2860 // derived class more than once.
2861 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2862 << KnownBase->getType() << Bases[idx]->getSourceRange();
2863
2864 // Delete the duplicate base class specifier; we're going to
2865 // overwrite its pointer later.
2866 Context.Deallocate(Bases[idx]);
2867
2868 Invalid = true;
2869 } else {
2870 // Okay, add this new base class.
2871 KnownBase = Bases[idx];
2872 Bases[NumGoodBases++] = Bases[idx];
2873
2874 if (NewBaseType->isDependentType())
2875 continue;
2876 // Note this base's direct & indirect bases, if there could be ambiguity.
2877 if (Bases.size() > 1)
2878 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2879
2880 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2881 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2882 if (Class->isInterface() &&
2883 (!RD->isInterfaceLike() ||
2884 KnownBase->getAccessSpecifier() != AS_public)) {
2885 // The Microsoft extension __interface does not permit bases that
2886 // are not themselves public interfaces.
2887 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2888 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2889 << RD->getSourceRange();
2890 Invalid = true;
2891 }
2892 if (RD->hasAttr<WeakAttr>())
2893 Class->addAttr(WeakAttr::CreateImplicit(Context));
2894 }
2895 }
2896 }
2897
2898 // Attach the remaining base class specifiers to the derived class.
2899 Class->setBases(Bases.data(), NumGoodBases);
2900
2901 // Check that the only base classes that are duplicate are virtual.
2902 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2903 // Check whether this direct base is inaccessible due to ambiguity.
2904 QualType BaseType = Bases[idx]->getType();
2905
2906 // Skip all dependent types in templates being used as base specifiers.
2907 // Checks below assume that the base specifier is a CXXRecord.
2908 if (BaseType->isDependentType())
2909 continue;
2910
2911 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2913
2914 if (IndirectBaseTypes.count(CanonicalBase)) {
2915 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2916 /*DetectVirtual=*/true);
2917 bool found
2918 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2919 assert(found);
2920 (void)found;
2921
2922 if (Paths.isAmbiguous(CanonicalBase))
2923 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2924 << BaseType << getAmbiguousPathsDisplayString(Paths)
2925 << Bases[idx]->getSourceRange();
2926 else
2927 assert(Bases[idx]->isVirtual());
2928 }
2929
2930 // Delete the base class specifier, since its data has been copied
2931 // into the CXXRecordDecl.
2932 Context.Deallocate(Bases[idx]);
2933 }
2934
2935 return Invalid;
2936}
2937
2940 if (!ClassDecl || Bases.empty())
2941 return;
2942
2943 AdjustDeclIfTemplate(ClassDecl);
2944 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2945}
2946
2948 if (!getLangOpts().CPlusPlus)
2949 return false;
2950
2951 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2952 if (!DerivedRD)
2953 return false;
2954
2955 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2956 if (!BaseRD)
2957 return false;
2958
2959 // If either the base or the derived type is invalid, don't try to
2960 // check whether one is derived from the other.
2961 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2962 return false;
2963
2964 // FIXME: In a modules build, do we need the entire path to be visible for us
2965 // to be able to use the inheritance relationship?
2966 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2967 return false;
2968
2969 return DerivedRD->isDerivedFrom(BaseRD);
2970}
2971
2973 CXXBasePaths &Paths) {
2974 if (!getLangOpts().CPlusPlus)
2975 return false;
2976
2977 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2978 if (!DerivedRD)
2979 return false;
2980
2981 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2982 if (!BaseRD)
2983 return false;
2984
2985 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2986 return false;
2987
2988 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2989}
2990
2992 CXXCastPath &BasePathArray) {
2993 // We first go backward and check if we have a virtual base.
2994 // FIXME: It would be better if CXXBasePath had the base specifier for
2995 // the nearest virtual base.
2996 unsigned Start = 0;
2997 for (unsigned I = Path.size(); I != 0; --I) {
2998 if (Path[I - 1].Base->isVirtual()) {
2999 Start = I - 1;
3000 break;
3001 }
3002 }
3003
3004 // Now add all bases.
3005 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3006 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3007}
3008
3009
3011 CXXCastPath &BasePathArray) {
3012 assert(BasePathArray.empty() && "Base path array must be empty!");
3013 assert(Paths.isRecordingPaths() && "Must record paths!");
3014 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3015}
3016
3017bool
3019 unsigned InaccessibleBaseID,
3020 unsigned AmbiguousBaseConvID,
3022 DeclarationName Name,
3023 CXXCastPath *BasePath,
3024 bool IgnoreAccess) {
3025 // First, determine whether the path from Derived to Base is
3026 // ambiguous. This is slightly more expensive than checking whether
3027 // the Derived to Base conversion exists, because here we need to
3028 // explore multiple paths to determine if there is an ambiguity.
3029 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3030 /*DetectVirtual=*/false);
3031 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3032 if (!DerivationOkay)
3033 return true;
3034
3035 const CXXBasePath *Path = nullptr;
3036 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3037 Path = &Paths.front();
3038
3039 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3040 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3041 // user to access such bases.
3042 if (!Path && getLangOpts().MSVCCompat) {
3043 for (const CXXBasePath &PossiblePath : Paths) {
3044 if (PossiblePath.size() == 1) {
3045 Path = &PossiblePath;
3046 if (AmbiguousBaseConvID)
3047 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3048 << Base << Derived << Range;
3049 break;
3050 }
3051 }
3052 }
3053
3054 if (Path) {
3055 if (!IgnoreAccess) {
3056 // Check that the base class can be accessed.
3057 switch (
3058 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3059 case AR_inaccessible:
3060 return true;
3061 case AR_accessible:
3062 case AR_dependent:
3063 case AR_delayed:
3064 break;
3065 }
3066 }
3067
3068 // Build a base path if necessary.
3069 if (BasePath)
3070 ::BuildBasePathArray(*Path, *BasePath);
3071 return false;
3072 }
3073
3074 if (AmbiguousBaseConvID) {
3075 // We know that the derived-to-base conversion is ambiguous, and
3076 // we're going to produce a diagnostic. Perform the derived-to-base
3077 // search just one more time to compute all of the possible paths so
3078 // that we can print them out. This is more expensive than any of
3079 // the previous derived-to-base checks we've done, but at this point
3080 // performance isn't as much of an issue.
3081 Paths.clear();
3082 Paths.setRecordingPaths(true);
3083 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3084 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3085 (void)StillOkay;
3086
3087 // Build up a textual representation of the ambiguous paths, e.g.,
3088 // D -> B -> A, that will be used to illustrate the ambiguous
3089 // conversions in the diagnostic. We only print one of the paths
3090 // to each base class subobject.
3091 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3092
3093 Diag(Loc, AmbiguousBaseConvID)
3094 << Derived << Base << PathDisplayStr << Range << Name;
3095 }
3096 return true;
3097}
3098
3099bool
3102 CXXCastPath *BasePath,
3103 bool IgnoreAccess) {
3105 Derived, Base, diag::err_upcast_to_inaccessible_base,
3106 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3107 BasePath, IgnoreAccess);
3108}
3109
3111 std::string PathDisplayStr;
3112 std::set<unsigned> DisplayedPaths;
3113 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3114 Path != Paths.end(); ++Path) {
3115 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3116 // We haven't displayed a path to this particular base
3117 // class subobject yet.
3118 PathDisplayStr += "\n ";
3119 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3120 for (CXXBasePath::const_iterator Element = Path->begin();
3121 Element != Path->end(); ++Element)
3122 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3123 }
3124 }
3125
3126 return PathDisplayStr;
3127}
3128
3129//===----------------------------------------------------------------------===//
3130// C++ class member Handling
3131//===----------------------------------------------------------------------===//
3132
3134 SourceLocation ColonLoc,
3135 const ParsedAttributesView &Attrs) {
3136 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3138 ASLoc, ColonLoc);
3139 CurContext->addHiddenDecl(ASDecl);
3140 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3141}
3142
3144 if (D->isInvalidDecl())
3145 return;
3146
3147 // We only care about "override" and "final" declarations.
3148 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3149 return;
3150
3151 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3152
3153 // We can't check dependent instance methods.
3154 if (MD && MD->isInstance() &&
3155 (MD->getParent()->hasAnyDependentBases() ||
3156 MD->getType()->isDependentType()))
3157 return;
3158
3159 if (MD && !MD->isVirtual()) {
3160 // If we have a non-virtual method, check if it hides a virtual method.
3161 // (In that case, it's most likely the method has the wrong type.)
3162 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3163 FindHiddenVirtualMethods(MD, OverloadedMethods);
3164
3165 if (!OverloadedMethods.empty()) {
3166 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3167 Diag(OA->getLocation(),
3168 diag::override_keyword_hides_virtual_member_function)
3169 << "override" << (OverloadedMethods.size() > 1);
3170 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3171 Diag(FA->getLocation(),
3172 diag::override_keyword_hides_virtual_member_function)
3173 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3174 << (OverloadedMethods.size() > 1);
3175 }
3176 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3177 MD->setInvalidDecl();
3178 return;
3179 }
3180 // Fall through into the general case diagnostic.
3181 // FIXME: We might want to attempt typo correction here.
3182 }
3183
3184 if (!MD || !MD->isVirtual()) {
3185 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3186 Diag(OA->getLocation(),
3187 diag::override_keyword_only_allowed_on_virtual_member_functions)
3188 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3189 D->dropAttr<OverrideAttr>();
3190 }
3191 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3192 Diag(FA->getLocation(),
3193 diag::override_keyword_only_allowed_on_virtual_member_functions)
3194 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3195 << FixItHint::CreateRemoval(FA->getLocation());
3196 D->dropAttr<FinalAttr>();
3197 }
3198 return;
3199 }
3200
3201 // C++11 [class.virtual]p5:
3202 // If a function is marked with the virt-specifier override and
3203 // does not override a member function of a base class, the program is
3204 // ill-formed.
3205 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3206 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3207 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3208 << MD->getDeclName();
3209}
3210
3212 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3213 return;
3214 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3215 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3216 return;
3217
3219 SourceLocation SpellingLoc = Loc;
3220 if (getSourceManager().isMacroArgExpansion(Loc))
3222 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3223 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3224 return;
3225
3226 if (MD->size_overridden_methods() > 0) {
3227 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3228 unsigned DiagID =
3229 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3230 ? DiagInconsistent
3231 : DiagSuggest;
3232 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3233 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3234 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3235 };
3236 if (isa<CXXDestructorDecl>(MD))
3237 EmitDiag(
3238 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3239 diag::warn_suggest_destructor_marked_not_override_overriding);
3240 else
3241 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3242 diag::warn_suggest_function_marked_not_override_overriding);
3243 }
3244}
3245
3247 const CXXMethodDecl *Old) {
3248 FinalAttr *FA = Old->getAttr<FinalAttr>();
3249 if (!FA)
3250 return false;
3251
3252 Diag(New->getLocation(), diag::err_final_function_overridden)
3253 << New->getDeclName()
3254 << FA->isSpelledAsSealed();
3255 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3256 return true;
3257}
3258
3260 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3261 // FIXME: Destruction of ObjC lifetime types has side-effects.
3262 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3263 return !RD->isCompleteDefinition() ||
3264 !RD->hasTrivialDefaultConstructor() ||
3265 !RD->hasTrivialDestructor();
3266 return false;
3267}
3268
3269void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3270 DeclarationName FieldName,
3271 const CXXRecordDecl *RD,
3272 bool DeclIsField) {
3273 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3274 return;
3275
3276 // To record a shadowed field in a base
3277 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3278 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3279 CXXBasePath &Path) {
3280 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3281 // Record an ambiguous path directly
3282 if (Bases.find(Base) != Bases.end())
3283 return true;
3284 for (const auto Field : Base->lookup(FieldName)) {
3285 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3286 Field->getAccess() != AS_private) {
3287 assert(Field->getAccess() != AS_none);
3288 assert(Bases.find(Base) == Bases.end());
3289 Bases[Base] = Field;
3290 return true;
3291 }
3292 }
3293 return false;
3294 };
3295
3296 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3297 /*DetectVirtual=*/true);
3298 if (!RD->lookupInBases(FieldShadowed, Paths))
3299 return;
3300
3301 for (const auto &P : Paths) {
3302 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3303 auto It = Bases.find(Base);
3304 // Skip duplicated bases
3305 if (It == Bases.end())
3306 continue;
3307 auto BaseField = It->second;
3308 assert(BaseField->getAccess() != AS_private);
3309 if (AS_none !=
3310 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3311 Diag(Loc, diag::warn_shadow_field)
3312 << FieldName << RD << Base << DeclIsField;
3313 Diag(BaseField->getLocation(), diag::note_shadow_field);
3314 Bases.erase(It);
3315 }
3316 }
3317}
3318
3319NamedDecl *
3321 MultiTemplateParamsArg TemplateParameterLists,
3322 Expr *BW, const VirtSpecifiers &VS,
3323 InClassInitStyle InitStyle) {
3324 const DeclSpec &DS = D.getDeclSpec();
3326 DeclarationName Name = NameInfo.getName();
3327 SourceLocation Loc = NameInfo.getLoc();
3328
3329 // For anonymous bitfields, the location should point to the type.
3330 if (Loc.isInvalid())
3331 Loc = D.getBeginLoc();
3332
3333 Expr *BitWidth = static_cast<Expr*>(BW);
3334
3335 assert(isa<CXXRecordDecl>(CurContext));
3336 assert(!DS.isFriendSpecified());
3337
3338 bool isFunc = D.isDeclarationOfFunction();
3339 const ParsedAttr *MSPropertyAttr =
3340 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3341
3342 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3343 // The Microsoft extension __interface only permits public member functions
3344 // and prohibits constructors, destructors, operators, non-public member
3345 // functions, static methods and data members.
3346 unsigned InvalidDecl;
3347 bool ShowDeclName = true;
3348 if (!isFunc &&
3349 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3350 InvalidDecl = 0;
3351 else if (!isFunc)
3352 InvalidDecl = 1;
3353 else if (AS != AS_public)
3354 InvalidDecl = 2;
3356 InvalidDecl = 3;
3357 else switch (Name.getNameKind()) {
3359 InvalidDecl = 4;
3360 ShowDeclName = false;
3361 break;
3362
3364 InvalidDecl = 5;
3365 ShowDeclName = false;
3366 break;
3367
3370 InvalidDecl = 6;
3371 break;
3372
3373 default:
3374 InvalidDecl = 0;
3375 break;
3376 }
3377
3378 if (InvalidDecl) {
3379 if (ShowDeclName)
3380 Diag(Loc, diag::err_invalid_member_in_interface)
3381 << (InvalidDecl-1) << Name;
3382 else
3383 Diag(Loc, diag::err_invalid_member_in_interface)
3384 << (InvalidDecl-1) << "";
3385 return nullptr;
3386 }
3387 }
3388
3389 // C++ 9.2p6: A member shall not be declared to have automatic storage
3390 // duration (auto, register) or with the extern storage-class-specifier.
3391 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3392 // data members and cannot be applied to names declared const or static,
3393 // and cannot be applied to reference members.
3394 switch (DS.getStorageClassSpec()) {
3398 break;
3400 if (isFunc) {
3401 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3402
3403 // FIXME: It would be nicer if the keyword was ignored only for this
3404 // declarator. Otherwise we could get follow-up errors.
3405 D.getMutableDeclSpec().ClearStorageClassSpecs();
3406 }
3407 break;
3408 default:
3410 diag::err_storageclass_invalid_for_member);
3411 D.getMutableDeclSpec().ClearStorageClassSpecs();
3412 break;
3413 }
3414
3415 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3417 !isFunc && TemplateParameterLists.empty();
3418
3419 if (DS.hasConstexprSpecifier() && isInstField) {
3421 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3422 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3423 if (InitStyle == ICIS_NoInit) {
3424 B << 0 << 0;
3425 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3426 B << FixItHint::CreateRemoval(ConstexprLoc);
3427 else {
3428 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3429 D.getMutableDeclSpec().ClearConstexprSpec();
3430 const char *PrevSpec;
3431 unsigned DiagID;
3432 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3433 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3434 (void)Failed;
3435 assert(!Failed && "Making a constexpr member const shouldn't fail");
3436 }
3437 } else {
3438 B << 1;
3439 const char *PrevSpec;
3440 unsigned DiagID;
3441 if (D.getMutableDeclSpec().SetStorageClassSpec(
3442 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3445 "This is the only DeclSpec that should fail to be applied");
3446 B << 1;
3447 } else {
3448 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3449 isInstField = false;
3450 }
3451 }
3452 }
3453
3455 if (isInstField) {
3456 CXXScopeSpec &SS = D.getCXXScopeSpec();
3457
3458 // Data members must have identifiers for names.
3459 if (!Name.isIdentifier()) {
3460 Diag(Loc, diag::err_bad_variable_name)
3461 << Name;
3462 return nullptr;
3463 }
3464
3465 IdentifierInfo *II = Name.getAsIdentifierInfo();
3466 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3467 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3468 << II
3469 << SourceRange(D.getName().TemplateId->LAngleLoc,
3470 D.getName().TemplateId->RAngleLoc)
3471 << D.getName().TemplateId->LAngleLoc;
3472 D.SetIdentifier(II, Loc);
3473 }
3474
3475 if (SS.isSet() && !SS.isInvalid()) {
3476 // The user provided a superfluous scope specifier inside a class
3477 // definition:
3478 //
3479 // class X {
3480 // int X::member;
3481 // };
3482 if (DeclContext *DC = computeDeclContext(SS, false)) {
3483 TemplateIdAnnotation *TemplateId =
3485 ? D.getName().TemplateId
3486 : nullptr;
3487 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3488 TemplateId,
3489 /*IsMemberSpecialization=*/false);
3490 } else {
3491 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3492 << Name << SS.getRange();
3493 }
3494 SS.clear();
3495 }
3496
3497 if (MSPropertyAttr) {
3498 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3499 BitWidth, InitStyle, AS, *MSPropertyAttr);
3500 if (!Member)
3501 return nullptr;
3502 isInstField = false;
3503 } else {
3504 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3505 BitWidth, InitStyle, AS);
3506 if (!Member)
3507 return nullptr;
3508 }
3509
3510 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3511 } else {
3512 Member = HandleDeclarator(S, D, TemplateParameterLists);
3513 if (!Member)
3514 return nullptr;
3515
3516 // Non-instance-fields can't have a bitfield.
3517 if (BitWidth) {
3518 if (Member->isInvalidDecl()) {
3519 // don't emit another diagnostic.
3520 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3521 // C++ 9.6p3: A bit-field shall not be a static member.
3522 // "static member 'A' cannot be a bit-field"
3523 Diag(Loc, diag::err_static_not_bitfield)
3524 << Name << BitWidth->getSourceRange();
3525 } else if (isa<TypedefDecl>(Member)) {
3526 // "typedef member 'x' cannot be a bit-field"
3527 Diag(Loc, diag::err_typedef_not_bitfield)
3528 << Name << BitWidth->getSourceRange();
3529 } else {
3530 // A function typedef ("typedef int f(); f a;").
3531 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3532 Diag(Loc, diag::err_not_integral_type_bitfield)
3533 << Name << cast<ValueDecl>(Member)->getType()
3534 << BitWidth->getSourceRange();
3535 }
3536
3537 BitWidth = nullptr;
3538 Member->setInvalidDecl();
3539 }
3540
3541 NamedDecl *NonTemplateMember = Member;
3542 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3543 NonTemplateMember = FunTmpl->getTemplatedDecl();
3544 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3545 NonTemplateMember = VarTmpl->getTemplatedDecl();
3546
3547 Member->setAccess(AS);
3548
3549 // If we have declared a member function template or static data member
3550 // template, set the access of the templated declaration as well.
3551 if (NonTemplateMember != Member)
3552 NonTemplateMember->setAccess(AS);
3553
3554 // C++ [temp.deduct.guide]p3:
3555 // A deduction guide [...] for a member class template [shall be
3556 // declared] with the same access [as the template].
3557 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3558 auto *TD = DG->getDeducedTemplate();
3559 // Access specifiers are only meaningful if both the template and the
3560 // deduction guide are from the same scope.
3561 if (AS != TD->getAccess() &&
3562 TD->getDeclContext()->getRedeclContext()->Equals(
3563 DG->getDeclContext()->getRedeclContext())) {
3564 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3565 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3566 << TD->getAccess();
3567 const AccessSpecDecl *LastAccessSpec = nullptr;
3568 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3569 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3570 LastAccessSpec = AccessSpec;
3571 }
3572 assert(LastAccessSpec && "differing access with no access specifier");
3573 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3574 << AS;
3575 }
3576 }
3577 }
3578
3579 if (VS.isOverrideSpecified())
3580 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3581 if (VS.isFinalSpecified())
3582 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3584 ? FinalAttr::Keyword_sealed
3585 : FinalAttr::Keyword_final));
3586
3587 if (VS.getLastLocation().isValid()) {
3588 // Update the end location of a method that has a virt-specifiers.
3589 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3590 MD->setRangeEnd(VS.getLastLocation());
3591 }
3592
3594
3595 assert((Name || isInstField) && "No identifier for non-field ?");
3596
3597 if (isInstField) {
3598 FieldDecl *FD = cast<FieldDecl>(Member);
3599 FieldCollector->Add(FD);
3600
3601 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3602 // Remember all explicit private FieldDecls that have a name, no side
3603 // effects and are not part of a dependent type declaration.
3604
3605 auto DeclHasUnusedAttr = [](const QualType &T) {
3606 if (const TagDecl *TD = T->getAsTagDecl())
3607 return TD->hasAttr<UnusedAttr>();
3608 if (const TypedefType *TDT = T->getAs<TypedefType>())
3609 return TDT->getDecl()->hasAttr<UnusedAttr>();
3610 return false;
3611 };
3612
3613 if (!FD->isImplicit() && FD->getDeclName() &&
3614 FD->getAccess() == AS_private &&
3615 !FD->hasAttr<UnusedAttr>() &&
3616 !FD->getParent()->isDependentContext() &&
3617 !DeclHasUnusedAttr(FD->getType()) &&
3619 UnusedPrivateFields.insert(FD);
3620 }
3621 }
3622
3623 return Member;
3624}
3625
3626namespace {
3627 class UninitializedFieldVisitor
3628 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3629 Sema &S;
3630 // List of Decls to generate a warning on. Also remove Decls that become
3631 // initialized.
3632 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3633 // List of base classes of the record. Classes are removed after their
3634 // initializers.
3635 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3636 // Vector of decls to be removed from the Decl set prior to visiting the
3637 // nodes. These Decls may have been initialized in the prior initializer.
3639 // If non-null, add a note to the warning pointing back to the constructor.
3640 const CXXConstructorDecl *Constructor;
3641 // Variables to hold state when processing an initializer list. When
3642 // InitList is true, special case initialization of FieldDecls matching
3643 // InitListFieldDecl.
3644 bool InitList;
3645 FieldDecl *InitListFieldDecl;
3646 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3647
3648 public:
3650 UninitializedFieldVisitor(Sema &S,
3651 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3652 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3653 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3654 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3655
3656 // Returns true if the use of ME is not an uninitialized use.
3657 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3658 bool CheckReferenceOnly) {
3660 bool ReferenceField = false;
3661 while (ME) {
3662 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3663 if (!FD)
3664 return false;
3665 Fields.push_back(FD);
3666 if (FD->getType()->isReferenceType())
3667 ReferenceField = true;
3668 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3669 }
3670
3671 // Binding a reference to an uninitialized field is not an
3672 // uninitialized use.
3673 if (CheckReferenceOnly && !ReferenceField)
3674 return true;
3675
3676 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3677 // Discard the first field since it is the field decl that is being
3678 // initialized.
3679 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3680 UsedFieldIndex.push_back(FD->getFieldIndex());
3681
3682 for (auto UsedIter = UsedFieldIndex.begin(),
3683 UsedEnd = UsedFieldIndex.end(),
3684 OrigIter = InitFieldIndex.begin(),
3685 OrigEnd = InitFieldIndex.end();
3686 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3687 if (*UsedIter < *OrigIter)
3688 return true;
3689 if (*UsedIter > *OrigIter)
3690 break;
3691 }
3692
3693 return false;
3694 }
3695
3696 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3697 bool AddressOf) {
3698 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3699 return;
3700
3701 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3702 // or union.
3703 MemberExpr *FieldME = ME;
3704
3705 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3706
3707 Expr *Base = ME;
3708 while (MemberExpr *SubME =
3709 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3710
3711 if (isa<VarDecl>(SubME->getMemberDecl()))
3712 return;
3713
3714 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3715 if (!FD->isAnonymousStructOrUnion())
3716 FieldME = SubME;
3717
3718 if (!FieldME->getType().isPODType(S.Context))
3719 AllPODFields = false;
3720
3721 Base = SubME->getBase();
3722 }
3723
3724 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3725 Visit(Base);
3726 return;
3727 }
3728
3729 if (AddressOf && AllPODFields)
3730 return;
3731
3732 ValueDecl* FoundVD = FieldME->getMemberDecl();
3733
3734 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3735 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3736 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3737 }
3738
3739 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3740 QualType T = BaseCast->getType();
3741 if (T->isPointerType() &&
3742 BaseClasses.count(T->getPointeeType())) {
3743 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3744 << T->getPointeeType() << FoundVD;
3745 }
3746 }
3747 }
3748
3749 if (!Decls.count(FoundVD))
3750 return;
3751
3752 const bool IsReference = FoundVD->getType()->isReferenceType();
3753
3754 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3755 // Special checking for initializer lists.
3756 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3757 return;
3758 }
3759 } else {
3760 // Prevent double warnings on use of unbounded references.
3761 if (CheckReferenceOnly && !IsReference)
3762 return;
3763 }
3764
3765 unsigned diag = IsReference
3766 ? diag::warn_reference_field_is_uninit
3767 : diag::warn_field_is_uninit;
3768 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3769 if (Constructor)
3770 S.Diag(Constructor->getLocation(),
3771 diag::note_uninit_in_this_constructor)
3772 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3773
3774 }
3775
3776 void HandleValue(Expr *E, bool AddressOf) {
3777 E = E->IgnoreParens();
3778
3779 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3780 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3781 AddressOf /*AddressOf*/);
3782 return;
3783 }
3784
3785 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3786 Visit(CO->getCond());
3787 HandleValue(CO->getTrueExpr(), AddressOf);
3788 HandleValue(CO->getFalseExpr(), AddressOf);
3789 return;
3790 }
3791
3792 if (BinaryConditionalOperator *BCO =
3793 dyn_cast<BinaryConditionalOperator>(E)) {
3794 Visit(BCO->getCond());
3795 HandleValue(BCO->getFalseExpr(), AddressOf);
3796 return;
3797 }
3798
3799 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3800 HandleValue(OVE->getSourceExpr(), AddressOf);
3801 return;
3802 }
3803
3804 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3805 switch (BO->getOpcode()) {
3806 default:
3807 break;
3808 case(BO_PtrMemD):
3809 case(BO_PtrMemI):
3810 HandleValue(BO->getLHS(), AddressOf);
3811 Visit(BO->getRHS());
3812 return;
3813 case(BO_Comma):
3814 Visit(BO->getLHS());
3815 HandleValue(BO->getRHS(), AddressOf);
3816 return;
3817 }
3818 }
3819
3820 Visit(E);
3821 }
3822
3823 void CheckInitListExpr(InitListExpr *ILE) {
3824 InitFieldIndex.push_back(0);
3825 for (auto *Child : ILE->children()) {
3826 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3827 CheckInitListExpr(SubList);
3828 } else {
3829 Visit(Child);
3830 }
3831 ++InitFieldIndex.back();
3832 }
3833 InitFieldIndex.pop_back();
3834 }
3835
3836 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3837 FieldDecl *Field, const Type *BaseClass) {
3838 // Remove Decls that may have been initialized in the previous
3839 // initializer.
3840 for (ValueDecl* VD : DeclsToRemove)
3841 Decls.erase(VD);
3842 DeclsToRemove.clear();
3843
3844 Constructor = FieldConstructor;
3845 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3846
3847 if (ILE && Field) {
3848 InitList = true;
3849 InitListFieldDecl = Field;
3850 InitFieldIndex.clear();
3851 CheckInitListExpr(ILE);
3852 } else {
3853 InitList = false;
3854 Visit(E);
3855 }
3856
3857 if (Field)
3858 Decls.erase(Field);
3859 if (BaseClass)
3860 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3861 }
3862
3863 void VisitMemberExpr(MemberExpr *ME) {
3864 // All uses of unbounded reference fields will warn.
3865 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3866 }
3867
3868 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3869 if (E->getCastKind() == CK_LValueToRValue) {
3870 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3871 return;
3872 }
3873
3874 Inherited::VisitImplicitCastExpr(E);
3875 }
3876
3877 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3878 if (E->getConstructor()->isCopyConstructor()) {
3879 Expr *ArgExpr = E->getArg(0);
3880 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3881 if (ILE->getNumInits() == 1)
3882 ArgExpr = ILE->getInit(0);
3883 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3884 if (ICE->getCastKind() == CK_NoOp)
3885 ArgExpr = ICE->getSubExpr();
3886 HandleValue(ArgExpr, false /*AddressOf*/);
3887 return;
3888 }
3889 Inherited::VisitCXXConstructExpr(E);
3890 }
3891
3892 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3893 Expr *Callee = E->getCallee();
3894 if (isa<MemberExpr>(Callee)) {
3895 HandleValue(Callee, false /*AddressOf*/);
3896 for (auto *Arg : E->arguments())
3897 Visit(Arg);
3898 return;
3899 }
3900
3901 Inherited::VisitCXXMemberCallExpr(E);
3902 }
3903
3904 void VisitCallExpr(CallExpr *E) {
3905 // Treat std::move as a use.
3906 if (E->isCallToStdMove()) {
3907 HandleValue(E->getArg(0), /*AddressOf=*/false);
3908 return;
3909 }
3910
3911 Inherited::VisitCallExpr(E);
3912 }
3913
3914 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3915 Expr *Callee = E->getCallee();
3916
3917 if (isa<UnresolvedLookupExpr>(Callee))
3918 return Inherited::VisitCXXOperatorCallExpr(E);
3919
3920 Visit(Callee);
3921 for (auto *Arg : E->arguments())
3922 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3923 }
3924
3925 void VisitBinaryOperator(BinaryOperator *E) {
3926 // If a field assignment is detected, remove the field from the
3927 // uninitiailized field set.
3928 if (E->getOpcode() == BO_Assign)
3929 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3930 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3931 if (!FD->getType()->isReferenceType())
3932 DeclsToRemove.push_back(FD);
3933
3934 if (E->isCompoundAssignmentOp()) {
3935 HandleValue(E->getLHS(), false /*AddressOf*/);
3936 Visit(E->getRHS());
3937 return;
3938 }
3939
3940 Inherited::VisitBinaryOperator(E);
3941 }
3942
3943 void VisitUnaryOperator(UnaryOperator *E) {
3944 if (E->isIncrementDecrementOp()) {
3945 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3946 return;
3947 }
3948 if (E->getOpcode() == UO_AddrOf) {
3949 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3950 HandleValue(ME->getBase(), true /*AddressOf*/);
3951 return;
3952 }
3953 }
3954
3955 Inherited::VisitUnaryOperator(E);
3956 }
3957 };
3958
3959 // Diagnose value-uses of fields to initialize themselves, e.g.
3960 // foo(foo)
3961 // where foo is not also a parameter to the constructor.
3962 // Also diagnose across field uninitialized use such as
3963 // x(y), y(x)
3964 // TODO: implement -Wuninitialized and fold this into that framework.
3965 static void DiagnoseUninitializedFields(
3966 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3967
3968 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3969 Constructor->getLocation())) {
3970 return;
3971 }
3972
3973 if (Constructor->isInvalidDecl())
3974 return;
3975
3976 const CXXRecordDecl *RD = Constructor->getParent();
3977
3978 if (RD->isDependentContext())
3979 return;
3980
3981 // Holds fields that are uninitialized.
3982 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3983
3984 // At the beginning, all fields are uninitialized.
3985 for (auto *I : RD->decls()) {
3986 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3987 UninitializedFields.insert(FD);
3988 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3989 UninitializedFields.insert(IFD->getAnonField());
3990 }
3991 }
3992
3993 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3994 for (const auto &I : RD->bases())
3995 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3996
3997 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3998 return;
3999
4000 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4001 UninitializedFields,
4002 UninitializedBaseClasses);
4003
4004 for (const auto *FieldInit : Constructor->inits()) {
4005 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4006 break;
4007
4008 Expr *InitExpr = FieldInit->getInit();
4009 if (!InitExpr)
4010 continue;
4011
4013 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4014 InitExpr = Default->getExpr();
4015 if (!InitExpr)
4016 continue;
4017 // In class initializers will point to the constructor.
4018 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4019 FieldInit->getAnyMember(),
4020 FieldInit->getBaseClass());
4021 } else {
4022 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4023 FieldInit->getAnyMember(),
4024 FieldInit->getBaseClass());
4025 }
4026 }
4027 }
4028} // namespace
4029
4031 // Create a synthetic function scope to represent the call to the constructor
4032 // that notionally surrounds a use of this initializer.
4034}
4035
4037 if (!D.isFunctionDeclarator())
4038 return;
4039 auto &FTI = D.getFunctionTypeInfo();
4040 if (!FTI.Params)
4041 return;
4042 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4043 FTI.NumParams)) {
4044 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4045 if (ParamDecl->getDeclName())
4046 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4047 }
4048}
4049
4051 return ActOnRequiresClause(ConstraintExpr);
4052}
4053
4055 if (ConstraintExpr.isInvalid())
4056 return ExprError();
4057
4058 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4059 if (ConstraintExpr.isInvalid())
4060 return ExprError();
4061
4062 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4064 return ExprError();
4065
4066 return ConstraintExpr;
4067}
4068
4070 Expr *InitExpr,
4071 SourceLocation InitLoc) {
4072 InitializedEntity Entity =
4074 InitializationKind Kind =
4077 InitExpr->getBeginLoc(),
4078 InitExpr->getEndLoc())
4079 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4080 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4081 return Seq.Perform(*this, Entity, Kind, InitExpr);
4082}
4083
4085 SourceLocation InitLoc,
4086 ExprResult InitExpr) {
4087 // Pop the notional constructor scope we created earlier.
4088 PopFunctionScopeInfo(nullptr, D);
4089
4090 // Microsoft C++'s property declaration cannot have a default member
4091 // initializer.
4092 if (isa<MSPropertyDecl>(D)) {
4093 D->setInvalidDecl();
4094 return;
4095 }
4096
4097 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4098 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4099 "must set init style when field is created");
4100
4101 if (!InitExpr.isUsable() ||
4103 FD->setInvalidDecl();
4104 ExprResult RecoveryInit =
4105 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4106 if (RecoveryInit.isUsable())
4107 FD->setInClassInitializer(RecoveryInit.get());
4108 return;
4109 }
4110
4111 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4112 /*RecoverUncorrectedTypos=*/true);
4113 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4114 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4115 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4116 // C++11 [class.base.init]p7:
4117 // The initialization of each base and member constitutes a
4118 // full-expression.
4119 if (!Init.isInvalid())
4120 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4121 if (Init.isInvalid()) {
4122 FD->setInvalidDecl();
4123 return;
4124 }
4125 }
4126
4127 FD->setInClassInitializer(Init.get());
4128}
4129
4130/// Find the direct and/or virtual base specifiers that
4131/// correspond to the given base type, for use in base initialization
4132/// within a constructor.
4134 CXXRecordDecl *ClassDecl,
4135 QualType BaseType,
4136 const CXXBaseSpecifier *&DirectBaseSpec,
4137 const CXXBaseSpecifier *&VirtualBaseSpec) {
4138 // First, check for a direct base class.
4139 DirectBaseSpec = nullptr;
4140 for (const auto &Base : ClassDecl->bases()) {
4141 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4142 // We found a direct base of this type. That's what we're
4143 // initializing.
4144 DirectBaseSpec = &Base;
4145 break;
4146 }
4147 }
4148
4149 // Check for a virtual base class.
4150 // FIXME: We might be able to short-circuit this if we know in advance that
4151 // there are no virtual bases.
4152 VirtualBaseSpec = nullptr;
4153 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4154 // We haven't found a base yet; search the class hierarchy for a
4155 // virtual base class.
4156 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4157 /*DetectVirtual=*/false);
4158 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4159 SemaRef.Context.getTypeDeclType(ClassDecl),
4160 BaseType, Paths)) {
4161 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4162 Path != Paths.end(); ++Path) {
4163 if (Path->back().Base->isVirtual()) {
4164 VirtualBaseSpec = Path->back().Base;
4165 break;
4166 }
4167 }
4168 }
4169 }
4170
4171 return DirectBaseSpec || VirtualBaseSpec;
4172}
4173
4176 Scope *S,
4177 CXXScopeSpec &SS,
4178 IdentifierInfo *MemberOrBase,
4179 ParsedType TemplateTypeTy,
4180 const DeclSpec &DS,
4181 SourceLocation IdLoc,
4182 Expr *InitList,
4183 SourceLocation EllipsisLoc) {
4184 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4185 DS, IdLoc, InitList,
4186 EllipsisLoc);
4187}
4188
4191 Scope *S,
4192 CXXScopeSpec &SS,
4193 IdentifierInfo *MemberOrBase,
4194 ParsedType TemplateTypeTy,
4195 const DeclSpec &DS,
4196 SourceLocation IdLoc,
4197 SourceLocation LParenLoc,
4198 ArrayRef<Expr *> Args,
4199 SourceLocation RParenLoc,
4200 SourceLocation EllipsisLoc) {
4201 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4202 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4203 DS, IdLoc, List, EllipsisLoc);
4204}
4205
4206namespace {
4207
4208// Callback to only accept typo corrections that can be a valid C++ member
4209// initializer: either a non-static field member or a base class.
4210class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4211public:
4212 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4213 : ClassDecl(ClassDecl) {}
4214
4215 bool ValidateCandidate(const TypoCorrection &candidate) override {
4216 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4217 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4218 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4219 return isa<TypeDecl>(ND);
4220 }
4221 return false;
4222 }
4223
4224 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4225 return std::make_unique<MemInitializerValidatorCCC>(*this);
4226 }
4227
4228private:
4229 CXXRecordDecl *ClassDecl;
4230};
4231
4232}
4233
4235 RecordDecl *ClassDecl,
4236 const IdentifierInfo *Name) {
4237 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4239 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4240 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4242 });
4243 // We did not find a placeholder variable
4244 if (Found == Result.end())
4245 return false;
4246 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4247 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4248 const NamedDecl *ND = *It;
4249 if (ND->getDeclContext() != ND->getDeclContext())
4250 break;
4251 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4253 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4254 }
4255 return true;
4256}
4257
4258ValueDecl *
4260 const IdentifierInfo *MemberOrBase) {
4261 ValueDecl *ND = nullptr;
4262 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4263 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4264 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4265 if (ND) {
4266 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4267 return nullptr;
4268 break;
4269 }
4270 if (!IsPlaceholder)
4271 return cast<ValueDecl>(D);
4272 ND = cast<ValueDecl>(D);
4273 }
4274 }
4275 return ND;
4276}
4277
4279 CXXScopeSpec &SS,
4280 ParsedType TemplateTypeTy,
4281 IdentifierInfo *MemberOrBase) {
4282 if (SS.getScopeRep() || TemplateTypeTy)
4283 return nullptr;
4284 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4285}
4286
4289 Scope *S,
4290 CXXScopeSpec &SS,
4291 IdentifierInfo *MemberOrBase,
4292 ParsedType TemplateTypeTy,
4293 const DeclSpec &DS,
4294 SourceLocation IdLoc,
4295 Expr *Init,
4296 SourceLocation EllipsisLoc) {
4297 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4298 /*RecoverUncorrectedTypos=*/true);
4299 if (!Res.isUsable())
4300 return true;
4301 Init = Res.get();
4302
4303 if (!ConstructorD)
4304 return true;
4305
4306 AdjustDeclIfTemplate(ConstructorD);
4307
4308 CXXConstructorDecl *Constructor
4309 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4310 if (!Constructor) {
4311 // The user wrote a constructor initializer on a function that is
4312 // not a C++ constructor. Ignore the error for now, because we may
4313 // have more member initializers coming; we'll diagnose it just
4314 // once in ActOnMemInitializers.
4315 return true;
4316 }
4317
4318 CXXRecordDecl *ClassDecl = Constructor->getParent();
4319
4320 // C++ [class.base.init]p2:
4321 // Names in a mem-initializer-id are looked up in the scope of the
4322 // constructor's class and, if not found in that scope, are looked
4323 // up in the scope containing the constructor's definition.
4324 // [Note: if the constructor's class contains a member with the
4325 // same name as a direct or virtual base class of the class, a
4326 // mem-initializer-id naming the member or base class and composed
4327 // of a single identifier refers to the class member. A
4328 // mem-initializer-id for the hidden base class may be specified
4329 // using a qualified name. ]
4330
4331 // Look for a member, first.
4333 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4334 if (EllipsisLoc.isValid())
4335 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4336 << MemberOrBase
4337 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4338
4339 return BuildMemberInitializer(Member, Init, IdLoc);
4340 }
4341 // It didn't name a member, so see if it names a class.
4342 QualType BaseType;
4343 TypeSourceInfo *TInfo = nullptr;
4344
4345 if (TemplateTypeTy) {
4346 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4347 if (BaseType.isNull())
4348 return true;
4349 } else if (DS.getTypeSpecType() == TST_decltype) {
4350 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4351 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4352 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4353 return true;
4354 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4355 BaseType =
4357 DS.getBeginLoc(), DS.getEllipsisLoc());
4358 } else {
4359 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4360 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4361
4362 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4363 if (!TyD) {
4364 if (R.isAmbiguous()) return true;
4365
4366 // We don't want access-control diagnostics here.
4368
4369 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4370 bool NotUnknownSpecialization = false;
4371 DeclContext *DC = computeDeclContext(SS, false);
4372 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4373 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4374
4375 if (!NotUnknownSpecialization) {
4376 // When the scope specifier can refer to a member of an unknown
4377 // specialization, we take it as a type name.
4378 BaseType = CheckTypenameType(
4380 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4381 if (BaseType.isNull())
4382 return true;
4383
4384 TInfo = Context.CreateTypeSourceInfo(BaseType);
4387 if (!TL.isNull()) {
4388 TL.setNameLoc(IdLoc);
4391 }
4392
4393 R.clear();
4394 R.setLookupName(MemberOrBase);
4395 }
4396 }
4397
4398 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4399 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4400 auto *TempSpec = cast<TemplateSpecializationType>(
4401 UnqualifiedBase->getInjectedClassNameSpecialization());
4402 TemplateName TN = TempSpec->getTemplateName();
4403 for (auto const &Base : ClassDecl->bases()) {
4404 auto BaseTemplate =
4405 Base.getType()->getAs<TemplateSpecializationType>();
4406 if (BaseTemplate &&
4407 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4408 /*IgnoreDeduced=*/true)) {
4409 Diag(IdLoc, diag::ext_unqualified_base_class)
4410 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4411 BaseType = Base.getType();
4412 break;
4413 }
4414 }
4415 }
4416 }
4417
4418 // If no results were found, try to correct typos.
4419 TypoCorrection Corr;
4420 MemInitializerValidatorCCC CCC(ClassDecl);
4421 if (R.empty() && BaseType.isNull() &&
4422 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4423 CCC, CTK_ErrorRecovery, ClassDecl))) {
4425 // We have found a non-static data member with a similar
4426 // name to what was typed; complain and initialize that
4427 // member.
4428 diagnoseTypo(Corr,
4429 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4430 << MemberOrBase << true);
4431 return BuildMemberInitializer(Member, Init, IdLoc);
4432 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4433 const CXXBaseSpecifier *DirectBaseSpec;
4434 const CXXBaseSpecifier *VirtualBaseSpec;
4435 if (FindBaseInitializer(*this, ClassDecl,
4437 DirectBaseSpec, VirtualBaseSpec)) {
4438 // We have found a direct or virtual base class with a
4439 // similar name to what was typed; complain and initialize
4440 // that base class.
4441 diagnoseTypo(Corr,
4442 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4443 << MemberOrBase << false,
4444 PDiag() /*Suppress note, we provide our own.*/);
4445
4446 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4447 : VirtualBaseSpec;
4448 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4449 << BaseSpec->getType() << BaseSpec->getSourceRange();
4450
4451 TyD = Type;
4452 }
4453 }
4454 }
4455
4456 if (!TyD && BaseType.isNull()) {
4457 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4458 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4459 return true;
4460 }
4461 }
4462
4463 if (BaseType.isNull()) {
4466 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4467 TInfo = Context.CreateTypeSourceInfo(BaseType);
4469 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4472 }
4473 }
4474
4475 if (!TInfo)
4476 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4477
4478 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4479}
4480
4483 SourceLocation IdLoc) {
4484 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4485 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4486 assert((DirectMember || IndirectMember) &&
4487 "Member must be a FieldDecl or IndirectFieldDecl");
4488
4490 return true;
4491
4492 if (Member->isInvalidDecl())
4493 return true;
4494
4495 MultiExprArg Args;
4496 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4497 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4498 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4499 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4500 } else {
4501 // Template instantiation doesn't reconstruct ParenListExprs for us.
4502 Args = Init;
4503 }
4504
4505 SourceRange InitRange = Init->getSourceRange();
4506
4507 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4508 // Can't check initialization for a member of dependent type or when
4509 // any of the arguments are type-dependent expressions.
4511 } else {
4512 bool InitList = false;
4513 if (isa<InitListExpr>(Init)) {
4514 InitList = true;
4515 Args = Init;
4516 }
4517
4518 // Initialize the member.
4519 InitializedEntity MemberEntity =
4520 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4521 : InitializedEntity::InitializeMember(IndirectMember,
4522 nullptr);
4523 InitializationKind Kind =
4525 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4526 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4527 InitRange.getEnd());
4528
4529 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4530 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4531 nullptr);
4532 if (!MemberInit.isInvalid()) {
4533 // C++11 [class.base.init]p7:
4534 // The initialization of each base and member constitutes a
4535 // full-expression.
4536 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4537 /*DiscardedValue*/ false);
4538 }
4539
4540 if (MemberInit.isInvalid()) {
4541 // Args were sensible expressions but we couldn't initialize the member
4542 // from them. Preserve them in a RecoveryExpr instead.
4543 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4544 Member->getType())
4545 .get();
4546 if (!Init)
4547 return true;
4548 } else {
4549 Init = MemberInit.get();
4550 }
4551 }
4552
4553 if (DirectMember) {
4554 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4555 InitRange.getBegin(), Init,
4556 InitRange.getEnd());
4557 } else {
4558 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4559 InitRange.getBegin(), Init,
4560 InitRange.getEnd());
4561 }
4562}
4563
4566 CXXRecordDecl *ClassDecl) {
4567 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4568 if (!LangOpts.CPlusPlus11)
4569 return Diag(NameLoc, diag::err_delegating_ctor)
4570 << TInfo->getTypeLoc().getSourceRange();
4571 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4572
4573 bool InitList = true;
4574 MultiExprArg Args = Init;
4575 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4576 InitList = false;
4577 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4578 }
4579
4580 SourceRange InitRange = Init->getSourceRange();
4581 // Initialize the object.
4583 QualType(ClassDecl->getTypeForDecl(), 0));
4584 InitializationKind Kind =
4586 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4587 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4588 InitRange.getEnd());
4589 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4590 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4591 Args, nullptr);
4592 if (!DelegationInit.isInvalid()) {
4593 assert((DelegationInit.get()->containsErrors() ||
4594 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4595 "Delegating constructor with no target?");
4596
4597 // C++11 [class.base.init]p7:
4598 // The initialization of each base and member constitutes a
4599 // full-expression.
4600 DelegationInit = ActOnFinishFullExpr(
4601 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4602 }
4603
4604 if (DelegationInit.isInvalid()) {
4605 DelegationInit =
4606 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4607 QualType(ClassDecl->getTypeForDecl(), 0));
4608 if (DelegationInit.isInvalid())
4609 return true;
4610 } else {
4611 // If we are in a dependent context, template instantiation will
4612 // perform this type-checking again. Just save the arguments that we
4613 // received in a ParenListExpr.
4614 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4615 // of the information that we have about the base
4616 // initializer. However, deconstructing the ASTs is a dicey process,
4617 // and this approach is far more likely to get the corner cases right.
4619 DelegationInit = Init;
4620 }
4621
4622 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4623 DelegationInit.getAs<Expr>(),
4624 InitRange.getEnd());
4625}
4626
4629 Expr *Init, CXXRecordDecl *ClassDecl,
4630 SourceLocation EllipsisLoc) {
4631 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4632
4633 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4634 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4635 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4636
4637 // C++ [class.base.init]p2:
4638 // [...] Unless the mem-initializer-id names a nonstatic data
4639 // member of the constructor's class or a direct or virtual base
4640 // of that class, the mem-initializer is ill-formed. A
4641 // mem-initializer-list can initialize a base class using any
4642 // name that denotes that base class type.
4643
4644 // We can store the initializers in "as-written" form and delay analysis until
4645 // instantiation if the constructor is dependent. But not for dependent
4646 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4648 (BaseType->isDependentType() || Init->isTypeDependent());
4649
4650 SourceRange InitRange = Init->getSourceRange();
4651 if (EllipsisLoc.isValid()) {
4652 // This is a pack expansion.
4653 if (!BaseType->containsUnexpandedParameterPack()) {
4654 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4655 << SourceRange(BaseLoc, InitRange.getEnd());
4656
4657 EllipsisLoc = SourceLocation();
4658 }
4659 } else {
4660 // Check for any unexpanded parameter packs.
4661 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4662 return true;
4663
4665 return true;
4666 }
4667
4668 // Check for direct and virtual base classes.
4669 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4670 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4671 if (!Dependent) {
4673 BaseType))
4674 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4675
4676 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4677 VirtualBaseSpec);
4678
4679 // C++ [base.class.init]p2:
4680 // Unless the mem-initializer-id names a nonstatic data member of the
4681 // constructor's class or a direct or virtual base of that class, the
4682 // mem-initializer is ill-formed.
4683 if (!DirectBaseSpec && !VirtualBaseSpec) {
4684 // If the class has any dependent bases, then it's possible that
4685 // one of those types will resolve to the same type as
4686 // BaseType. Therefore, just treat this as a dependent base
4687 // class initialization. FIXME: Should we try to check the
4688 // initialization anyway? It seems odd.
4689 if (ClassDecl->hasAnyDependentBases())
4690 Dependent = true;
4691 else
4692 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4693 << BaseType << Context.getTypeDeclType(ClassDecl)
4694 << BaseTInfo->getTypeLoc().getSourceRange();
4695 }
4696 }
4697
4698 if (Dependent) {
4700
4701 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4702 /*IsVirtual=*/false,
4703 InitRange.getBegin(), Init,
4704 InitRange.getEnd(), EllipsisLoc);
4705 }
4706
4707 // C++ [base.class.init]p2:
4708 // If a mem-initializer-id is ambiguous because it designates both
4709 // a direct non-virtual base class and an inherited virtual base
4710 // class, the mem-initializer is ill-formed.
4711 if (DirectBaseSpec && VirtualBaseSpec)
4712 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4713 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4714
4715 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4716 if (!BaseSpec)
4717 BaseSpec = VirtualBaseSpec;
4718
4719 // Initialize the base.
4720 bool InitList = true;
4721 MultiExprArg Args = Init;
4722 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4723 InitList = false;
4724 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4725 }
4726
4727 InitializedEntity BaseEntity =
4728 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4729 InitializationKind Kind =
4730 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4731 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4732 InitRange.getEnd());
4733 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4734 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4735 if (!BaseInit.isInvalid()) {
4736 // C++11 [class.base.init]p7:
4737 // The initialization of each base and member constitutes a
4738 // full-expression.
4739 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4740 /*DiscardedValue*/ false);
4741 }
4742
4743 if (BaseInit.isInvalid()) {
4744 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4745 Args, BaseType);
4746 if (BaseInit.isInvalid())
4747 return true;
4748 } else {
4749 // If we are in a dependent context, template instantiation will
4750 // perform this type-checking again. Just save the arguments that we
4751 // received in a ParenListExpr.
4752 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4753 // of the information that we have about the base
4754 // initializer. However, deconstructing the ASTs is a dicey process,
4755 // and this approach is far more likely to get the corner cases right.
4757 BaseInit = Init;
4758 }
4759
4760 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4761 BaseSpec->isVirtual(),
4762 InitRange.getBegin(),
4763 BaseInit.getAs<Expr>(),
4764 InitRange.getEnd(), EllipsisLoc);
4765}
4766
4767// Create a static_cast<T&&>(expr).
4769 QualType TargetType =
4770 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4772 SourceLocation ExprLoc = E->getBeginLoc();
4774 TargetType, ExprLoc);
4775
4776 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4777 SourceRange(ExprLoc, ExprLoc),
4778 E->getSourceRange()).get();
4779}
4780
4781/// ImplicitInitializerKind - How an implicit base or member initializer should
4782/// initialize its base or member.
4789
4790static bool
4792 ImplicitInitializerKind ImplicitInitKind,
4793 CXXBaseSpecifier *BaseSpec,
4794 bool IsInheritedVirtualBase,
4795 CXXCtorInitializer *&CXXBaseInit) {
4796 InitializedEntity InitEntity
4798 IsInheritedVirtualBase);
4799
4800 ExprResult BaseInit;
4801
4802 switch (ImplicitInitKind) {
4803 case IIK_Inherit:
4804 case IIK_Default: {
4805 InitializationKind InitKind
4806 = InitializationKind::CreateDefault(Constructor->getLocation());
4807 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4808 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4809 break;
4810 }
4811
4812 case IIK_Move:
4813 case IIK_Copy: {
4814 bool Moving = ImplicitInitKind == IIK_Move;
4815 ParmVarDecl *Param = Constructor->getParamDecl(0);
4816 QualType ParamType = Param->getType().getNonReferenceType();
4817
4818 Expr *CopyCtorArg =
4820 SourceLocation(), Param, false,
4821 Constructor->getLocation(), ParamType,
4822 VK_LValue, nullptr);
4823
4824 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4825
4826 // Cast to the base class to avoid ambiguities.
4827 QualType ArgTy =
4829 ParamType.getQualifiers());
4830
4831 if (Moving) {
4832 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4833 }
4834
4835 CXXCastPath BasePath;
4836 BasePath.push_back(BaseSpec);
4837 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4838 CK_UncheckedDerivedToBase,
4839 Moving ? VK_XValue : VK_LValue,
4840 &BasePath).get();
4841
4842 InitializationKind InitKind
4843 = InitializationKind::CreateDirect(Constructor->getLocation(),
4845 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4846 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4847 break;
4848 }
4849 }
4850
4851 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4852 if (BaseInit.isInvalid())
4853 return true;
4854
4855 CXXBaseInit =
4858 SourceLocation()),
4859 BaseSpec->isVirtual(),
4861 BaseInit.getAs<Expr>(),
4863 SourceLocation());
4864
4865 return false;
4866}
4867
4868static bool RefersToRValueRef(Expr *MemRef) {
4869 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4870 return Referenced->getType()->isRValueReferenceType();
4871}
4872
4873static bool
4875 ImplicitInitializerKind ImplicitInitKind,
4877 CXXCtorInitializer *&CXXMemberInit) {
4878 if (Field->isInvalidDecl())
4879 return true;
4880
4881 SourceLocation Loc = Constructor->getLocation();
4882
4883 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4884 bool Moving = ImplicitInitKind == IIK_Move;
4885 ParmVarDecl *Param = Constructor->getParamDecl(0);
4886 QualType ParamType = Param->getType().getNonReferenceType();
4887
4888 // Suppress copying zero-width bitfields.
4889 if (Field->isZeroLengthBitField())
4890 return false;
4891
4892 Expr *MemberExprBase =
4894 SourceLocation(), Param, false,
4895 Loc, ParamType, VK_LValue, nullptr);
4896
4897 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4898
4899 if (Moving) {
4900 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4901 }
4902
4903 // Build a reference to this field within the parameter.
4904 CXXScopeSpec SS;
4905 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4907 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4908 : cast<ValueDecl>(Field), AS_public);
4909 MemberLookup.resolveKind();
4910 ExprResult CtorArg
4911 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4912 ParamType, Loc,
4913 /*IsArrow=*/false,
4914 SS,
4915 /*TemplateKWLoc=*/SourceLocation(),
4916 /*FirstQualifierInScope=*/nullptr,
4917 MemberLookup,
4918 /*TemplateArgs=*/nullptr,
4919 /*S*/nullptr);
4920 if (CtorArg.isInvalid())
4921 return true;
4922
4923 // C++11 [class.copy]p15:
4924 // - if a member m has rvalue reference type T&&, it is direct-initialized
4925 // with static_cast<T&&>(x.m);
4926 if (RefersToRValueRef(CtorArg.get())) {
4927 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4928 }
4929
4930 InitializedEntity Entity =
4932 /*Implicit*/ true)
4933 : InitializedEntity::InitializeMember(Field, nullptr,
4934 /*Implicit*/ true);
4935
4936 // Direct-initialize to use the copy constructor.
4937 InitializationKind InitKind =
4939
4940 Expr *CtorArgE = CtorArg.getAs<Expr>();
4941 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4942 ExprResult MemberInit =
4943 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4944 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4945 if (MemberInit.isInvalid())
4946 return true;
4947
4948 if (Indirect)
4949 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4950 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4951 else
4952 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4953 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4954 return false;
4955 }
4956
4957 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4958 "Unhandled implicit init kind!");
4959
4960 QualType FieldBaseElementType =
4961 SemaRef.Context.getBaseElementType(Field->getType());
4962
4963 if (FieldBaseElementType->isRecordType()) {
4964 InitializedEntity InitEntity =
4966 /*Implicit*/ true)
4967 : InitializedEntity::InitializeMember(Field, nullptr,
4968 /*Implicit*/ true);
4969 InitializationKind InitKind =
4971
4972 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4973 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4974
4975 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4976 if (MemberInit.isInvalid())
4977 return true;
4978
4979 if (Indirect)
4980 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4981 Indirect, Loc,
4982 Loc,
4983 MemberInit.get(),
4984 Loc);
4985 else
4986 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4987 Field, Loc, Loc,
4988 MemberInit.get(),
4989 Loc);
4990 return false;
4991 }
4992
4993 if (!Field->getParent()->isUnion()) {
4994 if (FieldBaseElementType->isReferenceType()) {
4995 SemaRef.Diag(Constructor->getLocation(),
4996 diag::err_uninitialized_member_in_ctor)
4997 << (int)Constructor->isImplicit()
4998 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4999 << 0 << Field->getDeclName();
5000 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5001 return true;
5002 }
5003
5004 if (FieldBaseElementType.isConstQualified()) {
5005 SemaRef.Diag(Constructor->getLocation(),
5006 diag::err_uninitialized_member_in_ctor)
5007 << (int)Constructor->isImplicit()
5008 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5009 << 1 << Field->getDeclName();
5010 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5011 return true;
5012 }
5013 }
5014
5015 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5016 // ARC and Weak:
5017 // Default-initialize Objective-C pointers to NULL.
5018 CXXMemberInit
5020 Loc, Loc,
5021 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5022 Loc);
5023 return false;
5024 }
5025
5026 // Nothing to initialize.
5027 CXXMemberInit = nullptr;
5028 return false;
5029}
5030
5031namespace {
5032struct BaseAndFieldInfo {
5033 Sema &S;
5034 CXXConstructorDecl *Ctor;
5035 bool AnyErrorsInInits;
5037 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5039 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5040
5041 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5042 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5043 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5044 if (Ctor->getInheritedConstructor())
5045 IIK = IIK_Inherit;
5046 else if (Generated && Ctor->isCopyConstructor())
5047 IIK = IIK_Copy;
5048 else if (Generated && Ctor->isMoveConstructor())
5049 IIK = IIK_Move;
5050 else
5051 IIK = IIK_Default;
5052 }
5053
5054 bool isImplicitCopyOrMove() const {
5055 switch (IIK) {
5056 case IIK_Copy:
5057 case IIK_Move:
5058 return true;
5059
5060 case IIK_Default:
5061 case IIK_Inherit:
5062 return false;
5063 }
5064
5065 llvm_unreachable("Invalid ImplicitInitializerKind!");
5066 }
5067
5068 bool addFieldInitializer(CXXCtorInitializer *Init) {
5069 AllToInit.push_back(Init);
5070
5071 // Check whether this initializer makes the field "used".
5072 if (Init->getInit()->HasSideEffects(S.Context))
5073 S.UnusedPrivateFields.remove(Init->getAnyMember());
5074
5075 return false;
5076 }
5077
5078 bool isInactiveUnionMember(FieldDecl *Field) {
5079 RecordDecl *Record = Field->getParent();
5080 if (!Record->isUnion())
5081 return false;
5082
5083 if (FieldDecl *Active =
5084 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5085 return Active != Field->getCanonicalDecl();
5086
5087 // In an implicit copy or move constructor, ignore any in-class initializer.
5088 if (isImplicitCopyOrMove())
5089 return true;
5090
5091 // If there's no explicit initialization, the field is active only if it
5092 // has an in-class initializer...
5093 if (Field->hasInClassInitializer())
5094 return false;
5095 // ... or it's an anonymous struct or union whose class has an in-class
5096 // initializer.
5097 if (!Field->isAnonymousStructOrUnion())
5098 return true;
5099 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5100 return !FieldRD->hasInClassInitializer();
5101 }
5102
5103 /// Determine whether the given field is, or is within, a union member
5104 /// that is inactive (because there was an initializer given for a different
5105 /// member of the union, or because the union was not initialized at all).
5106 bool isWithinInactiveUnionMember(FieldDecl *Field,
5108 if (!Indirect)
5109 return isInactiveUnionMember(Field);
5110
5111 for (auto *C : Indirect->chain()) {
5112 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5113 if (Field && isInactiveUnionMember(Field))
5114 return true;
5115 }
5116 return false;
5117 }
5118};
5119}
5120
5121/// Determine whether the given type is an incomplete or zero-lenfgth
5122/// array type.
5124 if (T->isIncompleteArrayType())
5125 return true;
5126
5127 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5128 if (ArrayT->isZeroSize())
5129 return true;
5130
5131 T = ArrayT->getElementType();
5132 }
5133
5134 return false;
5135}
5136
5137static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5138 FieldDecl *Field,
5139 IndirectFieldDecl *Indirect = nullptr) {
5140 if (Field->isInvalidDecl())
5141 return false;
5142
5143 // Overwhelmingly common case: we have a direct initializer for this field.
5145 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5146 return Info.addFieldInitializer(Init);
5147
5148 // C++11 [class.base.init]p8:
5149 // if the entity is a non-static data member that has a
5150 // brace-or-equal-initializer and either
5151 // -- the constructor's class is a union and no other variant member of that
5152 // union is designated by a mem-initializer-id or
5153 // -- the constructor's class is not a union, and, if the entity is a member
5154 // of an anonymous union, no other member of that union is designated by
5155 // a mem-initializer-id,
5156 // the entity is initialized as specified in [dcl.init].
5157 //
5158 // We also apply the same rules to handle anonymous structs within anonymous
5159 // unions.
5160 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5161 return false;
5162
5163 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5164 ExprResult DIE =
5165 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5166 if (DIE.isInvalid())
5167 return true;
5168
5169 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5170 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5171
5173 if (Indirect)
5174 Init = new (SemaRef.Context)
5176 SourceLocation(), DIE.get(), SourceLocation());
5177 else
5178 Init = new (SemaRef.Context)
5180 SourceLocation(), DIE.get(), SourceLocation());
5181 return Info.addFieldInitializer(Init);
5182 }
5183
5184 // Don't initialize incomplete or zero-length arrays.
5185 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5186 return false;
5187
5188 // Don't try to build an implicit initializer if there were semantic
5189 // errors in any of the initializers (and therefore we might be
5190 // missing some that the user actually wrote).
5191 if (Info.AnyErrorsInInits)
5192 return false;
5193
5194 CXXCtorInitializer *Init = nullptr;
5195 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5196 Indirect, Init))
5197 return true;
5198
5199 if (!Init)
5200 return false;
5201
5202 return Info.addFieldInitializer(Init);
5203}
5204
5205bool
5208 assert(Initializer->isDelegatingInitializer());
5209 Constructor->setNumCtorInitializers(1);
5210 CXXCtorInitializer **initializer =
5211 new (Context) CXXCtorInitializer*[1];
5212 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5213 Constructor->setCtorInitializers(initializer);
5214
5215 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5216 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5217 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5218 }
5219
5220 DelegatingCtorDecls.push_back(Constructor);
5221
5222 DiagnoseUninitializedFields(*this, Constructor);
5223
5224 return false;
5225}
5226
5227bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5228 ArrayRef<CXXCtorInitializer *> Initializers) {
5229 if (Constructor->isDependentContext()) {
5230 // Just store the initializers as written, they will be checked during
5231 // instantiation.
5232 if (!Initializers.empty()) {
5233 Constructor->setNumCtorInitializers(Initializers.size());
5234 CXXCtorInitializer **baseOrMemberInitializers =
5235 new (Context) CXXCtorInitializer*[Initializers.size()];
5236 memcpy(baseOrMemberInitializers, Initializers.data(),
5237 Initializers.size() * sizeof(CXXCtorInitializer*));
5238 Constructor->setCtorInitializers(baseOrMemberInitializers);
5239 }
5240
5241 // Let template instantiation know whether we had errors.
5242 if (AnyErrors)
5243 Constructor->setInvalidDecl();
5244
5245 return false;
5246 }
5247
5248 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5249
5250 // We need to build the initializer AST according to order of construction
5251 // and not what user specified in the Initializers list.
5252 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5253 if (!ClassDecl)
5254 return true;
5255
5256 bool HadError = false;
5257
5258 for (unsigned i = 0; i < Initializers.size(); i++) {
5259 CXXCtorInitializer *Member = Initializers[i];
5260
5261 if (Member->isBaseInitializer())
5262 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5263 else {
5264 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5265
5266 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5267 for (auto *C : F->chain()) {
5268 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5269 if (FD && FD->getParent()->isUnion())
5270 Info.ActiveUnionMember.insert(std::make_pair(
5272 }
5273 } else if (FieldDecl *FD = Member->getMember()) {
5274 if (FD->getParent()->isUnion())
5275 Info.ActiveUnionMember.insert(std::make_pair(
5277 }
5278 }
5279 }
5280
5281 // Keep track of the direct virtual bases.
5283 for (auto &I : ClassDecl->bases()) {
5284 if (I.isVirtual())
5285 DirectVBases.insert(&I);
5286 }
5287
5288 // Push virtual bases before others.
5289 for (auto &VBase : ClassDecl->vbases()) {
5291 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5292 // [class.base.init]p7, per DR257:
5293 // A mem-initializer where the mem-initializer-id names a virtual base
5294 // class is ignored during execution of a constructor of any class that
5295 // is not the most derived class.
5296 if (ClassDecl->isAbstract()) {
5297 // FIXME: Provide a fixit to remove the base specifier. This requires
5298 // tracking the location of the associated comma for a base specifier.
5299 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5300 << VBase.getType() << ClassDecl;
5301 DiagnoseAbstractType(ClassDecl);
5302 }
5303
5304 Info.AllToInit.push_back(Value);
5305 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5306 // [class.base.init]p8, per DR257:
5307 // If a given [...] base class is not named by a mem-initializer-id
5308 // [...] and the entity is not a virtual base class of an abstract
5309 // class, then [...] the entity is default-initialized.
5310 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5311 CXXCtorInitializer *CXXBaseInit;
5312 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5313 &VBase, IsInheritedVirtualBase,
5314 CXXBaseInit)) {
5315 HadError = true;
5316 continue;
5317 }
5318
5319 Info.AllToInit.push_back(CXXBaseInit);
5320 }
5321 }
5322
5323 // Non-virtual bases.
5324 for (auto &Base : ClassDecl->bases()) {
5325 // Virtuals are in the virtual base list and already constructed.
5326 if (Base.isVirtual())
5327 continue;
5328
5330 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5331 Info.AllToInit.push_back(Value);
5332 } else if (!AnyErrors) {
5333 CXXCtorInitializer *CXXBaseInit;
5334 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5335 &Base, /*IsInheritedVirtualBase=*/false,
5336 CXXBaseInit)) {
5337 HadError = true;
5338 continue;
5339 }
5340
5341 Info.AllToInit.push_back(CXXBaseInit);
5342 }
5343 }
5344
5345 // Fields.
5346 for (auto *Mem : ClassDecl->decls()) {
5347 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5348 // C++ [class.bit]p2:
5349 // A declaration for a bit-field that omits the identifier declares an
5350 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5351 // initialized.
5352 if (F->isUnnamedBitField())
5353 continue;
5354
5355 // If we're not generating the implicit copy/move constructor, then we'll
5356 // handle anonymous struct/union fields based on their individual
5357 // indirect fields.
5358 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5359 continue;
5360
5361 if (CollectFieldInitializer(*this, Info, F))
5362 HadError = true;
5363 continue;
5364 }
5365
5366 // Beyond this point, we only consider default initialization.
5367 if (Info.isImplicitCopyOrMove())
5368 continue;
5369
5370 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5371 if (F->getType()->isIncompleteArrayType()) {
5372 assert(ClassDecl->hasFlexibleArrayMember() &&
5373 "Incomplete array type is not valid");
5374 continue;
5375 }
5376
5377 // Initialize each field of an anonymous struct individually.
5378 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5379 HadError = true;
5380
5381 continue;
5382 }
5383 }
5384
5385 unsigned NumInitializers = Info.AllToInit.size();
5386 if (NumInitializers > 0) {
5387 Constructor->setNumCtorInitializers(NumInitializers);
5388 CXXCtorInitializer **baseOrMemberInitializers =
5389 new (Context) CXXCtorInitializer*[NumInitializers];
5390 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5391 NumInitializers * sizeof(CXXCtorInitializer*));
5392 Constructor->setCtorInitializers(baseOrMemberInitializers);
5393
5394 // Constructors implicitly reference the base and member
5395 // destructors.
5396 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5397 Constructor->getParent());
5398 }
5399
5400 return HadError;
5401}
5402
5404 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5405 const RecordDecl *RD = RT->getDecl();
5406 if (RD->isAnonymousStructOrUnion()) {
5407 for (auto *Field : RD->fields())
5408 PopulateKeysForFields(Field, IdealInits);
5409 return;
5410 }
5411 }
5412 IdealInits.push_back(Field->getCanonicalDecl());
5413}
5414
5415static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5416 return Context.getCanonicalType(BaseType).getTypePtr();
5417}
5418
5421 if (!Member->isAnyMemberInitializer())
5422 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5423
5424 return Member->getAnyMember()->getCanonicalDecl();
5425}
5426
5429 const CXXCtorInitializer *Current) {
5430 if (Previous->isAnyMemberInitializer())
5431 Diag << 0 << Previous->getAnyMember();
5432 else
5433 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5434
5435 if (Current->isAnyMemberInitializer())
5436 Diag << 0 << Current->getAnyMember();
5437 else
5438 Diag << 1 << Current->getTypeSourceInfo()->getType();
5439}
5440
5442 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5444 if (Constructor->getDeclContext()->isDependentContext())
5445 return;
5446
5447 // Don't check initializers order unless the warning is enabled at the
5448 // location of at least one initializer.
5449 bool ShouldCheckOrder = false;
5450 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5451 CXXCtorInitializer *Init = Inits[InitIndex];
5452 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5453 Init->getSourceLocation())) {
5454 ShouldCheckOrder = true;
5455 break;
5456 }
5457 }
5458 if (!ShouldCheckOrder)
5459 return;
5460
5461 // Build the list of bases and members in the order that they'll
5462 // actually be initialized. The explicit initializers should be in
5463 // this same order but may be missing things.
5464 SmallVector<const void*, 32> IdealInitKeys;
5465
5466 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5467
5468 // 1. Virtual bases.
5469 for (const auto &VBase : ClassDecl->vbases())
5470 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5471
5472 // 2. Non-virtual bases.
5473 for (const auto &Base : ClassDecl->bases()) {
5474 if (Base.isVirtual())
5475 continue;
5476 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5477 }
5478
5479 // 3. Direct fields.
5480 for (auto *Field : ClassDecl->fields()) {
5481 if (Field->isUnnamedBitField())
5482 continue;
5483
5484 PopulateKeysForFields(Field, IdealInitKeys);
5485 }
5486
5487 unsigned NumIdealInits = IdealInitKeys.size();
5488 unsigned IdealIndex = 0;
5489
5490 // Track initializers that are in an incorrect order for either a warning or
5491 // note if multiple ones occur.
5492 SmallVector<unsigned> WarnIndexes;
5493 // Correlates the index of an initializer in the init-list to the index of
5494 // the field/base in the class.
5495 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5496
5497 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5498 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5499
5500 // Scan forward to try to find this initializer in the idealized
5501 // initializers list.
5502 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5503 if (InitKey == IdealInitKeys[IdealIndex])
5504 break;
5505
5506 // If we didn't find this initializer, it must be because we
5507 // scanned past it on a previous iteration. That can only
5508 // happen if we're out of order; emit a warning.
5509 if (IdealIndex == NumIdealInits && InitIndex) {
5510 WarnIndexes.push_back(InitIndex);
5511
5512 // Move back to the initializer's location in the ideal list.
5513 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5514 if (InitKey == IdealInitKeys[IdealIndex])
5515 break;
5516
5517 assert(IdealIndex < NumIdealInits &&
5518 "initializer not found in initializer list");
5519 }
5520 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5521 }
5522
5523 if (WarnIndexes.empty())
5524 return;
5525
5526 // Sort based on the ideal order, first in the pair.
5527 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5528
5529 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5530 // emit the diagnostic before we can try adding notes.
5531 {
5533 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5534 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5535 : diag::warn_some_initializers_out_of_order);
5536
5537 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5538 if (CorrelatedInitOrder[I].second == I)
5539 continue;
5540 // Ideally we would be using InsertFromRange here, but clang doesn't
5541 // appear to handle InsertFromRange correctly when the source range is
5542 // modified by another fix-it.
5544 Inits[I]->getSourceRange(),
5547 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5549 }
5550
5551 // If there is only 1 item out of order, the warning expects the name and
5552 // type of each being added to it.
5553 if (WarnIndexes.size() == 1) {
5554 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5555 Inits[WarnIndexes.front()]);
5556 return;
5557 }
5558 }
5559 // More than 1 item to warn, create notes letting the user know which ones
5560 // are bad.
5561 for (unsigned WarnIndex : WarnIndexes) {
5562 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5563 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5564 diag::note_initializer_out_of_order);
5565 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5566 D << PrevInit->getSourceRange();
5567 }
5568}
5569
5570namespace {
5571bool CheckRedundantInit(Sema &S,
5573 CXXCtorInitializer *&PrevInit) {
5574 if (!PrevInit) {
5575 PrevInit = Init;
5576 return false;
5577 }
5578
5579 if (FieldDecl *Field = Init->getAnyMember())
5580 S.Diag(Init->getSourceLocation(),
5581 diag::err_multiple_mem_initialization)
5582 << Field->getDeclName()
5583 << Init->getSourceRange();
5584 else {
5585 const Type *BaseClass = Init->getBaseClass();
5586 assert(BaseClass && "neither field nor base");
5587 S.Diag(Init->getSourceLocation(),
5588 diag::err_multiple_base_initialization)
5589 << QualType(BaseClass, 0)
5590 << Init->getSourceRange();
5591 }
5592 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5593 << 0 << PrevInit->getSourceRange();
5594
5595 return true;
5596}
5597
5598typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5599typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5600
5601bool CheckRedundantUnionInit(Sema &S,
5603 RedundantUnionMap &Unions) {
5604 FieldDecl *Field = Init->getAnyMember();
5605 RecordDecl *Parent = Field->getParent();
5606 NamedDecl *Child = Field;
5607
5608 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5609 if (Parent->isUnion()) {
5610 UnionEntry &En = Unions[Parent];
5611 if (En.first && En.first != Child) {
5612 S.Diag(Init->getSourceLocation(),
5613 diag::err_multiple_mem_union_initialization)
5614 << Field->getDeclName()
5615 << Init->getSourceRange();
5616 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5617 << 0 << En.second->getSourceRange();
5618 return true;
5619 }
5620 if (!En.first) {
5621 En.first = Child;
5622 En.second = Init;
5623 }
5624 if (!Parent->isAnonymousStructOrUnion())
5625 return false;
5626 }
5627
5628 Child = Parent;
5629 Parent = cast<RecordDecl>(Parent->getDeclContext());
5630 }
5631
5632 return false;
5633}
5634} // namespace
5635
5636void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5637 SourceLocation ColonLoc,
5639 bool AnyErrors) {
5640 if (!ConstructorDecl)
5641 return;
5642
5643 AdjustDeclIfTemplate(ConstructorDecl);
5644
5645 CXXConstructorDecl *Constructor
5646 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5647
5648 if (!Constructor) {
5649 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5650 return;
5651 }
5652
5653 // Mapping for the duplicate initializers check.
5654 // For member initializers, this is keyed with a FieldDecl*.
5655 // For base initializers, this is keyed with a Type*.
5656 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5657
5658 // Mapping for the inconsistent anonymous-union initializers check.
5659 RedundantUnionMap MemberUnions;
5660
5661 bool HadError = false;
5662 for (unsigned i = 0; i < MemInits.size(); i++) {
5663 CXXCtorInitializer *Init = MemInits[i];
5664
5665 // Set the source order index.
5666 Init->setSourceOrder(i);
5667
5668 if (Init->isAnyMemberInitializer()) {
5669 const void *Key = GetKeyForMember(Context, Init);
5670 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5671 CheckRedundantUnionInit(*this, Init, MemberUnions))
5672 HadError = true;
5673 } else if (Init->isBaseInitializer()) {
5674 const void *Key = GetKeyForMember(Context, Init);
5675 if (CheckRedundantInit(*this, Init, Members[Key]))
5676 HadError = true;
5677 } else {
5678 assert(Init->isDelegatingInitializer());
5679 // This must be the only initializer
5680 if (MemInits.size() != 1) {
5681 Diag(Init->getSourceLocation(),
5682 diag::err_delegating_initializer_alone)
5683 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5684 // We will treat this as being the only initializer.
5685 }
5686 SetDelegatingInitializer(Constructor, MemInits[i]);
5687 // Return immediately as the initializer is set.
5688 return;
5689 }
5690 }
5691
5692 if (HadError)
5693 return;
5694
5695 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5696
5697 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5698
5699 DiagnoseUninitializedFields(*this, Constructor);
5700}
5701
5702void
5704 CXXRecordDecl *ClassDecl) {
5705 // Ignore dependent contexts. Also ignore unions, since their members never
5706 // have destructors implicitly called.
5707 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5708 return;
5709
5710 // FIXME: all the access-control diagnostics are positioned on the
5711 // field/base declaration. That's probably good; that said, the
5712 // user might reasonably want to know why the destructor is being
5713 // emitted, and we currently don't say.
5714
5715 // Non-static data members.
5716 for (auto *Field : ClassDecl->fields()) {
5717 if (Field->isInvalidDecl())
5718 continue;
5719
5720 // Don't destroy incomplete or zero-length arrays.
5721 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5722 continue;
5723
5724 QualType FieldType = Context.getBaseElementType(Field->getType());
5725
5726 const RecordType* RT = FieldType->getAs<RecordType>();
5727 if (!RT)
5728 continue;
5729
5730 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5731 if (FieldClassDecl->isInvalidDecl())
5732 continue;
5733 if (FieldClassDecl->hasIrrelevantDestructor())
5734 continue;
5735 // The destructor for an implicit anonymous union member is never invoked.
5736 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5737 continue;
5738
5739 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5740 // Dtor might still be missing, e.g because it's invalid.
5741 if (!Dtor)
5742 continue;
5743 CheckDestructorAccess(Field->getLocation(), Dtor,
5744 PDiag(diag::err_access_dtor_field)
5745 << Field->getDeclName()
5746 << FieldType);
5747
5748 MarkFunctionReferenced(Location, Dtor);
5749 DiagnoseUseOfDecl(Dtor, Location);
5750 }
5751
5752 // We only potentially invoke the destructors of potentially constructed
5753 // subobjects.
5754 bool VisitVirtualBases = !ClassDecl->isAbstract();
5755
5756 // If the destructor exists and has already been marked used in the MS ABI,
5757 // then virtual base destructors have already been checked and marked used.
5758 // Skip checking them again to avoid duplicate diagnostics.
5760 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5761 if (Dtor && Dtor->isUsed())
5762 VisitVirtualBases = false;
5763 }
5764
5766
5767 // Bases.
5768 for (const auto &Base : ClassDecl->bases()) {
5769 const RecordType *RT = Base.getType()->getAs<RecordType>();
5770 if (!RT)
5771 continue;
5772
5773 // Remember direct virtual bases.
5774 if (Base.isVirtual()) {
5775 if (!VisitVirtualBases)
5776 continue;
5777 DirectVirtualBases.insert(RT);
5778 }
5779
5780 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5781 // If our base class is invalid, we probably can't get its dtor anyway.
5782 if (BaseClassDecl->isInvalidDecl())
5783 continue;
5784 if (BaseClassDecl->hasIrrelevantDestructor())
5785 continue;
5786
5787 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5788 // Dtor might still be missing, e.g because it's invalid.
5789 if (!Dtor)
5790 continue;
5791
5792 // FIXME: caret should be on the start of the class name
5793 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5794 PDiag(diag::err_access_dtor_base)
5795 << Base.getType() << Base.getSourceRange(),
5796 Context.getTypeDeclType(ClassDecl));
5797
5798 MarkFunctionReferenced(Location, Dtor);
5799 DiagnoseUseOfDecl(Dtor, Location);
5800 }
5801
5802 if (VisitVirtualBases)
5803 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5804 &DirectVirtualBases);
5805}
5806
5808 SourceLocation Location, CXXRecordDecl *ClassDecl,
5809 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5810 // Virtual bases.
5811 for (const auto &VBase : ClassDecl->vbases()) {
5812 // Bases are always records in a well-formed non-dependent class.
5813 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5814
5815 // Ignore already visited direct virtual bases.
5816 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5817 continue;
5818
5819 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5820 // If our base class is invalid, we probably can't get its dtor anyway.
5821 if (BaseClassDecl->isInvalidDecl())
5822 continue;
5823 if (BaseClassDecl->hasIrrelevantDestructor())
5824 continue;
5825
5826 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5827 // Dtor might still be missing, e.g because it's invalid.
5828 if (!Dtor)
5829 continue;
5831 ClassDecl->getLocation(), Dtor,
5832 PDiag(diag::err_access_dtor_vbase)
5833 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5834 Context.getTypeDeclType(ClassDecl)) ==
5835 AR_accessible) {
5837 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5838 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5839 SourceRange(), DeclarationName(), nullptr);
5840 }
5841
5842 MarkFunctionReferenced(Location, Dtor);
5843 DiagnoseUseOfDecl(Dtor, Location);
5844 }
5845}
5846
5848 if (!CDtorDecl)
5849 return;
5850
5851 if (CXXConstructorDecl *Constructor
5852 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5853 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5854 !ClassDecl || ClassDecl->isInvalidDecl()) {
5855 return;
5856 }
5857 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5858 DiagnoseUninitializedFields(*this, Constructor);
5859 }
5860}
5861
5863 if (!getLangOpts().CPlusPlus)
5864 return false;
5865
5866 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5867 if (!RD)
5868 return false;
5869
5870 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5871 // class template specialization here, but doing so breaks a lot of code.
5872
5873 // We can't answer whether something is abstract until it has a
5874 // definition. If it's currently being defined, we'll walk back
5875 // over all the declarations when we have a full definition.
5876 const CXXRecordDecl *Def = RD->getDefinition();
5877 if (!Def || Def->isBeingDefined())
5878 return false;
5879
5880 return RD->isAbstract();
5881}
5882
5884 TypeDiagnoser &Diagnoser) {
5885 if (!isAbstractType(Loc, T))
5886 return false;
5887
5889 Diagnoser.diagnose(*this, Loc, T);
5891 return true;
5892}
5893
5895 // Check if we've already emitted the list of pure virtual functions
5896 // for this class.
5898 return;
5899
5900 // If the diagnostic is suppressed, don't emit the notes. We're only
5901 // going to emit them once, so try to attach them to a diagnostic we're
5902 // actually going to show.
5904 return;
5905
5906 CXXFinalOverriderMap FinalOverriders;
5907 RD->getFinalOverriders(FinalOverriders);
5908
5909 // Keep a set of seen pure methods so we won't diagnose the same method
5910 // more than once.
5912
5913 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5914 MEnd = FinalOverriders.end();
5915 M != MEnd;
5916 ++M) {
5917 for (OverridingMethods::iterator SO = M->second.begin(),
5918 SOEnd = M->second.end();
5919 SO != SOEnd; ++SO) {
5920 // C++ [class.abstract]p4:
5921 // A class is abstract if it contains or inherits at least one
5922 // pure virtual function for which the final overrider is pure
5923 // virtual.
5924
5925 //
5926 if (SO->second.size() != 1)
5927 continue;
5928
5929 if (!SO->second.front().Method->isPureVirtual())
5930 continue;
5931
5932 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5933 continue;
5934
5935 Diag(SO->second.front().Method->getLocation(),
5936 diag::note_pure_virtual_function)
5937 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5938 }
5939 }
5940
5943 PureVirtualClassDiagSet->insert(RD);
5944}
5945
5946namespace {
5947struct AbstractUsageInfo {
5948 Sema &S;
5950 CanQualType AbstractType;
5951 bool Invalid;
5952
5953 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5954 : S(S), Record(Record),
5955 AbstractType(S.Context.getCanonicalType(
5956 S.Context.getTypeDeclType(Record))),
5957 Invalid(false) {}
5958
5959 void DiagnoseAbstractType() {
5960 if (Invalid) return;
5962 Invalid = true;
5963 }
5964
5965 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5966};
5967
5968struct CheckAbstractUsage {
5969 AbstractUsageInfo &Info;
5970 const NamedDecl *Ctx;
5971
5972 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5973 : Info(Info), Ctx(Ctx) {}
5974
5975 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5976 switch (TL.getTypeLocClass()) {
5977#define ABSTRACT_TYPELOC(CLASS, PARENT)
5978#define TYPELOC(CLASS, PARENT) \
5979 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5980#include "clang/AST/TypeLocNodes.def"
5981 }
5982 }
5983
5984 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5986 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5987 if (!TL.getParam(I))
5988 continue;
5989
5991 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5992 }
5993 }
5994
5995 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5997 }
5998
6000 // Visit the type parameters from a permissive context.
6001 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6002 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6004 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6005 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6006 // TODO: other template argument types?
6007 }
6008 }
6009
6010 // Visit pointee types from a permissive context.
6011#define CheckPolymorphic(Type) \
6012 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6013 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6014 }
6020
6021 /// Handle all the types we haven't given a more specific
6022 /// implementation for above.
6023 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6024 // Every other kind of type that we haven't called out already
6025 // that has an inner type is either (1) sugar or (2) contains that
6026 // inner type in some way as a subobject.
6027 if (TypeLoc Next = TL.getNextTypeLoc())
6028 return Visit(Next, Sel);
6029
6030 // If there's no inner type and we're in a permissive context,
6031 // don't diagnose.
6032 if (Sel == Sema::AbstractNone) return;
6033
6034 // Check whether the type matches the abstract type.
6035 QualType T = TL.getType();
6036 if (T->isArrayType()) {
6038 T = Info.S.Context.getBaseElementType(T);
6039 }
6041 if (CT != Info.AbstractType) return;
6042
6043 // It matched; do some magic.
6044 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6045 if (Sel == Sema::AbstractArrayType) {
6046 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6047 << T << TL.getSourceRange();
6048 } else {
6049 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6050 << Sel << T << TL.getSourceRange();
6051 }
6052 Info.DiagnoseAbstractType();
6053 }
6054};
6055
6056void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6058 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6059}
6060
6061}
6062
6063/// Check for invalid uses of an abstract type in a function declaration.
6064static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6065 FunctionDecl *FD) {
6066 // Only definitions are required to refer to complete and
6067 // non-abstract types.
6069 return;
6070
6071 // For safety's sake, just ignore it if we don't have type source
6072 // information. This should never happen for non-implicit methods,
6073 // but...
6074 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6075 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6076}
6077
6078/// Check for invalid uses of an abstract type in a variable0 declaration.
6079static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6080 VarDecl *VD) {
6081 // No need to do the check on definitions, which require that
6082 // the type is complete.
6084 return;
6085
6086 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6088}
6089
6090/// Check for invalid uses of an abstract type within a class definition.
6091static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6092 CXXRecordDecl *RD) {
6093 for (auto *D : RD->decls()) {
6094 if (D->isImplicit()) continue;
6095
6096 // Step through friends to the befriended declaration.
6097 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6098 D = FD->getFriendDecl();
6099 if (!D) continue;
6100 }
6101
6102 // Functions and function templates.
6103 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6104 CheckAbstractClassUsage(Info, FD);
6105 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6106 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6107
6108 // Fields and static variables.
6109 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6110 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6111 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6112 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6113 CheckAbstractClassUsage(Info, VD);
6114 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6115 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6116
6117 // Nested classes and class templates.
6118 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6119 CheckAbstractClassUsage(Info, RD);
6120 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6121 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6122 }
6123 }
6124}
6125
6127 Attr *ClassAttr = getDLLAttr(Class);
6128 if (!ClassAttr)
6129 return;
6130
6131 assert(ClassAttr->getKind() == attr::DLLExport);
6132
6133 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6134
6136 // Don't go any further if this is just an explicit instantiation
6137 // declaration.
6138 return;
6139
6140 // Add a context note to explain how we got to any diagnostics produced below.
6141 struct MarkingClassDllexported {
6142 Sema &S;
6143 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6144 SourceLocation AttrLoc)
6145 : S(S) {
6148 Ctx.PointOfInstantiation = AttrLoc;
6149 Ctx.Entity = Class;
6151 }
6152 ~MarkingClassDllexported() {
6154 }
6155 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6156
6157 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6158 S.MarkVTableUsed(Class->getLocation(), Class, true);
6159
6160 for (Decl *Member : Class->decls()) {
6161 // Skip members that were not marked exported.
6162 if (!Member->hasAttr<DLLExportAttr>())
6163 continue;
6164
6165 // Defined static variables that are members of an exported base
6166 // class must be marked export too.
6167 auto *VD = dyn_cast<VarDecl>(Member);
6168 if (VD && VD->getStorageClass() == SC_Static &&
6170 S.MarkVariableReferenced(VD->getLocation(), VD);
6171
6172 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6173 if (!MD)
6174 continue;
6175
6176 if (MD->isUserProvided()) {
6177 // Instantiate non-default class member functions ...
6178
6179 // .. except for certain kinds of template specializations.
6180 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6181 continue;
6182
6183 // If this is an MS ABI dllexport default constructor, instantiate any
6184 // default arguments.
6186 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6187 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6189 }
6190 }
6191
6192 S.MarkFunctionReferenced(Class->getLocation(), MD);
6193
6194 // The function will be passed to the consumer when its definition is
6195 // encountered.
6196 } else if (MD->isExplicitlyDefaulted()) {
6197 // Synthesize and instantiate explicitly defaulted methods.
6198 S.MarkFunctionReferenced(Class->getLocation(), MD);
6199
6201 // Except for explicit instantiation defs, we will not see the
6202 // definition again later, so pass it to the consumer now.
6204 }
6205 } else if (!MD->isTrivial() ||
6206 MD->isCopyAssignmentOperator() ||
6207 MD->isMoveAssignmentOperator()) {
6208 // Synthesize and instantiate non-trivial implicit methods, and the copy
6209 // and move assignment operators. The latter are exported even if they
6210 // are trivial, because the address of an operator can be taken and
6211 // should compare equal across libraries.
6212 S.MarkFunctionReferenced(Class->getLocation(), MD);
6213
6214 // There is no later point when we will see the definition of this
6215 // function, so pass it to the consumer now.
6217 }
6218 }
6219}
6220
6223 // Only the MS ABI has default constructor closures, so we don't need to do
6224 // this semantic checking anywhere else.
6226 return;
6227
6228 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6229 for (Decl *Member : Class->decls()) {
6230 // Look for exported default constructors.
6231 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6232 if (!CD || !CD->isDefaultConstructor())
6233 continue;
6234 auto *Attr = CD->getAttr<DLLExportAttr>();
6235 if (!Attr)
6236 continue;
6237
6238 // If the class is non-dependent, mark the default arguments as ODR-used so
6239 // that we can properly codegen the constructor closure.
6240 if (!Class->isDependentContext()) {
6241 for (ParmVarDecl *PD : CD->parameters()) {
6242 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6244 }
6245 }
6246
6247 if (LastExportedDefaultCtor) {
6248 S.Diag(LastExportedDefaultCtor->getLocation(),
6249 diag::err_attribute_dll_ambiguous_default_ctor)
6250 << Class;
6251 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6252 << CD->getDeclName();
6253 return;
6254 }
6255 LastExportedDefaultCtor = CD;
6256 }
6257}
6258
6261 bool ErrorReported = false;
6262 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6263 ClassTemplateDecl *TD) {
6264 if (ErrorReported)
6265 return;
6266 S.Diag(TD->getLocation(),
6267 diag::err_cuda_device_builtin_surftex_cls_template)
6268 << /*surface*/ 0 << TD;
6269 ErrorReported = true;
6270 };
6271
6272 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6273 if (!TD) {
6274 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6275 if (!SD) {
6276 S.Diag(Class->getLocation(),
6277 diag::err_cuda_device_builtin_surftex_ref_decl)
6278 << /*surface*/ 0 << Class;
6279 S.Diag(Class->getLocation(),
6280 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6281 << Class;
6282 return;
6283 }
6284 TD = SD->getSpecializedTemplate();
6285 }
6286
6288 unsigned N = Params->size();
6289
6290 if (N != 2) {
6291 reportIllegalClassTemplate(S, TD);
6292 S.Diag(TD->getLocation(),
6293 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6294 << TD << 2;
6295 }
6296 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6297 reportIllegalClassTemplate(S, TD);
6298 S.Diag(TD->getLocation(),
6299 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6300 << TD << /*1st*/ 0 << /*type*/ 0;
6301 }
6302 if (N > 1) {
6303 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6304 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6305 reportIllegalClassTemplate(S, TD);
6306 S.Diag(TD->getLocation(),
6307 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6308 << TD << /*2nd*/ 1 << /*integer*/ 1;
6309 }
6310 }
6311}
6312
6315 bool ErrorReported = false;
6316 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6317 ClassTemplateDecl *TD) {
6318 if (ErrorReported)
6319 return;
6320 S.Diag(TD->getLocation(),
6321 diag::err_cuda_device_builtin_surftex_cls_template)
6322 << /*texture*/ 1 << TD;
6323 ErrorReported = true;
6324 };
6325
6326 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6327 if (!TD) {
6328 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6329 if (!SD) {
6330 S.Diag(Class->getLocation(),
6331 diag::err_cuda_device_builtin_surftex_ref_decl)
6332 << /*texture*/ 1 << Class;
6333 S.Diag(Class->getLocation(),
6334 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6335 << Class;
6336 return;
6337 }
6338 TD = SD->getSpecializedTemplate();
6339 }
6340
6342 unsigned N = Params->size();
6343
6344 if (N != 3) {
6345 reportIllegalClassTemplate(S, TD);
6346 S.Diag(TD->getLocation(),
6347 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6348 << TD << 3;
6349 }
6350 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6351 reportIllegalClassTemplate(S, TD);
6352 S.Diag(TD->getLocation(),
6353 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6354 << TD << /*1st*/ 0 << /*type*/ 0;
6355 }
6356 if (N > 1) {
6357 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6358 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6359 reportIllegalClassTemplate(S, TD);
6360 S.Diag(TD->getLocation(),
6361 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6362 << TD << /*2nd*/ 1 << /*integer*/ 1;
6363 }
6364 }
6365 if (N > 2) {
6366 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6367 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6368 reportIllegalClassTemplate(S, TD);
6369 S.Diag(TD->getLocation(),
6370 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6371 << TD << /*3rd*/ 2 << /*integer*/ 1;
6372 }
6373 }
6374}
6375
6377 // Mark any compiler-generated routines with the implicit code_seg attribute.
6378 for (auto *Method : Class->methods()) {
6379 if (Method->isUserProvided())
6380 continue;
6381 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6382 Method->addAttr(A);
6383 }
6384}
6385
6387 Attr *ClassAttr = getDLLAttr(Class);
6388
6389 // MSVC inherits DLL attributes to partial class template specializations.
6390 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6391 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6392 if (Attr *TemplateAttr =
6393 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6394 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6395 A->setInherited(true);
6396 ClassAttr = A;
6397 }
6398 }
6399 }
6400
6401 if (!ClassAttr)
6402 return;
6403
6404 // MSVC allows imported or exported template classes that have UniqueExternal
6405 // linkage. This occurs when the template class has been instantiated with
6406 // a template parameter which itself has internal linkage.
6407 // We drop the attribute to avoid exporting or importing any members.
6409 Context.getTargetInfo().getTriple().isPS()) &&
6410 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6411 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6412 return;
6413 }
6414
6415 if (!Class->isExternallyVisible()) {
6416 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6417 << Class << ClassAttr;
6418 return;
6419 }
6420
6422 !ClassAttr->isInherited()) {
6423 // Diagnose dll attributes on members of class with dll attribute.
6424 for (Decl *Member : Class->decls()) {
6425 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6426 continue;
6427 InheritableAttr *MemberAttr = getDLLAttr(Member);
6428 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6429 continue;
6430
6431 Diag(MemberAttr->getLocation(),
6432 diag::err_attribute_dll_member_of_dll_class)
6433 << MemberAttr << ClassAttr;
6434 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6435 Member->setInvalidDecl();
6436 }
6437 }
6438
6439 if (Class->getDescribedClassTemplate())
6440 // Don't inherit dll attribute until the template is instantiated.
6441 return;
6442
6443 // The class is either imported or exported.
6444 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6445
6446 // Check if this was a dllimport attribute propagated from a derived class to
6447 // a base class template specialization. We don't apply these attributes to
6448 // static data members.
6449 const bool PropagatedImport =
6450 !ClassExported &&
6451 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6452
6453 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6454
6455 // Ignore explicit dllexport on explicit class template instantiation
6456 // declarations, except in MinGW mode.
6457 if (ClassExported && !ClassAttr->isInherited() &&
6459 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6460 Class->dropAttr<DLLExportAttr>();
6461 return;
6462 }
6463
6464 // Force declaration of implicit members so they can inherit the attribute.
6466
6467 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6468 // seem to be true in practice?
6469
6470 for (Decl *Member : Class->decls()) {
6471 VarDecl *VD = dyn_cast<VarDecl>(Member);
6472 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6473
6474 // Only methods and static fields inherit the attributes.
6475 if (!VD && !MD)
6476 continue;
6477
6478 if (MD) {
6479 // Don't process deleted methods.
6480 if (MD->isDeleted())
6481 continue;
6482
6483 if (MD->isInlined()) {
6484 // MinGW does not import or export inline methods. But do it for
6485 // template instantiations.
6489 continue;
6490
6491 // MSVC versions before 2015 don't export the move assignment operators
6492 // and move constructor, so don't attempt to import/export them if
6493 // we have a definition.
6494 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6495 if ((MD->isMoveAssignmentOperator() ||
6496 (Ctor && Ctor->isMoveConstructor())) &&
6497 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6498 continue;
6499
6500 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6501 // operator is exported anyway.
6502 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6503 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6504 continue;
6505 }
6506 }
6507
6508 // Don't apply dllimport attributes to static data members of class template
6509 // instantiations when the attribute is propagated from a derived class.
6510 if (VD && PropagatedImport)
6511 continue;
6512
6513 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6514 continue;
6515
6516 if (!getDLLAttr(Member)) {
6517 InheritableAttr *NewAttr = nullptr;
6518
6519 // Do not export/import inline function when -fno-dllexport-inlines is
6520 // passed. But add attribute for later local static var check.
6521 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6524 if (ClassExported) {
6525 NewAttr = ::new (getASTContext())
6526 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6527 } else {
6528 NewAttr = ::new (getASTContext())
6529 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6530 }
6531 } else {
6532 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6533 }
6534
6535 NewAttr->setInherited(true);
6536 Member->addAttr(NewAttr);
6537
6538 if (MD) {
6539 // Propagate DLLAttr to friend re-declarations of MD that have already
6540 // been constructed.
6541 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6542 FD = FD->getPreviousDecl()) {
6544 continue;
6545 assert(!getDLLAttr(FD) &&
6546 "friend re-decl should not already have a DLLAttr");
6547 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6548 NewAttr->setInherited(true);
6549 FD->addAttr(NewAttr);
6550 }
6551 }
6552 }
6553 }
6554
6555 if (ClassExported)
6556 DelayedDllExportClasses.push_back(Class);
6557}
6558
6560 CXXRecordDecl *Class, Attr *ClassAttr,
6561 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6562 if (getDLLAttr(
6563 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6564 // If the base class template has a DLL attribute, don't try to change it.
6565 return;
6566 }
6567
6568 auto TSK = BaseTemplateSpec->getSpecializationKind();
6569 if (!getDLLAttr(BaseTemplateSpec) &&
6571 TSK == TSK_ImplicitInstantiation)) {
6572 // The template hasn't been instantiated yet (or it has, but only as an
6573 // explicit instantiation declaration or implicit instantiation, which means
6574 // we haven't codegenned any members yet), so propagate the attribute.
6575 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6576 NewAttr->setInherited(true);
6577 BaseTemplateSpec->addAttr(NewAttr);
6578
6579 // If this was an import, mark that we propagated it from a derived class to
6580 // a base class template specialization.
6581 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6582 ImportAttr->setPropagatedToBaseTemplate();
6583
6584 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6585 // needs to be run again to work see the new attribute. Otherwise this will
6586 // get run whenever the template is instantiated.
6587 if (TSK != TSK_Undeclared)
6588 checkClassLevelDLLAttribute(BaseTemplateSpec);
6589
6590 return;
6591 }
6592
6593 if (getDLLAttr(BaseTemplateSpec)) {
6594 // The template has already been specialized or instantiated with an
6595 // attribute, explicitly or through propagation. We should not try to change
6596 // it.
6597 return;
6598 }
6599
6600 // The template was previously instantiated or explicitly specialized without
6601 // a dll attribute, It's too late for us to add an attribute, so warn that
6602 // this is unsupported.
6603 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6604 << BaseTemplateSpec->isExplicitSpecialization();
6605 Diag(ClassAttr->getLocation(), diag::note_attribute);
6606 if (BaseTemplateSpec->isExplicitSpecialization()) {
6607 Diag(BaseTemplateSpec->getLocation(),
6608 diag::note_template_class_explicit_specialization_was_here)
6609 << BaseTemplateSpec;
6610 } else {
6611 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6612 diag::note_template_class_instantiation_was_here)
6613 << BaseTemplateSpec;
6614 }
6615}
6616
6619 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6620 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6621 if (Ctor->isDefaultConstructor())
6623
6624 if (Ctor->isCopyConstructor())
6626
6627 if (Ctor->isMoveConstructor())
6629 }
6630
6631 if (MD->isCopyAssignmentOperator())
6633
6634 if (MD->isMoveAssignmentOperator())
6636
6637 if (isa<CXXDestructorDecl>(FD))
6639 }
6640
6641 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6642 case OO_EqualEqual:
6644
6645 case OO_ExclaimEqual:
6647
6648 case OO_Spaceship:
6649 // No point allowing this if <=> doesn't exist in the current language mode.
6650 if (!getLangOpts().CPlusPlus20)
6651 break;
6653
6654 case OO_Less:
6655 case OO_LessEqual:
6656 case OO_Greater:
6657 case OO_GreaterEqual:
6658 // No point allowing this if <=> doesn't exist in the current language mode.
6659 if (!getLangOpts().CPlusPlus20)
6660 break;
6662
6663 default:
6664 break;
6665 }
6666
6667 // Not defaultable.
6668 return DefaultedFunctionKind();
6669}
6670
6672 SourceLocation DefaultLoc) {
6674 if (DFK.isComparison())
6675 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6676
6677 switch (DFK.asSpecialMember()) {
6680 cast<CXXConstructorDecl>(FD));
6681 break;
6683 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6684 break;
6686 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6687 break;
6689 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6690 break;
6692 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6693 break;
6695 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6696 break;
6698 llvm_unreachable("Invalid special member.");
6699 }
6700}
6701
6702/// Determine whether a type is permitted to be passed or returned in
6703/// registers, per C++ [class.temporary]p3.
6706 if (D->isDependentType() || D->isInvalidDecl())
6707 return false;
6708
6709 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6710 // The PS4 platform ABI follows the behavior of Clang 3.2.
6712 return !D->hasNonTrivialDestructorForCall() &&
6713 !D->hasNonTrivialCopyConstructorForCall();
6714
6715 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6716 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6717 bool DtorIsTrivialForCall = false;
6718
6719 // If a class has at least one eligible, trivial copy constructor, it
6720 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6721 //
6722 // Note: This permits classes with non-trivial copy or move ctors to be
6723 // passed in registers, so long as they *also* have a trivial copy ctor,
6724 // which is non-conforming.
6725 if (D->needsImplicitCopyConstructor()) {
6726 if (!D->defaultedCopyConstructorIsDeleted()) {
6727 if (D->hasTrivialCopyConstructor())
6728 CopyCtorIsTrivial = true;
6729 if (D->hasTrivialCopyConstructorForCall())
6730 CopyCtorIsTrivialForCall = true;
6731 }
6732 } else {
6733 for (const CXXConstructorDecl *CD : D->ctors()) {
6734 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6735 !CD->isIneligibleOrNotSelected()) {
6736 if (CD->isTrivial())
6737 CopyCtorIsTrivial = true;
6738 if (CD->isTrivialForCall())
6739 CopyCtorIsTrivialForCall = true;
6740 }
6741 }
6742 }
6743
6744 if (D->needsImplicitDestructor()) {
6745 if (!D->defaultedDestructorIsDeleted() &&
6746 D->hasTrivialDestructorForCall())
6747 DtorIsTrivialForCall = true;
6748 } else if (const auto *DD = D->getDestructor()) {
6749 if (!DD->isDeleted() && DD->isTrivialForCall())
6750 DtorIsTrivialForCall = true;
6751 }
6752
6753 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6754 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6755 return true;
6756
6757 // If a class has a destructor, we'd really like to pass it indirectly
6758 // because it allows us to elide copies. Unfortunately, MSVC makes that
6759 // impossible for small types, which it will pass in a single register or
6760 // stack slot. Most objects with dtors are large-ish, so handle that early.
6761 // We can't call out all large objects as being indirect because there are
6762 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6763 // how we pass large POD types.
6764
6765 // Note: This permits small classes with nontrivial destructors to be
6766 // passed in registers, which is non-conforming.
6767 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6768 uint64_t TypeSize = isAArch64 ? 128 : 64;
6769
6770 if (CopyCtorIsTrivial &&
6771 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6772 return true;
6773 return false;
6774 }
6775
6776 // Per C++ [class.temporary]p3, the relevant condition is:
6777 // each copy constructor, move constructor, and destructor of X is
6778 // either trivial or deleted, and X has at least one non-deleted copy
6779 // or move constructor
6780 bool HasNonDeletedCopyOrMove = false;
6781
6782 if (D->needsImplicitCopyConstructor() &&
6783 !D->defaultedCopyConstructorIsDeleted()) {
6784 if (!D->hasTrivialCopyConstructorForCall())
6785 return false;
6786 HasNonDeletedCopyOrMove = true;
6787 }
6788
6789 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6790 !D->defaultedMoveConstructorIsDeleted()) {
6791 if (!D->hasTrivialMoveConstructorForCall())
6792 return false;
6793 HasNonDeletedCopyOrMove = true;
6794 }
6795
6796 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6797 !D->hasTrivialDestructorForCall())
6798 return false;
6799
6800 for (const CXXMethodDecl *MD : D->methods()) {
6801 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6802 continue;
6803
6804 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6805 if (CD && CD->isCopyOrMoveConstructor())
6806 HasNonDeletedCopyOrMove = true;
6807 else if (!isa<CXXDestructorDecl>(MD))
6808 continue;
6809
6810 if (!MD->isTrivialForCall())
6811 return false;
6812 }
6813
6814 return HasNonDeletedCopyOrMove;
6815}
6816
6817/// Report an error regarding overriding, along with any relevant
6818/// overridden methods.
6819///
6820/// \param DiagID the primary error to report.
6821/// \param MD the overriding method.
6822static bool
6823ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6824 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6825 bool IssuedDiagnostic = false;
6826 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6827 if (Report(O)) {
6828 if (!IssuedDiagnostic) {
6829 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6830 IssuedDiagnostic = true;
6831 }
6832 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6833 }
6834 }
6835 return IssuedDiagnostic;
6836}
6837
6839 if (!Record)
6840 return;
6841
6842 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6843 AbstractUsageInfo Info(*this, Record);
6845 }
6846
6847 // If this is not an aggregate type and has no user-declared constructor,
6848 // complain about any non-static data members of reference or const scalar
6849 // type, since they will never get initializers.
6850 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6851 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6852 !Record->isLambda()) {
6853 bool Complained = false;
6854 for (const auto *F : Record->fields()) {
6855 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6856 continue;
6857
6858 if (F->getType()->isReferenceType() ||
6859 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6860 if (!Complained) {
6861 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6862 << llvm::to_underlying(Record->getTagKind()) << Record;
6863 Complained = true;
6864 }
6865
6866 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6867 << F->getType()->isReferenceType()
6868 << F->getDeclName();
6869 }
6870 }
6871 }
6872
6873 if (Record->getIdentifier()) {
6874 // C++ [class.mem]p13:
6875 // If T is the name of a class, then each of the following shall have a
6876 // name different from T:
6877 // - every member of every anonymous union that is a member of class T.
6878 //
6879 // C++ [class.mem]p14:
6880 // In addition, if class T has a user-declared constructor (12.1), every
6881 // non-static data member of class T shall have a name different from T.
6882 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6883 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6884 ++I) {
6885 NamedDecl *D = (*I)->getUnderlyingDecl();
6886 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6887 Record->hasUserDeclaredConstructor()) ||
6888 isa<IndirectFieldDecl>(D)) {
6889 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6890 << D->getDeclName();
6891 break;
6892 }
6893 }
6894 }
6895
6896 // Warn if the class has virtual methods but non-virtual public destructor.
6897 if (Record->isPolymorphic() && !Record->isDependentType()) {
6898 CXXDestructorDecl *dtor = Record->getDestructor();
6899 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6900 !Record->hasAttr<FinalAttr>())
6901 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6902 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6903 }
6904
6905 if (Record->isAbstract()) {
6906 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6907 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6908 << FA->isSpelledAsSealed();
6910 }
6911 }
6912
6913 // Warn if the class has a final destructor but is not itself marked final.
6914 if (!Record->hasAttr<FinalAttr>()) {
6915 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6916 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6917 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6918 << FA->isSpelledAsSealed()
6920 getLocForEndOfToken(Record->getLocation()),
6921 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6922 Diag(Record->getLocation(),
6923 diag::note_final_dtor_non_final_class_silence)
6924 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6925 }
6926 }
6927 }
6928
6929 // See if trivial_abi has to be dropped.
6930 if (Record->hasAttr<TrivialABIAttr>())
6932
6933 // Set HasTrivialSpecialMemberForCall if the record has attribute
6934 // "trivial_abi".
6935 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6936
6937 if (HasTrivialABI)
6938 Record->setHasTrivialSpecialMemberForCall();
6939
6940 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6941 // We check these last because they can depend on the properties of the
6942 // primary comparison functions (==, <=>).
6943 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6944
6945 // Perform checks that can't be done until we know all the properties of a
6946 // member function (whether it's defaulted, deleted, virtual, overriding,
6947 // ...).
6948 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6949 // A static function cannot override anything.
6950 if (MD->getStorageClass() == SC_Static) {
6951 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6952 [](const CXXMethodDecl *) { return true; }))
6953 return;
6954 }
6955
6956 // A deleted function cannot override a non-deleted function and vice
6957 // versa.
6958 if (ReportOverrides(*this,
6959 MD->isDeleted() ? diag::err_deleted_override
6960 : diag::err_non_deleted_override,
6961 MD, [&](const CXXMethodDecl *V) {
6962 return MD->isDeleted() != V->isDeleted();
6963 })) {
6964 if (MD->isDefaulted() && MD->isDeleted())
6965 // Explain why this defaulted function was deleted.
6967 return;
6968 }
6969
6970 // A consteval function cannot override a non-consteval function and vice
6971 // versa.
6972 if (ReportOverrides(*this,
6973 MD->isConsteval() ? diag::err_consteval_override
6974 : diag::err_non_consteval_override,
6975 MD, [&](const CXXMethodDecl *V) {
6976 return MD->isConsteval() != V->isConsteval();
6977 })) {
6978 if (MD->isDefaulted() && MD->isDeleted())
6979 // Explain why this defaulted function was deleted.
6981 return;
6982 }
6983 };
6984
6985 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6986 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6987 return false;
6988
6992 DefaultedSecondaryComparisons.push_back(FD);
6993 return true;
6994 }
6995
6997 return false;
6998 };
6999
7000 if (!Record->isInvalidDecl() &&
7001 Record->hasAttr<VTablePointerAuthenticationAttr>())
7003
7004 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7005 // Check whether the explicitly-defaulted members are valid.
7006 bool Incomplete = CheckForDefaultedFunction(M);
7007
7008 // Skip the rest of the checks for a member of a dependent class.
7009 if (Record->isDependentType())
7010 return;
7011
7012 // For an explicitly defaulted or deleted special member, we defer
7013 // determining triviality until the class is complete. That time is now!
7015 if (!M->isImplicit() && !M->isUserProvided()) {
7016 if (CSM != CXXSpecialMemberKind::Invalid) {
7017 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7018 // Inform the class that we've finished declaring this member.
7019 Record->finishedDefaultedOrDeletedMember(M);
7020 M->setTrivialForCall(
7021 HasTrivialABI ||
7023 Record->setTrivialForCallFlags(M);
7024 }
7025 }
7026
7027 // Set triviality for the purpose of calls if this is a user-provided
7028 // copy/move constructor or destructor.
7032 M->isUserProvided()) {
7033 M->setTrivialForCall(HasTrivialABI);
7034 Record->setTrivialForCallFlags(M);
7035 }
7036
7037 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7038 M->hasAttr<DLLExportAttr>()) {
7039 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7040 M->isTrivial() &&
7044 M->dropAttr<DLLExportAttr>();
7045
7046 if (M->hasAttr<DLLExportAttr>()) {
7047 // Define after any fields with in-class initializers have been parsed.
7049 }
7050 }
7051
7052 bool EffectivelyConstexprDestructor = true;
7053 // Avoid triggering vtable instantiation due to a dtor that is not
7054 // "effectively constexpr" for better compatibility.
7055 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7056 if (isa<CXXDestructorDecl>(M)) {
7057 auto Check = [](QualType T, auto &&Check) -> bool {
7058 const CXXRecordDecl *RD =
7060 if (!RD || !RD->isCompleteDefinition())
7061 return true;
7062
7063 if (!RD->hasConstexprDestructor())
7064 return false;
7065
7066 QualType CanUnqualT = T.getCanonicalType().getUnqualifiedType();
7067 for (const CXXBaseSpecifier &B : RD->bases())
7068 if (B.getType().getCanonicalType().getUnqualifiedType() !=
7069 CanUnqualT &&
7070 !Check(B.getType(), Check))
7071 return false;
7072 for (const FieldDecl *FD : RD->fields())
7074 CanUnqualT &&
7075 !Check(FD->getType(), Check))
7076 return false;
7077 return true;
7078 };
7079 EffectivelyConstexprDestructor =
7080 Check(QualType(Record->getTypeForDecl(), 0), Check);
7081 }
7082
7083 // Define defaulted constexpr virtual functions that override a base class
7084 // function right away.
7085 // FIXME: We can defer doing this until the vtable is marked as used.
7086 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7087 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7088 EffectivelyConstexprDestructor)
7089 DefineDefaultedFunction(*this, M, M->getLocation());
7090
7091 if (!Incomplete)
7092 CheckCompletedMemberFunction(M);
7093 };
7094
7095 // Check the destructor before any other member function. We need to
7096 // determine whether it's trivial in order to determine whether the claas
7097 // type is a literal type, which is a prerequisite for determining whether
7098 // other special member functions are valid and whether they're implicitly
7099 // 'constexpr'.
7100 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7101 CompleteMemberFunction(Dtor);
7102
7103 bool HasMethodWithOverrideControl = false,
7104 HasOverridingMethodWithoutOverrideControl = false;
7105 for (auto *D : Record->decls()) {
7106 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7107 // FIXME: We could do this check for dependent types with non-dependent
7108 // bases.
7109 if (!Record->isDependentType()) {
7110 // See if a method overloads virtual methods in a base
7111 // class without overriding any.
7112 if (!M->isStatic())
7114 if (M->hasAttr<OverrideAttr>())
7115 HasMethodWithOverrideControl = true;
7116 else if (M->size_overridden_methods() > 0)
7117 HasOverridingMethodWithoutOverrideControl = true;
7118 }
7119
7120 if (!isa<CXXDestructorDecl>(M))
7121 CompleteMemberFunction(M);
7122 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7123 CheckForDefaultedFunction(
7124 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7125 }
7126 }
7127
7128 if (HasOverridingMethodWithoutOverrideControl) {
7129 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7130 for (auto *M : Record->methods())
7131 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7132 }
7133
7134 // Check the defaulted secondary comparisons after any other member functions.
7135 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7137
7138 // If this is a member function, we deferred checking it until now.
7139 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7140 CheckCompletedMemberFunction(MD);
7141 }
7142
7143 // ms_struct is a request to use the same ABI rules as MSVC. Check
7144 // whether this class uses any C++ features that are implemented
7145 // completely differently in MSVC, and if so, emit a diagnostic.
7146 // That diagnostic defaults to an error, but we allow projects to
7147 // map it down to a warning (or ignore it). It's a fairly common
7148 // practice among users of the ms_struct pragma to mass-annotate
7149 // headers, sweeping up a bunch of types that the project doesn't
7150 // really rely on MSVC-compatible layout for. We must therefore
7151 // support "ms_struct except for C++ stuff" as a secondary ABI.
7152 // Don't emit this diagnostic if the feature was enabled as a
7153 // language option (as opposed to via a pragma or attribute), as
7154 // the option -mms-bitfields otherwise essentially makes it impossible
7155 // to build C++ code, unless this diagnostic is turned off.
7156 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7157 (Record->isPolymorphic() || Record->getNumBases())) {
7158 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7159 }
7160
7163
7164 bool ClangABICompat4 =
7165 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7167 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7168 bool CanPass = canPassInRegisters(*this, Record, CCK);
7169
7170 // Do not change ArgPassingRestrictions if it has already been set to
7171 // RecordArgPassingKind::CanNeverPassInRegs.
7172 if (Record->getArgPassingRestrictions() !=
7174 Record->setArgPassingRestrictions(
7177
7178 // If canPassInRegisters returns true despite the record having a non-trivial
7179 // destructor, the record is destructed in the callee. This happens only when
7180 // the record or one of its subobjects has a field annotated with trivial_abi
7181 // or a field qualified with ObjC __strong/__weak.
7183 Record->setParamDestroyedInCallee(true);
7184 else if (Record->hasNonTrivialDestructor())
7185 Record->setParamDestroyedInCallee(CanPass);
7186
7187 if (getLangOpts().ForceEmitVTables) {
7188 // If we want to emit all the vtables, we need to mark it as used. This
7189 // is especially required for cases like vtable assumption loads.
7190 MarkVTableUsed(Record->getInnerLocStart(), Record);
7191 }
7192
7193 if (getLangOpts().CUDA) {
7194 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7196 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7198 }
7199}
7200
7201/// Look up the special member function that would be called by a special
7202/// member function for a subobject of class type.
7203///
7204/// \param Class The class type of the subobject.
7205/// \param CSM The kind of special member function.
7206/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7207/// \param ConstRHS True if this is a copy operation with a const object
7208/// on its RHS, that is, if the argument to the outer special member
7209/// function is 'const' and this is not a field marked 'mutable'.
7212 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7213 bool ConstRHS) {
7214 unsigned LHSQuals = 0;
7217 LHSQuals = FieldQuals;
7218
7219 unsigned RHSQuals = FieldQuals;
7222 RHSQuals = 0;
7223 else if (ConstRHS)
7224 RHSQuals |= Qualifiers::Const;
7225
7226 return S.LookupSpecialMember(Class, CSM,
7227 RHSQuals & Qualifiers::Const,
7228 RHSQuals & Qualifiers::Volatile,
7229 false,
7230 LHSQuals & Qualifiers::Const,
7231 LHSQuals & Qualifiers::Volatile);
7232}
7233
7235 Sema &S;
7236 SourceLocation UseLoc;
7237
7238 /// A mapping from the base classes through which the constructor was
7239 /// inherited to the using shadow declaration in that base class (or a null
7240 /// pointer if the constructor was declared in that base class).
7241 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7242 InheritedFromBases;
7243
7244public:
7247 : S(S), UseLoc(UseLoc) {
7248 bool DiagnosedMultipleConstructedBases = false;
7249 CXXRecordDecl *ConstructedBase = nullptr;
7250 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7251
7252 // Find the set of such base class subobjects and check that there's a
7253 // unique constructed subobject.
7254 for (auto *D : Shadow->redecls()) {
7255 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7256 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7257 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7258
7259 InheritedFromBases.insert(
7260 std::make_pair(DNominatedBase->getCanonicalDecl(),
7261 DShadow->getNominatedBaseClassShadowDecl()));
7262 if (DShadow->constructsVirtualBase())
7263 InheritedFromBases.insert(
7264 std::make_pair(DConstructedBase->getCanonicalDecl(),
7265 DShadow->getConstructedBaseClassShadowDecl()));
7266 else
7267 assert(DNominatedBase == DConstructedBase);
7268
7269 // [class.inhctor.init]p2:
7270 // If the constructor was inherited from multiple base class subobjects
7271 // of type B, the program is ill-formed.
7272 if (!ConstructedBase) {
7273 ConstructedBase = DConstructedBase;
7274 ConstructedBaseIntroducer = D->getIntroducer();
7275 } else if (ConstructedBase != DConstructedBase &&
7276 !Shadow->isInvalidDecl()) {
7277 if (!DiagnosedMultipleConstructedBases) {
7278 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7279 << Shadow->getTargetDecl();
7280 S.Diag(ConstructedBaseIntroducer->getLocation(),
7281 diag::note_ambiguous_inherited_constructor_using)
7282 << ConstructedBase;
7283 DiagnosedMultipleConstructedBases = true;
7284 }
7285 S.Diag(D->getIntroducer()->getLocation(),
7286 diag::note_ambiguous_inherited_constructor_using)
7287 << DConstructedBase;
7288 }
7289 }
7290
7291 if (DiagnosedMultipleConstructedBases)
7292 Shadow->setInvalidDecl();
7293 }
7294
7295 /// Find the constructor to use for inherited construction of a base class,
7296 /// and whether that base class constructor inherits the constructor from a
7297 /// virtual base class (in which case it won't actually invoke it).
7298 std::pair<CXXConstructorDecl *, bool>
7300 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7301 if (It == InheritedFromBases.end())
7302 return std::make_pair(nullptr, false);
7303
7304 // This is an intermediary class.
7305 if (It->second)
7306 return std::make_pair(
7307 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7308 It->second->constructsVirtualBase());
7309
7310 // This is the base class from which the constructor was inherited.
7311 return std::make_pair(Ctor, false);
7312 }
7313};
7314
7315/// Is the special member function which would be selected to perform the
7316/// specified operation on the specified class type a constexpr constructor?
7318 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7319 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7320 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7321 // Suppress duplicate constraint checking here, in case a constraint check
7322 // caused us to decide to do this. Any truely recursive checks will get
7323 // caught during these checks anyway.
7325
7326 // If we're inheriting a constructor, see if we need to call it for this base
7327 // class.
7328 if (InheritedCtor) {
7330 auto BaseCtor =
7331 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7332 if (BaseCtor)
7333 return BaseCtor->isConstexpr();
7334 }
7335
7337 return ClassDecl->hasConstexprDefaultConstructor();
7339 return ClassDecl->hasConstexprDestructor();
7340
7342 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7343 if (!SMOR.getMethod())
7344 // A constructor we wouldn't select can't be "involved in initializing"
7345 // anything.
7346 return true;
7347 return SMOR.getMethod()->isConstexpr();
7348}
7349
7350/// Determine whether the specified special member function would be constexpr
7351/// if it were implicitly defined.
7353 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7354 CXXConstructorDecl *InheritedCtor = nullptr,
7355 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7356 if (!S.getLangOpts().CPlusPlus11)
7357 return false;
7358
7359 // C++11 [dcl.constexpr]p4:
7360 // In the definition of a constexpr constructor [...]
7361 bool Ctor = true;
7362 switch (CSM) {
7364 if (Inherited)
7365 break;
7366 // Since default constructor lookup is essentially trivial (and cannot
7367 // involve, for instance, template instantiation), we compute whether a
7368 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7369 //
7370 // This is important for performance; we need to know whether the default
7371 // constructor is constexpr to determine whether the type is a literal type.
7372 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7373
7376 // For copy or move constructors, we need to perform overload resolution.
7377 break;
7378
7381 if (!S.getLangOpts().CPlusPlus14)
7382 return false;
7383 // In C++1y, we need to perform overload resolution.
7384 Ctor = false;
7385 break;
7386
7388 return ClassDecl->defaultedDestructorIsConstexpr();
7389
7391 return false;
7392 }
7393
7394 // -- if the class is a non-empty union, or for each non-empty anonymous
7395 // union member of a non-union class, exactly one non-static data member
7396 // shall be initialized; [DR1359]
7397 //
7398 // If we squint, this is guaranteed, since exactly one non-static data member
7399 // will be initialized (if the constructor isn't deleted), we just don't know
7400 // which one.
7401 if (Ctor && ClassDecl->isUnion())
7403 ? ClassDecl->hasInClassInitializer() ||
7404 !ClassDecl->hasVariantMembers()
7405 : true;
7406
7407 // -- the class shall not have any virtual base classes;
7408 if (Ctor && ClassDecl->getNumVBases())
7409 return false;
7410
7411 // C++1y [class.copy]p26:
7412 // -- [the class] is a literal type, and
7413 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7414 return false;
7415
7416 // -- every constructor involved in initializing [...] base class
7417 // sub-objects shall be a constexpr constructor;
7418 // -- the assignment operator selected to copy/move each direct base
7419 // class is a constexpr function, and
7420 if (!S.getLangOpts().CPlusPlus23) {
7421 for (const auto &B : ClassDecl->bases()) {
7422 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7423 if (!BaseType)
7424 continue;
7425 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7426 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7427 InheritedCtor, Inherited))
7428 return false;
7429 }
7430 }
7431
7432 // -- every constructor involved in initializing non-static data members
7433 // [...] shall be a constexpr constructor;
7434 // -- every non-static data member and base class sub-object shall be
7435 // initialized
7436 // -- for each non-static data member of X that is of class type (or array
7437 // thereof), the assignment operator selected to copy/move that member is
7438 // a constexpr function
7439 if (!S.getLangOpts().CPlusPlus23) {
7440 for (const auto *F : ClassDecl->fields()) {
7441 if (F->isInvalidDecl())
7442 continue;
7444 F->hasInClassInitializer())
7445 continue;
7446 QualType BaseType = S.Context.getBaseElementType(F->getType());
7447 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7448 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7449 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7450 BaseType.getCVRQualifiers(),
7451 ConstArg && !F->isMutable()))
7452 return false;
7453 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7454 return false;
7455 }
7456 }
7457 }
7458
7459 // All OK, it's constexpr!
7460 return true;
7461}
7462
7463namespace {
7464/// RAII object to register a defaulted function as having its exception
7465/// specification computed.
7466struct ComputingExceptionSpec {
7467 Sema &S;
7468
7469 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7470 : S(S) {
7473 Ctx.PointOfInstantiation = Loc;
7474 Ctx.Entity = FD;
7476 }
7477 ~ComputingExceptionSpec() {
7479 }
7480};
7481}
7482
7485 CXXMethodDecl *MD,
7488
7491 FunctionDecl *FD,
7493
7496 auto DFK = S.getDefaultedFunctionKind(FD);
7497 if (DFK.isSpecialMember())
7499 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7500 if (DFK.isComparison())
7502 DFK.asComparison());
7503
7504 auto *CD = cast<CXXConstructorDecl>(FD);
7505 assert(CD->getInheritedConstructor() &&
7506 "only defaulted functions and inherited constructors have implicit "
7507 "exception specs");
7509 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7512}
7513
7515 CXXMethodDecl *MD) {
7517
7518 // Build an exception specification pointing back at this member.
7520 EPI.ExceptionSpec.SourceDecl = MD;
7521
7522 // Set the calling convention to the default for C++ instance methods.
7524 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7525 /*IsCXXMethod=*/true));
7526 return EPI;
7527}
7528
7530 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7532 return;
7533
7534 // Evaluate the exception specification.
7535 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7536 auto ESI = IES.getExceptionSpec();
7537
7538 // Update the type of the special member to use it.
7539 UpdateExceptionSpec(FD, ESI);
7540}
7541
7543 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7544
7546 if (!DefKind) {
7547 assert(FD->getDeclContext()->isDependentContext());
7548 return;
7549 }
7550
7551 if (DefKind.isComparison()) {
7552 auto PT = FD->getParamDecl(0)->getType();
7553 if (const CXXRecordDecl *RD =
7554 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7555 for (FieldDecl *Field : RD->fields()) {
7556 UnusedPrivateFields.remove(Field);
7557 }
7558 }
7559 }
7560
7561 if (DefKind.isSpecialMember()
7562 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7563 DefKind.asSpecialMember(),
7564 FD->getDefaultLoc())
7566 FD->setInvalidDecl();
7567}
7568
7571 SourceLocation DefaultLoc) {
7572 CXXRecordDecl *RD = MD->getParent();
7573
7575 "not an explicitly-defaulted special member");
7576
7577 // Defer all checking for special members of a dependent type.
7578 if (RD->isDependentType())
7579 return false;
7580
7581 // Whether this was the first-declared instance of the constructor.
7582 // This affects whether we implicitly add an exception spec and constexpr.
7583 bool First = MD == MD->getCanonicalDecl();
7584
7585 bool HadError = false;
7586
7587 // C++11 [dcl.fct.def.default]p1:
7588 // A function that is explicitly defaulted shall
7589 // -- be a special member function [...] (checked elsewhere),
7590 // -- have the same type (except for ref-qualifiers, and except that a
7591 // copy operation can take a non-const reference) as an implicit
7592 // declaration, and
7593 // -- not have default arguments.
7594 // C++2a changes the second bullet to instead delete the function if it's
7595 // defaulted on its first declaration, unless it's "an assignment operator,
7596 // and its return type differs or its parameter type is not a reference".
7597 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7598 bool ShouldDeleteForTypeMismatch = false;
7599 unsigned ExpectedParams = 1;
7602 ExpectedParams = 0;
7603 if (MD->getNumExplicitParams() != ExpectedParams) {
7604 // This checks for default arguments: a copy or move constructor with a
7605 // default argument is classified as a default constructor, and assignment
7606 // operations and destructors can't have default arguments.
7607 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7608 << llvm::to_underlying(CSM) << MD->getSourceRange();
7609 HadError = true;
7610 } else if (MD->isVariadic()) {
7611 if (DeleteOnTypeMismatch)
7612 ShouldDeleteForTypeMismatch = true;
7613 else {
7614 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7615 << llvm::to_underlying(CSM) << MD->getSourceRange();
7616 HadError = true;
7617 }
7618 }
7619
7621
7622 bool CanHaveConstParam = false;
7624 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7626 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7627
7628 QualType ReturnType = Context.VoidTy;
7631 // Check for return type matching.
7632 ReturnType = Type->getReturnType();
7634
7635 QualType DeclType = Context.getTypeDeclType(RD);
7637 DeclType, nullptr);
7638 DeclType = Context.getAddrSpaceQualType(
7639 DeclType, ThisType.getQualifiers().getAddressSpace());
7640 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7641
7642 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7643 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7645 << ExpectedReturnType;
7646 HadError = true;
7647 }
7648
7649 // A defaulted special member cannot have cv-qualifiers.
7650 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7651 if (DeleteOnTypeMismatch)
7652 ShouldDeleteForTypeMismatch = true;
7653 else {
7654 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7656 << getLangOpts().CPlusPlus14;
7657 HadError = true;
7658 }
7659 }
7660 // [C++23][dcl.fct.def.default]/p2.2
7661 // if F2 has an implicit object parameter of type “reference to C”,
7662 // F1 may be an explicit object member function whose explicit object
7663 // parameter is of (possibly different) type “reference to C”,
7664 // in which case the type of F1 would differ from the type of F2
7665 // in that the type of F1 has an additional parameter;
7666 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7667 ? MD->getParamDecl(0)->getType()
7668 : QualType();
7669 if (!ExplicitObjectParameter.isNull() &&
7670 (!ExplicitObjectParameter->isReferenceType() ||
7671 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7672 Context.getRecordType(RD)))) {
7673 if (DeleteOnTypeMismatch)
7674 ShouldDeleteForTypeMismatch = true;
7675 else {
7676 Diag(MD->getLocation(),
7677 diag::err_defaulted_special_member_explicit_object_mismatch)
7678 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7679 << MD->getSourceRange();
7680 HadError = true;
7681 }
7682 }
7683 }
7684
7685 // Check for parameter type matching.
7686 QualType ArgType =
7687 ExpectedParams
7688 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7689 : QualType();
7690 bool HasConstParam = false;
7691 if (ExpectedParams && ArgType->isReferenceType()) {
7692 // Argument must be reference to possibly-const T.
7693 QualType ReferentType = ArgType->getPointeeType();
7694 HasConstParam = ReferentType.isConstQualified();
7695
7696 if (ReferentType.isVolatileQualified()) {
7697 if (DeleteOnTypeMismatch)
7698 ShouldDeleteForTypeMismatch = true;
7699 else {
7700 Diag(MD->getLocation(),
7701 diag::err_defaulted_special_member_volatile_param)
7702 << llvm::to_underlying(CSM);
7703 HadError = true;
7704 }
7705 }
7706
7707 if (HasConstParam && !CanHaveConstParam) {
7708 if (DeleteOnTypeMismatch)
7709 ShouldDeleteForTypeMismatch = true;
7710 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7712 Diag(MD->getLocation(),
7713 diag::err_defaulted_special_member_copy_const_param)
7715 // FIXME: Explain why this special member can't be const.
7716 HadError = true;
7717 } else {
7718 Diag(MD->getLocation(),
7719 diag::err_defaulted_special_member_move_const_param)
7721 HadError = true;
7722 }
7723 }
7724 } else if (ExpectedParams) {
7725 // A copy assignment operator can take its argument by value, but a
7726 // defaulted one cannot.
7728 "unexpected non-ref argument");
7729 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7730 HadError = true;
7731 }
7732
7733 // C++11 [dcl.fct.def.default]p2:
7734 // An explicitly-defaulted function may be declared constexpr only if it
7735 // would have been implicitly declared as constexpr,
7736 // Do not apply this rule to members of class templates, since core issue 1358
7737 // makes such functions always instantiate to constexpr functions. For
7738 // functions which cannot be constexpr (for non-constructors in C++11 and for
7739 // destructors in C++14 and C++17), this is checked elsewhere.
7740 //
7741 // FIXME: This should not apply if the member is deleted.
7742 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7743 HasConstParam);
7744
7745 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7746 // If the instantiated template specialization of a constexpr function
7747 // template or member function of a class template would fail to satisfy
7748 // the requirements for a constexpr function or constexpr constructor, that
7749 // specialization is still a constexpr function or constexpr constructor,
7750 // even though a call to such a function cannot appear in a constant
7751 // expression.
7752 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7753 Constexpr = true;
7754
7755 if ((getLangOpts().CPlusPlus20 ||
7756 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7757 : isa<CXXConstructorDecl>(MD))) &&
7758 MD->isConstexpr() && !Constexpr &&
7760 if (!MD->isConsteval() && RD->getNumVBases()) {
7761 Diag(MD->getBeginLoc(),
7762 diag::err_incorrect_defaulted_constexpr_with_vb)
7763 << llvm::to_underlying(CSM);
7764 for (const auto &I : RD->vbases())
7765 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7766 } else {
7767 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7768 << llvm::to_underlying(CSM) << MD->isConsteval();
7769 }
7770 HadError = true;
7771 // FIXME: Explain why the special member can't be constexpr.
7772 }
7773
7774 if (First) {
7775 // C++2a [dcl.fct.def.default]p3:
7776 // If a function is explicitly defaulted on its first declaration, it is
7777 // implicitly considered to be constexpr if the implicit declaration
7778 // would be.
7783
7784 if (!Type->hasExceptionSpec()) {
7785 // C++2a [except.spec]p3:
7786 // If a declaration of a function does not have a noexcept-specifier
7787 // [and] is defaulted on its first declaration, [...] the exception
7788 // specification is as specified below
7789 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7791 EPI.ExceptionSpec.SourceDecl = MD;
7792 MD->setType(
7793 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7794 }
7795 }
7796
7797 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7798 if (First) {
7799 SetDeclDeleted(MD, MD->getLocation());
7800 if (!inTemplateInstantiation() && !HadError) {
7801 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7802 << llvm::to_underlying(CSM);
7803 if (ShouldDeleteForTypeMismatch) {
7804 Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7805 << llvm::to_underlying(CSM);
7806 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7807 /*Diagnose*/ true) &&
7808 DefaultLoc.isValid()) {
7809 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7810 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7811 }
7812 }
7813 if (ShouldDeleteForTypeMismatch && !HadError) {
7814 Diag(MD->getLocation(),
7815 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7816 << llvm::to_underlying(CSM);
7817 }
7818 } else {
7819 // C++11 [dcl.fct.def.default]p4:
7820 // [For a] user-provided explicitly-defaulted function [...] if such a
7821 // function is implicitly defined as deleted, the program is ill-formed.
7822 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7823 << llvm::to_underlying(CSM);
7824 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7825 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7826 HadError = true;
7827 }
7828 }
7829
7830 return HadError;
7831}
7832
7833namespace {
7834/// Helper class for building and checking a defaulted comparison.
7835///
7836/// Defaulted functions are built in two phases:
7837///
7838/// * First, the set of operations that the function will perform are
7839/// identified, and some of them are checked. If any of the checked
7840/// operations is invalid in certain ways, the comparison function is
7841/// defined as deleted and no body is built.
7842/// * Then, if the function is not defined as deleted, the body is built.
7843///
7844/// This is accomplished by performing two visitation steps over the eventual
7845/// body of the function.
7846template<typename Derived, typename ResultList, typename Result,
7847 typename Subobject>
7848class DefaultedComparisonVisitor {
7849public:
7850 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7851
7852 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7853 DefaultedComparisonKind DCK)
7854 : S(S), RD(RD), FD(FD), DCK(DCK) {
7855 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7856 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7857 // UnresolvedSet to avoid this copy.
7858 Fns.assign(Info->getUnqualifiedLookups().begin(),
7859 Info->getUnqualifiedLookups().end());
7860 }
7861 }
7862
7863 ResultList visit() {
7864 // The type of an lvalue naming a parameter of this function.
7865 QualType ParamLvalType =
7867
7868 ResultList Results;
7869
7870 switch (DCK) {
7871 case DefaultedComparisonKind::None:
7872 llvm_unreachable("not a defaulted comparison");
7873
7874 case DefaultedComparisonKind::Equal:
7875 case DefaultedComparisonKind::ThreeWay:
7876 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7877 return Results;
7878
7879 case DefaultedComparisonKind::NotEqual:
7880 case DefaultedComparisonKind::Relational:
7881 Results.add(getDerived().visitExpandedSubobject(
7882 ParamLvalType, getDerived().getCompleteObject()));
7883 return Results;
7884 }
7885 llvm_unreachable("");
7886 }
7887
7888protected:
7889 Derived &getDerived() { return static_cast<Derived&>(*this); }
7890
7891 /// Visit the expanded list of subobjects of the given type, as specified in
7892 /// C++2a [class.compare.default].
7893 ///
7894 /// \return \c true if the ResultList object said we're done, \c false if not.
7895 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7896 Qualifiers Quals) {
7897 // C++2a [class.compare.default]p4:
7898 // The direct base class subobjects of C
7899 for (CXXBaseSpecifier &Base : Record->bases())
7900 if (Results.add(getDerived().visitSubobject(
7901 S.Context.getQualifiedType(Base.getType(), Quals),
7902 getDerived().getBase(&Base))))
7903 return true;
7904
7905 // followed by the non-static data members of C
7906 for (FieldDecl *Field : Record->fields()) {
7907 // C++23 [class.bit]p2:
7908 // Unnamed bit-fields are not members ...
7909 if (Field->isUnnamedBitField())
7910 continue;
7911 // Recursively expand anonymous structs.
7912 if (Field->isAnonymousStructOrUnion()) {
7913 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7914 Quals))
7915 return true;
7916 continue;
7917 }
7918
7919 // Figure out the type of an lvalue denoting this field.
7920 Qualifiers FieldQuals = Quals;
7921 if (Field->isMutable())
7922 FieldQuals.removeConst();
7923 QualType FieldType =
7924 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7925
7926 if (Results.add(getDerived().visitSubobject(
7927 FieldType, getDerived().getField(Field))))
7928 return true;
7929 }
7930
7931 // form a list of subobjects.
7932 return false;
7933 }
7934
7935 Result visitSubobject(QualType Type, Subobject Subobj) {
7936 // In that list, any subobject of array type is recursively expanded
7937 const ArrayType *AT = S.Context.getAsArrayType(Type);
7938 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7939 return getDerived().visitSubobjectArray(CAT->getElementType(),
7940 CAT->getSize(), Subobj);
7941 return getDerived().visitExpandedSubobject(Type, Subobj);
7942 }
7943
7944 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7945 Subobject Subobj) {
7946 return getDerived().visitSubobject(Type, Subobj);
7947 }
7948
7949protected:
7950 Sema &S;
7951 CXXRecordDecl *RD;
7952 FunctionDecl *FD;
7953 DefaultedComparisonKind DCK;
7955};
7956
7957/// Information about a defaulted comparison, as determined by
7958/// DefaultedComparisonAnalyzer.
7959struct DefaultedComparisonInfo {
7960 bool Deleted = false;
7961 bool Constexpr = true;
7962 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7963
7964 static DefaultedComparisonInfo deleted() {
7965 DefaultedComparisonInfo Deleted;
7966 Deleted.Deleted = true;
7967 return Deleted;
7968 }
7969
7970 bool add(const DefaultedComparisonInfo &R) {
7971 Deleted |= R.Deleted;
7972 Constexpr &= R.Constexpr;
7973 Category = commonComparisonType(Category, R.Category);
7974 return Deleted;
7975 }
7976};
7977
7978/// An element in the expanded list of subobjects of a defaulted comparison, as
7979/// specified in C++2a [class.compare.default]p4.
7980struct DefaultedComparisonSubobject {
7981 enum { CompleteObject, Member, Base } Kind;
7982 NamedDecl *Decl;
7984};
7985
7986/// A visitor over the notional body of a defaulted comparison that determines
7987/// whether that body would be deleted or constexpr.
7988class DefaultedComparisonAnalyzer
7989 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7990 DefaultedComparisonInfo,
7991 DefaultedComparisonInfo,
7992 DefaultedComparisonSubobject> {
7993public:
7994 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7995
7996private:
7997 DiagnosticKind Diagnose;
7998
7999public:
8000 using Base = DefaultedComparisonVisitor;
8001 using Result = DefaultedComparisonInfo;
8002 using Subobject = DefaultedComparisonSubobject;
8003
8004 friend Base;
8005
8006 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8007 DefaultedComparisonKind DCK,
8008 DiagnosticKind Diagnose = NoDiagnostics)
8009 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8010
8011 Result visit() {
8012 if ((DCK == DefaultedComparisonKind::Equal ||
8013 DCK == DefaultedComparisonKind::ThreeWay) &&
8014 RD->hasVariantMembers()) {
8015 // C++2a [class.compare.default]p2 [P2002R0]:
8016 // A defaulted comparison operator function for class C is defined as
8017 // deleted if [...] C has variant members.
8018 if (Diagnose == ExplainDeleted) {
8019 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8020 << FD << RD->isUnion() << RD;
8021 }
8022 return Result::deleted();
8023 }
8024
8025 return Base::visit();
8026 }
8027
8028private:
8029 Subobject getCompleteObject() {
8030 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8031 }
8032
8033 Subobject getBase(CXXBaseSpecifier *Base) {
8034 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8035 Base->getBaseTypeLoc()};
8036 }
8037
8038 Subobject getField(FieldDecl *Field) {
8039 return Subobject{Subobject::Member, Field, Field->getLocation()};
8040 }
8041
8042 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8043 // C++2a [class.compare.default]p2 [P2002R0]:
8044 // A defaulted <=> or == operator function for class C is defined as
8045 // deleted if any non-static data member of C is of reference type
8046 if (Type->isReferenceType()) {
8047 if (Diagnose == ExplainDeleted) {
8048 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8049 << FD << RD;
8050 }
8051 return Result::deleted();
8052 }
8053
8054 // [...] Let xi be an lvalue denoting the ith element [...]
8056 Expr *Args[] = {&Xi, &Xi};
8057
8058 // All operators start by trying to apply that same operator recursively.
8060 assert(OO != OO_None && "not an overloaded operator!");
8061 return visitBinaryOperator(OO, Args, Subobj);
8062 }
8063
8064 Result
8065 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8066 Subobject Subobj,
8067 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8068 // Note that there is no need to consider rewritten candidates here if
8069 // we've already found there is no viable 'operator<=>' candidate (and are
8070 // considering synthesizing a '<=>' from '==' and '<').
8071 OverloadCandidateSet CandidateSet(
8074 OO, FD->getLocation(),
8075 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8076
8077 /// C++2a [class.compare.default]p1 [P2002R0]:
8078 /// [...] the defaulted function itself is never a candidate for overload
8079 /// resolution [...]
8080 CandidateSet.exclude(FD);
8081
8082 if (Args[0]->getType()->isOverloadableType())
8083 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8084 else
8085 // FIXME: We determine whether this is a valid expression by checking to
8086 // see if there's a viable builtin operator candidate for it. That isn't
8087 // really what the rules ask us to do, but should give the right results.
8088 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8089
8090 Result R;
8091
8093 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8094 case OR_Success: {
8095 // C++2a [class.compare.secondary]p2 [P2002R0]:
8096 // The operator function [...] is defined as deleted if [...] the
8097 // candidate selected by overload resolution is not a rewritten
8098 // candidate.
8099 if ((DCK == DefaultedComparisonKind::NotEqual ||
8100 DCK == DefaultedComparisonKind::Relational) &&
8101 !Best->RewriteKind) {
8102 if (Diagnose == ExplainDeleted) {
8103 if (Best->Function) {
8104 S.Diag(Best->Function->getLocation(),
8105 diag::note_defaulted_comparison_not_rewritten_callee)
8106 << FD;
8107 } else {
8108 assert(Best->Conversions.size() == 2 &&
8109 Best->Conversions[0].isUserDefined() &&
8110 "non-user-defined conversion from class to built-in "
8111 "comparison");
8112 S.Diag(Best->Conversions[0]
8113 .UserDefined.FoundConversionFunction.getDecl()
8114 ->getLocation(),
8115 diag::note_defaulted_comparison_not_rewritten_conversion)
8116 << FD;
8117 }
8118 }
8119 return Result::deleted();
8120 }
8121
8122 // Throughout C++2a [class.compare]: if overload resolution does not
8123 // result in a usable function, the candidate function is defined as
8124 // deleted. This requires that we selected an accessible function.
8125 //
8126 // Note that this only considers the access of the function when named
8127 // within the type of the subobject, and not the access path for any
8128 // derived-to-base conversion.
8129 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8130 if (ArgClass && Best->FoundDecl.getDecl() &&
8131 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8132 QualType ObjectType = Subobj.Kind == Subobject::Member
8133 ? Args[0]->getType()
8134 : S.Context.getRecordType(RD);
8136 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8137 Diagnose == ExplainDeleted
8138 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8139 << FD << Subobj.Kind << Subobj.Decl
8140 : S.PDiag()))
8141 return Result::deleted();
8142 }
8143
8144 bool NeedsDeducing =
8145 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8146
8147 if (FunctionDecl *BestFD = Best->Function) {
8148 // C++2a [class.compare.default]p3 [P2002R0]:
8149 // A defaulted comparison function is constexpr-compatible if
8150 // [...] no overlod resolution performed [...] results in a
8151 // non-constexpr function.
8152 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8153 // If it's not constexpr, explain why not.
8154 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8155 if (Subobj.Kind != Subobject::CompleteObject)
8156 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8157 << Subobj.Kind << Subobj.Decl;
8158 S.Diag(BestFD->getLocation(),
8159 diag::note_defaulted_comparison_not_constexpr_here);
8160 // Bail out after explaining; we don't want any more notes.
8161 return Result::deleted();
8162 }
8163 R.Constexpr &= BestFD->isConstexpr();
8164
8165 if (NeedsDeducing) {
8166 // If any callee has an undeduced return type, deduce it now.
8167 // FIXME: It's not clear how a failure here should be handled. For
8168 // now, we produce an eager diagnostic, because that is forward
8169 // compatible with most (all?) other reasonable options.
8170 if (BestFD->getReturnType()->isUndeducedType() &&
8171 S.DeduceReturnType(BestFD, FD->getLocation(),
8172 /*Diagnose=*/false)) {
8173 // Don't produce a duplicate error when asked to explain why the
8174 // comparison is deleted: we diagnosed that when initially checking
8175 // the defaulted operator.
8176 if (Diagnose == NoDiagnostics) {
8177 S.Diag(
8178 FD->getLocation(),
8179 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8180 << Subobj.Kind << Subobj.Decl;
8181 S.Diag(
8182 Subobj.Loc,
8183 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8184 << Subobj.Kind << Subobj.Decl;
8185 S.Diag(BestFD->getLocation(),
8186 diag::note_defaulted_comparison_cannot_deduce_callee)
8187 << Subobj.Kind << Subobj.Decl;
8188 }
8189 return Result::deleted();
8190 }
8192 BestFD->getCallResultType());
8193 if (!Info) {
8194 if (Diagnose == ExplainDeleted) {
8195 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8196 << Subobj.Kind << Subobj.Decl
8197 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8198 S.Diag(BestFD->getLocation(),
8199 diag::note_defaulted_comparison_cannot_deduce_callee)
8200 << Subobj.Kind << Subobj.Decl;
8201 }
8202 return Result::deleted();
8203 }
8204 R.Category = Info->Kind;
8205 }
8206 } else {
8207 QualType T = Best->BuiltinParamTypes[0];
8208 assert(T == Best->BuiltinParamTypes[1] &&
8209 "builtin comparison for different types?");
8210 assert(Best->BuiltinParamTypes[2].isNull() &&
8211 "invalid builtin comparison");
8212
8213 if (NeedsDeducing) {
8214 std::optional<ComparisonCategoryType> Cat =
8216 assert(Cat && "no category for builtin comparison?");
8217 R.Category = *Cat;
8218 }
8219 }
8220
8221 // Note that we might be rewriting to a different operator. That call is
8222 // not considered until we come to actually build the comparison function.
8223 break;
8224 }
8225
8226 case OR_Ambiguous:
8227 if (Diagnose == ExplainDeleted) {
8228 unsigned Kind = 0;
8229 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8230 Kind = OO == OO_EqualEqual ? 1 : 2;
8231 CandidateSet.NoteCandidates(
8233 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8234 << FD << Kind << Subobj.Kind << Subobj.Decl),
8235 S, OCD_AmbiguousCandidates, Args);
8236 }
8237 R = Result::deleted();
8238 break;
8239
8240 case OR_Deleted:
8241 if (Diagnose == ExplainDeleted) {
8242 if ((DCK == DefaultedComparisonKind::NotEqual ||
8243 DCK == DefaultedComparisonKind::Relational) &&
8244 !Best->RewriteKind) {
8245 S.Diag(Best->Function->getLocation(),
8246 diag::note_defaulted_comparison_not_rewritten_callee)
8247 << FD;
8248 } else {
8249 S.Diag(Subobj.Loc,
8250 diag::note_defaulted_comparison_calls_deleted)
8251 << FD << Subobj.Kind << Subobj.Decl;
8252 S.NoteDeletedFunction(Best->Function);
8253 }
8254 }
8255 R = Result::deleted();
8256 break;
8257
8259 // If there's no usable candidate, we're done unless we can rewrite a
8260 // '<=>' in terms of '==' and '<'.
8261 if (OO == OO_Spaceship &&
8263 // For any kind of comparison category return type, we need a usable
8264 // '==' and a usable '<'.
8265 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8266 &CandidateSet)))
8267 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8268 break;
8269 }
8270
8271 if (Diagnose == ExplainDeleted) {
8272 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8273 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8274 << Subobj.Kind << Subobj.Decl;
8275
8276 // For a three-way comparison, list both the candidates for the
8277 // original operator and the candidates for the synthesized operator.
8278 if (SpaceshipCandidates) {
8279 SpaceshipCandidates->NoteCandidates(
8280 S, Args,
8281 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8282 Args, FD->getLocation()));
8283 S.Diag(Subobj.Loc,
8284 diag::note_defaulted_comparison_no_viable_function_synthesized)
8285 << (OO == OO_EqualEqual ? 0 : 1);
8286 }
8287
8288 CandidateSet.NoteCandidates(
8289 S, Args,
8290 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8291 FD->getLocation()));
8292 }
8293 R = Result::deleted();
8294 break;
8295 }
8296
8297 return R;
8298 }
8299};
8300
8301/// A list of statements.
8302struct StmtListResult {
8303 bool IsInvalid = false;
8305
8306 bool add(const StmtResult &S) {
8307 IsInvalid |= S.isInvalid();
8308 if (IsInvalid)
8309 return true;
8310 Stmts.push_back(S.get());
8311 return false;
8312 }
8313};
8314
8315/// A visitor over the notional body of a defaulted comparison that synthesizes
8316/// the actual body.
8317class DefaultedComparisonSynthesizer
8318 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8319 StmtListResult, StmtResult,
8320 std::pair<ExprResult, ExprResult>> {
8322 unsigned ArrayDepth = 0;
8323
8324public:
8325 using Base = DefaultedComparisonVisitor;
8326 using ExprPair = std::pair<ExprResult, ExprResult>;
8327
8328 friend Base;
8329
8330 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8331 DefaultedComparisonKind DCK,
8332 SourceLocation BodyLoc)
8333 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8334
8335 /// Build a suitable function body for this defaulted comparison operator.
8336 StmtResult build() {
8337 Sema::CompoundScopeRAII CompoundScope(S);
8338
8339 StmtListResult Stmts = visit();
8340 if (Stmts.IsInvalid)
8341 return StmtError();
8342
8343 ExprResult RetVal;
8344 switch (DCK) {
8345 case DefaultedComparisonKind::None:
8346 llvm_unreachable("not a defaulted comparison");
8347
8348 case DefaultedComparisonKind::Equal: {
8349 // C++2a [class.eq]p3:
8350 // [...] compar[e] the corresponding elements [...] until the first
8351 // index i where xi == yi yields [...] false. If no such index exists,
8352 // V is true. Otherwise, V is false.
8353 //
8354 // Join the comparisons with '&&'s and return the result. Use a right
8355 // fold (traversing the conditions right-to-left), because that
8356 // short-circuits more naturally.
8357 auto OldStmts = std::move(Stmts.Stmts);
8358 Stmts.Stmts.clear();
8359 ExprResult CmpSoFar;
8360 // Finish a particular comparison chain.
8361 auto FinishCmp = [&] {
8362 if (Expr *Prior = CmpSoFar.get()) {
8363 // Convert the last expression to 'return ...;'
8364 if (RetVal.isUnset() && Stmts.Stmts.empty())
8365 RetVal = CmpSoFar;
8366 // Convert any prior comparison to 'if (!(...)) return false;'
8367 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8368 return true;
8369 CmpSoFar = ExprResult();
8370 }
8371 return false;
8372 };
8373 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8374 Expr *E = dyn_cast<Expr>(EAsStmt);
8375 if (!E) {
8376 // Found an array comparison.
8377 if (FinishCmp() || Stmts.add(EAsStmt))
8378 return StmtError();
8379 continue;
8380 }
8381
8382 if (CmpSoFar.isUnset()) {
8383 CmpSoFar = E;
8384 continue;
8385 }
8386 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8387 if (CmpSoFar.isInvalid())
8388 return StmtError();
8389 }
8390 if (FinishCmp())
8391 return StmtError();
8392 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8393 // If no such index exists, V is true.
8394 if (RetVal.isUnset())
8395 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8396 break;
8397 }
8398
8399 case DefaultedComparisonKind::ThreeWay: {
8400 // Per C++2a [class.spaceship]p3, as a fallback add:
8401 // return static_cast<R>(std::strong_ordering::equal);
8403 ComparisonCategoryType::StrongOrdering, Loc,
8404 Sema::ComparisonCategoryUsage::DefaultedOperator);
8405 if (StrongOrdering.isNull())
8406 return StmtError();
8408 .getValueInfo(ComparisonCategoryResult::Equal)
8409 ->VD;
8410 RetVal = getDecl(EqualVD);
8411 if (RetVal.isInvalid())
8412 return StmtError();
8413 RetVal = buildStaticCastToR(RetVal.get());
8414 break;
8415 }
8416
8417 case DefaultedComparisonKind::NotEqual:
8418 case DefaultedComparisonKind::Relational:
8419 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8420 break;
8421 }
8422
8423 // Build the final return statement.
8424 if (RetVal.isInvalid())
8425 return StmtError();
8427 if (ReturnStmt.isInvalid())
8428 return StmtError();
8429 Stmts.Stmts.push_back(ReturnStmt.get());
8430
8431 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8432 }
8433
8434private:
8435 ExprResult getDecl(ValueDecl *VD) {
8436 return S.BuildDeclarationNameExpr(
8438 }
8439
8440 ExprResult getParam(unsigned I) {
8441 ParmVarDecl *PD = FD->getParamDecl(I);
8442 return getDecl(PD);
8443 }
8444
8445 ExprPair getCompleteObject() {
8446 unsigned Param = 0;
8447 ExprResult LHS;
8448 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8449 MD && MD->isImplicitObjectMemberFunction()) {
8450 // LHS is '*this'.
8451 LHS = S.ActOnCXXThis(Loc);
8452 if (!LHS.isInvalid())
8453 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8454 } else {
8455 LHS = getParam(Param++);
8456 }
8457 ExprResult RHS = getParam(Param++);
8458 assert(Param == FD->getNumParams());
8459 return {LHS, RHS};
8460 }
8461
8462 ExprPair getBase(CXXBaseSpecifier *Base) {
8463 ExprPair Obj = getCompleteObject();
8464 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8465 return {ExprError(), ExprError()};
8466 CXXCastPath Path = {Base};
8467 const auto CastToBase = [&](Expr *E) {
8469 Base->getType(), E->getType().getQualifiers());
8470 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8471 };
8472 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8473 }
8474
8475 ExprPair getField(FieldDecl *Field) {
8476 ExprPair Obj = getCompleteObject();
8477 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8478 return {ExprError(), ExprError()};
8479
8480 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8481 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8482 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8483 CXXScopeSpec(), Field, Found, NameInfo),
8484 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8485 CXXScopeSpec(), Field, Found, NameInfo)};
8486 }
8487
8488 // FIXME: When expanding a subobject, register a note in the code synthesis
8489 // stack to say which subobject we're comparing.
8490
8491 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8492 if (Cond.isInvalid())
8493 return StmtError();
8494
8495 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8496 if (NotCond.isInvalid())
8497 return StmtError();
8498
8499 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8500 assert(!False.isInvalid() && "should never fail");
8501 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8502 if (ReturnFalse.isInvalid())
8503 return StmtError();
8504
8505 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8506 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8507 Sema::ConditionKind::Boolean),
8508 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8509 }
8510
8511 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8512 ExprPair Subobj) {
8513 QualType SizeType = S.Context.getSizeType();
8514 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8515
8516 // Build 'size_t i$n = 0'.
8517 IdentifierInfo *IterationVarName = nullptr;
8518 {
8519 SmallString<8> Str;
8520 llvm::raw_svector_ostream OS(Str);
8521 OS << "i" << ArrayDepth;
8522 IterationVarName = &S.Context.Idents.get(OS.str());
8523 }
8524 VarDecl *IterationVar = VarDecl::Create(
8525 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8527 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8528 IterationVar->setInit(
8529 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8530 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8531
8532 auto IterRef = [&] {
8534 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8535 IterationVar);
8536 assert(!Ref.isInvalid() && "can't reference our own variable?");
8537 return Ref.get();
8538 };
8539
8540 // Build 'i$n != Size'.
8542 Loc, BO_NE, IterRef(),
8543 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8544 assert(!Cond.isInvalid() && "should never fail");
8545
8546 // Build '++i$n'.
8547 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8548 assert(!Inc.isInvalid() && "should never fail");
8549
8550 // Build 'a[i$n]' and 'b[i$n]'.
8551 auto Index = [&](ExprResult E) {
8552 if (E.isInvalid())
8553 return ExprError();
8554 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8555 };
8556 Subobj.first = Index(Subobj.first);
8557 Subobj.second = Index(Subobj.second);
8558
8559 // Compare the array elements.
8560 ++ArrayDepth;
8561 StmtResult Substmt = visitSubobject(Type, Subobj);
8562 --ArrayDepth;
8563
8564 if (Substmt.isInvalid())
8565 return StmtError();
8566
8567 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8568 // For outer levels or for an 'operator<=>' we already have a suitable
8569 // statement that returns as necessary.
8570 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8571 assert(DCK == DefaultedComparisonKind::Equal &&
8572 "should have non-expression statement");
8573 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8574 if (Substmt.isInvalid())
8575 return StmtError();
8576 }
8577
8578 // Build 'for (...) ...'
8579 return S.ActOnForStmt(Loc, Loc, Init,
8580 S.ActOnCondition(nullptr, Loc, Cond.get(),
8581 Sema::ConditionKind::Boolean),
8583 Substmt.get());
8584 }
8585
8586 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8587 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8588 return StmtError();
8589
8592 ExprResult Op;
8593 if (Type->isOverloadableType())
8594 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8595 Obj.second.get(), /*PerformADL=*/true,
8596 /*AllowRewrittenCandidates=*/true, FD);
8597 else
8598 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8599 if (Op.isInvalid())
8600 return StmtError();
8601
8602 switch (DCK) {
8603 case DefaultedComparisonKind::None:
8604 llvm_unreachable("not a defaulted comparison");
8605
8606 case DefaultedComparisonKind::Equal:
8607 // Per C++2a [class.eq]p2, each comparison is individually contextually
8608 // converted to bool.
8610 if (Op.isInvalid())
8611 return StmtError();
8612 return Op.get();
8613
8614 case DefaultedComparisonKind::ThreeWay: {
8615 // Per C++2a [class.spaceship]p3, form:
8616 // if (R cmp = static_cast<R>(op); cmp != 0)
8617 // return cmp;
8618 QualType R = FD->getReturnType();
8619 Op = buildStaticCastToR(Op.get());
8620 if (Op.isInvalid())
8621 return StmtError();
8622
8623 // R cmp = ...;
8624 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8625 VarDecl *VD =
8626 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8628 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8629 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8630
8631 // cmp != 0
8632 ExprResult VDRef = getDecl(VD);
8633 if (VDRef.isInvalid())
8634 return StmtError();
8635 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8636 Expr *Zero =
8639 if (VDRef.get()->getType()->isOverloadableType())
8640 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8641 true, FD);
8642 else
8643 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8644 if (Comp.isInvalid())
8645 return StmtError();
8647 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8648 if (Cond.isInvalid())
8649 return StmtError();
8650
8651 // return cmp;
8652 VDRef = getDecl(VD);
8653 if (VDRef.isInvalid())
8654 return StmtError();
8656 if (ReturnStmt.isInvalid())
8657 return StmtError();
8658
8659 // if (...)
8660 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8661 Loc, ReturnStmt.get(),
8662 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8663 }
8664
8665 case DefaultedComparisonKind::NotEqual:
8666 case DefaultedComparisonKind::Relational:
8667 // C++2a [class.compare.secondary]p2:
8668 // Otherwise, the operator function yields x @ y.
8669 return Op.get();
8670 }
8671 llvm_unreachable("");
8672 }
8673
8674 /// Build "static_cast<R>(E)".
8675 ExprResult buildStaticCastToR(Expr *E) {
8676 QualType R = FD->getReturnType();
8677 assert(!R->isUndeducedType() && "type should have been deduced already");
8678
8679 // Don't bother forming a no-op cast in the common case.
8680 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8681 return E;
8682 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8685 }
8686};
8687}
8688
8689/// Perform the unqualified lookups that might be needed to form a defaulted
8690/// comparison function for the given operator.
8692 UnresolvedSetImpl &Operators,
8694 auto Lookup = [&](OverloadedOperatorKind OO) {
8695 Self.LookupOverloadedOperatorName(OO, S, Operators);
8696 };
8697
8698 // Every defaulted operator looks up itself.
8699 Lookup(Op);
8700 // ... and the rewritten form of itself, if any.
8702 Lookup(ExtraOp);
8703
8704 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8705 // synthesize a three-way comparison from '<' and '=='. In a dependent
8706 // context, we also need to look up '==' in case we implicitly declare a
8707 // defaulted 'operator=='.
8708 if (Op == OO_Spaceship) {
8709 Lookup(OO_ExclaimEqual);
8710 Lookup(OO_Less);
8711 Lookup(OO_EqualEqual);
8712 }
8713}
8714
8717 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8718
8719 // Perform any unqualified lookups we're going to need to default this
8720 // function.
8721 if (S) {
8722 UnresolvedSet<32> Operators;
8723 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8724 FD->getOverloadedOperator());
8727 Context, Operators.pairs()));
8728 }
8729
8730 // C++2a [class.compare.default]p1:
8731 // A defaulted comparison operator function for some class C shall be a
8732 // non-template function declared in the member-specification of C that is
8733 // -- a non-static const non-volatile member of C having one parameter of
8734 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8735 // -- a friend of C having two parameters of type const C& or two
8736 // parameters of type C.
8737
8738 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8739 bool IsMethod = isa<CXXMethodDecl>(FD);
8740 if (IsMethod) {
8741 auto *MD = cast<CXXMethodDecl>(FD);
8742 assert(!MD->isStatic() && "comparison function cannot be a static member");
8743
8744 if (MD->getRefQualifier() == RQ_RValue) {
8745 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8746
8747 // Remove the ref qualifier to recover.
8748 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8749 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8750 EPI.RefQualifier = RQ_None;
8751 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8752 FPT->getParamTypes(), EPI));
8753 }
8754
8755 // If we're out-of-class, this is the class we're comparing.
8756 if (!RD)
8757 RD = MD->getParent();
8759 if (!T.getNonReferenceType().isConstQualified() &&
8761 SourceLocation Loc, InsertLoc;
8763 Loc = MD->getParamDecl(0)->getBeginLoc();
8764 InsertLoc = getLocForEndOfToken(
8766 } else {
8767 Loc = MD->getLocation();
8769 InsertLoc = Loc.getRParenLoc();
8770 }
8771 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8772 // corresponding defaulted 'operator<=>' already.
8773 if (!MD->isImplicit()) {
8774 Diag(Loc, diag::err_defaulted_comparison_non_const)
8775 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8776 }
8777
8778 // Add the 'const' to the type to recover.
8780 assert(T->isLValueReferenceType());
8782 T.getNonReferenceType().withConst()));
8783 } else {
8784 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8785 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8786 EPI.TypeQuals.addConst();
8787 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8788 FPT->getParamTypes(), EPI));
8789 }
8790 }
8791
8792 if (MD->isVolatile()) {
8793 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8794
8795 // Remove the 'volatile' from the type to recover.
8796 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8797 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8799 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8800 FPT->getParamTypes(), EPI));
8801 }
8802 }
8803
8804 if ((FD->getNumParams() -
8805 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8806 (IsMethod ? 1 : 2)) {
8807 // Let's not worry about using a variadic template pack here -- who would do
8808 // such a thing?
8809 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8810 << int(IsMethod) << int(DCK);
8811 return true;
8812 }
8813
8814 const ParmVarDecl *KnownParm = nullptr;
8815 for (const ParmVarDecl *Param : FD->parameters()) {
8816 QualType ParmTy = Param->getType();
8817 if (!KnownParm) {
8818 auto CTy = ParmTy;
8819 // Is it `T const &`?
8820 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
8821 QualType ExpectedTy;
8822 if (RD)
8823 ExpectedTy = Context.getRecordType(RD);
8824 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
8825 CTy = Ref->getPointeeType();
8826 if (RD)
8827 ExpectedTy.addConst();
8828 Ok = true;
8829 }
8830
8831 // Is T a class?
8832 if (RD) {
8833 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
8834 } else {
8835 RD = CTy->getAsCXXRecordDecl();
8836 Ok &= RD != nullptr;
8837 }
8838
8839 if (Ok) {
8840 KnownParm = Param;
8841 } else {
8842 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8843 // corresponding defaulted 'operator<=>' already.
8844 if (!FD->isImplicit()) {
8845 if (RD) {
8846 QualType PlainTy = Context.getRecordType(RD);
8847 QualType RefTy =
8849 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8850 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8851 << Param->getSourceRange();
8852 } else {
8853 assert(!IsMethod && "should know expected type for method");
8854 Diag(FD->getLocation(),
8855 diag::err_defaulted_comparison_param_unknown)
8856 << int(DCK) << ParmTy << Param->getSourceRange();
8857 }
8858 }
8859 return true;
8860 }
8861 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8862 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8863 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8864 << ParmTy << Param->getSourceRange();
8865 return true;
8866 }
8867 }
8868
8869 assert(RD && "must have determined class");
8870 if (IsMethod) {
8871 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8872 // In-class, must be a friend decl.
8873 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8874 } else {
8875 // Out of class, require the defaulted comparison to be a friend (of a
8876 // complete type, per CWG2547).
8878 diag::err_defaulted_comparison_not_friend, int(DCK),
8879 int(1)))
8880 return true;
8881
8882 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8883 return FD->getCanonicalDecl() ==
8884 F->getFriendDecl()->getCanonicalDecl();
8885 })) {
8886 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8887 << int(DCK) << int(0) << RD;
8888 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8889 return true;
8890 }
8891 }
8892
8893 // C++2a [class.eq]p1, [class.rel]p1:
8894 // A [defaulted comparison other than <=>] shall have a declared return
8895 // type bool.
8899 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8900 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8901 << FD->getReturnTypeSourceRange();
8902 return true;
8903 }
8904 // C++2a [class.spaceship]p2 [P2002R0]:
8905 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8906 // R shall not contain a placeholder type.
8907 if (QualType RT = FD->getDeclaredReturnType();
8909 RT->getContainedDeducedType() &&
8911 RT->getContainedAutoType()->isConstrained())) {
8912 Diag(FD->getLocation(),
8913 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8914 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8915 << FD->getReturnTypeSourceRange();
8916 return true;
8917 }
8918
8919 // For a defaulted function in a dependent class, defer all remaining checks
8920 // until instantiation.
8921 if (RD->isDependentType())
8922 return false;
8923
8924 // Determine whether the function should be defined as deleted.
8925 DefaultedComparisonInfo Info =
8926 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8927
8928 bool First = FD == FD->getCanonicalDecl();
8929
8930 if (!First) {
8931 if (Info.Deleted) {
8932 // C++11 [dcl.fct.def.default]p4:
8933 // [For a] user-provided explicitly-defaulted function [...] if such a
8934 // function is implicitly defined as deleted, the program is ill-formed.
8935 //
8936 // This is really just a consequence of the general rule that you can
8937 // only delete a function on its first declaration.
8938 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8939 << FD->isImplicit() << (int)DCK;
8940 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8941 DefaultedComparisonAnalyzer::ExplainDeleted)
8942 .visit();
8943 return true;
8944 }
8945 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8946 // C++20 [class.compare.default]p1:
8947 // [...] A definition of a comparison operator as defaulted that appears
8948 // in a class shall be the first declaration of that function.
8949 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8950 << (int)DCK;
8952 diag::note_previous_declaration);
8953 return true;
8954 }
8955 }
8956
8957 // If we want to delete the function, then do so; there's nothing else to
8958 // check in that case.
8959 if (Info.Deleted) {
8960 SetDeclDeleted(FD, FD->getLocation());
8961 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8962 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8963 << (int)DCK;
8964 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8965 DefaultedComparisonAnalyzer::ExplainDeleted)
8966 .visit();
8967 if (FD->getDefaultLoc().isValid())
8968 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8969 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8970 }
8971 return false;
8972 }
8973
8974 // C++2a [class.spaceship]p2:
8975 // The return type is deduced as the common comparison type of R0, R1, ...
8979 if (RetLoc.isInvalid())
8980 RetLoc = FD->getBeginLoc();
8981 // FIXME: Should we really care whether we have the complete type and the
8982 // 'enumerator' constants here? A forward declaration seems sufficient.
8984 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8985 if (Cat.isNull())
8986 return true;
8988 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8989 }
8990
8991 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8992 // An explicitly-defaulted function that is not defined as deleted may be
8993 // declared constexpr or consteval only if it is constexpr-compatible.
8994 // C++2a [class.compare.default]p3 [P2002R0]:
8995 // A defaulted comparison function is constexpr-compatible if it satisfies
8996 // the requirements for a constexpr function [...]
8997 // The only relevant requirements are that the parameter and return types are
8998 // literal types. The remaining conditions are checked by the analyzer.
8999 //
9000 // We support P2448R2 in language modes earlier than C++23 as an extension.
9001 // The concept of constexpr-compatible was removed.
9002 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9003 // A function explicitly defaulted on its first declaration is implicitly
9004 // inline, and is implicitly constexpr if it is constexpr-suitable.
9005 // C++23 [dcl.constexpr]p3
9006 // A function is constexpr-suitable if
9007 // - it is not a coroutine, and
9008 // - if the function is a constructor or destructor, its class does not
9009 // have any virtual base classes.
9010 if (FD->isConstexpr()) {
9011 if (!getLangOpts().CPlusPlus23 &&
9014 !Info.Constexpr) {
9015 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9016 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9017 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9018 DefaultedComparisonAnalyzer::ExplainConstexpr)
9019 .visit();
9020 }
9021 }
9022
9023 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9024 // If a constexpr-compatible function is explicitly defaulted on its first
9025 // declaration, it is implicitly considered to be constexpr.
9026 // FIXME: Only applying this to the first declaration seems problematic, as
9027 // simple reorderings can affect the meaning of the program.
9028 if (First && !FD->isConstexpr() && Info.Constexpr)
9030
9031 // C++2a [except.spec]p3:
9032 // If a declaration of a function does not have a noexcept-specifier
9033 // [and] is defaulted on its first declaration, [...] the exception
9034 // specification is as specified below
9035 if (FD->getExceptionSpecType() == EST_None) {
9036 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9037 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9039 EPI.ExceptionSpec.SourceDecl = FD;
9040 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9041 FPT->getParamTypes(), EPI));
9042 }
9043
9044 return false;
9045}
9046
9048 FunctionDecl *Spaceship) {
9051 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9052 Ctx.Entity = Spaceship;
9054
9055 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9056 EqualEqual->setImplicit();
9057
9059}
9060
9063 assert(FD->isDefaulted() && !FD->isDeleted() &&
9065 if (FD->willHaveBody() || FD->isInvalidDecl())
9066 return;
9067
9069
9070 // Add a context note for diagnostics produced after this point.
9071 Scope.addContextNote(UseLoc);
9072
9073 {
9074 // Build and set up the function body.
9075 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9076 // the type of the class being compared.
9077 auto PT = FD->getParamDecl(0)->getType();
9078 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9079 SourceLocation BodyLoc =
9080 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9081 StmtResult Body =
9082 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9083 if (Body.isInvalid()) {
9084 FD->setInvalidDecl();
9085 return;
9086 }
9087 FD->setBody(Body.get());
9088 FD->markUsed(Context);
9089 }
9090
9091 // The exception specification is needed because we are defining the
9092 // function. Note that this will reuse the body we just built.
9094
9096 L->CompletedImplicitDefinition(FD);
9097}
9098
9101 FunctionDecl *FD,
9103 ComputingExceptionSpec CES(S, FD, Loc);
9105
9106 if (FD->isInvalidDecl())
9107 return ExceptSpec;
9108
9109 // The common case is that we just defined the comparison function. In that
9110 // case, just look at whether the body can throw.
9111 if (FD->hasBody()) {
9112 ExceptSpec.CalledStmt(FD->getBody());
9113 } else {
9114 // Otherwise, build a body so we can check it. This should ideally only
9115 // happen when we're not actually marking the function referenced. (This is
9116 // only really important for efficiency: we don't want to build and throw
9117 // away bodies for comparison functions more than we strictly need to.)
9118
9119 // Pretend to synthesize the function body in an unevaluated context.
9120 // Note that we can't actually just go ahead and define the function here:
9121 // we are not permitted to mark its callees as referenced.
9125
9126 CXXRecordDecl *RD =
9127 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9128 ? FD->getDeclContext()
9129 : FD->getLexicalDeclContext());
9130 SourceLocation BodyLoc =
9131 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9132 StmtResult Body =
9133 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9134 if (!Body.isInvalid())
9135 ExceptSpec.CalledStmt(Body.get());
9136
9137 // FIXME: Can we hold onto this body and just transform it to potentially
9138 // evaluated when we're asked to define the function rather than rebuilding
9139 // it? Either that, or we should only build the bits of the body that we
9140 // need (the expressions, not the statements).
9141 }
9142
9143 return ExceptSpec;
9144}
9145
9147 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9149
9150 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9152
9153 // Perform any deferred checking of exception specifications for virtual
9154 // destructors.
9155 for (auto &Check : Overriding)
9156 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9157
9158 // Perform any deferred checking of exception specifications for befriended
9159 // special members.
9160 for (auto &Check : Equivalent)
9161 CheckEquivalentExceptionSpec(Check.second, Check.first);
9162}
9163
9164namespace {
9165/// CRTP base class for visiting operations performed by a special member
9166/// function (or inherited constructor).
9167template<typename Derived>
9168struct SpecialMemberVisitor {
9169 Sema &S;
9170 CXXMethodDecl *MD;
9173
9174 // Properties of the special member, computed for convenience.
9175 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9176
9177 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9179 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9180 switch (CSM) {
9181 case CXXSpecialMemberKind::DefaultConstructor:
9182 case CXXSpecialMemberKind::CopyConstructor:
9183 case CXXSpecialMemberKind::MoveConstructor:
9184 IsConstructor = true;
9185 break;
9186 case CXXSpecialMemberKind::CopyAssignment:
9187 case CXXSpecialMemberKind::MoveAssignment:
9188 IsAssignment = true;
9189 break;
9190 case CXXSpecialMemberKind::Destructor:
9191 break;
9192 case CXXSpecialMemberKind::Invalid:
9193 llvm_unreachable("invalid special member kind");
9194 }
9195
9196 if (MD->getNumExplicitParams()) {
9197 if (const ReferenceType *RT =
9199 ConstArg = RT->getPointeeType().isConstQualified();
9200 }
9201 }
9202
9203 Derived &getDerived() { return static_cast<Derived&>(*this); }
9204
9205 /// Is this a "move" special member?
9206 bool isMove() const {
9207 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9208 CSM == CXXSpecialMemberKind::MoveAssignment;
9209 }
9210
9211 /// Look up the corresponding special member in the given class.
9213 unsigned Quals, bool IsMutable) {
9214 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9215 ConstArg && !IsMutable);
9216 }
9217
9218 /// Look up the constructor for the specified base class to see if it's
9219 /// overridden due to this being an inherited constructor.
9220 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9221 if (!ICI)
9222 return {};
9223 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9224 auto *BaseCtor =
9225 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9226 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9227 return MD;
9228 return {};
9229 }
9230
9231 /// A base or member subobject.
9232 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9233
9234 /// Get the location to use for a subobject in diagnostics.
9235 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9236 // FIXME: For an indirect virtual base, the direct base leading to
9237 // the indirect virtual base would be a more useful choice.
9238 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9239 return B->getBaseTypeLoc();
9240 else
9241 return cast<FieldDecl *>(Subobj)->getLocation();
9242 }
9243
9244 enum BasesToVisit {
9245 /// Visit all non-virtual (direct) bases.
9246 VisitNonVirtualBases,
9247 /// Visit all direct bases, virtual or not.
9248 VisitDirectBases,
9249 /// Visit all non-virtual bases, and all virtual bases if the class
9250 /// is not abstract.
9251 VisitPotentiallyConstructedBases,
9252 /// Visit all direct or virtual bases.
9253 VisitAllBases
9254 };
9255
9256 // Visit the bases and members of the class.
9257 bool visit(BasesToVisit Bases) {
9258 CXXRecordDecl *RD = MD->getParent();
9259
9260 if (Bases == VisitPotentiallyConstructedBases)
9261 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9262
9263 for (auto &B : RD->bases())
9264 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9265 getDerived().visitBase(&B))
9266 return true;
9267
9268 if (Bases == VisitAllBases)
9269 for (auto &B : RD->vbases())
9270 if (getDerived().visitBase(&B))
9271 return true;
9272
9273 for (auto *F : RD->fields())
9274 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9275 getDerived().visitField(F))
9276 return true;
9277
9278 return false;
9279 }
9280};
9281}
9282
9283namespace {
9284struct SpecialMemberDeletionInfo
9285 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9286 bool Diagnose;
9287
9289
9290 bool AllFieldsAreConst;
9291
9292 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9294 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9295 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9296 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9297
9298 bool inUnion() const { return MD->getParent()->isUnion(); }
9299
9300 CXXSpecialMemberKind getEffectiveCSM() {
9301 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9302 }
9303
9304 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9305
9306 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9307 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9308
9309 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9310 bool shouldDeleteForField(FieldDecl *FD);
9311 bool shouldDeleteForAllConstMembers();
9312
9313 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9314 unsigned Quals);
9315 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9317 bool IsDtorCallInCtor);
9318
9319 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9320};
9321}
9322
9323/// Is the given special member inaccessible when used on the given
9324/// sub-object.
9325bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9326 CXXMethodDecl *target) {
9327 /// If we're operating on a base class, the object type is the
9328 /// type of this special member.
9329 QualType objectTy;
9330 AccessSpecifier access = target->getAccess();
9331 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9332 objectTy = S.Context.getTypeDeclType(MD->getParent());
9333 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9334
9335 // If we're operating on a field, the object type is the type of the field.
9336 } else {
9337 objectTy = S.Context.getTypeDeclType(target->getParent());
9338 }
9339
9341 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9342}
9343
9344/// Check whether we should delete a special member due to the implicit
9345/// definition containing a call to a special member of a subobject.
9346bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9347 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9348 bool IsDtorCallInCtor) {
9349 CXXMethodDecl *Decl = SMOR.getMethod();
9350 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9351
9352 int DiagKind = -1;
9353
9355 DiagKind = !Decl ? 0 : 1;
9357 DiagKind = 2;
9358 else if (!isAccessible(Subobj, Decl))
9359 DiagKind = 3;
9360 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9361 !Decl->isTrivial()) {
9362 // A member of a union must have a trivial corresponding special member.
9363 // As a weird special case, a destructor call from a union's constructor
9364 // must be accessible and non-deleted, but need not be trivial. Such a
9365 // destructor is never actually called, but is semantically checked as
9366 // if it were.
9368 // [class.default.ctor]p2:
9369 // A defaulted default constructor for class X is defined as deleted if
9370 // - X is a union that has a variant member with a non-trivial default
9371 // constructor and no variant member of X has a default member
9372 // initializer
9373 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9374 if (!RD->hasInClassInitializer())
9375 DiagKind = 4;
9376 } else {
9377 DiagKind = 4;
9378 }
9379 }
9380
9381 if (DiagKind == -1)
9382 return false;
9383
9384 if (Diagnose) {
9385 if (Field) {
9386 S.Diag(Field->getLocation(),
9387 diag::note_deleted_special_member_class_subobject)
9388 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9389 << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9390 << /*IsObjCPtr*/ false;
9391 } else {
9392 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9393 S.Diag(Base->getBeginLoc(),
9394 diag::note_deleted_special_member_class_subobject)
9395 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9396 << /*IsField*/ false << Base->getType() << DiagKind
9397 << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9398 }
9399
9400 if (DiagKind == 1)
9402 // FIXME: Explain inaccessibility if DiagKind == 3.
9403 }
9404
9405 return true;
9406}
9407
9408/// Check whether we should delete a special member function due to having a
9409/// direct or virtual base class or non-static data member of class type M.
9410bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9411 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9412 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9413 bool IsMutable = Field && Field->isMutable();
9414
9415 // C++11 [class.ctor]p5:
9416 // -- any direct or virtual base class, or non-static data member with no
9417 // brace-or-equal-initializer, has class type M (or array thereof) and
9418 // either M has no default constructor or overload resolution as applied
9419 // to M's default constructor results in an ambiguity or in a function
9420 // that is deleted or inaccessible
9421 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9422 // -- a direct or virtual base class B that cannot be copied/moved because
9423 // overload resolution, as applied to B's corresponding special member,
9424 // results in an ambiguity or a function that is deleted or inaccessible
9425 // from the defaulted special member
9426 // C++11 [class.dtor]p5:
9427 // -- any direct or virtual base class [...] has a type with a destructor
9428 // that is deleted or inaccessible
9429 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9430 Field->hasInClassInitializer()) &&
9431 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9432 false))
9433 return true;
9434
9435 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9436 // -- any direct or virtual base class or non-static data member has a
9437 // type with a destructor that is deleted or inaccessible
9438 if (IsConstructor) {
9441 false, false, false, false);
9442 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9443 return true;
9444 }
9445
9446 return false;
9447}
9448
9449bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9450 FieldDecl *FD, QualType FieldType) {
9451 // The defaulted special functions are defined as deleted if this is a variant
9452 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9453 // type under ARC.
9454 if (!FieldType.hasNonTrivialObjCLifetime())
9455 return false;
9456
9457 // Don't make the defaulted default constructor defined as deleted if the
9458 // member has an in-class initializer.
9461 return false;
9462
9463 if (Diagnose) {
9464 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9465 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9466 << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9467 << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9468 << /*IsObjCPtr*/ true;
9469 }
9470
9471 return true;
9472}
9473
9474/// Check whether we should delete a special member function due to the class
9475/// having a particular direct or virtual base class.
9476bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9477 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9478 // If program is correct, BaseClass cannot be null, but if it is, the error
9479 // must be reported elsewhere.
9480 if (!BaseClass)
9481 return false;
9482 // If we have an inheriting constructor, check whether we're calling an
9483 // inherited constructor instead of a default constructor.
9484 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9485 if (auto *BaseCtor = SMOR.getMethod()) {
9486 // Note that we do not check access along this path; other than that,
9487 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9488 // FIXME: Check that the base has a usable destructor! Sink this into
9489 // shouldDeleteForClassSubobject.
9490 if (BaseCtor->isDeleted() && Diagnose) {
9491 S.Diag(Base->getBeginLoc(),
9492 diag::note_deleted_special_member_class_subobject)
9493 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9494 << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9495 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9496 S.NoteDeletedFunction(BaseCtor);
9497 }
9498 return BaseCtor->isDeleted();
9499 }
9500 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9501}
9502
9503/// Check whether we should delete a special member function due to the class
9504/// having a particular non-static data member.
9505bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9506 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9507 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9508
9509 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9510 return true;
9511
9513 // For a default constructor, all references must be initialized in-class
9514 // and, if a union, it must have a non-const member.
9515 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9516 if (Diagnose)
9517 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9518 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9519 return true;
9520 }
9521 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9522 // data member of const-qualified type (or array thereof) with no
9523 // brace-or-equal-initializer is not const-default-constructible.
9524 if (!inUnion() && FieldType.isConstQualified() &&
9525 !FD->hasInClassInitializer() &&
9526 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9527 if (Diagnose)
9528 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9529 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9530 return true;
9531 }
9532
9533 if (inUnion() && !FieldType.isConstQualified())
9534 AllFieldsAreConst = false;
9535 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9536 // For a copy constructor, data members must not be of rvalue reference
9537 // type.
9538 if (FieldType->isRValueReferenceType()) {
9539 if (Diagnose)
9540 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9541 << MD->getParent() << FD << FieldType;
9542 return true;
9543 }
9544 } else if (IsAssignment) {
9545 // For an assignment operator, data members must not be of reference type.
9546 if (FieldType->isReferenceType()) {
9547 if (Diagnose)
9548 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9549 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9550 return true;
9551 }
9552 if (!FieldRecord && FieldType.isConstQualified()) {
9553 // C++11 [class.copy]p23:
9554 // -- a non-static data member of const non-class type (or array thereof)
9555 if (Diagnose)
9556 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9557 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9558 return true;
9559 }
9560 }
9561
9562 if (FieldRecord) {
9563 // Some additional restrictions exist on the variant members.
9564 if (!inUnion() && FieldRecord->isUnion() &&
9565 FieldRecord->isAnonymousStructOrUnion()) {
9566 bool AllVariantFieldsAreConst = true;
9567
9568 // FIXME: Handle anonymous unions declared within anonymous unions.
9569 for (auto *UI : FieldRecord->fields()) {
9570 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9571
9572 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9573 return true;
9574
9575 if (!UnionFieldType.isConstQualified())
9576 AllVariantFieldsAreConst = false;
9577
9578 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9579 if (UnionFieldRecord &&
9580 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9581 UnionFieldType.getCVRQualifiers()))
9582 return true;
9583 }
9584
9585 // At least one member in each anonymous union must be non-const
9587 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9588 if (Diagnose)
9589 S.Diag(FieldRecord->getLocation(),
9590 diag::note_deleted_default_ctor_all_const)
9591 << !!ICI << MD->getParent() << /*anonymous union*/1;
9592 return true;
9593 }
9594
9595 // Don't check the implicit member of the anonymous union type.
9596 // This is technically non-conformant but supported, and we have a
9597 // diagnostic for this elsewhere.
9598 return false;
9599 }
9600
9601 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9602 FieldType.getCVRQualifiers()))
9603 return true;
9604 }
9605
9606 return false;
9607}
9608
9609/// C++11 [class.ctor] p5:
9610/// A defaulted default constructor for a class X is defined as deleted if
9611/// X is a union and all of its variant members are of const-qualified type.
9612bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9613 // This is a silly definition, because it gives an empty union a deleted
9614 // default constructor. Don't do that.
9615 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9616 AllFieldsAreConst) {
9617 bool AnyFields = false;
9618 for (auto *F : MD->getParent()->fields())
9619 if ((AnyFields = !F->isUnnamedBitField()))
9620 break;
9621 if (!AnyFields)
9622 return false;
9623 if (Diagnose)
9624 S.Diag(MD->getParent()->getLocation(),
9625 diag::note_deleted_default_ctor_all_const)
9626 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9627 return true;
9628 }
9629 return false;
9630}
9631
9632/// Determine whether a defaulted special member function should be defined as
9633/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9634/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9638 bool Diagnose) {
9639 if (MD->isInvalidDecl())
9640 return false;
9641 CXXRecordDecl *RD = MD->getParent();
9642 assert(!RD->isDependentType() && "do deletion after instantiation");
9643 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9644 RD->isInvalidDecl())
9645 return false;
9646
9647 // C++11 [expr.lambda.prim]p19:
9648 // The closure type associated with a lambda-expression has a
9649 // deleted (8.4.3) default constructor and a deleted copy
9650 // assignment operator.
9651 // C++2a adds back these operators if the lambda has no lambda-capture.
9655 if (Diagnose)
9656 Diag(RD->getLocation(), diag::note_lambda_decl);
9657 return true;
9658 }
9659
9660 // For an anonymous struct or union, the copy and assignment special members
9661 // will never be used, so skip the check. For an anonymous union declared at
9662 // namespace scope, the constructor and destructor are used.
9665 return false;
9666
9667 // C++11 [class.copy]p7, p18:
9668 // If the class definition declares a move constructor or move assignment
9669 // operator, an implicitly declared copy constructor or copy assignment
9670 // operator is defined as deleted.
9673 CXXMethodDecl *UserDeclaredMove = nullptr;
9674
9675 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9676 // deletion of the corresponding copy operation, not both copy operations.
9677 // MSVC 2015 has adopted the standards conforming behavior.
9678 bool DeletesOnlyMatchingCopy =
9679 getLangOpts().MSVCCompat &&
9681
9683 (!DeletesOnlyMatchingCopy ||
9685 if (!Diagnose) return true;
9686
9687 // Find any user-declared move constructor.
9688 for (auto *I : RD->ctors()) {
9689 if (I->isMoveConstructor()) {
9690 UserDeclaredMove = I;
9691 break;
9692 }
9693 }
9694 assert(UserDeclaredMove);
9695 } else if (RD->hasUserDeclaredMoveAssignment() &&
9696 (!DeletesOnlyMatchingCopy ||
9698 if (!Diagnose) return true;
9699
9700 // Find any user-declared move assignment operator.
9701 for (auto *I : RD->methods()) {
9702 if (I->isMoveAssignmentOperator()) {
9703 UserDeclaredMove = I;
9704 break;
9705 }
9706 }
9707 assert(UserDeclaredMove);
9708 }
9709
9710 if (UserDeclaredMove) {
9711 Diag(UserDeclaredMove->getLocation(),
9712 diag::note_deleted_copy_user_declared_move)
9713 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9714 << UserDeclaredMove->isMoveAssignmentOperator();
9715 return true;
9716 }
9717 }
9718
9719 // Do access control from the special member function
9720 ContextRAII MethodContext(*this, MD);
9721
9722 // C++11 [class.dtor]p5:
9723 // -- for a virtual destructor, lookup of the non-array deallocation function
9724 // results in an ambiguity or in a function that is deleted or inaccessible
9725 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9726 FunctionDecl *OperatorDelete = nullptr;
9727 DeclarationName Name =
9729 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9730 OperatorDelete, /*Diagnose*/false)) {
9731 if (Diagnose)
9732 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9733 return true;
9734 }
9735 }
9736
9737 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9738
9739 // Per DR1611, do not consider virtual bases of constructors of abstract
9740 // classes, since we are not going to construct them.
9741 // Per DR1658, do not consider virtual bases of destructors of abstract
9742 // classes either.
9743 // Per DR2180, for assignment operators we only assign (and thus only
9744 // consider) direct bases.
9745 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9746 : SMI.VisitPotentiallyConstructedBases))
9747 return true;
9748
9749 if (SMI.shouldDeleteForAllConstMembers())
9750 return true;
9751
9752 if (getLangOpts().CUDA) {
9753 // We should delete the special member in CUDA mode if target inference
9754 // failed.
9755 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9756 // is treated as certain special member, which may not reflect what special
9757 // member MD really is. However inferTargetForImplicitSpecialMember
9758 // expects CSM to match MD, therefore recalculate CSM.
9759 assert(ICI || CSM == getSpecialMember(MD));
9760 auto RealCSM = CSM;
9761 if (ICI)
9762 RealCSM = getSpecialMember(MD);
9763
9764 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9765 SMI.ConstArg, Diagnose);
9766 }
9767
9768 return false;
9769}
9770
9773 assert(DFK && "not a defaultable function");
9774 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9775
9776 if (DFK.isSpecialMember()) {
9777 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9778 nullptr, /*Diagnose=*/true);
9779 } else {
9780 DefaultedComparisonAnalyzer(
9781 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9782 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9783 .visit();
9784 }
9785}
9786
9787/// Perform lookup for a special member of the specified kind, and determine
9788/// whether it is trivial. If the triviality can be determined without the
9789/// lookup, skip it. This is intended for use when determining whether a
9790/// special member of a containing object is trivial, and thus does not ever
9791/// perform overload resolution for default constructors.
9792///
9793/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9794/// member that was most likely to be intended to be trivial, if any.
9795///
9796/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9797/// determine whether the special member is trivial.
9799 CXXSpecialMemberKind CSM, unsigned Quals,
9800 bool ConstRHS,
9802 CXXMethodDecl **Selected) {
9803 if (Selected)
9804 *Selected = nullptr;
9805
9806 switch (CSM) {
9808 llvm_unreachable("not a special member");
9809
9811 // C++11 [class.ctor]p5:
9812 // A default constructor is trivial if:
9813 // - all the [direct subobjects] have trivial default constructors
9814 //
9815 // Note, no overload resolution is performed in this case.
9817 return true;
9818
9819 if (Selected) {
9820 // If there's a default constructor which could have been trivial, dig it
9821 // out. Otherwise, if there's any user-provided default constructor, point
9822 // to that as an example of why there's not a trivial one.
9823 CXXConstructorDecl *DefCtor = nullptr;
9826 for (auto *CI : RD->ctors()) {
9827 if (!CI->isDefaultConstructor())
9828 continue;
9829 DefCtor = CI;
9830 if (!DefCtor->isUserProvided())
9831 break;
9832 }
9833
9834 *Selected = DefCtor;
9835 }
9836
9837 return false;
9838
9840 // C++11 [class.dtor]p5:
9841 // A destructor is trivial if:
9842 // - all the direct [subobjects] have trivial destructors
9843 if (RD->hasTrivialDestructor() ||
9846 return true;
9847
9848 if (Selected) {
9849 if (RD->needsImplicitDestructor())
9851 *Selected = RD->getDestructor();
9852 }
9853
9854 return false;
9855
9857 // C++11 [class.copy]p12:
9858 // A copy constructor is trivial if:
9859 // - the constructor selected to copy each direct [subobject] is trivial
9860 if (RD->hasTrivialCopyConstructor() ||
9863 if (Quals == Qualifiers::Const)
9864 // We must either select the trivial copy constructor or reach an
9865 // ambiguity; no need to actually perform overload resolution.
9866 return true;
9867 } else if (!Selected) {
9868 return false;
9869 }
9870 // In C++98, we are not supposed to perform overload resolution here, but we
9871 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9872 // cases like B as having a non-trivial copy constructor:
9873 // struct A { template<typename T> A(T&); };
9874 // struct B { mutable A a; };
9875 goto NeedOverloadResolution;
9876
9878 // C++11 [class.copy]p25:
9879 // A copy assignment operator is trivial if:
9880 // - the assignment operator selected to copy each direct [subobject] is
9881 // trivial
9882 if (RD->hasTrivialCopyAssignment()) {
9883 if (Quals == Qualifiers::Const)
9884 return true;
9885 } else if (!Selected) {
9886 return false;
9887 }
9888 // In C++98, we are not supposed to perform overload resolution here, but we
9889 // treat that as a language defect.
9890 goto NeedOverloadResolution;
9891
9894 NeedOverloadResolution:
9896 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9897
9898 // The standard doesn't describe how to behave if the lookup is ambiguous.
9899 // We treat it as not making the member non-trivial, just like the standard
9900 // mandates for the default constructor. This should rarely matter, because
9901 // the member will also be deleted.
9903 return true;
9904
9905 if (!SMOR.getMethod()) {
9906 assert(SMOR.getKind() ==
9908 return false;
9909 }
9910
9911 // We deliberately don't check if we found a deleted special member. We're
9912 // not supposed to!
9913 if (Selected)
9914 *Selected = SMOR.getMethod();
9915
9916 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9919 return SMOR.getMethod()->isTrivialForCall();
9920 return SMOR.getMethod()->isTrivial();
9921 }
9922
9923 llvm_unreachable("unknown special method kind");
9924}
9925
9927 for (auto *CI : RD->ctors())
9928 if (!CI->isImplicit())
9929 return CI;
9930
9931 // Look for constructor templates.
9933 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9934 if (CXXConstructorDecl *CD =
9935 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9936 return CD;
9937 }
9938
9939 return nullptr;
9940}
9941
9942/// The kind of subobject we are checking for triviality. The values of this
9943/// enumeration are used in diagnostics.
9945 /// The subobject is a base class.
9947 /// The subobject is a non-static data member.
9949 /// The object is actually the complete object.
9952
9953/// Check whether the special member selected for a given type would be trivial.
9955 QualType SubType, bool ConstRHS,
9959 bool Diagnose) {
9960 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9961 if (!SubRD)
9962 return true;
9963
9964 CXXMethodDecl *Selected;
9965 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9966 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9967 return true;
9968
9969 if (Diagnose) {
9970 if (ConstRHS)
9971 SubType.addConst();
9972
9973 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
9974 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9975 << Kind << SubType.getUnqualifiedType();
9977 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9978 } else if (!Selected)
9979 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9980 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
9981 << SubType;
9982 else if (Selected->isUserProvided()) {
9983 if (Kind == TSK_CompleteObject)
9984 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9985 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9986 else {
9987 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9988 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9989 S.Diag(Selected->getLocation(), diag::note_declared_at);
9990 }
9991 } else {
9992 if (Kind != TSK_CompleteObject)
9993 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9994 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9995
9996 // Explain why the defaulted or deleted special member isn't trivial.
9998 Diagnose);
9999 }
10000 }
10001
10002 return false;
10003}
10004
10005/// Check whether the members of a class type allow a special member to be
10006/// trivial.
10008 CXXSpecialMemberKind CSM, bool ConstArg,
10010 bool Diagnose) {
10011 for (const auto *FI : RD->fields()) {
10012 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10013 continue;
10014
10015 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10016
10017 // Pretend anonymous struct or union members are members of this class.
10018 if (FI->isAnonymousStructOrUnion()) {
10019 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10020 CSM, ConstArg, TAH, Diagnose))
10021 return false;
10022 continue;
10023 }
10024
10025 // C++11 [class.ctor]p5:
10026 // A default constructor is trivial if [...]
10027 // -- no non-static data member of its class has a
10028 // brace-or-equal-initializer
10030 FI->hasInClassInitializer()) {
10031 if (Diagnose)
10032 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10033 << FI;
10034 return false;
10035 }
10036
10037 // Objective C ARC 4.3.5:
10038 // [...] nontrivally ownership-qualified types are [...] not trivially
10039 // default constructible, copy constructible, move constructible, copy
10040 // assignable, move assignable, or destructible [...]
10041 if (FieldType.hasNonTrivialObjCLifetime()) {
10042 if (Diagnose)
10043 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10044 << RD << FieldType.getObjCLifetime();
10045 return false;
10046 }
10047
10048 bool ConstRHS = ConstArg && !FI->isMutable();
10049 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10050 CSM, TSK_Field, TAH, Diagnose))
10051 return false;
10052 }
10053
10054 return true;
10055}
10056
10060
10061 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10063 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10065 /*Diagnose*/true);
10066}
10067
10069 TrivialABIHandling TAH, bool Diagnose) {
10070 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10071 "not special enough");
10072
10073 CXXRecordDecl *RD = MD->getParent();
10074
10075 bool ConstArg = false;
10076
10077 // C++11 [class.copy]p12, p25: [DR1593]
10078 // A [special member] is trivial if [...] its parameter-type-list is
10079 // equivalent to the parameter-type-list of an implicit declaration [...]
10080 switch (CSM) {
10083 // Trivial default constructors and destructors cannot have parameters.
10084 break;
10085
10088 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10089 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10090
10091 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10092 // if they are not user-provided and their parameter-type-list is equivalent
10093 // to the parameter-type-list of an implicit declaration. This maintains the
10094 // behavior before dr2171 was implemented.
10095 //
10096 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10097 // trivial, if they are not user-provided, regardless of the qualifiers on
10098 // the reference type.
10099 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10101 if (!RT ||
10103 ClangABICompat14)) {
10104 if (Diagnose)
10105 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10106 << Param0->getSourceRange() << Param0->getType()
10109 return false;
10110 }
10111
10112 ConstArg = RT->getPointeeType().isConstQualified();
10113 break;
10114 }
10115
10118 // Trivial move operations always have non-cv-qualified parameters.
10119 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10120 const RValueReferenceType *RT =
10121 Param0->getType()->getAs<RValueReferenceType>();
10122 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10123 if (Diagnose)
10124 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10125 << Param0->getSourceRange() << Param0->getType()
10127 return false;
10128 }
10129 break;
10130 }
10131
10133 llvm_unreachable("not a special member");
10134 }
10135
10136 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10137 if (Diagnose)
10139 diag::note_nontrivial_default_arg)
10141 return false;
10142 }
10143 if (MD->isVariadic()) {
10144 if (Diagnose)
10145 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10146 return false;
10147 }
10148
10149 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10150 // A copy/move [constructor or assignment operator] is trivial if
10151 // -- the [member] selected to copy/move each direct base class subobject
10152 // is trivial
10153 //
10154 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10155 // A [default constructor or destructor] is trivial if
10156 // -- all the direct base classes have trivial [default constructors or
10157 // destructors]
10158 for (const auto &BI : RD->bases())
10159 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10160 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10161 return false;
10162
10163 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10164 // A copy/move [constructor or assignment operator] for a class X is
10165 // trivial if
10166 // -- for each non-static data member of X that is of class type (or array
10167 // thereof), the constructor selected to copy/move that member is
10168 // trivial
10169 //
10170 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10171 // A [default constructor or destructor] is trivial if
10172 // -- for all of the non-static data members of its class that are of class
10173 // type (or array thereof), each such class has a trivial [default
10174 // constructor or destructor]
10175 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10176 return false;
10177
10178 // C++11 [class.dtor]p5:
10179 // A destructor is trivial if [...]
10180 // -- the destructor is not virtual
10181 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10182 if (Diagnose)
10183 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10184 return false;
10185 }
10186
10187 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10188 // A [special member] for class X is trivial if [...]
10189 // -- class X has no virtual functions and no virtual base classes
10191 MD->getParent()->isDynamicClass()) {
10192 if (!Diagnose)
10193 return false;
10194
10195 if (RD->getNumVBases()) {
10196 // Check for virtual bases. We already know that the corresponding
10197 // member in all bases is trivial, so vbases must all be direct.
10198 CXXBaseSpecifier &BS = *RD->vbases_begin();
10199 assert(BS.isVirtual());
10200 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10201 return false;
10202 }
10203
10204 // Must have a virtual method.
10205 for (const auto *MI : RD->methods()) {
10206 if (MI->isVirtual()) {
10207 SourceLocation MLoc = MI->getBeginLoc();
10208 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10209 return false;
10210 }
10211 }
10212
10213 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10214 }
10215
10216 // Looks like it's trivial!
10217 return true;
10218}
10219
10220namespace {
10221struct FindHiddenVirtualMethod {
10222 Sema *S;
10223 CXXMethodDecl *Method;
10224 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10225 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10226
10227private:
10228 /// Check whether any most overridden method from MD in Methods
10229 static bool CheckMostOverridenMethods(
10230 const CXXMethodDecl *MD,
10231 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10232 if (MD->size_overridden_methods() == 0)
10233 return Methods.count(MD->getCanonicalDecl());
10234 for (const CXXMethodDecl *O : MD->overridden_methods())
10235 if (CheckMostOverridenMethods(O, Methods))
10236 return true;
10237 return false;
10238 }
10239
10240public:
10241 /// Member lookup function that determines whether a given C++
10242 /// method overloads virtual methods in a base class without overriding any,
10243 /// to be used with CXXRecordDecl::lookupInBases().
10244 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10245 RecordDecl *BaseRecord =
10246 Specifier->getType()->castAs<RecordType>()->getDecl();
10247
10248 DeclarationName Name = Method->getDeclName();
10249 assert(Name.getNameKind() == DeclarationName::Identifier);
10250
10251 bool foundSameNameMethod = false;
10252 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10253 for (Path.Decls = BaseRecord->lookup(Name).begin();
10254 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10255 NamedDecl *D = *Path.Decls;
10256 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10257 MD = MD->getCanonicalDecl();
10258 foundSameNameMethod = true;
10259 // Interested only in hidden virtual methods.
10260 if (!MD->isVirtual())
10261 continue;
10262 // If the method we are checking overrides a method from its base
10263 // don't warn about the other overloaded methods. Clang deviates from
10264 // GCC by only diagnosing overloads of inherited virtual functions that
10265 // do not override any other virtual functions in the base. GCC's
10266 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10267 // function from a base class. These cases may be better served by a
10268 // warning (not specific to virtual functions) on call sites when the
10269 // call would select a different function from the base class, were it
10270 // visible.
10271 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10272 if (!S->IsOverload(Method, MD, false))
10273 return true;
10274 // Collect the overload only if its hidden.
10275 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10276 overloadedMethods.push_back(MD);
10277 }
10278 }
10279
10280 if (foundSameNameMethod)
10281 OverloadedMethods.append(overloadedMethods.begin(),
10282 overloadedMethods.end());
10283 return foundSameNameMethod;
10284 }
10285};
10286} // end anonymous namespace
10287
10288/// Add the most overridden methods from MD to Methods
10290 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10291 if (MD->size_overridden_methods() == 0)
10292 Methods.insert(MD->getCanonicalDecl());
10293 else
10294 for (const CXXMethodDecl *O : MD->overridden_methods())
10295 AddMostOverridenMethods(O, Methods);
10296}
10297
10299 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10300 if (!MD->getDeclName().isIdentifier())
10301 return;
10302
10303 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10304 /*bool RecordPaths=*/false,
10305 /*bool DetectVirtual=*/false);
10306 FindHiddenVirtualMethod FHVM;
10307 FHVM.Method = MD;
10308 FHVM.S = this;
10309
10310 // Keep the base methods that were overridden or introduced in the subclass
10311 // by 'using' in a set. A base method not in this set is hidden.
10312 CXXRecordDecl *DC = MD->getParent();
10314 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10315 NamedDecl *ND = *I;
10316 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10317 ND = shad->getTargetDecl();
10318 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10319 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10320 }
10321
10322 if (DC->lookupInBases(FHVM, Paths))
10323 OverloadedMethods = FHVM.OverloadedMethods;
10324}
10325
10327 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10328 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10329 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10331 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10332 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10333 Diag(overloadedMD->getLocation(), PD);
10334 }
10335}
10336
10338 if (MD->isInvalidDecl())
10339 return;
10340
10341 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10342 return;
10343
10344 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10345 FindHiddenVirtualMethods(MD, OverloadedMethods);
10346 if (!OverloadedMethods.empty()) {
10347 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10348 << MD << (OverloadedMethods.size() > 1);
10349
10350 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10351 }
10352}
10353
10355 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10356 // No diagnostics if this is a template instantiation.
10358 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10359 diag::ext_cannot_use_trivial_abi) << &RD;
10360 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10361 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10362 }
10363 RD.dropAttr<TrivialABIAttr>();
10364 };
10365
10366 // Ill-formed if the copy and move constructors are deleted.
10367 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10368 // If the type is dependent, then assume it might have
10369 // implicit copy or move ctor because we won't know yet at this point.
10370 if (RD.isDependentType())
10371 return true;
10374 return true;
10377 return true;
10378 for (const CXXConstructorDecl *CD : RD.ctors())
10379 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10380 return true;
10381 return false;
10382 };
10383
10384 if (!HasNonDeletedCopyOrMoveConstructor()) {
10385 PrintDiagAndRemoveAttr(0);
10386 return;
10387 }
10388
10389 // Ill-formed if the struct has virtual functions.
10390 if (RD.isPolymorphic()) {
10391 PrintDiagAndRemoveAttr(1);
10392 return;
10393 }
10394
10395 for (const auto &B : RD.bases()) {
10396 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10397 // virtual base.
10398 if (!B.getType()->isDependentType() &&
10399 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10400 PrintDiagAndRemoveAttr(2);
10401 return;
10402 }
10403
10404 if (B.isVirtual()) {
10405 PrintDiagAndRemoveAttr(3);
10406 return;
10407 }
10408 }
10409
10410 for (const auto *FD : RD.fields()) {
10411 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10412 // non-trivial for the purpose of calls.
10413 QualType FT = FD->getType();
10415 PrintDiagAndRemoveAttr(4);
10416 return;
10417 }
10418
10419 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10420 if (!RT->isDependentType() &&
10421 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10422 PrintDiagAndRemoveAttr(5);
10423 return;
10424 }
10425 }
10426}
10427
10429 CXXRecordDecl &RD) {
10431 diag::err_incomplete_type_vtable_pointer_auth))
10432 return;
10433
10434 const CXXRecordDecl *PrimaryBase = &RD;
10435 if (PrimaryBase->hasAnyDependentBases())
10436 return;
10437
10438 while (1) {
10439 assert(PrimaryBase);
10440 const CXXRecordDecl *Base = nullptr;
10441 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10442 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10443 continue;
10444 Base = BasePtr.getType()->getAsCXXRecordDecl();
10445 break;
10446 }
10447 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10448 break;
10449 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10450 diag::err_non_top_level_vtable_pointer_auth)
10451 << &RD << Base;
10452 PrimaryBase = Base;
10453 }
10454
10455 if (!RD.isPolymorphic())
10456 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10457 diag::err_non_polymorphic_vtable_pointer_auth)
10458 << &RD;
10459}
10460
10463 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10464 if (!TagDecl)
10465 return;
10466
10468
10469 for (const ParsedAttr &AL : AttrList) {
10470 if (AL.getKind() != ParsedAttr::AT_Visibility)
10471 continue;
10472 AL.setInvalid();
10473 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10474 }
10475
10476 ActOnFields(S, RLoc, TagDecl,
10478 // strict aliasing violation!
10479 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10480 FieldCollector->getCurNumFields()),
10481 LBrac, RBrac, AttrList);
10482
10483 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10484}
10485
10486/// Find the equality comparison functions that should be implicitly declared
10487/// in a given class definition, per C++2a [class.compare.default]p3.
10489 ASTContext &Ctx, CXXRecordDecl *RD,
10491 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10492 if (!RD->lookup(EqEq).empty())
10493 // Member operator== explicitly declared: no implicit operator==s.
10494 return;
10495
10496 // Traverse friends looking for an '==' or a '<=>'.
10497 for (FriendDecl *Friend : RD->friends()) {
10498 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10499 if (!FD) continue;
10500
10501 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10502 // Friend operator== explicitly declared: no implicit operator==s.
10503 Spaceships.clear();
10504 return;
10505 }
10506
10507 if (FD->getOverloadedOperator() == OO_Spaceship &&
10509 Spaceships.push_back(FD);
10510 }
10511
10512 // Look for members named 'operator<=>'.
10513 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10514 for (NamedDecl *ND : RD->lookup(Cmp)) {
10515 // Note that we could find a non-function here (either a function template
10516 // or a using-declaration). Neither case results in an implicit
10517 // 'operator=='.
10518 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10519 if (FD->isExplicitlyDefaulted())
10520 Spaceships.push_back(FD);
10521 }
10522}
10523
10525 // Don't add implicit special members to templated classes.
10526 // FIXME: This means unqualified lookups for 'operator=' within a class
10527 // template don't work properly.
10528 if (!ClassDecl->isDependentType()) {
10529 if (ClassDecl->needsImplicitDefaultConstructor()) {
10531
10532 if (ClassDecl->hasInheritedConstructor())
10534 }
10535
10536 if (ClassDecl->needsImplicitCopyConstructor()) {
10538
10539 // If the properties or semantics of the copy constructor couldn't be
10540 // determined while the class was being declared, force a declaration
10541 // of it now.
10543 ClassDecl->hasInheritedConstructor())
10545 // For the MS ABI we need to know whether the copy ctor is deleted. A
10546 // prerequisite for deleting the implicit copy ctor is that the class has
10547 // a move ctor or move assignment that is either user-declared or whose
10548 // semantics are inherited from a subobject. FIXME: We should provide a
10549 // more direct way for CodeGen to ask whether the constructor was deleted.
10550 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10551 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10553 ClassDecl->hasUserDeclaredMoveAssignment() ||
10556 }
10557
10558 if (getLangOpts().CPlusPlus11 &&
10559 ClassDecl->needsImplicitMoveConstructor()) {
10561
10563 ClassDecl->hasInheritedConstructor())
10565 }
10566
10567 if (ClassDecl->needsImplicitCopyAssignment()) {
10569
10570 // If we have a dynamic class, then the copy assignment operator may be
10571 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10572 // it shows up in the right place in the vtable and that we diagnose
10573 // problems with the implicit exception specification.
10574 if (ClassDecl->isDynamicClass() ||
10576 ClassDecl->hasInheritedAssignment())
10578 }
10579
10580 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10582
10583 // Likewise for the move assignment operator.
10584 if (ClassDecl->isDynamicClass() ||
10586 ClassDecl->hasInheritedAssignment())
10588 }
10589
10590 if (ClassDecl->needsImplicitDestructor()) {
10592
10593 // If we have a dynamic class, then the destructor may be virtual, so we
10594 // have to declare the destructor immediately. This ensures that, e.g., it
10595 // shows up in the right place in the vtable and that we diagnose problems
10596 // with the implicit exception specification.
10597 if (ClassDecl->isDynamicClass() ||
10599 DeclareImplicitDestructor(ClassDecl);
10600 }
10601 }
10602
10603 // C++2a [class.compare.default]p3:
10604 // If the member-specification does not explicitly declare any member or
10605 // friend named operator==, an == operator function is declared implicitly
10606 // for each defaulted three-way comparison operator function defined in
10607 // the member-specification
10608 // FIXME: Consider doing this lazily.
10609 // We do this during the initial parse for a class template, not during
10610 // instantiation, so that we can handle unqualified lookups for 'operator=='
10611 // when parsing the template.
10613 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10615 DefaultedSpaceships);
10616 for (auto *FD : DefaultedSpaceships)
10617 DeclareImplicitEqualityComparison(ClassDecl, FD);
10618 }
10619}
10620
10621unsigned
10623 llvm::function_ref<Scope *()> EnterScope) {
10624 if (!D)
10625 return 0;
10627
10628 // In order to get name lookup right, reenter template scopes in order from
10629 // outermost to innermost.
10631 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10632
10633 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10634 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10635 ParameterLists.push_back(DD->getTemplateParameterList(i));
10636
10637 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10638 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10639 ParameterLists.push_back(FTD->getTemplateParameters());
10640 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10641 LookupDC = VD->getDeclContext();
10642
10644 ParameterLists.push_back(VTD->getTemplateParameters());
10645 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10646 ParameterLists.push_back(PSD->getTemplateParameters());
10647 }
10648 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10649 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10650 ParameterLists.push_back(TD->getTemplateParameterList(i));
10651
10652 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10654 ParameterLists.push_back(CTD->getTemplateParameters());
10655 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10656 ParameterLists.push_back(PSD->getTemplateParameters());
10657 }
10658 }
10659 // FIXME: Alias declarations and concepts.
10660
10661 unsigned Count = 0;
10662 Scope *InnermostTemplateScope = nullptr;
10663 for (TemplateParameterList *Params : ParameterLists) {
10664 // Ignore explicit specializations; they don't contribute to the template
10665 // depth.
10666 if (Params->size() == 0)
10667 continue;
10668
10669 InnermostTemplateScope = EnterScope();
10670 for (NamedDecl *Param : *Params) {
10671 if (Param->getDeclName()) {
10672 InnermostTemplateScope->AddDecl(Param);
10673 IdResolver.AddDecl(Param);
10674 }
10675 }
10676 ++Count;
10677 }
10678
10679 // Associate the new template scopes with the corresponding entities.
10680 if (InnermostTemplateScope) {
10681 assert(LookupDC && "no enclosing DeclContext for template lookup");
10682 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10683 }
10684
10685 return Count;
10686}
10687
10689 if (!RecordD) return;
10690 AdjustDeclIfTemplate(RecordD);
10691 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10693}
10694
10696 if (!RecordD) return;
10698}
10699
10701 if (!Param)
10702 return;
10703
10704 S->AddDecl(Param);
10705 if (Param->getDeclName())
10706 IdResolver.AddDecl(Param);
10707}
10708
10710}
10711
10712/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10713/// C++ method declaration. We're (re-)introducing the given
10714/// function parameter into scope for use in parsing later parts of
10715/// the method declaration. For example, we could see an
10716/// ActOnParamDefaultArgument event for this parameter.
10718 if (!ParamD)
10719 return;
10720
10721 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10722
10723 S->AddDecl(Param);
10724 if (Param->getDeclName())
10725 IdResolver.AddDecl(Param);
10726}
10727
10729 if (!MethodD)
10730 return;
10731
10732 AdjustDeclIfTemplate(MethodD);
10733
10734 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10735
10736 // Now that we have our default arguments, check the constructor
10737 // again. It could produce additional diagnostics or affect whether
10738 // the class has implicitly-declared destructors, among other
10739 // things.
10740 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10741 CheckConstructor(Constructor);
10742
10743 // Check the default arguments, which we may have added.
10744 if (!Method->isInvalidDecl())
10746}
10747
10748// Emit the given diagnostic for each non-address-space qualifier.
10749// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10750static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10751 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10752 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10753 bool DiagOccured = false;
10755 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10756 SourceLocation SL) {
10757 // This diagnostic should be emitted on any qualifier except an addr
10758 // space qualifier. However, forEachQualifier currently doesn't visit
10759 // addr space qualifiers, so there's no way to write this condition
10760 // right now; we just diagnose on everything.
10761 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10762 DiagOccured = true;
10763 });
10764 if (DiagOccured)
10765 D.setInvalidType();
10766 }
10767}
10768
10770 unsigned Kind) {
10771 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
10772 return;
10773
10774 DeclaratorChunk &Chunk = D.getTypeObject(D.getNumTypeObjects() - 1);
10775 if (Chunk.Kind == DeclaratorChunk::Paren ||
10777 return;
10778
10779 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
10780 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
10781 << Kind << Chunk.getSourceRange();
10782 D.setInvalidType();
10783}
10784
10786 StorageClass &SC) {
10787 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10788
10789 // C++ [class.ctor]p3:
10790 // A constructor shall not be virtual (10.3) or static (9.4). A
10791 // constructor can be invoked for a const, volatile or const
10792 // volatile object. A constructor shall not be declared const,
10793 // volatile, or const volatile (9.3.2).
10794 if (isVirtual) {
10795 if (!D.isInvalidType())
10796 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10797 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10798 << SourceRange(D.getIdentifierLoc());
10799 D.setInvalidType();
10800 }
10801 if (SC == SC_Static) {
10802 if (!D.isInvalidType())
10803 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10804 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10805 << SourceRange(D.getIdentifierLoc());
10806 D.setInvalidType();
10807 SC = SC_None;
10808 }
10809
10810 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10812 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10813 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10814 D.getDeclSpec().getRestrictSpecLoc(),
10815 D.getDeclSpec().getAtomicSpecLoc());
10816 D.setInvalidType();
10817 }
10818
10819 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10820 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
10821
10822 // C++0x [class.ctor]p4:
10823 // A constructor shall not be declared with a ref-qualifier.
10824 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10825 if (FTI.hasRefQualifier()) {
10826 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10829 D.setInvalidType();
10830 }
10831
10832 // Rebuild the function type "R" without any type qualifiers (in
10833 // case any of the errors above fired) and with "void" as the
10834 // return type, since constructors don't have return types.
10835 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10836 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10837 return R;
10838
10840 EPI.TypeQuals = Qualifiers();
10841 EPI.RefQualifier = RQ_None;
10842
10843 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10844}
10845
10847 CXXRecordDecl *ClassDecl
10848 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10849 if (!ClassDecl)
10850 return Constructor->setInvalidDecl();
10851
10852 // C++ [class.copy]p3:
10853 // A declaration of a constructor for a class X is ill-formed if
10854 // its first parameter is of type (optionally cv-qualified) X and
10855 // either there are no other parameters or else all other
10856 // parameters have default arguments.
10857 if (!Constructor->isInvalidDecl() &&
10858 Constructor->hasOneParamOrDefaultArgs() &&
10859 Constructor->getTemplateSpecializationKind() !=
10861 QualType ParamType = Constructor->getParamDecl(0)->getType();
10862 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10863 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10864 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10865 const char *ConstRef
10866 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10867 : " const &";
10868 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10869 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10870
10871 // FIXME: Rather that making the constructor invalid, we should endeavor
10872 // to fix the type.
10873 Constructor->setInvalidDecl();
10874 }
10875 }
10876}
10877
10879 CXXRecordDecl *RD = Destructor->getParent();
10880
10881 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10883
10884 if (!Destructor->isImplicit())
10885 Loc = Destructor->getLocation();
10886 else
10887 Loc = RD->getLocation();
10888
10889 // If we have a virtual destructor, look up the deallocation function
10890 if (FunctionDecl *OperatorDelete =
10892 Expr *ThisArg = nullptr;
10893
10894 // If the notional 'delete this' expression requires a non-trivial
10895 // conversion from 'this' to the type of a destroying operator delete's
10896 // first parameter, perform that conversion now.
10897 if (OperatorDelete->isDestroyingOperatorDelete()) {
10898 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10899 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10900 // C++ [class.dtor]p13:
10901 // ... as if for the expression 'delete this' appearing in a
10902 // non-virtual destructor of the destructor's class.
10903 ContextRAII SwitchContext(*this, Destructor);
10904 ExprResult This =
10905 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10906 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10907 This = PerformImplicitConversion(This.get(), ParamType,
10909 if (This.isInvalid()) {
10910 // FIXME: Register this as a context note so that it comes out
10911 // in the right order.
10912 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10913 return true;
10914 }
10915 ThisArg = This.get();
10916 }
10917 }
10918
10919 DiagnoseUseOfDecl(OperatorDelete, Loc);
10920 MarkFunctionReferenced(Loc, OperatorDelete);
10921 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10922 }
10923 }
10924
10925 return false;
10926}
10927
10929 StorageClass& SC) {
10930 // C++ [class.dtor]p1:
10931 // [...] A typedef-name that names a class is a class-name
10932 // (7.1.3); however, a typedef-name that names a class shall not
10933 // be used as the identifier in the declarator for a destructor
10934 // declaration.
10935 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10936 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10937 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10938 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10939 else if (const TemplateSpecializationType *TST =
10940 DeclaratorType->getAs<TemplateSpecializationType>())
10941 if (TST->isTypeAlias())
10942 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10943 << DeclaratorType << 1;
10944
10945 // C++ [class.dtor]p2:
10946 // A destructor is used to destroy objects of its class type. A
10947 // destructor takes no parameters, and no return type can be
10948 // specified for it (not even void). The address of a destructor
10949 // shall not be taken. A destructor shall not be static. A
10950 // destructor can be invoked for a const, volatile or const
10951 // volatile object. A destructor shall not be declared const,
10952 // volatile or const volatile (9.3.2).
10953 if (SC == SC_Static) {
10954 if (!D.isInvalidType())
10955 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10956 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10957 << SourceRange(D.getIdentifierLoc())
10958 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10959
10960 SC = SC_None;
10961 }
10962 if (!D.isInvalidType()) {
10963 // Destructors don't have return types, but the parser will
10964 // happily parse something like:
10965 //
10966 // class X {
10967 // float ~X();
10968 // };
10969 //
10970 // The return type will be eliminated later.
10971 if (D.getDeclSpec().hasTypeSpecifier())
10972 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10973 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10974 << SourceRange(D.getIdentifierLoc());
10975 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10976 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10978 D.getDeclSpec().getConstSpecLoc(),
10979 D.getDeclSpec().getVolatileSpecLoc(),
10980 D.getDeclSpec().getRestrictSpecLoc(),
10981 D.getDeclSpec().getAtomicSpecLoc());
10982 D.setInvalidType();
10983 }
10984 }
10985
10986 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10987 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
10988
10989 // C++0x [class.dtor]p2:
10990 // A destructor shall not be declared with a ref-qualifier.
10991 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10992 if (FTI.hasRefQualifier()) {
10993 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10996 D.setInvalidType();
10997 }
10998
10999 // Make sure we don't have any parameters.
11000 if (FTIHasNonVoidParameters(FTI)) {
11001 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11002
11003 // Delete the parameters.
11004 FTI.freeParams();
11005 D.setInvalidType();
11006 }
11007
11008 // Make sure the destructor isn't variadic.
11009 if (FTI.isVariadic) {
11010 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11011 D.setInvalidType();
11012 }
11013
11014 // Rebuild the function type "R" without any type qualifiers or
11015 // parameters (in case any of the errors above fired) and with
11016 // "void" as the return type, since destructors don't have return
11017 // types.
11018 if (!D.isInvalidType())
11019 return R;
11020
11021 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11023 EPI.Variadic = false;
11024 EPI.TypeQuals = Qualifiers();
11025 EPI.RefQualifier = RQ_None;
11026 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11027}
11028
11029static void extendLeft(SourceRange &R, SourceRange Before) {
11030 if (Before.isInvalid())
11031 return;
11032 R.setBegin(Before.getBegin());
11033 if (R.getEnd().isInvalid())
11034 R.setEnd(Before.getEnd());
11035}
11036
11037static void extendRight(SourceRange &R, SourceRange After) {
11038 if (After.isInvalid())
11039 return;
11040 if (R.getBegin().isInvalid())
11041 R.setBegin(After.getBegin());
11042 R.setEnd(After.getEnd());
11043}
11044
11046 StorageClass& SC) {
11047 // C++ [class.conv.fct]p1:
11048 // Neither parameter types nor return type can be specified. The
11049 // type of a conversion function (8.3.5) is "function taking no
11050 // parameter returning conversion-type-id."
11051 if (SC == SC_Static) {
11052 if (!D.isInvalidType())
11053 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11054 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11055 << D.getName().getSourceRange();
11056 D.setInvalidType();
11057 SC = SC_None;
11058 }
11059
11060 TypeSourceInfo *ConvTSI = nullptr;
11061 QualType ConvType =
11062 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11063
11064 const DeclSpec &DS = D.getDeclSpec();
11065 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11066 // Conversion functions don't have return types, but the parser will
11067 // happily parse something like:
11068 //
11069 // class X {
11070 // float operator bool();
11071 // };
11072 //
11073 // The return type will be changed later anyway.
11074 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11076 << SourceRange(D.getIdentifierLoc());
11077 D.setInvalidType();
11078 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11079 // It's also plausible that the user writes type qualifiers in the wrong
11080 // place, such as:
11081 // struct S { const operator int(); };
11082 // FIXME: we could provide a fixit to move the qualifiers onto the
11083 // conversion type.
11084 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11085 << SourceRange(D.getIdentifierLoc()) << 0;
11086 D.setInvalidType();
11087 }
11088 const auto *Proto = R->castAs<FunctionProtoType>();
11089 // Make sure we don't have any parameters.
11090 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11091 unsigned NumParam = Proto->getNumParams();
11092
11093 // [C++2b]
11094 // A conversion function shall have no non-object parameters.
11095 if (NumParam == 1) {
11096 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11097 if (const auto *First =
11098 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11099 First && First->isExplicitObjectParameter())
11100 NumParam--;
11101 }
11102
11103 if (NumParam != 0) {
11104 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11105 // Delete the parameters.
11106 FTI.freeParams();
11107 D.setInvalidType();
11108 } else if (Proto->isVariadic()) {
11109 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11110 D.setInvalidType();
11111 }
11112
11113 // Diagnose "&operator bool()" and other such nonsense. This
11114 // is actually a gcc extension which we don't support.
11115 if (Proto->getReturnType() != ConvType) {
11116 bool NeedsTypedef = false;
11117 SourceRange Before, After;
11118
11119 // Walk the chunks and extract information on them for our diagnostic.
11120 bool PastFunctionChunk = false;
11121 for (auto &Chunk : D.type_objects()) {
11122 switch (Chunk.Kind) {
11124 if (!PastFunctionChunk) {
11125 if (Chunk.Fun.HasTrailingReturnType) {
11126 TypeSourceInfo *TRT = nullptr;
11127 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11128 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11129 }
11130 PastFunctionChunk = true;
11131 break;
11132 }
11133 [[fallthrough]];
11135 NeedsTypedef = true;
11136 extendRight(After, Chunk.getSourceRange());
11137 break;
11138
11144 extendLeft(Before, Chunk.getSourceRange());
11145 break;
11146
11148 extendLeft(Before, Chunk.Loc);
11149 extendRight(After, Chunk.EndLoc);
11150 break;
11151 }
11152 }
11153
11154 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11155 After.isValid() ? After.getBegin() :
11156 D.getIdentifierLoc();
11157 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11158 DB << Before << After;
11159
11160 if (!NeedsTypedef) {
11161 DB << /*don't need a typedef*/0;
11162
11163 // If we can provide a correct fix-it hint, do so.
11164 if (After.isInvalid() && ConvTSI) {
11165 SourceLocation InsertLoc =
11167 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11169 InsertLoc, CharSourceRange::getTokenRange(Before))
11170 << FixItHint::CreateRemoval(Before);
11171 }
11172 } else if (!Proto->getReturnType()->isDependentType()) {
11173 DB << /*typedef*/1 << Proto->getReturnType();
11174 } else if (getLangOpts().CPlusPlus11) {
11175 DB << /*alias template*/2 << Proto->getReturnType();
11176 } else {
11177 DB << /*might not be fixable*/3;
11178 }
11179
11180 // Recover by incorporating the other type chunks into the result type.
11181 // Note, this does *not* change the name of the function. This is compatible
11182 // with the GCC extension:
11183 // struct S { &operator int(); } s;
11184 // int &r = s.operator int(); // ok in GCC
11185 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11186 ConvType = Proto->getReturnType();
11187 }
11188
11189 // C++ [class.conv.fct]p4:
11190 // The conversion-type-id shall not represent a function type nor
11191 // an array type.
11192 if (ConvType->isArrayType()) {
11193 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11194 ConvType = Context.getPointerType(ConvType);
11195 D.setInvalidType();
11196 } else if (ConvType->isFunctionType()) {
11197 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11198 ConvType = Context.getPointerType(ConvType);
11199 D.setInvalidType();
11200 }
11201
11202 // Rebuild the function type "R" without any parameters (in case any
11203 // of the errors above fired) and with the conversion type as the
11204 // return type.
11205 if (D.isInvalidType())
11206 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11207
11208 // C++0x explicit conversion operators.
11212 ? diag::warn_cxx98_compat_explicit_conversion_functions
11213 : diag::ext_explicit_conversion_functions)
11215}
11216
11218 assert(Conversion && "Expected to receive a conversion function declaration");
11219
11220 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11221
11222 // Make sure we aren't redeclaring the conversion function.
11223 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11224 // C++ [class.conv.fct]p1:
11225 // [...] A conversion function is never used to convert a
11226 // (possibly cv-qualified) object to the (possibly cv-qualified)
11227 // same object type (or a reference to it), to a (possibly
11228 // cv-qualified) base class of that type (or a reference to it),
11229 // or to (possibly cv-qualified) void.
11230 QualType ClassType
11232 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11233 ConvType = ConvTypeRef->getPointeeType();
11234 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11236 /* Suppress diagnostics for instantiations. */;
11237 else if (Conversion->size_overridden_methods() != 0)
11238 /* Suppress diagnostics for overriding virtual function in a base class. */;
11239 else if (ConvType->isRecordType()) {
11240 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11241 if (ConvType == ClassType)
11242 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11243 << ClassType;
11244 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11245 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11246 << ClassType << ConvType;
11247 } else if (ConvType->isVoidType()) {
11248 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11249 << ClassType << ConvType;
11250 }
11251
11252 if (FunctionTemplateDecl *ConversionTemplate =
11253 Conversion->getDescribedFunctionTemplate()) {
11254 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11255 ConvType = ConvTypePtr->getPointeeType();
11256 }
11257 if (ConvType->isUndeducedAutoType()) {
11258 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11259 << getReturnTypeLoc(Conversion).getSourceRange()
11260 << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11261 << /* in declaration of conversion function template= */ 24;
11262 }
11263
11264 return ConversionTemplate;
11265 }
11266
11267 return Conversion;
11268}
11269
11271 DeclarationName Name, QualType R) {
11272 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11273}
11274
11276 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11277}
11278
11280 DeclarationName Name, QualType R,
11281 bool IsLambda, DeclContext *DC) {
11282 if (!D.isFunctionDeclarator())
11283 return;
11284
11285 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11286 if (FTI.NumParams == 0)
11287 return;
11288 ParmVarDecl *ExplicitObjectParam = nullptr;
11289 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11290 const auto &ParamInfo = FTI.Params[Idx];
11291 if (!ParamInfo.Param)
11292 continue;
11293 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11294 if (!Param->isExplicitObjectParameter())
11295 continue;
11296 if (Idx == 0) {
11297 ExplicitObjectParam = Param;
11298 continue;
11299 } else {
11300 Diag(Param->getLocation(),
11301 diag::err_explicit_object_parameter_must_be_first)
11302 << IsLambda << Param->getSourceRange();
11303 }
11304 }
11305 if (!ExplicitObjectParam)
11306 return;
11307
11308 if (ExplicitObjectParam->hasDefaultArg()) {
11309 Diag(ExplicitObjectParam->getLocation(),
11310 diag::err_explicit_object_default_arg)
11311 << ExplicitObjectParam->getSourceRange();
11312 }
11313
11314 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11315 (D.getContext() == clang::DeclaratorContext::Member &&
11316 D.isStaticMember())) {
11317 Diag(ExplicitObjectParam->getBeginLoc(),
11318 diag::err_explicit_object_parameter_nonmember)
11319 << D.getSourceRange() << /*static=*/0 << IsLambda;
11320 D.setInvalidType();
11321 }
11322
11323 if (D.getDeclSpec().isVirtualSpecified()) {
11324 Diag(ExplicitObjectParam->getBeginLoc(),
11325 diag::err_explicit_object_parameter_nonmember)
11326 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11327 D.setInvalidType();
11328 }
11329
11330 // Friend declarations require some care. Consider:
11331 //
11332 // namespace N {
11333 // struct A{};
11334 // int f(A);
11335 // }
11336 //
11337 // struct S {
11338 // struct T {
11339 // int f(this T);
11340 // };
11341 //
11342 // friend int T::f(this T); // Allow this.
11343 // friend int f(this S); // But disallow this.
11344 // friend int N::f(this A); // And disallow this.
11345 // };
11346 //
11347 // Here, it seems to suffice to check whether the scope
11348 // specifier designates a class type.
11349 if (D.getDeclSpec().isFriendSpecified() &&
11350 !isa_and_present<CXXRecordDecl>(
11351 computeDeclContext(D.getCXXScopeSpec()))) {
11352 Diag(ExplicitObjectParam->getBeginLoc(),
11353 diag::err_explicit_object_parameter_nonmember)
11354 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11355 D.setInvalidType();
11356 }
11357
11358 if (IsLambda && FTI.hasMutableQualifier()) {
11359 Diag(ExplicitObjectParam->getBeginLoc(),
11360 diag::err_explicit_object_parameter_mutable)
11361 << D.getSourceRange();
11362 }
11363
11364 if (IsLambda)
11365 return;
11366
11367 if (!DC || !DC->isRecord()) {
11368 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11369 "should have been diagnosed already");
11370 return;
11371 }
11372
11373 // CWG2674: constructors and destructors cannot have explicit parameters.
11374 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11375 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11376 Diag(ExplicitObjectParam->getBeginLoc(),
11377 diag::err_explicit_object_parameter_constructor)
11378 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11379 << D.getSourceRange();
11380 D.setInvalidType();
11381 }
11382}
11383
11384namespace {
11385/// Utility class to accumulate and print a diagnostic listing the invalid
11386/// specifier(s) on a declaration.
11387struct BadSpecifierDiagnoser {
11388 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11389 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11390 ~BadSpecifierDiagnoser() {
11391 Diagnostic << Specifiers;
11392 }
11393
11394 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11395 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11396 }
11397 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11398 return check(SpecLoc,
11400 }
11401 void check(SourceLocation SpecLoc, const char *Spec) {
11402 if (SpecLoc.isInvalid()) return;
11403 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11404 if (!Specifiers.empty()) Specifiers += " ";
11405 Specifiers += Spec;
11406 }
11407
11408 Sema &S;
11410 std::string Specifiers;
11411};
11412}
11413
11415 StorageClass &SC) {
11416 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11417 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11418 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11419
11420 // C++ [temp.deduct.guide]p3:
11421 // A deduction-gide shall be declared in the same scope as the
11422 // corresponding class template.
11424 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11425 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11426 << GuidedTemplateDecl;
11427 NoteTemplateLocation(*GuidedTemplateDecl);
11428 }
11429
11430 auto &DS = D.getMutableDeclSpec();
11431 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11432 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11433 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11434 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11435 BadSpecifierDiagnoser Diagnoser(
11436 *this, D.getIdentifierLoc(),
11437 diag::err_deduction_guide_invalid_specifier);
11438
11439 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11440 DS.ClearStorageClassSpecs();
11441 SC = SC_None;
11442
11443 // 'explicit' is permitted.
11444 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11445 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11446 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11447 DS.ClearConstexprSpec();
11448
11449 Diagnoser.check(DS.getConstSpecLoc(), "const");
11450 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11451 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11452 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11453 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11454 DS.ClearTypeQualifiers();
11455
11456 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11457 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11458 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11459 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11460 DS.ClearTypeSpecType();
11461 }
11462
11463 if (D.isInvalidType())
11464 return true;
11465
11466 // Check the declarator is simple enough.
11467 bool FoundFunction = false;
11468 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11469 if (Chunk.Kind == DeclaratorChunk::Paren)
11470 continue;
11471 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11472 Diag(D.getDeclSpec().getBeginLoc(),
11473 diag::err_deduction_guide_with_complex_decl)
11474 << D.getSourceRange();
11475 break;
11476 }
11477 if (!Chunk.Fun.hasTrailingReturnType())
11478 return Diag(D.getName().getBeginLoc(),
11479 diag::err_deduction_guide_no_trailing_return_type);
11480
11481 // Check that the return type is written as a specialization of
11482 // the template specified as the deduction-guide's name.
11483 // The template name may not be qualified. [temp.deduct.guide]
11484 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11485 TypeSourceInfo *TSI = nullptr;
11486 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11487 assert(TSI && "deduction guide has valid type but invalid return type?");
11488 bool AcceptableReturnType = false;
11489 bool MightInstantiateToSpecialization = false;
11490 if (auto RetTST =
11492 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11493 bool TemplateMatches = Context.hasSameTemplateName(
11494 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11495
11497 SpecifiedName.getAsQualifiedTemplateName();
11498 assert(Qualifiers && "expected QualifiedTemplate");
11499 bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11500 Qualifiers->getQualifier() == nullptr;
11501 if (SimplyWritten && TemplateMatches)
11502 AcceptableReturnType = true;
11503 else {
11504 // This could still instantiate to the right type, unless we know it
11505 // names the wrong class template.
11506 auto *TD = SpecifiedName.getAsTemplateDecl();
11507 MightInstantiateToSpecialization =
11508 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11509 }
11510 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11511 MightInstantiateToSpecialization = true;
11512 }
11513
11514 if (!AcceptableReturnType)
11515 return Diag(TSI->getTypeLoc().getBeginLoc(),
11516 diag::err_deduction_guide_bad_trailing_return_type)
11517 << GuidedTemplate << TSI->getType()
11518 << MightInstantiateToSpecialization
11519 << TSI->getTypeLoc().getSourceRange();
11520
11521 // Keep going to check that we don't have any inner declarator pieces (we
11522 // could still have a function returning a pointer to a function).
11523 FoundFunction = true;
11524 }
11525
11526 if (D.isFunctionDefinition())
11527 // we can still create a valid deduction guide here.
11528 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11529 return false;
11530}
11531
11532//===----------------------------------------------------------------------===//
11533// Namespace Handling
11534//===----------------------------------------------------------------------===//
11535
11536/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11537/// reopened.
11540 IdentifierInfo *II, bool *IsInline,
11541 NamespaceDecl *PrevNS) {
11542 assert(*IsInline != PrevNS->isInline());
11543
11544 // 'inline' must appear on the original definition, but not necessarily
11545 // on all extension definitions, so the note should point to the first
11546 // definition to avoid confusion.
11547 PrevNS = PrevNS->getFirstDecl();
11548
11549 if (PrevNS->isInline())
11550 // The user probably just forgot the 'inline', so suggest that it
11551 // be added back.
11552 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11553 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11554 else
11555 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11556
11557 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11558 *IsInline = PrevNS->isInline();
11559}
11560
11561/// ActOnStartNamespaceDef - This is called at the start of a namespace
11562/// definition.
11564 SourceLocation InlineLoc,
11565 SourceLocation NamespaceLoc,
11566 SourceLocation IdentLoc, IdentifierInfo *II,
11567 SourceLocation LBrace,
11568 const ParsedAttributesView &AttrList,
11569 UsingDirectiveDecl *&UD, bool IsNested) {
11570 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11571 // For anonymous namespace, take the location of the left brace.
11572 SourceLocation Loc = II ? IdentLoc : LBrace;
11573 bool IsInline = InlineLoc.isValid();
11574 bool IsInvalid = false;
11575 bool IsStd = false;
11576 bool AddToKnown = false;
11577 Scope *DeclRegionScope = NamespcScope->getParent();
11578
11579 NamespaceDecl *PrevNS = nullptr;
11580 if (II) {
11581 // C++ [namespace.std]p7:
11582 // A translation unit shall not declare namespace std to be an inline
11583 // namespace (9.8.2).
11584 //
11585 // Precondition: the std namespace is in the file scope and is declared to
11586 // be inline
11587 auto DiagnoseInlineStdNS = [&]() {
11588 assert(IsInline && II->isStr("std") &&
11590 "Precondition of DiagnoseInlineStdNS not met");
11591 Diag(InlineLoc, diag::err_inline_namespace_std)
11592 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11593 IsInline = false;
11594 };
11595 // C++ [namespace.def]p2:
11596 // The identifier in an original-namespace-definition shall not
11597 // have been previously defined in the declarative region in
11598 // which the original-namespace-definition appears. The
11599 // identifier in an original-namespace-definition is the name of
11600 // the namespace. Subsequently in that declarative region, it is
11601 // treated as an original-namespace-name.
11602 //
11603 // Since namespace names are unique in their scope, and we don't
11604 // look through using directives, just look for any ordinary names
11605 // as if by qualified name lookup.
11606 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11607 RedeclarationKind::ForExternalRedeclaration);
11609 NamedDecl *PrevDecl =
11610 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11611 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11612
11613 if (PrevNS) {
11614 // This is an extended namespace definition.
11615 if (IsInline && II->isStr("std") &&
11617 DiagnoseInlineStdNS();
11618 else if (IsInline != PrevNS->isInline())
11619 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11620 &IsInline, PrevNS);
11621 } else if (PrevDecl) {
11622 // This is an invalid name redefinition.
11623 Diag(Loc, diag::err_redefinition_different_kind)
11624 << II;
11625 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11626 IsInvalid = true;
11627 // Continue on to push Namespc as current DeclContext and return it.
11628 } else if (II->isStr("std") &&
11630 if (IsInline)
11631 DiagnoseInlineStdNS();
11632 // This is the first "real" definition of the namespace "std", so update
11633 // our cache of the "std" namespace to point at this definition.
11634 PrevNS = getStdNamespace();
11635 IsStd = true;
11636 AddToKnown = !IsInline;
11637 } else {
11638 // We've seen this namespace for the first time.
11639 AddToKnown = !IsInline;
11640 }
11641 } else {
11642 // Anonymous namespaces.
11643
11644 // Determine whether the parent already has an anonymous namespace.
11646 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11647 PrevNS = TU->getAnonymousNamespace();
11648 } else {
11649 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11650 PrevNS = ND->getAnonymousNamespace();
11651 }
11652
11653 if (PrevNS && IsInline != PrevNS->isInline())
11654 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11655 &IsInline, PrevNS);
11656 }
11657
11659 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11660 if (IsInvalid)
11661 Namespc->setInvalidDecl();
11662
11663 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11664 AddPragmaAttributes(DeclRegionScope, Namespc);
11665 ProcessAPINotes(Namespc);
11666
11667 // FIXME: Should we be merging attributes?
11668 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11670
11671 if (IsStd)
11672 StdNamespace = Namespc;
11673 if (AddToKnown)
11674 KnownNamespaces[Namespc] = false;
11675
11676 if (II) {
11677 PushOnScopeChains(Namespc, DeclRegionScope);
11678 } else {
11679 // Link the anonymous namespace into its parent.
11681 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11682 TU->setAnonymousNamespace(Namespc);
11683 } else {
11684 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11685 }
11686
11687 CurContext->addDecl(Namespc);
11688
11689 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11690 // behaves as if it were replaced by
11691 // namespace unique { /* empty body */ }
11692 // using namespace unique;
11693 // namespace unique { namespace-body }
11694 // where all occurrences of 'unique' in a translation unit are
11695 // replaced by the same identifier and this identifier differs
11696 // from all other identifiers in the entire program.
11697
11698 // We just create the namespace with an empty name and then add an
11699 // implicit using declaration, just like the standard suggests.
11700 //
11701 // CodeGen enforces the "universally unique" aspect by giving all
11702 // declarations semantically contained within an anonymous
11703 // namespace internal linkage.
11704
11705 if (!PrevNS) {
11707 /* 'using' */ LBrace,
11708 /* 'namespace' */ SourceLocation(),
11709 /* qualifier */ NestedNameSpecifierLoc(),
11710 /* identifier */ SourceLocation(),
11711 Namespc,
11712 /* Ancestor */ Parent);
11713 UD->setImplicit();
11714 Parent->addDecl(UD);
11715 }
11716 }
11717
11718 ActOnDocumentableDecl(Namespc);
11719
11720 // Although we could have an invalid decl (i.e. the namespace name is a
11721 // redefinition), push it as current DeclContext and try to continue parsing.
11722 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11723 // for the namespace has the declarations that showed up in that particular
11724 // namespace definition.
11725 PushDeclContext(NamespcScope, Namespc);
11726 return Namespc;
11727}
11728
11729/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11730/// is a namespace alias, returns the namespace it points to.
11732 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11733 return AD->getNamespace();
11734 return dyn_cast_or_null<NamespaceDecl>(D);
11735}
11736
11738 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11739 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11740 Namespc->setRBraceLoc(RBrace);
11742 if (Namespc->hasAttr<VisibilityAttr>())
11743 PopPragmaVisibility(true, RBrace);
11744 // If this namespace contains an export-declaration, export it now.
11745 if (DeferredExportedNamespaces.erase(Namespc))
11747}
11748
11750 return cast_or_null<CXXRecordDecl>(
11752}
11753
11755 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11756}
11757
11759 return cast_or_null<NamespaceDecl>(
11761}
11762namespace {
11763
11764enum UnsupportedSTLSelect {
11765 USS_InvalidMember,
11766 USS_MissingMember,
11767 USS_NonTrivial,
11768 USS_Other
11769};
11770
11771struct InvalidSTLDiagnoser {
11772 Sema &S;
11774 QualType TyForDiags;
11775
11776 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11777 const VarDecl *VD = nullptr) {
11778 {
11779 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11780 << TyForDiags << ((int)Sel);
11781 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11782 assert(!Name.empty());
11783 D << Name;
11784 }
11785 }
11786 if (Sel == USS_InvalidMember) {
11787 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11788 << VD << VD->getSourceRange();
11789 }
11790 return QualType();
11791 }
11792};
11793} // namespace
11794
11798 assert(getLangOpts().CPlusPlus &&
11799 "Looking for comparison category type outside of C++.");
11800
11801 // Use an elaborated type for diagnostics which has a name containing the
11802 // prepended 'std' namespace but not any inline namespace names.
11803 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11804 auto *NNS =
11807 Info->getType());
11808 };
11809
11810 // Check if we've already successfully checked the comparison category type
11811 // before. If so, skip checking it again.
11813 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11814 // The only thing we need to check is that the type has a reachable
11815 // definition in the current context.
11816 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11817 return QualType();
11818
11819 return Info->getType();
11820 }
11821
11822 // If lookup failed
11823 if (!Info) {
11824 std::string NameForDiags = "std::";
11825 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11826 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11827 << NameForDiags << (int)Usage;
11828 return QualType();
11829 }
11830
11831 assert(Info->Kind == Kind);
11832 assert(Info->Record);
11833
11834 // Update the Record decl in case we encountered a forward declaration on our
11835 // first pass. FIXME: This is a bit of a hack.
11836 if (Info->Record->hasDefinition())
11837 Info->Record = Info->Record->getDefinition();
11838
11839 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11840 return QualType();
11841
11842 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11843
11844 if (!Info->Record->isTriviallyCopyable())
11845 return UnsupportedSTLError(USS_NonTrivial);
11846
11847 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11848 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11849 // Tolerate empty base classes.
11850 if (Base->isEmpty())
11851 continue;
11852 // Reject STL implementations which have at least one non-empty base.
11853 return UnsupportedSTLError();
11854 }
11855
11856 // Check that the STL has implemented the types using a single integer field.
11857 // This expectation allows better codegen for builtin operators. We require:
11858 // (1) The class has exactly one field.
11859 // (2) The field is an integral or enumeration type.
11860 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11861 if (std::distance(FIt, FEnd) != 1 ||
11862 !FIt->getType()->isIntegralOrEnumerationType()) {
11863 return UnsupportedSTLError();
11864 }
11865
11866 // Build each of the require values and store them in Info.
11867 for (ComparisonCategoryResult CCR :
11869 StringRef MemName = ComparisonCategories::getResultString(CCR);
11870 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11871
11872 if (!ValInfo)
11873 return UnsupportedSTLError(USS_MissingMember, MemName);
11874
11875 VarDecl *VD = ValInfo->VD;
11876 assert(VD && "should not be null!");
11877
11878 // Attempt to diagnose reasons why the STL definition of this type
11879 // might be foobar, including it failing to be a constant expression.
11880 // TODO Handle more ways the lookup or result can be invalid.
11881 if (!VD->isStaticDataMember() ||
11883 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11884
11885 // Attempt to evaluate the var decl as a constant expression and extract
11886 // the value of its first field as a ICE. If this fails, the STL
11887 // implementation is not supported.
11888 if (!ValInfo->hasValidIntValue())
11889 return UnsupportedSTLError();
11890
11892 }
11893
11894 // We've successfully built the required types and expressions. Update
11895 // the cache and return the newly cached value.
11896 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11897 return Info->getType();
11898}
11899
11901 if (!StdNamespace) {
11902 // The "std" namespace has not yet been defined, so build one implicitly.
11905 /*Inline=*/false, SourceLocation(), SourceLocation(),
11906 &PP.getIdentifierTable().get("std"),
11907 /*PrevDecl=*/nullptr, /*Nested=*/false);
11909 // We want the created NamespaceDecl to be available for redeclaration
11910 // lookups, but not for regular name lookups.
11913 }
11914
11915 return getStdNamespace();
11916}
11917
11919 assert(getLangOpts().CPlusPlus &&
11920 "Looking for std::initializer_list outside of C++.");
11921
11922 // We're looking for implicit instantiations of
11923 // template <typename E> class std::initializer_list.
11924
11925 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11926 return false;
11927
11928 ClassTemplateDecl *Template = nullptr;
11929 const TemplateArgument *Arguments = nullptr;
11930
11931 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11932
11934 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11935 if (!Specialization)
11936 return false;
11937
11938 Template = Specialization->getSpecializedTemplate();
11939 Arguments = Specialization->getTemplateArgs().data();
11940 } else {
11941 const TemplateSpecializationType *TST = nullptr;
11942 if (auto *ICN = Ty->getAs<InjectedClassNameType>())
11943 TST = ICN->getInjectedTST();
11944 else
11945 TST = Ty->getAs<TemplateSpecializationType>();
11946 if (TST) {
11947 Template = dyn_cast_or_null<ClassTemplateDecl>(
11949 Arguments = TST->template_arguments().begin();
11950 }
11951 }
11952 if (!Template)
11953 return false;
11954
11955 if (!StdInitializerList) {
11956 // Haven't recognized std::initializer_list yet, maybe this is it.
11957 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11958 if (TemplateClass->getIdentifier() !=
11959 &PP.getIdentifierTable().get("initializer_list") ||
11960 !getStdNamespace()->InEnclosingNamespaceSetOf(
11961 TemplateClass->getNonTransparentDeclContext()))
11962 return false;
11963 // This is a template called std::initializer_list, but is it the right
11964 // template?
11965 TemplateParameterList *Params = Template->getTemplateParameters();
11966 if (Params->getMinRequiredArguments() != 1)
11967 return false;
11968 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11969 return false;
11970
11971 // It's the right template.
11972 StdInitializerList = Template;
11973 }
11974
11976 return false;
11977
11978 // This is an instance of std::initializer_list. Find the argument type.
11979 if (Element)
11980 *Element = Arguments[0].getAsType();
11981 return true;
11982}
11983
11986 if (!Std) {
11987 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11988 return nullptr;
11989 }
11990
11991 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11993 if (!S.LookupQualifiedName(Result, Std)) {
11994 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11995 return nullptr;
11996 }
11997 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11998 if (!Template) {
11999 Result.suppressDiagnostics();
12000 // We found something weird. Complain about the first thing we found.
12001 NamedDecl *Found = *Result.begin();
12002 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12003 return nullptr;
12004 }
12005
12006 // We found some template called std::initializer_list. Now verify that it's
12007 // correct.
12008 TemplateParameterList *Params = Template->getTemplateParameters();
12009 if (Params->getMinRequiredArguments() != 1 ||
12010 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12011 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12012 return nullptr;
12013 }
12014
12015 return Template;
12016}
12017
12019 if (!StdInitializerList) {
12021 if (!StdInitializerList)
12022 return QualType();
12023 }
12024
12028 Loc)));
12033}
12034
12036 // C++ [dcl.init.list]p2:
12037 // A constructor is an initializer-list constructor if its first parameter
12038 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12039 // std::initializer_list<E> for some type E, and either there are no other
12040 // parameters or else all other parameters have default arguments.
12041 if (!Ctor->hasOneParamOrDefaultArgs())
12042 return false;
12043
12044 QualType ArgType = Ctor->getParamDecl(0)->getType();
12045 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12046 ArgType = RT->getPointeeType().getUnqualifiedType();
12047
12048 return isStdInitializerList(ArgType, nullptr);
12049}
12050
12051/// Determine whether a using statement is in a context where it will be
12052/// apply in all contexts.
12054 switch (CurContext->getDeclKind()) {
12055 case Decl::TranslationUnit:
12056 return true;
12057 case Decl::LinkageSpec:
12059 default:
12060 return false;
12061 }
12062}
12063
12064namespace {
12065
12066// Callback to only accept typo corrections that are namespaces.
12067class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12068public:
12069 bool ValidateCandidate(const TypoCorrection &candidate) override {
12070 if (NamedDecl *ND = candidate.getCorrectionDecl())
12071 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12072 return false;
12073 }
12074
12075 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12076 return std::make_unique<NamespaceValidatorCCC>(*this);
12077 }
12078};
12079
12080}
12081
12082static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12083 Sema &S) {
12084 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12085 Module *M = ND->getOwningModule();
12086 assert(M && "hidden namespace definition not in a module?");
12087
12088 if (M->isExplicitGlobalModule())
12089 S.Diag(Corrected.getCorrectionRange().getBegin(),
12090 diag::err_module_unimported_use_header)
12092 << /*Header Name*/ false;
12093 else
12094 S.Diag(Corrected.getCorrectionRange().getBegin(),
12095 diag::err_module_unimported_use)
12097 << M->getTopLevelModuleName();
12098}
12099
12101 CXXScopeSpec &SS,
12102 SourceLocation IdentLoc,
12103 IdentifierInfo *Ident) {
12104 R.clear();
12105 NamespaceValidatorCCC CCC{};
12106 if (TypoCorrection Corrected =
12107 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12109 // Generally we find it is confusing more than helpful to diagnose the
12110 // invisible namespace.
12111 // See https://github.com/llvm/llvm-project/issues/73893.
12112 //
12113 // However, we should diagnose when the users are trying to using an
12114 // invisible namespace. So we handle the case specially here.
12115 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12116 Corrected.requiresImport()) {
12117 DiagnoseInvisibleNamespace(Corrected, S);
12118 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12119 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12120 bool DroppedSpecifier =
12121 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12122 S.diagnoseTypo(Corrected,
12123 S.PDiag(diag::err_using_directive_member_suggest)
12124 << Ident << DC << DroppedSpecifier << SS.getRange(),
12125 S.PDiag(diag::note_namespace_defined_here));
12126 } else {
12127 S.diagnoseTypo(Corrected,
12128 S.PDiag(diag::err_using_directive_suggest) << Ident,
12129 S.PDiag(diag::note_namespace_defined_here));
12130 }
12131 R.addDecl(Corrected.getFoundDecl());
12132 return true;
12133 }
12134 return false;
12135}
12136
12138 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12139 SourceLocation IdentLoc,
12140 IdentifierInfo *NamespcName,
12141 const ParsedAttributesView &AttrList) {
12142 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12143 assert(NamespcName && "Invalid NamespcName.");
12144 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12145
12146 // Get the innermost enclosing declaration scope.
12147 S = S->getDeclParent();
12148
12149 UsingDirectiveDecl *UDir = nullptr;
12150 NestedNameSpecifier *Qualifier = nullptr;
12151 if (SS.isSet())
12152 Qualifier = SS.getScopeRep();
12153
12154 // Lookup namespace name.
12155 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12156 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12157 if (R.isAmbiguous())
12158 return nullptr;
12159
12160 if (R.empty()) {
12161 R.clear();
12162 // Allow "using namespace std;" or "using namespace ::std;" even if
12163 // "std" hasn't been defined yet, for GCC compatibility.
12164 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12165 NamespcName->isStr("std")) {
12166 Diag(IdentLoc, diag::ext_using_undefined_std);
12168 R.resolveKind();
12169 }
12170 // Otherwise, attempt typo correction.
12171 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12172 }
12173
12174 if (!R.empty()) {
12175 NamedDecl *Named = R.getRepresentativeDecl();
12177 assert(NS && "expected namespace decl");
12178
12179 // The use of a nested name specifier may trigger deprecation warnings.
12180 DiagnoseUseOfDecl(Named, IdentLoc);
12181
12182 // C++ [namespace.udir]p1:
12183 // A using-directive specifies that the names in the nominated
12184 // namespace can be used in the scope in which the
12185 // using-directive appears after the using-directive. During
12186 // unqualified name lookup (3.4.1), the names appear as if they
12187 // were declared in the nearest enclosing namespace which
12188 // contains both the using-directive and the nominated
12189 // namespace. [Note: in this context, "contains" means "contains
12190 // directly or indirectly". ]
12191
12192 // Find enclosing context containing both using-directive and
12193 // nominated namespace.
12194 DeclContext *CommonAncestor = NS;
12195 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12196 CommonAncestor = CommonAncestor->getParent();
12197
12198 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12200 IdentLoc, Named, CommonAncestor);
12201
12204 Diag(IdentLoc, diag::warn_using_directive_in_header);
12205 }
12206
12207 PushUsingDirective(S, UDir);
12208 } else {
12209 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12210 }
12211
12212 if (UDir) {
12213 ProcessDeclAttributeList(S, UDir, AttrList);
12214 ProcessAPINotes(UDir);
12215 }
12216
12217 return UDir;
12218}
12219
12221 // If the scope has an associated entity and the using directive is at
12222 // namespace or translation unit scope, add the UsingDirectiveDecl into
12223 // its lookup structure so qualified name lookup can find it.
12224 DeclContext *Ctx = S->getEntity();
12225 if (Ctx && !Ctx->isFunctionOrMethod())
12226 Ctx->addDecl(UDir);
12227 else
12228 // Otherwise, it is at block scope. The using-directives will affect lookup
12229 // only to the end of the scope.
12230 S->PushUsingDirective(UDir);
12231}
12232
12234 SourceLocation UsingLoc,
12235 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12236 UnqualifiedId &Name,
12237 SourceLocation EllipsisLoc,
12238 const ParsedAttributesView &AttrList) {
12239 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12240
12241 if (SS.isEmpty()) {
12242 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12243 return nullptr;
12244 }
12245
12246 switch (Name.getKind()) {
12252 break;
12253
12256 // C++11 inheriting constructors.
12257 Diag(Name.getBeginLoc(),
12259 ? diag::warn_cxx98_compat_using_decl_constructor
12260 : diag::err_using_decl_constructor)
12261 << SS.getRange();
12262
12263 if (getLangOpts().CPlusPlus11) break;
12264
12265 return nullptr;
12266
12268 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12269 return nullptr;
12270
12272 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12273 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12274 return nullptr;
12275
12277 llvm_unreachable("cannot parse qualified deduction guide name");
12278 }
12279
12280 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12281 DeclarationName TargetName = TargetNameInfo.getName();
12282 if (!TargetName)
12283 return nullptr;
12284
12285 // Warn about access declarations.
12286 if (UsingLoc.isInvalid()) {
12287 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12288 ? diag::err_access_decl
12289 : diag::warn_access_decl_deprecated)
12290 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12291 }
12292
12293 if (EllipsisLoc.isInvalid()) {
12296 return nullptr;
12297 } else {
12299 !TargetNameInfo.containsUnexpandedParameterPack()) {
12300 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12301 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12302 EllipsisLoc = SourceLocation();
12303 }
12304 }
12305
12306 NamedDecl *UD =
12307 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12308 SS, TargetNameInfo, EllipsisLoc, AttrList,
12309 /*IsInstantiation*/ false,
12310 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12311 if (UD)
12312 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12313
12314 return UD;
12315}
12316
12318 SourceLocation UsingLoc,
12319 SourceLocation EnumLoc, SourceRange TyLoc,
12320 const IdentifierInfo &II, ParsedType Ty,
12321 CXXScopeSpec *SS) {
12322 assert(SS && !SS->isInvalid() && "ScopeSpec is invalid");
12323 TypeSourceInfo *TSI = nullptr;
12324 SourceLocation IdentLoc = TyLoc.getBegin();
12325 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12326 if (EnumTy.isNull()) {
12327 Diag(IdentLoc, isDependentScopeSpecifier(*SS)
12328 ? diag::err_using_enum_is_dependent
12329 : diag::err_unknown_typename)
12330 << II.getName() << SourceRange(SS->getBeginLoc(), TyLoc.getEnd());
12331 return nullptr;
12332 }
12333
12334 if (EnumTy->isDependentType()) {
12335 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12336 return nullptr;
12337 }
12338
12339 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12340 if (!Enum) {
12341 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12342 return nullptr;
12343 }
12344
12345 if (auto *Def = Enum->getDefinition())
12346 Enum = Def;
12347
12348 if (TSI == nullptr)
12349 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12350
12351 auto *UD =
12352 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12353
12354 if (UD)
12355 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12356
12357 return UD;
12358}
12359
12360/// Determine whether a using declaration considers the given
12361/// declarations as "equivalent", e.g., if they are redeclarations of
12362/// the same entity or are both typedefs of the same type.
12363static bool
12365 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12366 return true;
12367
12368 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12369 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12370 return Context.hasSameType(TD1->getUnderlyingType(),
12371 TD2->getUnderlyingType());
12372
12373 // Two using_if_exists using-declarations are equivalent if both are
12374 // unresolved.
12375 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12376 isa<UnresolvedUsingIfExistsDecl>(D2))
12377 return true;
12378
12379 return false;
12380}
12381
12383 const LookupResult &Previous,
12384 UsingShadowDecl *&PrevShadow) {
12385 // Diagnose finding a decl which is not from a base class of the
12386 // current class. We do this now because there are cases where this
12387 // function will silently decide not to build a shadow decl, which
12388 // will pre-empt further diagnostics.
12389 //
12390 // We don't need to do this in C++11 because we do the check once on
12391 // the qualifier.
12392 //
12393 // FIXME: diagnose the following if we care enough:
12394 // struct A { int foo; };
12395 // struct B : A { using A::foo; };
12396 // template <class T> struct C : A {};
12397 // template <class T> struct D : C<T> { using B::foo; } // <---
12398 // This is invalid (during instantiation) in C++03 because B::foo
12399 // resolves to the using decl in B, which is not a base class of D<T>.
12400 // We can't diagnose it immediately because C<T> is an unknown
12401 // specialization. The UsingShadowDecl in D<T> then points directly
12402 // to A::foo, which will look well-formed when we instantiate.
12403 // The right solution is to not collapse the shadow-decl chain.
12405 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12406 DeclContext *OrigDC = Orig->getDeclContext();
12407
12408 // Handle enums and anonymous structs.
12409 if (isa<EnumDecl>(OrigDC))
12410 OrigDC = OrigDC->getParent();
12411 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12412 while (OrigRec->isAnonymousStructOrUnion())
12413 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12414
12415 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12416 if (OrigDC == CurContext) {
12417 Diag(Using->getLocation(),
12418 diag::err_using_decl_nested_name_specifier_is_current_class)
12419 << Using->getQualifierLoc().getSourceRange();
12420 Diag(Orig->getLocation(), diag::note_using_decl_target);
12421 Using->setInvalidDecl();
12422 return true;
12423 }
12424
12425 Diag(Using->getQualifierLoc().getBeginLoc(),
12426 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12427 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12428 << Using->getQualifierLoc().getSourceRange();
12429 Diag(Orig->getLocation(), diag::note_using_decl_target);
12430 Using->setInvalidDecl();
12431 return true;
12432 }
12433 }
12434
12435 if (Previous.empty()) return false;
12436
12437 NamedDecl *Target = Orig;
12438 if (isa<UsingShadowDecl>(Target))
12439 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12440
12441 // If the target happens to be one of the previous declarations, we
12442 // don't have a conflict.
12443 //
12444 // FIXME: but we might be increasing its access, in which case we
12445 // should redeclare it.
12446 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12447 bool FoundEquivalentDecl = false;
12448 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12449 I != E; ++I) {
12450 NamedDecl *D = (*I)->getUnderlyingDecl();
12451 // We can have UsingDecls in our Previous results because we use the same
12452 // LookupResult for checking whether the UsingDecl itself is a valid
12453 // redeclaration.
12454 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12455 continue;
12456
12457 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12458 // C++ [class.mem]p19:
12459 // If T is the name of a class, then [every named member other than
12460 // a non-static data member] shall have a name different from T
12461 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12462 !isa<IndirectFieldDecl>(Target) &&
12463 !isa<UnresolvedUsingValueDecl>(Target) &&
12465 CurContext,
12467 return true;
12468 }
12469
12471 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12472 PrevShadow = Shadow;
12473 FoundEquivalentDecl = true;
12475 // We don't conflict with an existing using shadow decl of an equivalent
12476 // declaration, but we're not a redeclaration of it.
12477 FoundEquivalentDecl = true;
12478 }
12479
12480 if (isVisible(D))
12481 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12482 }
12483
12484 if (FoundEquivalentDecl)
12485 return false;
12486
12487 // Always emit a diagnostic for a mismatch between an unresolved
12488 // using_if_exists and a resolved using declaration in either direction.
12489 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12490 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12491 if (!NonTag && !Tag)
12492 return false;
12493 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12494 Diag(Target->getLocation(), diag::note_using_decl_target);
12495 Diag((NonTag ? NonTag : Tag)->getLocation(),
12496 diag::note_using_decl_conflict);
12497 BUD->setInvalidDecl();
12498 return true;
12499 }
12500
12501 if (FunctionDecl *FD = Target->getAsFunction()) {
12502 NamedDecl *OldDecl = nullptr;
12503 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12504 /*IsForUsingDecl*/ true)) {
12505 case Ovl_Overload:
12506 return false;
12507
12508 case Ovl_NonFunction:
12509 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12510 break;
12511
12512 // We found a decl with the exact signature.
12513 case Ovl_Match:
12514 // If we're in a record, we want to hide the target, so we
12515 // return true (without a diagnostic) to tell the caller not to
12516 // build a shadow decl.
12517 if (CurContext->isRecord())
12518 return true;
12519
12520 // If we're not in a record, this is an error.
12521 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12522 break;
12523 }
12524
12525 Diag(Target->getLocation(), diag::note_using_decl_target);
12526 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12527 BUD->setInvalidDecl();
12528 return true;
12529 }
12530
12531 // Target is not a function.
12532
12533 if (isa<TagDecl>(Target)) {
12534 // No conflict between a tag and a non-tag.
12535 if (!Tag) return false;
12536
12537 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12538 Diag(Target->getLocation(), diag::note_using_decl_target);
12539 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12540 BUD->setInvalidDecl();
12541 return true;
12542 }
12543
12544 // No conflict between a tag and a non-tag.
12545 if (!NonTag) return false;
12546
12547 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12548 Diag(Target->getLocation(), diag::note_using_decl_target);
12549 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12550 BUD->setInvalidDecl();
12551 return true;
12552}
12553
12554/// Determine whether a direct base class is a virtual base class.
12556 if (!Derived->getNumVBases())
12557 return false;
12558 for (auto &B : Derived->bases())
12559 if (B.getType()->getAsCXXRecordDecl() == Base)
12560 return B.isVirtual();
12561 llvm_unreachable("not a direct base class");
12562}
12563
12565 NamedDecl *Orig,
12566 UsingShadowDecl *PrevDecl) {
12567 // If we resolved to another shadow declaration, just coalesce them.
12568 NamedDecl *Target = Orig;
12569 if (isa<UsingShadowDecl>(Target)) {
12570 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12571 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12572 }
12573
12574 NamedDecl *NonTemplateTarget = Target;
12575 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12576 NonTemplateTarget = TargetTD->getTemplatedDecl();
12577
12578 UsingShadowDecl *Shadow;
12579 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12580 UsingDecl *Using = cast<UsingDecl>(BUD);
12581 bool IsVirtualBase =
12582 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12583 Using->getQualifier()->getAsRecordDecl());
12585 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12586 } else {
12588 Target->getDeclName(), BUD, Target);
12589 }
12590 BUD->addShadowDecl(Shadow);
12591
12592 Shadow->setAccess(BUD->getAccess());
12593 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12594 Shadow->setInvalidDecl();
12595
12596 Shadow->setPreviousDecl(PrevDecl);
12597
12598 if (S)
12599 PushOnScopeChains(Shadow, S);
12600 else
12601 CurContext->addDecl(Shadow);
12602
12603
12604 return Shadow;
12605}
12606
12608 if (Shadow->getDeclName().getNameKind() ==
12610 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12611
12612 // Remove it from the DeclContext...
12613 Shadow->getDeclContext()->removeDecl(Shadow);
12614
12615 // ...and the scope, if applicable...
12616 if (S) {
12617 S->RemoveDecl(Shadow);
12618 IdResolver.RemoveDecl(Shadow);
12619 }
12620
12621 // ...and the using decl.
12622 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12623
12624 // TODO: complain somehow if Shadow was used. It shouldn't
12625 // be possible for this to happen, because...?
12626}
12627
12628/// Find the base specifier for a base class with the given type.
12630 QualType DesiredBase,
12631 bool &AnyDependentBases) {
12632 // Check whether the named type is a direct base class.
12633 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12635 for (auto &Base : Derived->bases()) {
12636 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12637 if (CanonicalDesiredBase == BaseType)
12638 return &Base;
12639 if (BaseType->isDependentType())
12640 AnyDependentBases = true;
12641 }
12642 return nullptr;
12643}
12644
12645namespace {
12646class UsingValidatorCCC final : public CorrectionCandidateCallback {
12647public:
12648 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12649 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12650 : HasTypenameKeyword(HasTypenameKeyword),
12651 IsInstantiation(IsInstantiation), OldNNS(NNS),
12652 RequireMemberOf(RequireMemberOf) {}
12653
12654 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12655 NamedDecl *ND = Candidate.getCorrectionDecl();
12656
12657 // Keywords are not valid here.
12658 if (!ND || isa<NamespaceDecl>(ND))
12659 return false;
12660
12661 // Completely unqualified names are invalid for a 'using' declaration.
12662 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12663 return false;
12664
12665 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12666 // reject.
12667
12668 if (RequireMemberOf) {
12669 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12670 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12671 // No-one ever wants a using-declaration to name an injected-class-name
12672 // of a base class, unless they're declaring an inheriting constructor.
12673 ASTContext &Ctx = ND->getASTContext();
12674 if (!Ctx.getLangOpts().CPlusPlus11)
12675 return false;
12676 QualType FoundType = Ctx.getRecordType(FoundRecord);
12677
12678 // Check that the injected-class-name is named as a member of its own
12679 // type; we don't want to suggest 'using Derived::Base;', since that
12680 // means something else.
12682 Candidate.WillReplaceSpecifier()
12683 ? Candidate.getCorrectionSpecifier()
12684 : OldNNS;
12685 if (!Specifier->getAsType() ||
12686 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12687 return false;
12688
12689 // Check that this inheriting constructor declaration actually names a
12690 // direct base class of the current class.
12691 bool AnyDependentBases = false;
12692 if (!findDirectBaseWithType(RequireMemberOf,
12693 Ctx.getRecordType(FoundRecord),
12694 AnyDependentBases) &&
12695 !AnyDependentBases)
12696 return false;
12697 } else {
12698 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12699 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12700 return false;
12701
12702 // FIXME: Check that the base class member is accessible?
12703 }
12704 } else {
12705 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12706 if (FoundRecord && FoundRecord->isInjectedClassName())
12707 return false;
12708 }
12709
12710 if (isa<TypeDecl>(ND))
12711 return HasTypenameKeyword || !IsInstantiation;
12712
12713 return !HasTypenameKeyword;
12714 }
12715
12716 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12717 return std::make_unique<UsingValidatorCCC>(*this);
12718 }
12719
12720private:
12721 bool HasTypenameKeyword;
12722 bool IsInstantiation;
12723 NestedNameSpecifier *OldNNS;
12724 CXXRecordDecl *RequireMemberOf;
12725};
12726} // end anonymous namespace
12727
12729 // It is really dumb that we have to do this.
12730 LookupResult::Filter F = Previous.makeFilter();
12731 while (F.hasNext()) {
12732 NamedDecl *D = F.next();
12733 if (!isDeclInScope(D, CurContext, S))
12734 F.erase();
12735 // If we found a local extern declaration that's not ordinarily visible,
12736 // and this declaration is being added to a non-block scope, ignore it.
12737 // We're only checking for scope conflicts here, not also for violations
12738 // of the linkage rules.
12739 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12741 F.erase();
12742 }
12743 F.done();
12744}
12745
12747 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12748 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12749 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12750 const ParsedAttributesView &AttrList, bool IsInstantiation,
12751 bool IsUsingIfExists) {
12752 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12753 SourceLocation IdentLoc = NameInfo.getLoc();
12754 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12755
12756 // FIXME: We ignore attributes for now.
12757
12758 // For an inheriting constructor declaration, the name of the using
12759 // declaration is the name of a constructor in this class, not in the
12760 // base class.
12761 DeclarationNameInfo UsingName = NameInfo;
12763 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12766
12767 // Do the redeclaration lookup in the current scope.
12768 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12769 RedeclarationKind::ForVisibleRedeclaration);
12770 Previous.setHideTags(false);
12771 if (S) {
12772 LookupName(Previous, S);
12773
12775 } else {
12776 assert(IsInstantiation && "no scope in non-instantiation");
12777 if (CurContext->isRecord())
12779 else {
12780 // No redeclaration check is needed here; in non-member contexts we
12781 // diagnosed all possible conflicts with other using-declarations when
12782 // building the template:
12783 //
12784 // For a dependent non-type using declaration, the only valid case is
12785 // if we instantiate to a single enumerator. We check for conflicts
12786 // between shadow declarations we introduce, and we check in the template
12787 // definition for conflicts between a non-type using declaration and any
12788 // other declaration, which together covers all cases.
12789 //
12790 // A dependent typename using declaration will never successfully
12791 // instantiate, since it will always name a class member, so we reject
12792 // that in the template definition.
12793 }
12794 }
12795
12796 // Check for invalid redeclarations.
12797 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12798 SS, IdentLoc, Previous))
12799 return nullptr;
12800
12801 // 'using_if_exists' doesn't make sense on an inherited constructor.
12802 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12804 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12805 return nullptr;
12806 }
12807
12808 DeclContext *LookupContext = computeDeclContext(SS);
12810 if (!LookupContext || EllipsisLoc.isValid()) {
12811 NamedDecl *D;
12812 // Dependent scope, or an unexpanded pack
12813 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12814 SS, NameInfo, IdentLoc))
12815 return nullptr;
12816
12817 if (HasTypenameKeyword) {
12818 // FIXME: not all declaration name kinds are legal here
12820 UsingLoc, TypenameLoc,
12821 QualifierLoc,
12822 IdentLoc, NameInfo.getName(),
12823 EllipsisLoc);
12824 } else {
12826 QualifierLoc, NameInfo, EllipsisLoc);
12827 }
12828 D->setAccess(AS);
12830 ProcessDeclAttributeList(S, D, AttrList);
12831 return D;
12832 }
12833
12834 auto Build = [&](bool Invalid) {
12835 UsingDecl *UD =
12836 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12837 UsingName, HasTypenameKeyword);
12838 UD->setAccess(AS);
12839 CurContext->addDecl(UD);
12840 ProcessDeclAttributeList(S, UD, AttrList);
12842 return UD;
12843 };
12844 auto BuildInvalid = [&]{ return Build(true); };
12845 auto BuildValid = [&]{ return Build(false); };
12846
12847 if (RequireCompleteDeclContext(SS, LookupContext))
12848 return BuildInvalid();
12849
12850 // Look up the target name.
12851 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12852
12853 // Unlike most lookups, we don't always want to hide tag
12854 // declarations: tag names are visible through the using declaration
12855 // even if hidden by ordinary names, *except* in a dependent context
12856 // where they may be used by two-phase lookup.
12857 if (!IsInstantiation)
12858 R.setHideTags(false);
12859
12860 // For the purposes of this lookup, we have a base object type
12861 // equal to that of the current context.
12862 if (CurContext->isRecord()) {
12864 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12865 }
12866
12867 LookupQualifiedName(R, LookupContext);
12868
12869 // Validate the context, now we have a lookup
12870 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12871 IdentLoc, &R))
12872 return nullptr;
12873
12874 if (R.empty() && IsUsingIfExists)
12876 UsingName.getName()),
12877 AS_public);
12878
12879 // Try to correct typos if possible. If constructor name lookup finds no
12880 // results, that means the named class has no explicit constructors, and we
12881 // suppressed declaring implicit ones (probably because it's dependent or
12882 // invalid).
12883 if (R.empty() &&
12885 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12886 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12887 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12888 auto *II = NameInfo.getName().getAsIdentifierInfo();
12889 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12891 isa<TranslationUnitDecl>(LookupContext) &&
12892 getSourceManager().isInSystemHeader(UsingLoc))
12893 return nullptr;
12894 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12895 dyn_cast<CXXRecordDecl>(CurContext));
12896 if (TypoCorrection Corrected =
12897 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12899 // We reject candidates where DroppedSpecifier == true, hence the
12900 // literal '0' below.
12901 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12902 << NameInfo.getName() << LookupContext << 0
12903 << SS.getRange());
12904
12905 // If we picked a correction with no attached Decl we can't do anything
12906 // useful with it, bail out.
12907 NamedDecl *ND = Corrected.getCorrectionDecl();
12908 if (!ND)
12909 return BuildInvalid();
12910
12911 // If we corrected to an inheriting constructor, handle it as one.
12912 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12913 if (RD && RD->isInjectedClassName()) {
12914 // The parent of the injected class name is the class itself.
12915 RD = cast<CXXRecordDecl>(RD->getParent());
12916
12917 // Fix up the information we'll use to build the using declaration.
12918 if (Corrected.WillReplaceSpecifier()) {
12920 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12921 QualifierLoc.getSourceRange());
12922 QualifierLoc = Builder.getWithLocInContext(Context);
12923 }
12924
12925 // In this case, the name we introduce is the name of a derived class
12926 // constructor.
12927 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12930 UsingName.setNamedTypeInfo(nullptr);
12931 for (auto *Ctor : LookupConstructors(RD))
12932 R.addDecl(Ctor);
12933 R.resolveKind();
12934 } else {
12935 // FIXME: Pick up all the declarations if we found an overloaded
12936 // function.
12937 UsingName.setName(ND->getDeclName());
12938 R.addDecl(ND);
12939 }
12940 } else {
12941 Diag(IdentLoc, diag::err_no_member)
12942 << NameInfo.getName() << LookupContext << SS.getRange();
12943 return BuildInvalid();
12944 }
12945 }
12946
12947 if (R.isAmbiguous())
12948 return BuildInvalid();
12949
12950 if (HasTypenameKeyword) {
12951 // If we asked for a typename and got a non-type decl, error out.
12952 if (!R.getAsSingle<TypeDecl>() &&
12954 Diag(IdentLoc, diag::err_using_typename_non_type);
12955 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12956 Diag((*I)->getUnderlyingDecl()->getLocation(),
12957 diag::note_using_decl_target);
12958 return BuildInvalid();
12959 }
12960 } else {
12961 // If we asked for a non-typename and we got a type, error out,
12962 // but only if this is an instantiation of an unresolved using
12963 // decl. Otherwise just silently find the type name.
12964 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12965 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12966 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12967 return BuildInvalid();
12968 }
12969 }
12970
12971 // C++14 [namespace.udecl]p6:
12972 // A using-declaration shall not name a namespace.
12973 if (R.getAsSingle<NamespaceDecl>()) {
12974 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12975 << SS.getRange();
12976 // Suggest using 'using namespace ...' instead.
12977 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
12978 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
12979 return BuildInvalid();
12980 }
12981
12982 UsingDecl *UD = BuildValid();
12983
12984 // Some additional rules apply to inheriting constructors.
12985 if (UsingName.getName().getNameKind() ==
12987 // Suppress access diagnostics; the access check is instead performed at the
12988 // point of use for an inheriting constructor.
12991 return UD;
12992 }
12993
12994 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12995 UsingShadowDecl *PrevDecl = nullptr;
12996 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12997 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12998 }
12999
13000 return UD;
13001}
13002
13004 SourceLocation UsingLoc,
13005 SourceLocation EnumLoc,
13006 SourceLocation NameLoc,
13008 EnumDecl *ED) {
13009 bool Invalid = false;
13010
13012 /// In class scope, check if this is a duplicate, for better a diagnostic.
13013 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13014 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13015 RedeclarationKind::ForVisibleRedeclaration);
13016
13017 LookupName(Previous, S);
13018
13019 for (NamedDecl *D : Previous)
13020 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13021 if (UED->getEnumDecl() == ED) {
13022 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13023 << SourceRange(EnumLoc, NameLoc);
13024 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13025 Invalid = true;
13026 break;
13027 }
13028 }
13029
13030 if (RequireCompleteEnumDecl(ED, NameLoc))
13031 Invalid = true;
13032
13034 EnumLoc, NameLoc, EnumType);
13035 UD->setAccess(AS);
13036 CurContext->addDecl(UD);
13037
13038 if (Invalid) {
13039 UD->setInvalidDecl();
13040 return UD;
13041 }
13042
13043 // Create the shadow decls for each enumerator
13044 for (EnumConstantDecl *EC : ED->enumerators()) {
13045 UsingShadowDecl *PrevDecl = nullptr;
13046 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13048 RedeclarationKind::ForVisibleRedeclaration);
13049 LookupName(Previous, S);
13051
13052 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13053 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13054 }
13055
13056 return UD;
13057}
13058
13060 ArrayRef<NamedDecl *> Expansions) {
13061 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13062 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13063 isa<UsingPackDecl>(InstantiatedFrom));
13064
13065 auto *UPD =
13066 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13067 UPD->setAccess(InstantiatedFrom->getAccess());
13068 CurContext->addDecl(UPD);
13069 return UPD;
13070}
13071
13073 assert(!UD->hasTypename() && "expecting a constructor name");
13074
13075 const Type *SourceType = UD->getQualifier()->getAsType();
13076 assert(SourceType &&
13077 "Using decl naming constructor doesn't have type in scope spec.");
13078 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13079
13080 // Check whether the named type is a direct base class.
13081 bool AnyDependentBases = false;
13082 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13083 AnyDependentBases);
13084 if (!Base && !AnyDependentBases) {
13085 Diag(UD->getUsingLoc(),
13086 diag::err_using_decl_constructor_not_in_direct_base)
13087 << UD->getNameInfo().getSourceRange()
13088 << QualType(SourceType, 0) << TargetClass;
13089 UD->setInvalidDecl();
13090 return true;
13091 }
13092
13093 if (Base)
13094 Base->setInheritConstructors();
13095
13096 return false;
13097}
13098
13100 bool HasTypenameKeyword,
13101 const CXXScopeSpec &SS,
13102 SourceLocation NameLoc,
13103 const LookupResult &Prev) {
13104 NestedNameSpecifier *Qual = SS.getScopeRep();
13105
13106 // C++03 [namespace.udecl]p8:
13107 // C++0x [namespace.udecl]p10:
13108 // A using-declaration is a declaration and can therefore be used
13109 // repeatedly where (and only where) multiple declarations are
13110 // allowed.
13111 //
13112 // That's in non-member contexts.
13114 // A dependent qualifier outside a class can only ever resolve to an
13115 // enumeration type. Therefore it conflicts with any other non-type
13116 // declaration in the same scope.
13117 // FIXME: How should we check for dependent type-type conflicts at block
13118 // scope?
13119 if (Qual->isDependent() && !HasTypenameKeyword) {
13120 for (auto *D : Prev) {
13121 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13122 bool OldCouldBeEnumerator =
13123 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13124 Diag(NameLoc,
13125 OldCouldBeEnumerator ? diag::err_redefinition
13126 : diag::err_redefinition_different_kind)
13127 << Prev.getLookupName();
13128 Diag(D->getLocation(), diag::note_previous_definition);
13129 return true;
13130 }
13131 }
13132 }
13133 return false;
13134 }
13135
13136 const NestedNameSpecifier *CNNS =
13138 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13139 NamedDecl *D = *I;
13140
13141 bool DTypename;
13142 NestedNameSpecifier *DQual;
13143 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13144 DTypename = UD->hasTypename();
13145 DQual = UD->getQualifier();
13146 } else if (UnresolvedUsingValueDecl *UD
13147 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13148 DTypename = false;
13149 DQual = UD->getQualifier();
13150 } else if (UnresolvedUsingTypenameDecl *UD
13151 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13152 DTypename = true;
13153 DQual = UD->getQualifier();
13154 } else continue;
13155
13156 // using decls differ if one says 'typename' and the other doesn't.
13157 // FIXME: non-dependent using decls?
13158 if (HasTypenameKeyword != DTypename) continue;
13159
13160 // using decls differ if they name different scopes (but note that
13161 // template instantiation can cause this check to trigger when it
13162 // didn't before instantiation).
13163 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13164 continue;
13165
13166 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13167 Diag(D->getLocation(), diag::note_using_decl) << 1;
13168 return true;
13169 }
13170
13171 return false;
13172}
13173
13174bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13175 const CXXScopeSpec &SS,
13176 const DeclarationNameInfo &NameInfo,
13177 SourceLocation NameLoc,
13178 const LookupResult *R, const UsingDecl *UD) {
13179 DeclContext *NamedContext = computeDeclContext(SS);
13180 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13181 "resolvable context must have exactly one set of decls");
13182
13183 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13184 // relationship.
13185 bool Cxx20Enumerator = false;
13186 if (NamedContext) {
13187 EnumConstantDecl *EC = nullptr;
13188 if (R)
13189 EC = R->getAsSingle<EnumConstantDecl>();
13190 else if (UD && UD->shadow_size() == 1)
13191 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13192 if (EC)
13193 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13194
13195 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13196 // C++14 [namespace.udecl]p7:
13197 // A using-declaration shall not name a scoped enumerator.
13198 // C++20 p1099 permits enumerators.
13199 if (EC && R && ED->isScoped())
13200 Diag(SS.getBeginLoc(),
13202 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13203 : diag::ext_using_decl_scoped_enumerator)
13204 << SS.getRange();
13205
13206 // We want to consider the scope of the enumerator
13207 NamedContext = ED->getDeclContext();
13208 }
13209 }
13210
13211 if (!CurContext->isRecord()) {
13212 // C++03 [namespace.udecl]p3:
13213 // C++0x [namespace.udecl]p8:
13214 // A using-declaration for a class member shall be a member-declaration.
13215 // C++20 [namespace.udecl]p7
13216 // ... other than an enumerator ...
13217
13218 // If we weren't able to compute a valid scope, it might validly be a
13219 // dependent class or enumeration scope. If we have a 'typename' keyword,
13220 // the scope must resolve to a class type.
13221 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13222 : !HasTypename)
13223 return false; // OK
13224
13225 Diag(NameLoc,
13226 Cxx20Enumerator
13227 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13228 : diag::err_using_decl_can_not_refer_to_class_member)
13229 << SS.getRange();
13230
13231 if (Cxx20Enumerator)
13232 return false; // OK
13233
13234 auto *RD = NamedContext
13235 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13236 : nullptr;
13237 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13238 // See if there's a helpful fixit
13239
13240 if (!R) {
13241 // We will have already diagnosed the problem on the template
13242 // definition, Maybe we should do so again?
13243 } else if (R->getAsSingle<TypeDecl>()) {
13244 if (getLangOpts().CPlusPlus11) {
13245 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13246 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13247 << diag::MemClassWorkaround::AliasDecl
13249 NameInfo.getName().getAsString() +
13250 " = ");
13251 } else {
13252 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13253 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13254 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13255 << diag::MemClassWorkaround::TypedefDecl
13256 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13258 InsertLoc, " " + NameInfo.getName().getAsString());
13259 }
13260 } else if (R->getAsSingle<VarDecl>()) {
13261 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13262 // repeating the type of the static data member here.
13263 FixItHint FixIt;
13264 if (getLangOpts().CPlusPlus11) {
13265 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13267 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13268 }
13269
13270 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13271 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13272 } else if (R->getAsSingle<EnumConstantDecl>()) {
13273 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13274 // repeating the type of the enumeration here, and we can't do so if
13275 // the type is anonymous.
13276 FixItHint FixIt;
13277 if (getLangOpts().CPlusPlus11) {
13278 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13280 UsingLoc,
13281 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13282 }
13283
13284 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13285 << (getLangOpts().CPlusPlus11
13286 ? diag::MemClassWorkaround::ConstexprVar
13287 : diag::MemClassWorkaround::ConstVar)
13288 << FixIt;
13289 }
13290 }
13291
13292 return true; // Fail
13293 }
13294
13295 // If the named context is dependent, we can't decide much.
13296 if (!NamedContext) {
13297 // FIXME: in C++0x, we can diagnose if we can prove that the
13298 // nested-name-specifier does not refer to a base class, which is
13299 // still possible in some cases.
13300
13301 // Otherwise we have to conservatively report that things might be
13302 // okay.
13303 return false;
13304 }
13305
13306 // The current scope is a record.
13307 if (!NamedContext->isRecord()) {
13308 // Ideally this would point at the last name in the specifier,
13309 // but we don't have that level of source info.
13310 Diag(SS.getBeginLoc(),
13311 Cxx20Enumerator
13312 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13313 : diag::err_using_decl_nested_name_specifier_is_not_class)
13314 << SS.getScopeRep() << SS.getRange();
13315
13316 if (Cxx20Enumerator)
13317 return false; // OK
13318
13319 return true;
13320 }
13321
13322 if (!NamedContext->isDependentContext() &&
13323 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13324 return true;
13325
13326 if (getLangOpts().CPlusPlus11) {
13327 // C++11 [namespace.udecl]p3:
13328 // In a using-declaration used as a member-declaration, the
13329 // nested-name-specifier shall name a base class of the class
13330 // being defined.
13331
13332 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13333 cast<CXXRecordDecl>(NamedContext))) {
13334
13335 if (Cxx20Enumerator) {
13336 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13337 << SS.getRange();
13338 return false;
13339 }
13340
13341 if (CurContext == NamedContext) {
13342 Diag(SS.getBeginLoc(),
13343 diag::err_using_decl_nested_name_specifier_is_current_class)
13344 << SS.getRange();
13345 return !getLangOpts().CPlusPlus20;
13346 }
13347
13348 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13349 Diag(SS.getBeginLoc(),
13350 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13351 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13352 << SS.getRange();
13353 }
13354 return true;
13355 }
13356
13357 return false;
13358 }
13359
13360 // C++03 [namespace.udecl]p4:
13361 // A using-declaration used as a member-declaration shall refer
13362 // to a member of a base class of the class being defined [etc.].
13363
13364 // Salient point: SS doesn't have to name a base class as long as
13365 // lookup only finds members from base classes. Therefore we can
13366 // diagnose here only if we can prove that can't happen,
13367 // i.e. if the class hierarchies provably don't intersect.
13368
13369 // TODO: it would be nice if "definitely valid" results were cached
13370 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13371 // need to be repeated.
13372
13374 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13375 Bases.insert(Base);
13376 return true;
13377 };
13378
13379 // Collect all bases. Return false if we find a dependent base.
13380 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13381 return false;
13382
13383 // Returns true if the base is dependent or is one of the accumulated base
13384 // classes.
13385 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13386 return !Bases.count(Base);
13387 };
13388
13389 // Return false if the class has a dependent base or if it or one
13390 // of its bases is present in the base set of the current context.
13391 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13392 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13393 return false;
13394
13395 Diag(SS.getRange().getBegin(),
13396 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13397 << SS.getScopeRep()
13398 << cast<CXXRecordDecl>(CurContext)
13399 << SS.getRange();
13400
13401 return true;
13402}
13403
13405 MultiTemplateParamsArg TemplateParamLists,
13406 SourceLocation UsingLoc, UnqualifiedId &Name,
13407 const ParsedAttributesView &AttrList,
13408 TypeResult Type, Decl *DeclFromDeclSpec) {
13409 // Get the innermost enclosing declaration scope.
13410 S = S->getDeclParent();
13411
13412 if (Type.isInvalid())
13413 return nullptr;
13414
13415 bool Invalid = false;
13417 TypeSourceInfo *TInfo = nullptr;
13418 GetTypeFromParser(Type.get(), &TInfo);
13419
13420 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13421 return nullptr;
13422
13423 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13425 Invalid = true;
13427 TInfo->getTypeLoc().getBeginLoc());
13428 }
13429
13430 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13431 TemplateParamLists.size()
13433 : RedeclarationKind::ForVisibleRedeclaration);
13434 LookupName(Previous, S);
13435
13436 // Warn about shadowing the name of a template parameter.
13437 if (Previous.isSingleResult() &&
13438 Previous.getFoundDecl()->isTemplateParameter()) {
13439 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13440 Previous.clear();
13441 }
13442
13443 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13444 "name in alias declaration must be an identifier");
13446 Name.StartLocation,
13447 Name.Identifier, TInfo);
13448
13449 NewTD->setAccess(AS);
13450
13451 if (Invalid)
13452 NewTD->setInvalidDecl();
13453
13454 ProcessDeclAttributeList(S, NewTD, AttrList);
13455 AddPragmaAttributes(S, NewTD);
13456 ProcessAPINotes(NewTD);
13457
13459 Invalid |= NewTD->isInvalidDecl();
13460
13461 bool Redeclaration = false;
13462
13463 NamedDecl *NewND;
13464 if (TemplateParamLists.size()) {
13465 TypeAliasTemplateDecl *OldDecl = nullptr;
13466 TemplateParameterList *OldTemplateParams = nullptr;
13467
13468 if (TemplateParamLists.size() != 1) {
13469 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13470 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13471 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13472 Invalid = true;
13473 }
13474 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13475
13476 // Check that we can declare a template here.
13477 if (CheckTemplateDeclScope(S, TemplateParams))
13478 return nullptr;
13479
13480 // Only consider previous declarations in the same scope.
13481 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13482 /*ExplicitInstantiationOrSpecialization*/false);
13483 if (!Previous.empty()) {
13484 Redeclaration = true;
13485
13486 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13487 if (!OldDecl && !Invalid) {
13488 Diag(UsingLoc, diag::err_redefinition_different_kind)
13489 << Name.Identifier;
13490
13491 NamedDecl *OldD = Previous.getRepresentativeDecl();
13492 if (OldD->getLocation().isValid())
13493 Diag(OldD->getLocation(), diag::note_previous_definition);
13494
13495 Invalid = true;
13496 }
13497
13498 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13499 if (TemplateParameterListsAreEqual(TemplateParams,
13500 OldDecl->getTemplateParameters(),
13501 /*Complain=*/true,
13503 OldTemplateParams =
13505 else
13506 Invalid = true;
13507
13508 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13509 if (!Invalid &&
13511 NewTD->getUnderlyingType())) {
13512 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13513 // but we can't reasonably accept it.
13514 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13515 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13516 if (OldTD->getLocation().isValid())
13517 Diag(OldTD->getLocation(), diag::note_previous_definition);
13518 Invalid = true;
13519 }
13520 }
13521 }
13522
13523 // Merge any previous default template arguments into our parameters,
13524 // and check the parameter list.
13525 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13527 return nullptr;
13528
13529 TypeAliasTemplateDecl *NewDecl =
13531 Name.Identifier, TemplateParams,
13532 NewTD);
13533 NewTD->setDescribedAliasTemplate(NewDecl);
13534
13535 NewDecl->setAccess(AS);
13536
13537 if (Invalid)
13538 NewDecl->setInvalidDecl();
13539 else if (OldDecl) {
13540 NewDecl->setPreviousDecl(OldDecl);
13541 CheckRedeclarationInModule(NewDecl, OldDecl);
13542 }
13543
13544 NewND = NewDecl;
13545 } else {
13546 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13548 handleTagNumbering(TD, S);
13549 }
13550 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13551 NewND = NewTD;
13552 }
13553
13554 PushOnScopeChains(NewND, S);
13555 ActOnDocumentableDecl(NewND);
13556 return NewND;
13557}
13558
13560 SourceLocation AliasLoc,
13561 IdentifierInfo *Alias, CXXScopeSpec &SS,
13562 SourceLocation IdentLoc,
13563 IdentifierInfo *Ident) {
13564
13565 // Lookup the namespace name.
13566 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13567 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13568
13569 if (R.isAmbiguous())
13570 return nullptr;
13571
13572 if (R.empty()) {
13573 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13574 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13575 return nullptr;
13576 }
13577 }
13578 assert(!R.isAmbiguous() && !R.empty());
13580
13581 // Check if we have a previous declaration with the same name.
13582 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13583 RedeclarationKind::ForVisibleRedeclaration);
13584 LookupName(PrevR, S);
13585
13586 // Check we're not shadowing a template parameter.
13587 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13589 PrevR.clear();
13590 }
13591
13592 // Filter out any other lookup result from an enclosing scope.
13593 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13594 /*AllowInlineNamespace*/false);
13595
13596 // Find the previous declaration and check that we can redeclare it.
13597 NamespaceAliasDecl *Prev = nullptr;
13598 if (PrevR.isSingleResult()) {
13599 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13600 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13601 // We already have an alias with the same name that points to the same
13602 // namespace; check that it matches.
13603 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13604 Prev = AD;
13605 } else if (isVisible(PrevDecl)) {
13606 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13607 << Alias;
13608 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13609 << AD->getNamespace();
13610 return nullptr;
13611 }
13612 } else if (isVisible(PrevDecl)) {
13613 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13614 ? diag::err_redefinition
13615 : diag::err_redefinition_different_kind;
13616 Diag(AliasLoc, DiagID) << Alias;
13617 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13618 return nullptr;
13619 }
13620 }
13621
13622 // The use of a nested name specifier may trigger deprecation warnings.
13623 DiagnoseUseOfDecl(ND, IdentLoc);
13624
13626 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13627 Alias, SS.getWithLocInContext(Context),
13628 IdentLoc, ND);
13629 if (Prev)
13630 AliasDecl->setPreviousDecl(Prev);
13631
13633 return AliasDecl;
13634}
13635
13636namespace {
13637struct SpecialMemberExceptionSpecInfo
13638 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13641
13642 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13646 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13647
13648 bool visitBase(CXXBaseSpecifier *Base);
13649 bool visitField(FieldDecl *FD);
13650
13651 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13652 unsigned Quals);
13653
13654 void visitSubobjectCall(Subobject Subobj,
13656};
13657}
13658
13659bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13660 auto *RT = Base->getType()->getAs<RecordType>();
13661 if (!RT)
13662 return false;
13663
13664 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13665 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13666 if (auto *BaseCtor = SMOR.getMethod()) {
13667 visitSubobjectCall(Base, BaseCtor);
13668 return false;
13669 }
13670
13671 visitClassSubobject(BaseClass, Base, 0);
13672 return false;
13673}
13674
13675bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13677 FD->hasInClassInitializer()) {
13678 Expr *E = FD->getInClassInitializer();
13679 if (!E)
13680 // FIXME: It's a little wasteful to build and throw away a
13681 // CXXDefaultInitExpr here.
13682 // FIXME: We should have a single context note pointing at Loc, and
13683 // this location should be MD->getLocation() instead, since that's
13684 // the location where we actually use the default init expression.
13685 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13686 if (E)
13687 ExceptSpec.CalledExpr(E);
13688 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13689 ->getAs<RecordType>()) {
13690 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13691 FD->getType().getCVRQualifiers());
13692 }
13693 return false;
13694}
13695
13696void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13697 Subobject Subobj,
13698 unsigned Quals) {
13699 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13700 bool IsMutable = Field && Field->isMutable();
13701 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13702}
13703
13704void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13705 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13706 // Note, if lookup fails, it doesn't matter what exception specification we
13707 // choose because the special member will be deleted.
13708 if (CXXMethodDecl *MD = SMOR.getMethod())
13709 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13710}
13711
13713 llvm::APSInt Result;
13715 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13716 ExplicitSpec.setExpr(Converted.get());
13717 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13718 ExplicitSpec.setKind(Result.getBoolValue()
13721 return true;
13722 }
13724 return false;
13725}
13726
13729 if (!ExplicitExpr->isTypeDependent())
13731 return ES;
13732}
13733
13738 ComputingExceptionSpec CES(S, MD, Loc);
13739
13740 CXXRecordDecl *ClassDecl = MD->getParent();
13741
13742 // C++ [except.spec]p14:
13743 // An implicitly declared special member function (Clause 12) shall have an
13744 // exception-specification. [...]
13745 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13746 if (ClassDecl->isInvalidDecl())
13747 return Info.ExceptSpec;
13748
13749 // FIXME: If this diagnostic fires, we're probably missing a check for
13750 // attempting to resolve an exception specification before it's known
13751 // at a higher level.
13752 if (S.RequireCompleteType(MD->getLocation(),
13753 S.Context.getRecordType(ClassDecl),
13754 diag::err_exception_spec_incomplete_type))
13755 return Info.ExceptSpec;
13756
13757 // C++1z [except.spec]p7:
13758 // [Look for exceptions thrown by] a constructor selected [...] to
13759 // initialize a potentially constructed subobject,
13760 // C++1z [except.spec]p8:
13761 // The exception specification for an implicitly-declared destructor, or a
13762 // destructor without a noexcept-specifier, is potentially-throwing if and
13763 // only if any of the destructors for any of its potentially constructed
13764 // subojects is potentially throwing.
13765 // FIXME: We respect the first rule but ignore the "potentially constructed"
13766 // in the second rule to resolve a core issue (no number yet) that would have
13767 // us reject:
13768 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13769 // struct B : A {};
13770 // struct C : B { void f(); };
13771 // ... due to giving B::~B() a non-throwing exception specification.
13772 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13773 : Info.VisitAllBases);
13774
13775 return Info.ExceptSpec;
13776}
13777
13778namespace {
13779/// RAII object to register a special member as being currently declared.
13780struct DeclaringSpecialMember {
13781 Sema &S;
13783 Sema::ContextRAII SavedContext;
13784 bool WasAlreadyBeingDeclared;
13785
13786 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13787 : S(S), D(RD, CSM), SavedContext(S, RD) {
13788 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13789 if (WasAlreadyBeingDeclared)
13790 // This almost never happens, but if it does, ensure that our cache
13791 // doesn't contain a stale result.
13792 S.SpecialMemberCache.clear();
13793 else {
13794 // Register a note to be produced if we encounter an error while
13795 // declaring the special member.
13798 // FIXME: We don't have a location to use here. Using the class's
13799 // location maintains the fiction that we declare all special members
13800 // with the class, but (1) it's not clear that lying about that helps our
13801 // users understand what's going on, and (2) there may be outer contexts
13802 // on the stack (some of which are relevant) and printing them exposes
13803 // our lies.
13804 Ctx.PointOfInstantiation = RD->getLocation();
13805 Ctx.Entity = RD;
13806 Ctx.SpecialMember = CSM;
13808 }
13809 }
13810 ~DeclaringSpecialMember() {
13811 if (!WasAlreadyBeingDeclared) {
13814 }
13815 }
13816
13817 /// Are we already trying to declare this special member?
13818 bool isAlreadyBeingDeclared() const {
13819 return WasAlreadyBeingDeclared;
13820 }
13821};
13822}
13823
13825 // Look up any existing declarations, but don't trigger declaration of all
13826 // implicit special members with this name.
13827 DeclarationName Name = FD->getDeclName();
13829 RedeclarationKind::ForExternalRedeclaration);
13830 for (auto *D : FD->getParent()->lookup(Name))
13831 if (auto *Acceptable = R.getAcceptableDecl(D))
13832 R.addDecl(Acceptable);
13833 R.resolveKind();
13835
13836 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13838}
13839
13840void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13841 QualType ResultTy,
13842 ArrayRef<QualType> Args) {
13843 // Build an exception specification pointing back at this constructor.
13845
13847 if (AS != LangAS::Default) {
13848 EPI.TypeQuals.addAddressSpace(AS);
13849 }
13850
13851 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13852 SpecialMem->setType(QT);
13853
13854 // During template instantiation of implicit special member functions we need
13855 // a reliable TypeSourceInfo for the function prototype in order to allow
13856 // functions to be substituted.
13858 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13859 TypeSourceInfo *TSI =
13861 SpecialMem->setTypeSourceInfo(TSI);
13862 }
13863}
13864
13866 CXXRecordDecl *ClassDecl) {
13867 // C++ [class.ctor]p5:
13868 // A default constructor for a class X is a constructor of class X
13869 // that can be called without an argument. If there is no
13870 // user-declared constructor for class X, a default constructor is
13871 // implicitly declared. An implicitly-declared default constructor
13872 // is an inline public member of its class.
13873 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13874 "Should not build implicit default constructor!");
13875
13876 DeclaringSpecialMember DSM(*this, ClassDecl,
13878 if (DSM.isAlreadyBeingDeclared())
13879 return nullptr;
13880
13882 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
13883
13884 // Create the actual constructor declaration.
13885 CanQualType ClassType
13887 SourceLocation ClassLoc = ClassDecl->getLocation();
13888 DeclarationName Name
13890 DeclarationNameInfo NameInfo(Name, ClassLoc);
13892 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13893 /*TInfo=*/nullptr, ExplicitSpecifier(),
13894 getCurFPFeatures().isFPConstrained(),
13895 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13898 DefaultCon->setAccess(AS_public);
13899 DefaultCon->setDefaulted();
13900
13901 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
13902
13903 if (getLangOpts().CUDA)
13905 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
13906 /* ConstRHS */ false,
13907 /* Diagnose */ false);
13908
13909 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13910 // constructors is easy to compute.
13911 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13912
13913 // Note that we have declared this constructor.
13915
13916 Scope *S = getScopeForContext(ClassDecl);
13918
13919 if (ShouldDeleteSpecialMember(DefaultCon,
13921 SetDeclDeleted(DefaultCon, ClassLoc);
13922
13923 if (S)
13924 PushOnScopeChains(DefaultCon, S, false);
13925 ClassDecl->addDecl(DefaultCon);
13926
13927 return DefaultCon;
13928}
13929
13931 CXXConstructorDecl *Constructor) {
13932 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13933 !Constructor->doesThisDeclarationHaveABody() &&
13934 !Constructor->isDeleted()) &&
13935 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13936 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13937 return;
13938
13939 CXXRecordDecl *ClassDecl = Constructor->getParent();
13940 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13941 if (ClassDecl->isInvalidDecl()) {
13942 return;
13943 }
13944
13945 SynthesizedFunctionScope Scope(*this, Constructor);
13946
13947 // The exception specification is needed because we are defining the
13948 // function.
13949 ResolveExceptionSpec(CurrentLocation,
13950 Constructor->getType()->castAs<FunctionProtoType>());
13951 MarkVTableUsed(CurrentLocation, ClassDecl);
13952
13953 // Add a context note for diagnostics produced after this point.
13954 Scope.addContextNote(CurrentLocation);
13955
13956 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13957 Constructor->setInvalidDecl();
13958 return;
13959 }
13960
13961 SourceLocation Loc = Constructor->getEndLoc().isValid()
13962 ? Constructor->getEndLoc()
13963 : Constructor->getLocation();
13964 Constructor->setBody(new (Context) CompoundStmt(Loc));
13965 Constructor->markUsed(Context);
13966
13968 L->CompletedImplicitDefinition(Constructor);
13969 }
13970
13971 DiagnoseUninitializedFields(*this, Constructor);
13972}
13973
13975 // Perform any delayed checks on exception specifications.
13977}
13978
13979/// Find or create the fake constructor we synthesize to model constructing an
13980/// object of a derived class via a constructor of a base class.
13983 CXXConstructorDecl *BaseCtor,
13985 CXXRecordDecl *Derived = Shadow->getParent();
13986 SourceLocation UsingLoc = Shadow->getLocation();
13987
13988 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13989 // For now we use the name of the base class constructor as a member of the
13990 // derived class to indicate a (fake) inherited constructor name.
13991 DeclarationName Name = BaseCtor->getDeclName();
13992
13993 // Check to see if we already have a fake constructor for this inherited
13994 // constructor call.
13995 for (NamedDecl *Ctor : Derived->lookup(Name))
13996 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13997 ->getInheritedConstructor()
13998 .getConstructor(),
13999 BaseCtor))
14000 return cast<CXXConstructorDecl>(Ctor);
14001
14002 DeclarationNameInfo NameInfo(Name, UsingLoc);
14003 TypeSourceInfo *TInfo =
14004 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14005 FunctionProtoTypeLoc ProtoLoc =
14007
14008 // Check the inherited constructor is valid and find the list of base classes
14009 // from which it was inherited.
14010 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14011
14012 bool Constexpr = BaseCtor->isConstexpr() &&
14015 false, BaseCtor, &ICI);
14016
14018 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14019 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14020 /*isInline=*/true,
14021 /*isImplicitlyDeclared=*/true,
14023 InheritedConstructor(Shadow, BaseCtor),
14024 BaseCtor->getTrailingRequiresClause());
14025 if (Shadow->isInvalidDecl())
14026 DerivedCtor->setInvalidDecl();
14027
14028 // Build an unevaluated exception specification for this fake constructor.
14029 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14032 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14033 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14034 FPT->getParamTypes(), EPI));
14035
14036 // Build the parameter declarations.
14038 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14039 TypeSourceInfo *TInfo =
14042 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14043 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14044 PD->setScopeInfo(0, I);
14045 PD->setImplicit();
14046 // Ensure attributes are propagated onto parameters (this matters for
14047 // format, pass_object_size, ...).
14048 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14049 ParamDecls.push_back(PD);
14050 ProtoLoc.setParam(I, PD);
14051 }
14052
14053 // Set up the new constructor.
14054 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14055 DerivedCtor->setAccess(BaseCtor->getAccess());
14056 DerivedCtor->setParams(ParamDecls);
14057 Derived->addDecl(DerivedCtor);
14058
14059 if (ShouldDeleteSpecialMember(DerivedCtor,
14061 SetDeclDeleted(DerivedCtor, UsingLoc);
14062
14063 return DerivedCtor;
14064}
14065
14067 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14070 &ICI,
14071 /*Diagnose*/ true);
14072}
14073
14075 CXXConstructorDecl *Constructor) {
14076 CXXRecordDecl *ClassDecl = Constructor->getParent();
14077 assert(Constructor->getInheritedConstructor() &&
14078 !Constructor->doesThisDeclarationHaveABody() &&
14079 !Constructor->isDeleted());
14080 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14081 return;
14082
14083 // Initializations are performed "as if by a defaulted default constructor",
14084 // so enter the appropriate scope.
14085 SynthesizedFunctionScope Scope(*this, Constructor);
14086
14087 // The exception specification is needed because we are defining the
14088 // function.
14089 ResolveExceptionSpec(CurrentLocation,
14090 Constructor->getType()->castAs<FunctionProtoType>());
14091 MarkVTableUsed(CurrentLocation, ClassDecl);
14092
14093 // Add a context note for diagnostics produced after this point.
14094 Scope.addContextNote(CurrentLocation);
14095
14097 Constructor->getInheritedConstructor().getShadowDecl();
14098 CXXConstructorDecl *InheritedCtor =
14099 Constructor->getInheritedConstructor().getConstructor();
14100
14101 // [class.inhctor.init]p1:
14102 // initialization proceeds as if a defaulted default constructor is used to
14103 // initialize the D object and each base class subobject from which the
14104 // constructor was inherited
14105
14106 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14107 CXXRecordDecl *RD = Shadow->getParent();
14108 SourceLocation InitLoc = Shadow->getLocation();
14109
14110 // Build explicit initializers for all base classes from which the
14111 // constructor was inherited.
14113 for (bool VBase : {false, true}) {
14114 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14115 if (B.isVirtual() != VBase)
14116 continue;
14117
14118 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14119 if (!BaseRD)
14120 continue;
14121
14122 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14123 if (!BaseCtor.first)
14124 continue;
14125
14126 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14128 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14129
14130 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14131 Inits.push_back(new (Context) CXXCtorInitializer(
14132 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14133 SourceLocation()));
14134 }
14135 }
14136
14137 // We now proceed as if for a defaulted default constructor, with the relevant
14138 // initializers replaced.
14139
14140 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14141 Constructor->setInvalidDecl();
14142 return;
14143 }
14144
14145 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14146 Constructor->markUsed(Context);
14147
14149 L->CompletedImplicitDefinition(Constructor);
14150 }
14151
14152 DiagnoseUninitializedFields(*this, Constructor);
14153}
14154
14156 // C++ [class.dtor]p2:
14157 // If a class has no user-declared destructor, a destructor is
14158 // declared implicitly. An implicitly-declared destructor is an
14159 // inline public member of its class.
14160 assert(ClassDecl->needsImplicitDestructor());
14161
14162 DeclaringSpecialMember DSM(*this, ClassDecl,
14164 if (DSM.isAlreadyBeingDeclared())
14165 return nullptr;
14166
14168 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14169
14170 // Create the actual destructor declaration.
14171 CanQualType ClassType
14173 SourceLocation ClassLoc = ClassDecl->getLocation();
14174 DeclarationName Name
14176 DeclarationNameInfo NameInfo(Name, ClassLoc);
14178 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14179 getCurFPFeatures().isFPConstrained(),
14180 /*isInline=*/true,
14181 /*isImplicitlyDeclared=*/true,
14184 Destructor->setAccess(AS_public);
14185 Destructor->setDefaulted();
14186
14187 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14188
14189 if (getLangOpts().CUDA)
14192 /* ConstRHS */ false,
14193 /* Diagnose */ false);
14194
14195 // We don't need to use SpecialMemberIsTrivial here; triviality for
14196 // destructors is easy to compute.
14197 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14198 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14199 ClassDecl->hasTrivialDestructorForCall());
14200
14201 // Note that we have declared this destructor.
14203
14204 Scope *S = getScopeForContext(ClassDecl);
14206
14207 // We can't check whether an implicit destructor is deleted before we complete
14208 // the definition of the class, because its validity depends on the alignment
14209 // of the class. We'll check this from ActOnFields once the class is complete.
14210 if (ClassDecl->isCompleteDefinition() &&
14212 SetDeclDeleted(Destructor, ClassLoc);
14213
14214 // Introduce this destructor into its scope.
14215 if (S)
14216 PushOnScopeChains(Destructor, S, false);
14217 ClassDecl->addDecl(Destructor);
14218
14219 return Destructor;
14220}
14221
14224 assert((Destructor->isDefaulted() &&
14225 !Destructor->doesThisDeclarationHaveABody() &&
14226 !Destructor->isDeleted()) &&
14227 "DefineImplicitDestructor - call it for implicit default dtor");
14228 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14229 return;
14230
14231 CXXRecordDecl *ClassDecl = Destructor->getParent();
14232 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14233
14235
14236 // The exception specification is needed because we are defining the
14237 // function.
14238 ResolveExceptionSpec(CurrentLocation,
14239 Destructor->getType()->castAs<FunctionProtoType>());
14240 MarkVTableUsed(CurrentLocation, ClassDecl);
14241
14242 // Add a context note for diagnostics produced after this point.
14243 Scope.addContextNote(CurrentLocation);
14244
14246 Destructor->getParent());
14247
14249 Destructor->setInvalidDecl();
14250 return;
14251 }
14252
14253 SourceLocation Loc = Destructor->getEndLoc().isValid()
14254 ? Destructor->getEndLoc()
14255 : Destructor->getLocation();
14256 Destructor->setBody(new (Context) CompoundStmt(Loc));
14257 Destructor->markUsed(Context);
14258
14260 L->CompletedImplicitDefinition(Destructor);
14261 }
14262}
14263
14266 if (Destructor->isInvalidDecl())
14267 return;
14268
14269 CXXRecordDecl *ClassDecl = Destructor->getParent();
14271 "implicit complete dtors unneeded outside MS ABI");
14272 assert(ClassDecl->getNumVBases() > 0 &&
14273 "complete dtor only exists for classes with vbases");
14274
14276
14277 // Add a context note for diagnostics produced after this point.
14278 Scope.addContextNote(CurrentLocation);
14279
14280 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14281}
14282
14284 // If the context is an invalid C++ class, just suppress these checks.
14285 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14286 if (Record->isInvalidDecl()) {
14289 return;
14290 }
14292 }
14293}
14294
14297
14298 if (!DelayedDllExportMemberFunctions.empty()) {
14300 std::swap(DelayedDllExportMemberFunctions, WorkList);
14301 for (CXXMethodDecl *M : WorkList) {
14302 DefineDefaultedFunction(*this, M, M->getLocation());
14303
14304 // Pass the method to the consumer to get emitted. This is not necessary
14305 // for explicit instantiation definitions, as they will get emitted
14306 // anyway.
14307 if (M->getParent()->getTemplateSpecializationKind() !=
14310 }
14311 }
14312}
14313
14315 if (!DelayedDllExportClasses.empty()) {
14316 // Calling ReferenceDllExportedMembers might cause the current function to
14317 // be called again, so use a local copy of DelayedDllExportClasses.
14319 std::swap(DelayedDllExportClasses, WorkList);
14320 for (CXXRecordDecl *Class : WorkList)
14322 }
14323}
14324
14326 assert(getLangOpts().CPlusPlus11 &&
14327 "adjusting dtor exception specs was introduced in c++11");
14328
14329 if (Destructor->isDependentContext())
14330 return;
14331
14332 // C++11 [class.dtor]p3:
14333 // A declaration of a destructor that does not have an exception-
14334 // specification is implicitly considered to have the same exception-
14335 // specification as an implicit declaration.
14336 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14337 if (DtorType->hasExceptionSpec())
14338 return;
14339
14340 // Replace the destructor's type, building off the existing one. Fortunately,
14341 // the only thing of interest in the destructor type is its extended info.
14342 // The return and arguments are fixed.
14343 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14346 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14347
14348 // FIXME: If the destructor has a body that could throw, and the newly created
14349 // spec doesn't allow exceptions, we should emit a warning, because this
14350 // change in behavior can break conforming C++03 programs at runtime.
14351 // However, we don't have a body or an exception specification yet, so it
14352 // needs to be done somewhere else.
14353}
14354
14355namespace {
14356/// An abstract base class for all helper classes used in building the
14357// copy/move operators. These classes serve as factory functions and help us
14358// avoid using the same Expr* in the AST twice.
14359class ExprBuilder {
14360 ExprBuilder(const ExprBuilder&) = delete;
14361 ExprBuilder &operator=(const ExprBuilder&) = delete;
14362
14363protected:
14364 static Expr *assertNotNull(Expr *E) {
14365 assert(E && "Expression construction must not fail.");
14366 return E;
14367 }
14368
14369public:
14370 ExprBuilder() {}
14371 virtual ~ExprBuilder() {}
14372
14373 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14374};
14375
14376class RefBuilder: public ExprBuilder {
14377 VarDecl *Var;
14378 QualType VarType;
14379
14380public:
14381 Expr *build(Sema &S, SourceLocation Loc) const override {
14382 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14383 }
14384
14385 RefBuilder(VarDecl *Var, QualType VarType)
14386 : Var(Var), VarType(VarType) {}
14387};
14388
14389class ThisBuilder: public ExprBuilder {
14390public:
14391 Expr *build(Sema &S, SourceLocation Loc) const override {
14392 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14393 }
14394};
14395
14396class CastBuilder: public ExprBuilder {
14397 const ExprBuilder &Builder;
14398 QualType Type;
14400 const CXXCastPath &Path;
14401
14402public:
14403 Expr *build(Sema &S, SourceLocation Loc) const override {
14404 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14405 CK_UncheckedDerivedToBase, Kind,
14406 &Path).get());
14407 }
14408
14409 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14410 const CXXCastPath &Path)
14411 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14412};
14413
14414class DerefBuilder: public ExprBuilder {
14415 const ExprBuilder &Builder;
14416
14417public:
14418 Expr *build(Sema &S, SourceLocation Loc) const override {
14419 return assertNotNull(
14420 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14421 }
14422
14423 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14424};
14425
14426class MemberBuilder: public ExprBuilder {
14427 const ExprBuilder &Builder;
14428 QualType Type;
14429 CXXScopeSpec SS;
14430 bool IsArrow;
14431 LookupResult &MemberLookup;
14432
14433public:
14434 Expr *build(Sema &S, SourceLocation Loc) const override {
14435 return assertNotNull(S.BuildMemberReferenceExpr(
14436 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14437 nullptr, MemberLookup, nullptr, nullptr).get());
14438 }
14439
14440 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14441 LookupResult &MemberLookup)
14442 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14443 MemberLookup(MemberLookup) {}
14444};
14445
14446class MoveCastBuilder: public ExprBuilder {
14447 const ExprBuilder &Builder;
14448
14449public:
14450 Expr *build(Sema &S, SourceLocation Loc) const override {
14451 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14452 }
14453
14454 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14455};
14456
14457class LvalueConvBuilder: public ExprBuilder {
14458 const ExprBuilder &Builder;
14459
14460public:
14461 Expr *build(Sema &S, SourceLocation Loc) const override {
14462 return assertNotNull(
14463 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14464 }
14465
14466 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14467};
14468
14469class SubscriptBuilder: public ExprBuilder {
14470 const ExprBuilder &Base;
14471 const ExprBuilder &Index;
14472
14473public:
14474 Expr *build(Sema &S, SourceLocation Loc) const override {
14475 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14476 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14477 }
14478
14479 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14480 : Base(Base), Index(Index) {}
14481};
14482
14483} // end anonymous namespace
14484
14485/// When generating a defaulted copy or move assignment operator, if a field
14486/// should be copied with __builtin_memcpy rather than via explicit assignments,
14487/// do so. This optimization only applies for arrays of scalars, and for arrays
14488/// of class type where the selected copy/move-assignment operator is trivial.
14489static StmtResult
14491 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14492 // Compute the size of the memory buffer to be copied.
14493 QualType SizeType = S.Context.getSizeType();
14494 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14496
14497 // Take the address of the field references for "from" and "to". We
14498 // directly construct UnaryOperators here because semantic analysis
14499 // does not permit us to take the address of an xvalue.
14500 Expr *From = FromB.build(S, Loc);
14501 From = UnaryOperator::Create(
14502 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14504 Expr *To = ToB.build(S, Loc);
14506 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14508
14509 const Type *E = T->getBaseElementTypeUnsafe();
14510 bool NeedsCollectableMemCpy =
14511 E->isRecordType() &&
14512 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14513
14514 // Create a reference to the __builtin_objc_memmove_collectable function
14515 StringRef MemCpyName = NeedsCollectableMemCpy ?
14516 "__builtin_objc_memmove_collectable" :
14517 "__builtin_memcpy";
14518 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14520 S.LookupName(R, S.TUScope, true);
14521
14522 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14523 if (!MemCpy)
14524 // Something went horribly wrong earlier, and we will have complained
14525 // about it.
14526 return StmtError();
14527
14528 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14529 VK_PRValue, Loc, nullptr);
14530 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14531
14532 Expr *CallArgs[] = {
14533 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14534 };
14535 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14536 Loc, CallArgs, Loc);
14537
14538 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14539 return Call.getAs<Stmt>();
14540}
14541
14542/// Builds a statement that copies/moves the given entity from \p From to
14543/// \c To.
14544///
14545/// This routine is used to copy/move the members of a class with an
14546/// implicitly-declared copy/move assignment operator. When the entities being
14547/// copied are arrays, this routine builds for loops to copy them.
14548///
14549/// \param S The Sema object used for type-checking.
14550///
14551/// \param Loc The location where the implicit copy/move is being generated.
14552///
14553/// \param T The type of the expressions being copied/moved. Both expressions
14554/// must have this type.
14555///
14556/// \param To The expression we are copying/moving to.
14557///
14558/// \param From The expression we are copying/moving from.
14559///
14560/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14561/// Otherwise, it's a non-static member subobject.
14562///
14563/// \param Copying Whether we're copying or moving.
14564///
14565/// \param Depth Internal parameter recording the depth of the recursion.
14566///
14567/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14568/// if a memcpy should be used instead.
14569static StmtResult
14571 const ExprBuilder &To, const ExprBuilder &From,
14572 bool CopyingBaseSubobject, bool Copying,
14573 unsigned Depth = 0) {
14574 // C++11 [class.copy]p28:
14575 // Each subobject is assigned in the manner appropriate to its type:
14576 //
14577 // - if the subobject is of class type, as if by a call to operator= with
14578 // the subobject as the object expression and the corresponding
14579 // subobject of x as a single function argument (as if by explicit
14580 // qualification; that is, ignoring any possible virtual overriding
14581 // functions in more derived classes);
14582 //
14583 // C++03 [class.copy]p13:
14584 // - if the subobject is of class type, the copy assignment operator for
14585 // the class is used (as if by explicit qualification; that is,
14586 // ignoring any possible virtual overriding functions in more derived
14587 // classes);
14588 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14589 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14590
14591 // Look for operator=.
14592 DeclarationName Name
14594 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14595 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14596
14597 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14598 // operator.
14599 if (!S.getLangOpts().CPlusPlus11) {
14600 LookupResult::Filter F = OpLookup.makeFilter();
14601 while (F.hasNext()) {
14602 NamedDecl *D = F.next();
14603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14604 if (Method->isCopyAssignmentOperator() ||
14605 (!Copying && Method->isMoveAssignmentOperator()))
14606 continue;
14607
14608 F.erase();
14609 }
14610 F.done();
14611 }
14612
14613 // Suppress the protected check (C++ [class.protected]) for each of the
14614 // assignment operators we found. This strange dance is required when
14615 // we're assigning via a base classes's copy-assignment operator. To
14616 // ensure that we're getting the right base class subobject (without
14617 // ambiguities), we need to cast "this" to that subobject type; to
14618 // ensure that we don't go through the virtual call mechanism, we need
14619 // to qualify the operator= name with the base class (see below). However,
14620 // this means that if the base class has a protected copy assignment
14621 // operator, the protected member access check will fail. So, we
14622 // rewrite "protected" access to "public" access in this case, since we
14623 // know by construction that we're calling from a derived class.
14624 if (CopyingBaseSubobject) {
14625 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14626 L != LEnd; ++L) {
14627 if (L.getAccess() == AS_protected)
14628 L.setAccess(AS_public);
14629 }
14630 }
14631
14632 // Create the nested-name-specifier that will be used to qualify the
14633 // reference to operator=; this is required to suppress the virtual
14634 // call mechanism.
14635 CXXScopeSpec SS;
14636 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14637 SS.MakeTrivial(S.Context,
14638 NestedNameSpecifier::Create(S.Context, nullptr, false,
14639 CanonicalT),
14640 Loc);
14641
14642 // Create the reference to operator=.
14643 ExprResult OpEqualRef
14644 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14645 SS, /*TemplateKWLoc=*/SourceLocation(),
14646 /*FirstQualifierInScope=*/nullptr,
14647 OpLookup,
14648 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14649 /*SuppressQualifierCheck=*/true);
14650 if (OpEqualRef.isInvalid())
14651 return StmtError();
14652
14653 // Build the call to the assignment operator.
14654
14655 Expr *FromInst = From.build(S, Loc);
14656 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14657 OpEqualRef.getAs<Expr>(),
14658 Loc, FromInst, Loc);
14659 if (Call.isInvalid())
14660 return StmtError();
14661
14662 // If we built a call to a trivial 'operator=' while copying an array,
14663 // bail out. We'll replace the whole shebang with a memcpy.
14664 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14665 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14666 return StmtResult((Stmt*)nullptr);
14667
14668 // Convert to an expression-statement, and clean up any produced
14669 // temporaries.
14670 return S.ActOnExprStmt(Call);
14671 }
14672
14673 // - if the subobject is of scalar type, the built-in assignment
14674 // operator is used.
14676 if (!ArrayTy) {
14677 ExprResult Assignment = S.CreateBuiltinBinOp(
14678 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14679 if (Assignment.isInvalid())
14680 return StmtError();
14681 return S.ActOnExprStmt(Assignment);
14682 }
14683
14684 // - if the subobject is an array, each element is assigned, in the
14685 // manner appropriate to the element type;
14686
14687 // Construct a loop over the array bounds, e.g.,
14688 //
14689 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14690 //
14691 // that will copy each of the array elements.
14692 QualType SizeType = S.Context.getSizeType();
14693
14694 // Create the iteration variable.
14695 IdentifierInfo *IterationVarName = nullptr;
14696 {
14697 SmallString<8> Str;
14698 llvm::raw_svector_ostream OS(Str);
14699 OS << "__i" << Depth;
14700 IterationVarName = &S.Context.Idents.get(OS.str());
14701 }
14702 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14703 IterationVarName, SizeType,
14705 SC_None);
14706
14707 // Initialize the iteration variable to zero.
14708 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14709 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14710
14711 // Creates a reference to the iteration variable.
14712 RefBuilder IterationVarRef(IterationVar, SizeType);
14713 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14714
14715 // Create the DeclStmt that holds the iteration variable.
14716 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14717
14718 // Subscript the "from" and "to" expressions with the iteration variable.
14719 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14720 MoveCastBuilder FromIndexMove(FromIndexCopy);
14721 const ExprBuilder *FromIndex;
14722 if (Copying)
14723 FromIndex = &FromIndexCopy;
14724 else
14725 FromIndex = &FromIndexMove;
14726
14727 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14728
14729 // Build the copy/move for an individual element of the array.
14732 ToIndex, *FromIndex, CopyingBaseSubobject,
14733 Copying, Depth + 1);
14734 // Bail out if copying fails or if we determined that we should use memcpy.
14735 if (Copy.isInvalid() || !Copy.get())
14736 return Copy;
14737
14738 // Create the comparison against the array bound.
14739 llvm::APInt Upper
14740 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14741 Expr *Comparison = BinaryOperator::Create(
14742 S.Context, IterationVarRefRVal.build(S, Loc),
14743 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14746
14747 // Create the pre-increment of the iteration variable. We can determine
14748 // whether the increment will overflow based on the value of the array
14749 // bound.
14750 Expr *Increment = UnaryOperator::Create(
14751 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14752 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14753
14754 // Construct the loop that copies all elements of this array.
14755 return S.ActOnForStmt(
14756 Loc, Loc, InitStmt,
14757 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14758 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14759}
14760
14761static StmtResult
14763 const ExprBuilder &To, const ExprBuilder &From,
14764 bool CopyingBaseSubobject, bool Copying) {
14765 // Maybe we should use a memcpy?
14766 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14767 T.isTriviallyCopyableType(S.Context))
14768 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14769
14771 CopyingBaseSubobject,
14772 Copying, 0));
14773
14774 // If we ended up picking a trivial assignment operator for an array of a
14775 // non-trivially-copyable class type, just emit a memcpy.
14776 if (!Result.isInvalid() && !Result.get())
14777 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14778
14779 return Result;
14780}
14781
14783 // Note: The following rules are largely analoguous to the copy
14784 // constructor rules. Note that virtual bases are not taken into account
14785 // for determining the argument type of the operator. Note also that
14786 // operators taking an object instead of a reference are allowed.
14787 assert(ClassDecl->needsImplicitCopyAssignment());
14788
14789 DeclaringSpecialMember DSM(*this, ClassDecl,
14791 if (DSM.isAlreadyBeingDeclared())
14792 return nullptr;
14793
14794 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14796 ArgType, nullptr);
14798 if (AS != LangAS::Default)
14799 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14800 QualType RetType = Context.getLValueReferenceType(ArgType);
14801 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14802 if (Const)
14803 ArgType = ArgType.withConst();
14804
14805 ArgType = Context.getLValueReferenceType(ArgType);
14806
14808 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14809
14810 // An implicitly-declared copy assignment operator is an inline public
14811 // member of its class.
14813 SourceLocation ClassLoc = ClassDecl->getLocation();
14814 DeclarationNameInfo NameInfo(Name, ClassLoc);
14816 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14817 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14818 getCurFPFeatures().isFPConstrained(),
14819 /*isInline=*/true,
14821 SourceLocation());
14822 CopyAssignment->setAccess(AS_public);
14823 CopyAssignment->setDefaulted();
14824 CopyAssignment->setImplicit();
14825
14826 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14827
14828 if (getLangOpts().CUDA)
14831 /* ConstRHS */ Const,
14832 /* Diagnose */ false);
14833
14834 // Add the parameter to the operator.
14836 ClassLoc, ClassLoc,
14837 /*Id=*/nullptr, ArgType,
14838 /*TInfo=*/nullptr, SC_None,
14839 nullptr);
14840 CopyAssignment->setParams(FromParam);
14841
14842 CopyAssignment->setTrivial(
14846 : ClassDecl->hasTrivialCopyAssignment());
14847
14848 // Note that we have added this copy-assignment operator.
14850
14851 Scope *S = getScopeForContext(ClassDecl);
14853
14857 SetDeclDeleted(CopyAssignment, ClassLoc);
14858 }
14859
14860 if (S)
14862 ClassDecl->addDecl(CopyAssignment);
14863
14864 return CopyAssignment;
14865}
14866
14867/// Diagnose an implicit copy operation for a class which is odr-used, but
14868/// which is deprecated because the class has a user-declared copy constructor,
14869/// copy assignment operator, or destructor.
14871 assert(CopyOp->isImplicit());
14872
14873 CXXRecordDecl *RD = CopyOp->getParent();
14874 CXXMethodDecl *UserDeclaredOperation = nullptr;
14875
14876 if (RD->hasUserDeclaredDestructor()) {
14877 UserDeclaredOperation = RD->getDestructor();
14878 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14880 // Find any user-declared copy constructor.
14881 for (auto *I : RD->ctors()) {
14882 if (I->isCopyConstructor()) {
14883 UserDeclaredOperation = I;
14884 break;
14885 }
14886 }
14887 assert(UserDeclaredOperation);
14888 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14890 // Find any user-declared move assignment operator.
14891 for (auto *I : RD->methods()) {
14892 if (I->isCopyAssignmentOperator()) {
14893 UserDeclaredOperation = I;
14894 break;
14895 }
14896 }
14897 assert(UserDeclaredOperation);
14898 }
14899
14900 if (UserDeclaredOperation) {
14901 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14902 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14903 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14904 unsigned DiagID =
14905 (UDOIsUserProvided && UDOIsDestructor)
14906 ? diag::warn_deprecated_copy_with_user_provided_dtor
14907 : (UDOIsUserProvided && !UDOIsDestructor)
14908 ? diag::warn_deprecated_copy_with_user_provided_copy
14909 : (!UDOIsUserProvided && UDOIsDestructor)
14910 ? diag::warn_deprecated_copy_with_dtor
14911 : diag::warn_deprecated_copy;
14912 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14913 << RD << IsCopyAssignment;
14914 }
14915}
14916
14918 CXXMethodDecl *CopyAssignOperator) {
14919 assert((CopyAssignOperator->isDefaulted() &&
14920 CopyAssignOperator->isOverloadedOperator() &&
14921 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14922 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14923 !CopyAssignOperator->isDeleted()) &&
14924 "DefineImplicitCopyAssignment called for wrong function");
14925 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14926 return;
14927
14928 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14929 if (ClassDecl->isInvalidDecl()) {
14930 CopyAssignOperator->setInvalidDecl();
14931 return;
14932 }
14933
14934 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14935
14936 // The exception specification is needed because we are defining the
14937 // function.
14938 ResolveExceptionSpec(CurrentLocation,
14939 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14940
14941 // Add a context note for diagnostics produced after this point.
14942 Scope.addContextNote(CurrentLocation);
14943
14944 // C++11 [class.copy]p18:
14945 // The [definition of an implicitly declared copy assignment operator] is
14946 // deprecated if the class has a user-declared copy constructor or a
14947 // user-declared destructor.
14948 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14949 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14950
14951 // C++0x [class.copy]p30:
14952 // The implicitly-defined or explicitly-defaulted copy assignment operator
14953 // for a non-union class X performs memberwise copy assignment of its
14954 // subobjects. The direct base classes of X are assigned first, in the
14955 // order of their declaration in the base-specifier-list, and then the
14956 // immediate non-static data members of X are assigned, in the order in
14957 // which they were declared in the class definition.
14958
14959 // The statements that form the synthesized function body.
14960 SmallVector<Stmt*, 8> Statements;
14961
14962 // The parameter for the "other" object, which we are copying from.
14963 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
14964 Qualifiers OtherQuals = Other->getType().getQualifiers();
14965 QualType OtherRefType = Other->getType();
14966 if (OtherRefType->isLValueReferenceType()) {
14967 OtherRefType = OtherRefType->getPointeeType();
14968 OtherQuals = OtherRefType.getQualifiers();
14969 }
14970
14971 // Our location for everything implicitly-generated.
14972 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14973 ? CopyAssignOperator->getEndLoc()
14974 : CopyAssignOperator->getLocation();
14975
14976 // Builds a DeclRefExpr for the "other" object.
14977 RefBuilder OtherRef(Other, OtherRefType);
14978
14979 // Builds the function object parameter.
14980 std::optional<ThisBuilder> This;
14981 std::optional<DerefBuilder> DerefThis;
14982 std::optional<RefBuilder> ExplicitObject;
14983 bool IsArrow = false;
14984 QualType ObjectType;
14985 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
14986 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
14987 if (ObjectType->isReferenceType())
14988 ObjectType = ObjectType->getPointeeType();
14989 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
14990 } else {
14991 ObjectType = getCurrentThisType();
14992 This.emplace();
14993 DerefThis.emplace(*This);
14994 IsArrow = !LangOpts.HLSL;
14995 }
14996 ExprBuilder &ObjectParameter =
14997 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14998 : static_cast<ExprBuilder &>(*This);
14999
15000 // Assign base classes.
15001 bool Invalid = false;
15002 for (auto &Base : ClassDecl->bases()) {
15003 // Form the assignment:
15004 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15005 QualType BaseType = Base.getType().getUnqualifiedType();
15006 if (!BaseType->isRecordType()) {
15007 Invalid = true;
15008 continue;
15009 }
15010
15011 CXXCastPath BasePath;
15012 BasePath.push_back(&Base);
15013
15014 // Construct the "from" expression, which is an implicit cast to the
15015 // appropriately-qualified base type.
15016 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15017 VK_LValue, BasePath);
15018
15019 // Dereference "this".
15020 CastBuilder To(
15021 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15022 : static_cast<ExprBuilder &>(*DerefThis),
15023 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15024 VK_LValue, BasePath);
15025
15026 // Build the copy.
15027 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15028 To, From,
15029 /*CopyingBaseSubobject=*/true,
15030 /*Copying=*/true);
15031 if (Copy.isInvalid()) {
15032 CopyAssignOperator->setInvalidDecl();
15033 return;
15034 }
15035
15036 // Success! Record the copy.
15037 Statements.push_back(Copy.getAs<Expr>());
15038 }
15039
15040 // Assign non-static members.
15041 for (auto *Field : ClassDecl->fields()) {
15042 // FIXME: We should form some kind of AST representation for the implied
15043 // memcpy in a union copy operation.
15044 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15045 continue;
15046
15047 if (Field->isInvalidDecl()) {
15048 Invalid = true;
15049 continue;
15050 }
15051
15052 // Check for members of reference type; we can't copy those.
15053 if (Field->getType()->isReferenceType()) {
15054 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15055 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15056 Diag(Field->getLocation(), diag::note_declared_at);
15057 Invalid = true;
15058 continue;
15059 }
15060
15061 // Check for members of const-qualified, non-class type.
15062 QualType BaseType = Context.getBaseElementType(Field->getType());
15063 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15064 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15065 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15066 Diag(Field->getLocation(), diag::note_declared_at);
15067 Invalid = true;
15068 continue;
15069 }
15070
15071 // Suppress assigning zero-width bitfields.
15072 if (Field->isZeroLengthBitField())
15073 continue;
15074
15075 QualType FieldType = Field->getType().getNonReferenceType();
15076 if (FieldType->isIncompleteArrayType()) {
15077 assert(ClassDecl->hasFlexibleArrayMember() &&
15078 "Incomplete array type is not valid");
15079 continue;
15080 }
15081
15082 // Build references to the field in the object we're copying from and to.
15083 CXXScopeSpec SS; // Intentionally empty
15084 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15086 MemberLookup.addDecl(Field);
15087 MemberLookup.resolveKind();
15088
15089 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15090 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15091 // Build the copy of this field.
15092 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15093 To, From,
15094 /*CopyingBaseSubobject=*/false,
15095 /*Copying=*/true);
15096 if (Copy.isInvalid()) {
15097 CopyAssignOperator->setInvalidDecl();
15098 return;
15099 }
15100
15101 // Success! Record the copy.
15102 Statements.push_back(Copy.getAs<Stmt>());
15103 }
15104
15105 if (!Invalid) {
15106 // Add a "return *this;"
15107 Expr *ThisExpr =
15108 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15109 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15110 : static_cast<ExprBuilder &>(*DerefThis))
15111 .build(*this, Loc);
15112 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15113 if (Return.isInvalid())
15114 Invalid = true;
15115 else
15116 Statements.push_back(Return.getAs<Stmt>());
15117 }
15118
15119 if (Invalid) {
15120 CopyAssignOperator->setInvalidDecl();
15121 return;
15122 }
15123
15124 StmtResult Body;
15125 {
15126 CompoundScopeRAII CompoundScope(*this);
15127 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15128 /*isStmtExpr=*/false);
15129 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15130 }
15131 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15132 CopyAssignOperator->markUsed(Context);
15133
15135 L->CompletedImplicitDefinition(CopyAssignOperator);
15136 }
15137}
15138
15140 assert(ClassDecl->needsImplicitMoveAssignment());
15141
15142 DeclaringSpecialMember DSM(*this, ClassDecl,
15144 if (DSM.isAlreadyBeingDeclared())
15145 return nullptr;
15146
15147 // Note: The following rules are largely analoguous to the move
15148 // constructor rules.
15149
15150 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15152 ArgType, nullptr);
15154 if (AS != LangAS::Default)
15155 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15156 QualType RetType = Context.getLValueReferenceType(ArgType);
15157 ArgType = Context.getRValueReferenceType(ArgType);
15158
15160 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15161
15162 // An implicitly-declared move assignment operator is an inline public
15163 // member of its class.
15165 SourceLocation ClassLoc = ClassDecl->getLocation();
15166 DeclarationNameInfo NameInfo(Name, ClassLoc);
15168 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15169 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15170 getCurFPFeatures().isFPConstrained(),
15171 /*isInline=*/true,
15173 SourceLocation());
15174 MoveAssignment->setAccess(AS_public);
15175 MoveAssignment->setDefaulted();
15176 MoveAssignment->setImplicit();
15177
15178 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15179
15180 if (getLangOpts().CUDA)
15183 /* ConstRHS */ false,
15184 /* Diagnose */ false);
15185
15186 // Add the parameter to the operator.
15188 ClassLoc, ClassLoc,
15189 /*Id=*/nullptr, ArgType,
15190 /*TInfo=*/nullptr, SC_None,
15191 nullptr);
15192 MoveAssignment->setParams(FromParam);
15193
15194 MoveAssignment->setTrivial(
15198 : ClassDecl->hasTrivialMoveAssignment());
15199
15200 // Note that we have added this copy-assignment operator.
15202
15203 Scope *S = getScopeForContext(ClassDecl);
15205
15209 SetDeclDeleted(MoveAssignment, ClassLoc);
15210 }
15211
15212 if (S)
15214 ClassDecl->addDecl(MoveAssignment);
15215
15216 return MoveAssignment;
15217}
15218
15219/// Check if we're implicitly defining a move assignment operator for a class
15220/// with virtual bases. Such a move assignment might move-assign the virtual
15221/// base multiple times.
15223 SourceLocation CurrentLocation) {
15224 assert(!Class->isDependentContext() && "should not define dependent move");
15225
15226 // Only a virtual base could get implicitly move-assigned multiple times.
15227 // Only a non-trivial move assignment can observe this. We only want to
15228 // diagnose if we implicitly define an assignment operator that assigns
15229 // two base classes, both of which move-assign the same virtual base.
15230 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15231 Class->getNumBases() < 2)
15232 return;
15233
15235 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15236 VBaseMap VBases;
15237
15238 for (auto &BI : Class->bases()) {
15239 Worklist.push_back(&BI);
15240 while (!Worklist.empty()) {
15241 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15242 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15243
15244 // If the base has no non-trivial move assignment operators,
15245 // we don't care about moves from it.
15246 if (!Base->hasNonTrivialMoveAssignment())
15247 continue;
15248
15249 // If there's nothing virtual here, skip it.
15250 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15251 continue;
15252
15253 // If we're not actually going to call a move assignment for this base,
15254 // or the selected move assignment is trivial, skip it.
15257 /*ConstArg*/ false, /*VolatileArg*/ false,
15258 /*RValueThis*/ true, /*ConstThis*/ false,
15259 /*VolatileThis*/ false);
15260 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15262 continue;
15263
15264 if (BaseSpec->isVirtual()) {
15265 // We're going to move-assign this virtual base, and its move
15266 // assignment operator is not trivial. If this can happen for
15267 // multiple distinct direct bases of Class, diagnose it. (If it
15268 // only happens in one base, we'll diagnose it when synthesizing
15269 // that base class's move assignment operator.)
15270 CXXBaseSpecifier *&Existing =
15271 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15272 .first->second;
15273 if (Existing && Existing != &BI) {
15274 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15275 << Class << Base;
15276 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15277 << (Base->getCanonicalDecl() ==
15279 << Base << Existing->getType() << Existing->getSourceRange();
15280 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15281 << (Base->getCanonicalDecl() ==
15282 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15283 << Base << BI.getType() << BaseSpec->getSourceRange();
15284
15285 // Only diagnose each vbase once.
15286 Existing = nullptr;
15287 }
15288 } else {
15289 // Only walk over bases that have defaulted move assignment operators.
15290 // We assume that any user-provided move assignment operator handles
15291 // the multiple-moves-of-vbase case itself somehow.
15292 if (!SMOR.getMethod()->isDefaulted())
15293 continue;
15294
15295 // We're going to move the base classes of Base. Add them to the list.
15296 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15297 }
15298 }
15299 }
15300}
15301
15303 CXXMethodDecl *MoveAssignOperator) {
15304 assert((MoveAssignOperator->isDefaulted() &&
15305 MoveAssignOperator->isOverloadedOperator() &&
15306 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15307 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15308 !MoveAssignOperator->isDeleted()) &&
15309 "DefineImplicitMoveAssignment called for wrong function");
15310 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15311 return;
15312
15313 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15314 if (ClassDecl->isInvalidDecl()) {
15315 MoveAssignOperator->setInvalidDecl();
15316 return;
15317 }
15318
15319 // C++0x [class.copy]p28:
15320 // The implicitly-defined or move assignment operator for a non-union class
15321 // X performs memberwise move assignment of its subobjects. The direct base
15322 // classes of X are assigned first, in the order of their declaration in the
15323 // base-specifier-list, and then the immediate non-static data members of X
15324 // are assigned, in the order in which they were declared in the class
15325 // definition.
15326
15327 // Issue a warning if our implicit move assignment operator will move
15328 // from a virtual base more than once.
15329 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15330
15331 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15332
15333 // The exception specification is needed because we are defining the
15334 // function.
15335 ResolveExceptionSpec(CurrentLocation,
15336 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15337
15338 // Add a context note for diagnostics produced after this point.
15339 Scope.addContextNote(CurrentLocation);
15340
15341 // The statements that form the synthesized function body.
15342 SmallVector<Stmt*, 8> Statements;
15343
15344 // The parameter for the "other" object, which we are move from.
15345 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15346 QualType OtherRefType =
15347 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15348
15349 // Our location for everything implicitly-generated.
15350 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15351 ? MoveAssignOperator->getEndLoc()
15352 : MoveAssignOperator->getLocation();
15353
15354 // Builds a reference to the "other" object.
15355 RefBuilder OtherRef(Other, OtherRefType);
15356 // Cast to rvalue.
15357 MoveCastBuilder MoveOther(OtherRef);
15358
15359 // Builds the function object parameter.
15360 std::optional<ThisBuilder> This;
15361 std::optional<DerefBuilder> DerefThis;
15362 std::optional<RefBuilder> ExplicitObject;
15363 QualType ObjectType;
15364 bool IsArrow = false;
15365 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15366 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15367 if (ObjectType->isReferenceType())
15368 ObjectType = ObjectType->getPointeeType();
15369 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15370 } else {
15371 ObjectType = getCurrentThisType();
15372 This.emplace();
15373 DerefThis.emplace(*This);
15374 IsArrow = !getLangOpts().HLSL;
15375 }
15376 ExprBuilder &ObjectParameter =
15377 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15378
15379 // Assign base classes.
15380 bool Invalid = false;
15381 for (auto &Base : ClassDecl->bases()) {
15382 // C++11 [class.copy]p28:
15383 // It is unspecified whether subobjects representing virtual base classes
15384 // are assigned more than once by the implicitly-defined copy assignment
15385 // operator.
15386 // FIXME: Do not assign to a vbase that will be assigned by some other base
15387 // class. For a move-assignment, this can result in the vbase being moved
15388 // multiple times.
15389
15390 // Form the assignment:
15391 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15392 QualType BaseType = Base.getType().getUnqualifiedType();
15393 if (!BaseType->isRecordType()) {
15394 Invalid = true;
15395 continue;
15396 }
15397
15398 CXXCastPath BasePath;
15399 BasePath.push_back(&Base);
15400
15401 // Construct the "from" expression, which is an implicit cast to the
15402 // appropriately-qualified base type.
15403 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15404
15405 // Implicitly cast "this" to the appropriately-qualified base type.
15406 // Dereference "this".
15407 CastBuilder To(
15408 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15409 : static_cast<ExprBuilder &>(*DerefThis),
15410 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15411 VK_LValue, BasePath);
15412
15413 // Build the move.
15414 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15415 To, From,
15416 /*CopyingBaseSubobject=*/true,
15417 /*Copying=*/false);
15418 if (Move.isInvalid()) {
15419 MoveAssignOperator->setInvalidDecl();
15420 return;
15421 }
15422
15423 // Success! Record the move.
15424 Statements.push_back(Move.getAs<Expr>());
15425 }
15426
15427 // Assign non-static members.
15428 for (auto *Field : ClassDecl->fields()) {
15429 // FIXME: We should form some kind of AST representation for the implied
15430 // memcpy in a union copy operation.
15431 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15432 continue;
15433
15434 if (Field->isInvalidDecl()) {
15435 Invalid = true;
15436 continue;
15437 }
15438
15439 // Check for members of reference type; we can't move those.
15440 if (Field->getType()->isReferenceType()) {
15441 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15442 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15443 Diag(Field->getLocation(), diag::note_declared_at);
15444 Invalid = true;
15445 continue;
15446 }
15447
15448 // Check for members of const-qualified, non-class type.
15449 QualType BaseType = Context.getBaseElementType(Field->getType());
15450 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15451 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15452 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15453 Diag(Field->getLocation(), diag::note_declared_at);
15454 Invalid = true;
15455 continue;
15456 }
15457
15458 // Suppress assigning zero-width bitfields.
15459 if (Field->isZeroLengthBitField())
15460 continue;
15461
15462 QualType FieldType = Field->getType().getNonReferenceType();
15463 if (FieldType->isIncompleteArrayType()) {
15464 assert(ClassDecl->hasFlexibleArrayMember() &&
15465 "Incomplete array type is not valid");
15466 continue;
15467 }
15468
15469 // Build references to the field in the object we're copying from and to.
15470 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15472 MemberLookup.addDecl(Field);
15473 MemberLookup.resolveKind();
15474 MemberBuilder From(MoveOther, OtherRefType,
15475 /*IsArrow=*/false, MemberLookup);
15476 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15477
15478 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15479 "Member reference with rvalue base must be rvalue except for reference "
15480 "members, which aren't allowed for move assignment.");
15481
15482 // Build the move of this field.
15483 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15484 To, From,
15485 /*CopyingBaseSubobject=*/false,
15486 /*Copying=*/false);
15487 if (Move.isInvalid()) {
15488 MoveAssignOperator->setInvalidDecl();
15489 return;
15490 }
15491
15492 // Success! Record the copy.
15493 Statements.push_back(Move.getAs<Stmt>());
15494 }
15495
15496 if (!Invalid) {
15497 // Add a "return *this;"
15498 Expr *ThisExpr =
15499 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15500 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15501 : static_cast<ExprBuilder &>(*DerefThis))
15502 .build(*this, Loc);
15503
15504 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15505 if (Return.isInvalid())
15506 Invalid = true;
15507 else
15508 Statements.push_back(Return.getAs<Stmt>());
15509 }
15510
15511 if (Invalid) {
15512 MoveAssignOperator->setInvalidDecl();
15513 return;
15514 }
15515
15516 StmtResult Body;
15517 {
15518 CompoundScopeRAII CompoundScope(*this);
15519 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15520 /*isStmtExpr=*/false);
15521 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15522 }
15523 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15524 MoveAssignOperator->markUsed(Context);
15525
15527 L->CompletedImplicitDefinition(MoveAssignOperator);
15528 }
15529}
15530
15532 CXXRecordDecl *ClassDecl) {
15533 // C++ [class.copy]p4:
15534 // If the class definition does not explicitly declare a copy
15535 // constructor, one is declared implicitly.
15536 assert(ClassDecl->needsImplicitCopyConstructor());
15537
15538 DeclaringSpecialMember DSM(*this, ClassDecl,
15540 if (DSM.isAlreadyBeingDeclared())
15541 return nullptr;
15542
15543 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15544 QualType ArgType = ClassType;
15546 ArgType, nullptr);
15547 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15548 if (Const)
15549 ArgType = ArgType.withConst();
15550
15552 if (AS != LangAS::Default)
15553 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15554
15555 ArgType = Context.getLValueReferenceType(ArgType);
15556
15558 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15559
15560 DeclarationName Name
15562 Context.getCanonicalType(ClassType));
15563 SourceLocation ClassLoc = ClassDecl->getLocation();
15564 DeclarationNameInfo NameInfo(Name, ClassLoc);
15565
15566 // An implicitly-declared copy constructor is an inline public
15567 // member of its class.
15569 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15570 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15571 /*isInline=*/true,
15572 /*isImplicitlyDeclared=*/true,
15575 CopyConstructor->setAccess(AS_public);
15576 CopyConstructor->setDefaulted();
15577
15578 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15579
15580 if (getLangOpts().CUDA)
15583 /* ConstRHS */ Const,
15584 /* Diagnose */ false);
15585
15586 // During template instantiation of special member functions we need a
15587 // reliable TypeSourceInfo for the parameter types in order to allow functions
15588 // to be substituted.
15589 TypeSourceInfo *TSI = nullptr;
15590 if (inTemplateInstantiation() && ClassDecl->isLambda())
15591 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15592
15593 // Add the parameter to the constructor.
15594 ParmVarDecl *FromParam =
15595 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15596 /*IdentifierInfo=*/nullptr, ArgType,
15597 /*TInfo=*/TSI, SC_None, nullptr);
15598 CopyConstructor->setParams(FromParam);
15599
15600 CopyConstructor->setTrivial(
15604 : ClassDecl->hasTrivialCopyConstructor());
15605
15606 CopyConstructor->setTrivialForCall(
15607 ClassDecl->hasAttr<TrivialABIAttr>() ||
15612 : ClassDecl->hasTrivialCopyConstructorForCall()));
15613
15614 // Note that we have declared this constructor.
15616
15617 Scope *S = getScopeForContext(ClassDecl);
15619
15624 }
15625
15626 if (S)
15628 ClassDecl->addDecl(CopyConstructor);
15629
15630 return CopyConstructor;
15631}
15632
15635 assert((CopyConstructor->isDefaulted() &&
15636 CopyConstructor->isCopyConstructor() &&
15637 !CopyConstructor->doesThisDeclarationHaveABody() &&
15638 !CopyConstructor->isDeleted()) &&
15639 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15640 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15641 return;
15642
15643 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15644 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15645
15647
15648 // The exception specification is needed because we are defining the
15649 // function.
15650 ResolveExceptionSpec(CurrentLocation,
15651 CopyConstructor->getType()->castAs<FunctionProtoType>());
15652 MarkVTableUsed(CurrentLocation, ClassDecl);
15653
15654 // Add a context note for diagnostics produced after this point.
15655 Scope.addContextNote(CurrentLocation);
15656
15657 // C++11 [class.copy]p7:
15658 // The [definition of an implicitly declared copy constructor] is
15659 // deprecated if the class has a user-declared copy assignment operator
15660 // or a user-declared destructor.
15661 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15663
15664 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15665 CopyConstructor->setInvalidDecl();
15666 } else {
15667 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15668 ? CopyConstructor->getEndLoc()
15669 : CopyConstructor->getLocation();
15670 Sema::CompoundScopeRAII CompoundScope(*this);
15671 CopyConstructor->setBody(
15672 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
15673 CopyConstructor->markUsed(Context);
15674 }
15675
15677 L->CompletedImplicitDefinition(CopyConstructor);
15678 }
15679}
15680
15682 CXXRecordDecl *ClassDecl) {
15683 assert(ClassDecl->needsImplicitMoveConstructor());
15684
15685 DeclaringSpecialMember DSM(*this, ClassDecl,
15687 if (DSM.isAlreadyBeingDeclared())
15688 return nullptr;
15689
15690 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15691
15692 QualType ArgType = ClassType;
15694 ArgType, nullptr);
15696 if (AS != LangAS::Default)
15697 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15698 ArgType = Context.getRValueReferenceType(ArgType);
15699
15701 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15702
15703 DeclarationName Name
15705 Context.getCanonicalType(ClassType));
15706 SourceLocation ClassLoc = ClassDecl->getLocation();
15707 DeclarationNameInfo NameInfo(Name, ClassLoc);
15708
15709 // C++11 [class.copy]p11:
15710 // An implicitly-declared copy/move constructor is an inline public
15711 // member of its class.
15713 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15714 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15715 /*isInline=*/true,
15716 /*isImplicitlyDeclared=*/true,
15719 MoveConstructor->setAccess(AS_public);
15720 MoveConstructor->setDefaulted();
15721
15722 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15723
15724 if (getLangOpts().CUDA)
15727 /* ConstRHS */ false,
15728 /* Diagnose */ false);
15729
15730 // Add the parameter to the constructor.
15732 ClassLoc, ClassLoc,
15733 /*IdentifierInfo=*/nullptr,
15734 ArgType, /*TInfo=*/nullptr,
15735 SC_None, nullptr);
15736 MoveConstructor->setParams(FromParam);
15737
15738 MoveConstructor->setTrivial(
15742 : ClassDecl->hasTrivialMoveConstructor());
15743
15744 MoveConstructor->setTrivialForCall(
15745 ClassDecl->hasAttr<TrivialABIAttr>() ||
15750 : ClassDecl->hasTrivialMoveConstructorForCall()));
15751
15752 // Note that we have declared this constructor.
15754
15755 Scope *S = getScopeForContext(ClassDecl);
15757
15762 }
15763
15764 if (S)
15766 ClassDecl->addDecl(MoveConstructor);
15767
15768 return MoveConstructor;
15769}
15770
15773 assert((MoveConstructor->isDefaulted() &&
15774 MoveConstructor->isMoveConstructor() &&
15775 !MoveConstructor->doesThisDeclarationHaveABody() &&
15776 !MoveConstructor->isDeleted()) &&
15777 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15778 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15779 return;
15780
15781 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15782 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15783
15785
15786 // The exception specification is needed because we are defining the
15787 // function.
15788 ResolveExceptionSpec(CurrentLocation,
15789 MoveConstructor->getType()->castAs<FunctionProtoType>());
15790 MarkVTableUsed(CurrentLocation, ClassDecl);
15791
15792 // Add a context note for diagnostics produced after this point.
15793 Scope.addContextNote(CurrentLocation);
15794
15795 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15796 MoveConstructor->setInvalidDecl();
15797 } else {
15798 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15799 ? MoveConstructor->getEndLoc()
15800 : MoveConstructor->getLocation();
15801 Sema::CompoundScopeRAII CompoundScope(*this);
15802 MoveConstructor->setBody(
15803 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
15804 MoveConstructor->markUsed(Context);
15805 }
15806
15808 L->CompletedImplicitDefinition(MoveConstructor);
15809 }
15810}
15811
15813 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15814}
15815
15817 SourceLocation CurrentLocation,
15818 CXXConversionDecl *Conv) {
15819 SynthesizedFunctionScope Scope(*this, Conv);
15820 assert(!Conv->getReturnType()->isUndeducedType());
15821
15822 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15823 CallingConv CC =
15824 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15825
15826 CXXRecordDecl *Lambda = Conv->getParent();
15827 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15828 FunctionDecl *Invoker =
15829 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15830 ? CallOp
15831 : Lambda->getLambdaStaticInvoker(CC);
15832
15833 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15835 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15836 if (!CallOp)
15837 return;
15838
15839 if (CallOp != Invoker) {
15841 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15842 CurrentLocation);
15843 if (!Invoker)
15844 return;
15845 }
15846 }
15847
15848 if (CallOp->isInvalidDecl())
15849 return;
15850
15851 // Mark the call operator referenced (and add to pending instantiations
15852 // if necessary).
15853 // For both the conversion and static-invoker template specializations
15854 // we construct their body's in this function, so no need to add them
15855 // to the PendingInstantiations.
15856 MarkFunctionReferenced(CurrentLocation, CallOp);
15857
15858 if (Invoker != CallOp) {
15859 // Fill in the __invoke function with a dummy implementation. IR generation
15860 // will fill in the actual details. Update its type in case it contained
15861 // an 'auto'.
15862 Invoker->markUsed(Context);
15863 Invoker->setReferenced();
15864 Invoker->setType(Conv->getReturnType()->getPointeeType());
15865 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15866 }
15867
15868 // Construct the body of the conversion function { return __invoke; }.
15869 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15870 Conv->getLocation());
15871 assert(FunctionRef && "Can't refer to __invoke function?");
15872 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15874 Conv->getLocation(), Conv->getLocation()));
15875 Conv->markUsed(Context);
15876 Conv->setReferenced();
15877
15879 L->CompletedImplicitDefinition(Conv);
15880 if (Invoker != CallOp)
15881 L->CompletedImplicitDefinition(Invoker);
15882 }
15883}
15884
15886 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15887 assert(!Conv->getParent()->isGenericLambda());
15888
15889 SynthesizedFunctionScope Scope(*this, Conv);
15890
15891 // Copy-initialize the lambda object as needed to capture it.
15892 Expr *This = ActOnCXXThis(CurrentLocation).get();
15893 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15894
15895 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15896 Conv->getLocation(),
15897 Conv, DerefThis);
15898
15899 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15900 // behavior. Note that only the general conversion function does this
15901 // (since it's unusable otherwise); in the case where we inline the
15902 // block literal, it has block literal lifetime semantics.
15903 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15904 BuildBlock = ImplicitCastExpr::Create(
15905 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15906 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15907
15908 if (BuildBlock.isInvalid()) {
15909 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15910 Conv->setInvalidDecl();
15911 return;
15912 }
15913
15914 // Create the return statement that returns the block from the conversion
15915 // function.
15916 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15917 if (Return.isInvalid()) {
15918 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15919 Conv->setInvalidDecl();
15920 return;
15921 }
15922
15923 // Set the body of the conversion function.
15924 Stmt *ReturnS = Return.get();
15926 Conv->getLocation(), Conv->getLocation()));
15927 Conv->markUsed(Context);
15928
15929 // We're done; notify the mutation listener, if any.
15931 L->CompletedImplicitDefinition(Conv);
15932 }
15933}
15934
15935/// Determine whether the given list arguments contains exactly one
15936/// "real" (non-default) argument.
15938 switch (Args.size()) {
15939 case 0:
15940 return false;
15941
15942 default:
15943 if (!Args[1]->isDefaultArgument())
15944 return false;
15945
15946 [[fallthrough]];
15947 case 1:
15948 return !Args[0]->isDefaultArgument();
15949 }
15950
15951 return false;
15952}
15953
15955 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15956 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
15957 bool HadMultipleCandidates, bool IsListInitialization,
15958 bool IsStdInitListInitialization, bool RequiresZeroInit,
15959 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15960 bool Elidable = false;
15961
15962 // C++0x [class.copy]p34:
15963 // When certain criteria are met, an implementation is allowed to
15964 // omit the copy/move construction of a class object, even if the
15965 // copy/move constructor and/or destructor for the object have
15966 // side effects. [...]
15967 // - when a temporary class object that has not been bound to a
15968 // reference (12.2) would be copied/moved to a class object
15969 // with the same cv-unqualified type, the copy/move operation
15970 // can be omitted by constructing the temporary object
15971 // directly into the target of the omitted copy/move
15972 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
15973 // FIXME: Converting constructors should also be accepted.
15974 // But to fix this, the logic that digs down into a CXXConstructExpr
15975 // to find the source object needs to handle it.
15976 // Right now it assumes the source object is passed directly as the
15977 // first argument.
15978 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15979 Expr *SubExpr = ExprArgs[0];
15980 // FIXME: Per above, this is also incorrect if we want to accept
15981 // converting constructors, as isTemporaryObject will
15982 // reject temporaries with different type from the
15983 // CXXRecord itself.
15984 Elidable = SubExpr->isTemporaryObject(
15985 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15986 }
15987
15988 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15989 FoundDecl, Constructor,
15990 Elidable, ExprArgs, HadMultipleCandidates,
15991 IsListInitialization,
15992 IsStdInitListInitialization, RequiresZeroInit,
15993 ConstructKind, ParenRange);
15994}
15995
15997 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15998 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15999 bool HadMultipleCandidates, bool IsListInitialization,
16000 bool IsStdInitListInitialization, bool RequiresZeroInit,
16001 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16002 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16003 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16004 // The only way to get here is if we did overload resolution to find the
16005 // shadow decl, so we don't need to worry about re-checking the trailing
16006 // requires clause.
16007 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16008 return ExprError();
16009 }
16010
16011 return BuildCXXConstructExpr(
16012 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16013 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16014 RequiresZeroInit, ConstructKind, ParenRange);
16015}
16016
16017/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16018/// including handling of its default argument expressions.
16020 SourceLocation ConstructLoc, QualType DeclInitType,
16021 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16022 bool HadMultipleCandidates, bool IsListInitialization,
16023 bool IsStdInitListInitialization, bool RequiresZeroInit,
16024 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16025 assert(declaresSameEntity(
16026 Constructor->getParent(),
16027 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16028 "given constructor for wrong type");
16029 MarkFunctionReferenced(ConstructLoc, Constructor);
16030 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16031 return ExprError();
16032
16035 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16036 HadMultipleCandidates, IsListInitialization,
16037 IsStdInitListInitialization, RequiresZeroInit,
16038 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16039 Constructor);
16040}
16041
16043 if (VD->isInvalidDecl()) return;
16044 // If initializing the variable failed, don't also diagnose problems with
16045 // the destructor, they're likely related.
16046 if (VD->getInit() && VD->getInit()->containsErrors())
16047 return;
16048
16049 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16050 if (ClassDecl->isInvalidDecl()) return;
16051 if (ClassDecl->hasIrrelevantDestructor()) return;
16052 if (ClassDecl->isDependentContext()) return;
16053
16054 if (VD->isNoDestroy(getASTContext()))
16055 return;
16056
16058 // The result of `LookupDestructor` might be nullptr if the destructor is
16059 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16060 // will not be selected by `CXXRecordDecl::getDestructor()`.
16061 if (!Destructor)
16062 return;
16063 // If this is an array, we'll require the destructor during initialization, so
16064 // we can skip over this. We still want to emit exit-time destructor warnings
16065 // though.
16066 if (!VD->getType()->isArrayType()) {
16069 PDiag(diag::err_access_dtor_var)
16070 << VD->getDeclName() << VD->getType());
16072 }
16073
16074 if (Destructor->isTrivial()) return;
16075
16076 // If the destructor is constexpr, check whether the variable has constant
16077 // destruction now.
16078 if (Destructor->isConstexpr()) {
16079 bool HasConstantInit = false;
16080 if (VD->getInit() && !VD->getInit()->isValueDependent())
16081 HasConstantInit = VD->evaluateValue();
16083 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16084 HasConstantInit) {
16085 Diag(VD->getLocation(),
16086 diag::err_constexpr_var_requires_const_destruction) << VD;
16087 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16088 Diag(Notes[I].first, Notes[I].second);
16089 }
16090 }
16091
16092 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16093 return;
16094
16095 // Emit warning for non-trivial dtor in global scope (a real global,
16096 // class-static, function-static).
16097 if (!VD->hasAttr<AlwaysDestroyAttr>())
16098 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16099
16100 // TODO: this should be re-enabled for static locals by !CXAAtExit
16101 if (!VD->isStaticLocal())
16102 Diag(VD->getLocation(), diag::warn_global_destructor);
16103}
16104
16106 QualType DeclInitType, MultiExprArg ArgsPtr,
16108 SmallVectorImpl<Expr *> &ConvertedArgs,
16109 bool AllowExplicit,
16110 bool IsListInitialization) {
16111 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16112 unsigned NumArgs = ArgsPtr.size();
16113 Expr **Args = ArgsPtr.data();
16114
16115 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16116 unsigned NumParams = Proto->getNumParams();
16117
16118 // If too few arguments are available, we'll fill in the rest with defaults.
16119 if (NumArgs < NumParams)
16120 ConvertedArgs.reserve(NumParams);
16121 else
16122 ConvertedArgs.reserve(NumArgs);
16123
16124 VariadicCallType CallType =
16125 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16126 SmallVector<Expr *, 8> AllArgs;
16128 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16129 CallType, AllowExplicit, IsListInitialization);
16130 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16131
16132 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16133
16134 CheckConstructorCall(Constructor, DeclInitType,
16135 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16136 Loc);
16137
16138 return Invalid;
16139}
16140
16141static inline bool
16143 const FunctionDecl *FnDecl) {
16144 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16145 if (isa<NamespaceDecl>(DC)) {
16146 return SemaRef.Diag(FnDecl->getLocation(),
16147 diag::err_operator_new_delete_declared_in_namespace)
16148 << FnDecl->getDeclName();
16149 }
16150
16151 if (isa<TranslationUnitDecl>(DC) &&
16152 FnDecl->getStorageClass() == SC_Static) {
16153 return SemaRef.Diag(FnDecl->getLocation(),
16154 diag::err_operator_new_delete_declared_static)
16155 << FnDecl->getDeclName();
16156 }
16157
16158 return false;
16159}
16160
16162 const PointerType *PtrTy) {
16163 auto &Ctx = SemaRef.Context;
16164 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16165 PtrQuals.removeAddressSpace();
16167 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16168}
16169
16170static inline bool
16172 CanQualType ExpectedResultType,
16173 CanQualType ExpectedFirstParamType,
16174 unsigned DependentParamTypeDiag,
16175 unsigned InvalidParamTypeDiag) {
16176 QualType ResultType =
16177 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16178
16179 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16180 // The operator is valid on any address space for OpenCL.
16181 // Drop address space from actual and expected result types.
16182 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16183 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16184
16185 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16186 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16187 }
16188
16189 // Check that the result type is what we expect.
16190 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16191 // Reject even if the type is dependent; an operator delete function is
16192 // required to have a non-dependent result type.
16193 return SemaRef.Diag(
16194 FnDecl->getLocation(),
16195 ResultType->isDependentType()
16196 ? diag::err_operator_new_delete_dependent_result_type
16197 : diag::err_operator_new_delete_invalid_result_type)
16198 << FnDecl->getDeclName() << ExpectedResultType;
16199 }
16200
16201 // A function template must have at least 2 parameters.
16202 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16203 return SemaRef.Diag(FnDecl->getLocation(),
16204 diag::err_operator_new_delete_template_too_few_parameters)
16205 << FnDecl->getDeclName();
16206
16207 // The function decl must have at least 1 parameter.
16208 if (FnDecl->getNumParams() == 0)
16209 return SemaRef.Diag(FnDecl->getLocation(),
16210 diag::err_operator_new_delete_too_few_parameters)
16211 << FnDecl->getDeclName();
16212
16213 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16214 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16215 // The operator is valid on any address space for OpenCL.
16216 // Drop address space from actual and expected first parameter types.
16217 if (const auto *PtrTy =
16218 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16219 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16220
16221 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16222 ExpectedFirstParamType =
16223 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16224 }
16225
16226 // Check that the first parameter type is what we expect.
16227 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16228 ExpectedFirstParamType) {
16229 // The first parameter type is not allowed to be dependent. As a tentative
16230 // DR resolution, we allow a dependent parameter type if it is the right
16231 // type anyway, to allow destroying operator delete in class templates.
16232 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16233 ? DependentParamTypeDiag
16234 : InvalidParamTypeDiag)
16235 << FnDecl->getDeclName() << ExpectedFirstParamType;
16236 }
16237
16238 return false;
16239}
16240
16241static bool
16243 // C++ [basic.stc.dynamic.allocation]p1:
16244 // A program is ill-formed if an allocation function is declared in a
16245 // namespace scope other than global scope or declared static in global
16246 // scope.
16248 return true;
16249
16250 CanQualType SizeTy =
16252
16253 // C++ [basic.stc.dynamic.allocation]p1:
16254 // The return type shall be void*. The first parameter shall have type
16255 // std::size_t.
16257 SizeTy,
16258 diag::err_operator_new_dependent_param_type,
16259 diag::err_operator_new_param_type))
16260 return true;
16261
16262 // C++ [basic.stc.dynamic.allocation]p1:
16263 // The first parameter shall not have an associated default argument.
16264 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16265 return SemaRef.Diag(FnDecl->getLocation(),
16266 diag::err_operator_new_default_arg)
16267 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16268
16269 return false;
16270}
16271
16272static bool
16274 // C++ [basic.stc.dynamic.deallocation]p1:
16275 // A program is ill-formed if deallocation functions are declared in a
16276 // namespace scope other than global scope or declared static in global
16277 // scope.
16279 return true;
16280
16281 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16282
16283 // C++ P0722:
16284 // Within a class C, the first parameter of a destroying operator delete
16285 // shall be of type C *. The first parameter of any other deallocation
16286 // function shall be of type void *.
16287 CanQualType ExpectedFirstParamType =
16288 MD && MD->isDestroyingOperatorDelete()
16292
16293 // C++ [basic.stc.dynamic.deallocation]p2:
16294 // Each deallocation function shall return void
16296 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16297 diag::err_operator_delete_dependent_param_type,
16298 diag::err_operator_delete_param_type))
16299 return true;
16300
16301 // C++ P0722:
16302 // A destroying operator delete shall be a usual deallocation function.
16303 if (MD && !MD->getParent()->isDependentContext() &&
16306 SemaRef.Diag(MD->getLocation(),
16307 diag::err_destroying_operator_delete_not_usual);
16308 return true;
16309 }
16310
16311 return false;
16312}
16313
16315 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16316 "Expected an overloaded operator declaration");
16317
16319
16320 // C++ [over.oper]p5:
16321 // The allocation and deallocation functions, operator new,
16322 // operator new[], operator delete and operator delete[], are
16323 // described completely in 3.7.3. The attributes and restrictions
16324 // found in the rest of this subclause do not apply to them unless
16325 // explicitly stated in 3.7.3.
16326 if (Op == OO_Delete || Op == OO_Array_Delete)
16327 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16328
16329 if (Op == OO_New || Op == OO_Array_New)
16330 return CheckOperatorNewDeclaration(*this, FnDecl);
16331
16332 // C++ [over.oper]p7:
16333 // An operator function shall either be a member function or
16334 // be a non-member function and have at least one parameter
16335 // whose type is a class, a reference to a class, an enumeration,
16336 // or a reference to an enumeration.
16337 // Note: Before C++23, a member function could not be static. The only member
16338 // function allowed to be static is the call operator function.
16339 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16340 if (MethodDecl->isStatic()) {
16341 if (Op == OO_Call || Op == OO_Subscript)
16342 Diag(FnDecl->getLocation(),
16343 (LangOpts.CPlusPlus23
16344 ? diag::warn_cxx20_compat_operator_overload_static
16345 : diag::ext_operator_overload_static))
16346 << FnDecl;
16347 else
16348 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16349 << FnDecl;
16350 }
16351 } else {
16352 bool ClassOrEnumParam = false;
16353 for (auto *Param : FnDecl->parameters()) {
16354 QualType ParamType = Param->getType().getNonReferenceType();
16355 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16356 ParamType->isEnumeralType()) {
16357 ClassOrEnumParam = true;
16358 break;
16359 }
16360 }
16361
16362 if (!ClassOrEnumParam)
16363 return Diag(FnDecl->getLocation(),
16364 diag::err_operator_overload_needs_class_or_enum)
16365 << FnDecl->getDeclName();
16366 }
16367
16368 // C++ [over.oper]p8:
16369 // An operator function cannot have default arguments (8.3.6),
16370 // except where explicitly stated below.
16371 //
16372 // Only the function-call operator (C++ [over.call]p1) and the subscript
16373 // operator (CWG2507) allow default arguments.
16374 if (Op != OO_Call) {
16375 ParmVarDecl *FirstDefaultedParam = nullptr;
16376 for (auto *Param : FnDecl->parameters()) {
16377 if (Param->hasDefaultArg()) {
16378 FirstDefaultedParam = Param;
16379 break;
16380 }
16381 }
16382 if (FirstDefaultedParam) {
16383 if (Op == OO_Subscript) {
16384 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16385 ? diag::ext_subscript_overload
16386 : diag::error_subscript_overload)
16387 << FnDecl->getDeclName() << 1
16388 << FirstDefaultedParam->getDefaultArgRange();
16389 } else {
16390 return Diag(FirstDefaultedParam->getLocation(),
16391 diag::err_operator_overload_default_arg)
16392 << FnDecl->getDeclName()
16393 << FirstDefaultedParam->getDefaultArgRange();
16394 }
16395 }
16396 }
16397
16398 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16399 { false, false, false }
16400#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16401 , { Unary, Binary, MemberOnly }
16402#include "clang/Basic/OperatorKinds.def"
16403 };
16404
16405 bool CanBeUnaryOperator = OperatorUses[Op][0];
16406 bool CanBeBinaryOperator = OperatorUses[Op][1];
16407 bool MustBeMemberOperator = OperatorUses[Op][2];
16408
16409 // C++ [over.oper]p8:
16410 // [...] Operator functions cannot have more or fewer parameters
16411 // than the number required for the corresponding operator, as
16412 // described in the rest of this subclause.
16413 unsigned NumParams = FnDecl->getNumParams() +
16414 (isa<CXXMethodDecl>(FnDecl) &&
16416 ? 1
16417 : 0);
16418 if (Op != OO_Call && Op != OO_Subscript &&
16419 ((NumParams == 1 && !CanBeUnaryOperator) ||
16420 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16421 (NumParams > 2))) {
16422 // We have the wrong number of parameters.
16423 unsigned ErrorKind;
16424 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16425 ErrorKind = 2; // 2 -> unary or binary.
16426 } else if (CanBeUnaryOperator) {
16427 ErrorKind = 0; // 0 -> unary
16428 } else {
16429 assert(CanBeBinaryOperator &&
16430 "All non-call overloaded operators are unary or binary!");
16431 ErrorKind = 1; // 1 -> binary
16432 }
16433 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16434 << FnDecl->getDeclName() << NumParams << ErrorKind;
16435 }
16436
16437 if (Op == OO_Subscript && NumParams != 2) {
16438 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16439 ? diag::ext_subscript_overload
16440 : diag::error_subscript_overload)
16441 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16442 }
16443
16444 // Overloaded operators other than operator() and operator[] cannot be
16445 // variadic.
16446 if (Op != OO_Call &&
16447 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16448 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16449 << FnDecl->getDeclName();
16450 }
16451
16452 // Some operators must be member functions.
16453 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16454 return Diag(FnDecl->getLocation(),
16455 diag::err_operator_overload_must_be_member)
16456 << FnDecl->getDeclName();
16457 }
16458
16459 // C++ [over.inc]p1:
16460 // The user-defined function called operator++ implements the
16461 // prefix and postfix ++ operator. If this function is a member
16462 // function with no parameters, or a non-member function with one
16463 // parameter of class or enumeration type, it defines the prefix
16464 // increment operator ++ for objects of that type. If the function
16465 // is a member function with one parameter (which shall be of type
16466 // int) or a non-member function with two parameters (the second
16467 // of which shall be of type int), it defines the postfix
16468 // increment operator ++ for objects of that type.
16469 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16470 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16471 QualType ParamType = LastParam->getType();
16472
16473 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16474 !ParamType->isDependentType())
16475 return Diag(LastParam->getLocation(),
16476 diag::err_operator_overload_post_incdec_must_be_int)
16477 << LastParam->getType() << (Op == OO_MinusMinus);
16478 }
16479
16480 return false;
16481}
16482
16483static bool
16485 FunctionTemplateDecl *TpDecl) {
16486 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16487
16488 // Must have one or two template parameters.
16489 if (TemplateParams->size() == 1) {
16490 NonTypeTemplateParmDecl *PmDecl =
16491 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16492
16493 // The template parameter must be a char parameter pack.
16494 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16496 return false;
16497
16498 // C++20 [over.literal]p5:
16499 // A string literal operator template is a literal operator template
16500 // whose template-parameter-list comprises a single non-type
16501 // template-parameter of class type.
16502 //
16503 // As a DR resolution, we also allow placeholders for deduced class
16504 // template specializations.
16505 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16506 !PmDecl->isTemplateParameterPack() &&
16507 (PmDecl->getType()->isRecordType() ||
16509 return false;
16510 } else if (TemplateParams->size() == 2) {
16511 TemplateTypeParmDecl *PmType =
16512 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16513 NonTypeTemplateParmDecl *PmArgs =
16514 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16515
16516 // The second template parameter must be a parameter pack with the
16517 // first template parameter as its type.
16518 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16519 PmArgs->isTemplateParameterPack()) {
16520 const TemplateTypeParmType *TArgs =
16521 PmArgs->getType()->getAs<TemplateTypeParmType>();
16522 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16523 TArgs->getIndex() == PmType->getIndex()) {
16525 SemaRef.Diag(TpDecl->getLocation(),
16526 diag::ext_string_literal_operator_template);
16527 return false;
16528 }
16529 }
16530 }
16531
16533 diag::err_literal_operator_template)
16534 << TpDecl->getTemplateParameters()->getSourceRange();
16535 return true;
16536}
16537
16539 if (isa<CXXMethodDecl>(FnDecl)) {
16540 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16541 << FnDecl->getDeclName();
16542 return true;
16543 }
16544
16545 if (FnDecl->isExternC()) {
16546 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16547 if (const LinkageSpecDecl *LSD =
16548 FnDecl->getDeclContext()->getExternCContext())
16549 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16550 return true;
16551 }
16552
16553 // This might be the definition of a literal operator template.
16555
16556 // This might be a specialization of a literal operator template.
16557 if (!TpDecl)
16558 TpDecl = FnDecl->getPrimaryTemplate();
16559
16560 // template <char...> type operator "" name() and
16561 // template <class T, T...> type operator "" name() are the only valid
16562 // template signatures, and the only valid signatures with no parameters.
16563 //
16564 // C++20 also allows template <SomeClass T> type operator "" name().
16565 if (TpDecl) {
16566 if (FnDecl->param_size() != 0) {
16567 Diag(FnDecl->getLocation(),
16568 diag::err_literal_operator_template_with_params);
16569 return true;
16570 }
16571
16573 return true;
16574
16575 } else if (FnDecl->param_size() == 1) {
16576 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16577
16578 QualType ParamType = Param->getType().getUnqualifiedType();
16579
16580 // Only unsigned long long int, long double, any character type, and const
16581 // char * are allowed as the only parameters.
16582 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16583 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16584 Context.hasSameType(ParamType, Context.CharTy) ||
16585 Context.hasSameType(ParamType, Context.WideCharTy) ||
16586 Context.hasSameType(ParamType, Context.Char8Ty) ||
16587 Context.hasSameType(ParamType, Context.Char16Ty) ||
16588 Context.hasSameType(ParamType, Context.Char32Ty)) {
16589 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16590 QualType InnerType = Ptr->getPointeeType();
16591
16592 // Pointer parameter must be a const char *.
16593 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16594 Context.CharTy) &&
16595 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16596 Diag(Param->getSourceRange().getBegin(),
16597 diag::err_literal_operator_param)
16598 << ParamType << "'const char *'" << Param->getSourceRange();
16599 return true;
16600 }
16601
16602 } else if (ParamType->isRealFloatingType()) {
16603 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16604 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16605 return true;
16606
16607 } else if (ParamType->isIntegerType()) {
16608 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16609 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16610 return true;
16611
16612 } else {
16613 Diag(Param->getSourceRange().getBegin(),
16614 diag::err_literal_operator_invalid_param)
16615 << ParamType << Param->getSourceRange();
16616 return true;
16617 }
16618
16619 } else if (FnDecl->param_size() == 2) {
16620 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16621
16622 // First, verify that the first parameter is correct.
16623
16624 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16625
16626 // Two parameter function must have a pointer to const as a
16627 // first parameter; let's strip those qualifiers.
16628 const PointerType *PT = FirstParamType->getAs<PointerType>();
16629
16630 if (!PT) {
16631 Diag((*Param)->getSourceRange().getBegin(),
16632 diag::err_literal_operator_param)
16633 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16634 return true;
16635 }
16636
16637 QualType PointeeType = PT->getPointeeType();
16638 // First parameter must be const
16639 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16640 Diag((*Param)->getSourceRange().getBegin(),
16641 diag::err_literal_operator_param)
16642 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16643 return true;
16644 }
16645
16646 QualType InnerType = PointeeType.getUnqualifiedType();
16647 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16648 // const char32_t* are allowed as the first parameter to a two-parameter
16649 // function
16650 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16651 Context.hasSameType(InnerType, Context.WideCharTy) ||
16652 Context.hasSameType(InnerType, Context.Char8Ty) ||
16653 Context.hasSameType(InnerType, Context.Char16Ty) ||
16654 Context.hasSameType(InnerType, Context.Char32Ty))) {
16655 Diag((*Param)->getSourceRange().getBegin(),
16656 diag::err_literal_operator_param)
16657 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16658 return true;
16659 }
16660
16661 // Move on to the second and final parameter.
16662 ++Param;
16663
16664 // The second parameter must be a std::size_t.
16665 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16666 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16667 Diag((*Param)->getSourceRange().getBegin(),
16668 diag::err_literal_operator_param)
16669 << SecondParamType << Context.getSizeType()
16670 << (*Param)->getSourceRange();
16671 return true;
16672 }
16673 } else {
16674 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16675 return true;
16676 }
16677
16678 // Parameters are good.
16679
16680 // A parameter-declaration-clause containing a default argument is not
16681 // equivalent to any of the permitted forms.
16682 for (auto *Param : FnDecl->parameters()) {
16683 if (Param->hasDefaultArg()) {
16684 Diag(Param->getDefaultArgRange().getBegin(),
16685 diag::err_literal_operator_default_argument)
16686 << Param->getDefaultArgRange();
16687 break;
16688 }
16689 }
16690
16691 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16694 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16695 // C++23 [usrlit.suffix]p1:
16696 // Literal suffix identifiers that do not start with an underscore are
16697 // reserved for future standardization. Literal suffix identifiers that
16698 // contain a double underscore __ are reserved for use by C++
16699 // implementations.
16700 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16701 << static_cast<int>(Status)
16703 }
16704
16705 return false;
16706}
16707
16709 Expr *LangStr,
16710 SourceLocation LBraceLoc) {
16711 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16712 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16713
16714 StringRef Lang = Lit->getString();
16716 if (Lang == "C")
16718 else if (Lang == "C++")
16720 else {
16721 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16722 << LangStr->getSourceRange();
16723 return nullptr;
16724 }
16725
16726 // FIXME: Add all the various semantics of linkage specifications
16727
16729 LangStr->getExprLoc(), Language,
16730 LBraceLoc.isValid());
16731
16732 /// C++ [module.unit]p7.2.3
16733 /// - Otherwise, if the declaration
16734 /// - ...
16735 /// - ...
16736 /// - appears within a linkage-specification,
16737 /// it is attached to the global module.
16738 ///
16739 /// If the declaration is already in global module fragment, we don't
16740 /// need to attach it again.
16741 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16742 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16743 D->setLocalOwningModule(GlobalModule);
16744 }
16745
16747 PushDeclContext(S, D);
16748 return D;
16749}
16750
16752 Decl *LinkageSpec,
16753 SourceLocation RBraceLoc) {
16754 if (RBraceLoc.isValid()) {
16755 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16756 LSDecl->setRBraceLoc(RBraceLoc);
16757 }
16758
16759 // If the current module doesn't has Parent, it implies that the
16760 // LinkageSpec isn't in the module created by itself. So we don't
16761 // need to pop it.
16762 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16763 getCurrentModule()->isImplicitGlobalModule() &&
16765 PopImplicitGlobalModuleFragment();
16766
16768 return LinkageSpec;
16769}
16770
16772 const ParsedAttributesView &AttrList,
16773 SourceLocation SemiLoc) {
16774 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16775 // Attribute declarations appertain to empty declaration so we handle
16776 // them here.
16777 ProcessDeclAttributeList(S, ED, AttrList);
16778
16779 CurContext->addDecl(ED);
16780 return ED;
16781}
16782
16784 SourceLocation StartLoc,
16786 const IdentifierInfo *Name) {
16787 bool Invalid = false;
16788 QualType ExDeclType = TInfo->getType();
16789
16790 // Arrays and functions decay.
16791 if (ExDeclType->isArrayType())
16792 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16793 else if (ExDeclType->isFunctionType())
16794 ExDeclType = Context.getPointerType(ExDeclType);
16795
16796 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16797 // The exception-declaration shall not denote a pointer or reference to an
16798 // incomplete type, other than [cv] void*.
16799 // N2844 forbids rvalue references.
16800 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16801 Diag(Loc, diag::err_catch_rvalue_ref);
16802 Invalid = true;
16803 }
16804
16805 if (ExDeclType->isVariablyModifiedType()) {
16806 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16807 Invalid = true;
16808 }
16809
16810 QualType BaseType = ExDeclType;
16811 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16812 unsigned DK = diag::err_catch_incomplete;
16813 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16814 BaseType = Ptr->getPointeeType();
16815 Mode = 1;
16816 DK = diag::err_catch_incomplete_ptr;
16817 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16818 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16819 BaseType = Ref->getPointeeType();
16820 Mode = 2;
16821 DK = diag::err_catch_incomplete_ref;
16822 }
16823 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16824 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16825 Invalid = true;
16826
16827 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16828 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16829 Invalid = true;
16830 }
16831
16832 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16833 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16834 Invalid = true;
16835 }
16836
16837 if (!Invalid && !ExDeclType->isDependentType() &&
16838 RequireNonAbstractType(Loc, ExDeclType,
16839 diag::err_abstract_type_in_decl,
16841 Invalid = true;
16842
16843 // Only the non-fragile NeXT runtime currently supports C++ catches
16844 // of ObjC types, and no runtime supports catching ObjC types by value.
16845 if (!Invalid && getLangOpts().ObjC) {
16846 QualType T = ExDeclType;
16847 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16848 T = RT->getPointeeType();
16849
16850 if (T->isObjCObjectType()) {
16851 Diag(Loc, diag::err_objc_object_catch);
16852 Invalid = true;
16853 } else if (T->isObjCObjectPointerType()) {
16854 // FIXME: should this be a test for macosx-fragile specifically?
16856 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16857 }
16858 }
16859
16860 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16861 ExDeclType, TInfo, SC_None);
16862 ExDecl->setExceptionVariable(true);
16863
16864 // In ARC, infer 'retaining' for variables of retainable type.
16865 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
16866 Invalid = true;
16867
16868 if (!Invalid && !ExDeclType->isDependentType()) {
16869 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16870 // Insulate this from anything else we might currently be parsing.
16873
16874 // C++ [except.handle]p16:
16875 // The object declared in an exception-declaration or, if the
16876 // exception-declaration does not specify a name, a temporary (12.2) is
16877 // copy-initialized (8.5) from the exception object. [...]
16878 // The object is destroyed when the handler exits, after the destruction
16879 // of any automatic objects initialized within the handler.
16880 //
16881 // We just pretend to initialize the object with itself, then make sure
16882 // it can be destroyed later.
16883 QualType initType = Context.getExceptionObjectType(ExDeclType);
16884
16885 InitializedEntity entity =
16887 InitializationKind initKind =
16889
16890 Expr *opaqueValue =
16891 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16892 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16893 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16894 if (result.isInvalid())
16895 Invalid = true;
16896 else {
16897 // If the constructor used was non-trivial, set this as the
16898 // "initializer".
16899 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16900 if (!construct->getConstructor()->isTrivial()) {
16901 Expr *init = MaybeCreateExprWithCleanups(construct);
16902 ExDecl->setInit(init);
16903 }
16904
16905 // And make sure it's destructable.
16907 }
16908 }
16909 }
16910
16911 if (Invalid)
16912 ExDecl->setInvalidDecl();
16913
16914 return ExDecl;
16915}
16916
16919 bool Invalid = D.isInvalidType();
16920
16921 // Check for unexpanded parameter packs.
16922 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16925 D.getIdentifierLoc());
16926 Invalid = true;
16927 }
16928
16929 const IdentifierInfo *II = D.getIdentifier();
16930 if (NamedDecl *PrevDecl =
16931 LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
16932 RedeclarationKind::ForVisibleRedeclaration)) {
16933 // The scope should be freshly made just for us. There is just no way
16934 // it contains any previous declaration, except for function parameters in
16935 // a function-try-block's catch statement.
16936 assert(!S->isDeclScope(PrevDecl));
16937 if (isDeclInScope(PrevDecl, CurContext, S)) {
16938 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16939 << D.getIdentifier();
16940 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16941 Invalid = true;
16942 } else if (PrevDecl->isTemplateParameter())
16943 // Maybe we will complain about the shadowed template parameter.
16944 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16945 }
16946
16947 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16948 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16949 << D.getCXXScopeSpec().getRange();
16950 Invalid = true;
16951 }
16952
16954 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16955 if (Invalid)
16956 ExDecl->setInvalidDecl();
16957
16958 // Add the exception declaration into this scope.
16959 if (II)
16960 PushOnScopeChains(ExDecl, S);
16961 else
16962 CurContext->addDecl(ExDecl);
16963
16964 ProcessDeclAttributes(S, ExDecl, D);
16965 return ExDecl;
16966}
16967
16969 Expr *AssertExpr,
16970 Expr *AssertMessageExpr,
16971 SourceLocation RParenLoc) {
16973 return nullptr;
16974
16975 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16976 AssertMessageExpr, RParenLoc, false);
16977}
16978
16979static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
16980 switch (BTK) {
16981 case BuiltinType::Char_S:
16982 case BuiltinType::Char_U:
16983 break;
16984 case BuiltinType::Char8:
16985 OS << "u8";
16986 break;
16987 case BuiltinType::Char16:
16988 OS << 'u';
16989 break;
16990 case BuiltinType::Char32:
16991 OS << 'U';
16992 break;
16993 case BuiltinType::WChar_S:
16994 case BuiltinType::WChar_U:
16995 OS << 'L';
16996 break;
16997 default:
16998 llvm_unreachable("Non-character type");
16999 }
17000}
17001
17002/// Convert character's value, interpreted as a code unit, to a string.
17003/// The value needs to be zero-extended to 32-bits.
17004/// FIXME: This assumes Unicode literal encodings
17005static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17006 unsigned TyWidth,
17007 SmallVectorImpl<char> &Str) {
17008 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17009 char *Ptr = Arr;
17010 BuiltinType::Kind K = BTy->getKind();
17011 llvm::raw_svector_ostream OS(Str);
17012
17013 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17014 // other types.
17015 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17016 K == BuiltinType::Char8 || Value <= 0x7F) {
17017 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17018 if (!Escaped.empty())
17019 EscapeStringForDiagnostic(Escaped, Str);
17020 else
17021 OS << static_cast<char>(Value);
17022 return;
17023 }
17024
17025 switch (K) {
17026 case BuiltinType::Char16:
17027 case BuiltinType::Char32:
17028 case BuiltinType::WChar_S:
17029 case BuiltinType::WChar_U: {
17030 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17031 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17032 else
17033 OS << "\\x"
17034 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17035 break;
17036 }
17037 default:
17038 llvm_unreachable("Non-character type is passed");
17039 }
17040}
17041
17042/// Convert \V to a string we can present to the user in a diagnostic
17043/// \T is the type of the expression that has been evaluated into \V
17047 if (!V.hasValue())
17048 return false;
17049
17050 switch (V.getKind()) {
17052 if (T->isBooleanType()) {
17053 // Bools are reduced to ints during evaluation, but for
17054 // diagnostic purposes we want to print them as
17055 // true or false.
17056 int64_t BoolValue = V.getInt().getExtValue();
17057 assert((BoolValue == 0 || BoolValue == 1) &&
17058 "Bool type, but value is not 0 or 1");
17059 llvm::raw_svector_ostream OS(Str);
17060 OS << (BoolValue ? "true" : "false");
17061 } else {
17062 llvm::raw_svector_ostream OS(Str);
17063 // Same is true for chars.
17064 // We want to print the character representation for textual types
17065 const auto *BTy = T->getAs<BuiltinType>();
17066 if (BTy) {
17067 switch (BTy->getKind()) {
17068 case BuiltinType::Char_S:
17069 case BuiltinType::Char_U:
17070 case BuiltinType::Char8:
17071 case BuiltinType::Char16:
17072 case BuiltinType::Char32:
17073 case BuiltinType::WChar_S:
17074 case BuiltinType::WChar_U: {
17075 unsigned TyWidth = Context.getIntWidth(T);
17076 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17077 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17078 WriteCharTypePrefix(BTy->getKind(), OS);
17079 OS << '\'';
17080 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17081 OS << "' (0x"
17082 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17083 /*Upper=*/true)
17084 << ", " << V.getInt() << ')';
17085 return true;
17086 }
17087 default:
17088 break;
17089 }
17090 }
17091 V.getInt().toString(Str);
17092 }
17093
17094 break;
17095
17097 V.getFloat().toString(Str);
17098 break;
17099
17101 if (V.isNullPointer()) {
17102 llvm::raw_svector_ostream OS(Str);
17103 OS << "nullptr";
17104 } else
17105 return false;
17106 break;
17107
17109 llvm::raw_svector_ostream OS(Str);
17110 OS << '(';
17111 V.getComplexFloatReal().toString(Str);
17112 OS << " + ";
17113 V.getComplexFloatImag().toString(Str);
17114 OS << "i)";
17115 } break;
17116
17118 llvm::raw_svector_ostream OS(Str);
17119 OS << '(';
17120 V.getComplexIntReal().toString(Str);
17121 OS << " + ";
17122 V.getComplexIntImag().toString(Str);
17123 OS << "i)";
17124 } break;
17125
17126 default:
17127 return false;
17128 }
17129
17130 return true;
17131}
17132
17133/// Some Expression types are not useful to print notes about,
17134/// e.g. literals and values that have already been expanded
17135/// before such as int-valued template parameters.
17136static bool UsefulToPrintExpr(const Expr *E) {
17137 E = E->IgnoreParenImpCasts();
17138 // Literals are pretty easy for humans to understand.
17141 return false;
17142
17143 // These have been substituted from template parameters
17144 // and appear as literals in the static assert error.
17145 if (isa<SubstNonTypeTemplateParmExpr>(E))
17146 return false;
17147
17148 // -5 is also simple to understand.
17149 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17150 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17151
17152 // Only print nested arithmetic operators.
17153 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17154 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17155 BO->isBitwiseOp());
17156
17157 return true;
17158}
17159
17161 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17162 Op && Op->getOpcode() != BO_LOr) {
17163 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17164 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17165
17166 // Ignore comparisons of boolean expressions with a boolean literal.
17167 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17168 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17169 return;
17170
17171 // Don't print obvious expressions.
17172 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17173 return;
17174
17175 struct {
17176 const clang::Expr *Cond;
17178 SmallString<12> ValueString;
17179 bool Print;
17180 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17181 {RHS, Expr::EvalResult(), {}, false}};
17182 for (unsigned I = 0; I < 2; I++) {
17183 const Expr *Side = DiagSide[I].Cond;
17184
17185 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17186
17187 DiagSide[I].Print =
17188 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17189 DiagSide[I].ValueString, Context);
17190 }
17191 if (DiagSide[0].Print && DiagSide[1].Print) {
17192 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17193 << DiagSide[0].ValueString << Op->getOpcodeStr()
17194 << DiagSide[1].ValueString << Op->getSourceRange();
17195 }
17196 }
17197}
17198
17200 std::string &Result,
17201 ASTContext &Ctx,
17202 bool ErrorOnInvalidMessage) {
17203 assert(Message);
17204 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17205 "can't evaluate a dependant static assert message");
17206
17207 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17208 assert(SL->isUnevaluated() && "expected an unevaluated string");
17209 Result.assign(SL->getString().begin(), SL->getString().end());
17210 return true;
17211 }
17212
17213 SourceLocation Loc = Message->getBeginLoc();
17214 QualType T = Message->getType().getNonReferenceType();
17215 auto *RD = T->getAsCXXRecordDecl();
17216 if (!RD) {
17217 Diag(Loc, diag::err_static_assert_invalid_message);
17218 return false;
17219 }
17220
17221 auto FindMember = [&](StringRef Member, bool &Empty,
17222 bool Diag = false) -> std::optional<LookupResult> {
17224 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17225 LookupQualifiedName(MemberLookup, RD);
17226 Empty = MemberLookup.empty();
17227 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17229 if (MemberLookup.empty())
17230 return std::nullopt;
17231 return std::move(MemberLookup);
17232 };
17233
17234 bool SizeNotFound, DataNotFound;
17235 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17236 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17237 if (SizeNotFound || DataNotFound) {
17238 Diag(Loc, diag::err_static_assert_missing_member_function)
17239 << ((SizeNotFound && DataNotFound) ? 2
17240 : SizeNotFound ? 0
17241 : 1);
17242 return false;
17243 }
17244
17245 if (!SizeMember || !DataMember) {
17246 if (!SizeMember)
17247 FindMember("size", SizeNotFound, /*Diag=*/true);
17248 if (!DataMember)
17249 FindMember("data", DataNotFound, /*Diag=*/true);
17250 return false;
17251 }
17252
17253 auto BuildExpr = [&](LookupResult &LR) {
17255 Message, Message->getType(), Message->getBeginLoc(), false,
17256 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17257 if (Res.isInvalid())
17258 return ExprError();
17259 Res = BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr, false, true);
17260 if (Res.isInvalid())
17261 return ExprError();
17262 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17263 return ExprError();
17265 };
17266
17267 ExprResult SizeE = BuildExpr(*SizeMember);
17268 ExprResult DataE = BuildExpr(*DataMember);
17269
17270 QualType SizeT = Context.getSizeType();
17271 QualType ConstCharPtr =
17273
17274 ExprResult EvaluatedSize =
17275 SizeE.isInvalid() ? ExprError()
17277 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17278 if (EvaluatedSize.isInvalid()) {
17279 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17280 return false;
17281 }
17282
17283 ExprResult EvaluatedData =
17284 DataE.isInvalid()
17285 ? ExprError()
17286 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17288 if (EvaluatedData.isInvalid()) {
17289 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17290 return false;
17291 }
17292
17293 if (!ErrorOnInvalidMessage &&
17294 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17295 return true;
17296
17297 Expr::EvalResult Status;
17299 Status.Diag = &Notes;
17300 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17301 EvaluatedData.get(), Ctx, Status) ||
17302 !Notes.empty()) {
17303 Diag(Message->getBeginLoc(),
17304 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17305 : diag::warn_static_assert_message_constexpr);
17306 for (const auto &Note : Notes)
17307 Diag(Note.first, Note.second);
17308 return !ErrorOnInvalidMessage;
17309 }
17310 return true;
17311}
17312
17314 Expr *AssertExpr, Expr *AssertMessage,
17315 SourceLocation RParenLoc,
17316 bool Failed) {
17317 assert(AssertExpr != nullptr && "Expected non-null condition");
17318 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17319 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17320 !AssertMessage->isValueDependent())) &&
17321 !Failed) {
17322 // In a static_assert-declaration, the constant-expression shall be a
17323 // constant expression that can be contextually converted to bool.
17324 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17325 if (Converted.isInvalid())
17326 Failed = true;
17327
17328 ExprResult FullAssertExpr =
17329 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17330 /*DiscardedValue*/ false,
17331 /*IsConstexpr*/ true);
17332 if (FullAssertExpr.isInvalid())
17333 Failed = true;
17334 else
17335 AssertExpr = FullAssertExpr.get();
17336
17337 llvm::APSInt Cond;
17338 Expr *BaseExpr = AssertExpr;
17339 AllowFoldKind FoldKind = NoFold;
17340
17341 if (!getLangOpts().CPlusPlus) {
17342 // In C mode, allow folding as an extension for better compatibility with
17343 // C++ in terms of expressions like static_assert("test") or
17344 // static_assert(nullptr).
17345 FoldKind = AllowFold;
17346 }
17347
17348 if (!Failed && VerifyIntegerConstantExpression(
17349 BaseExpr, &Cond,
17350 diag::err_static_assert_expression_is_not_constant,
17351 FoldKind).isInvalid())
17352 Failed = true;
17353
17354 // If the static_assert passes, only verify that
17355 // the message is grammatically valid without evaluating it.
17356 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17357 std::string Str;
17358 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17359 /*ErrorOnInvalidMessage=*/false);
17360 }
17361
17362 // CWG2518
17363 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17364 // template definition, the declaration has no effect.
17365 bool InTemplateDefinition =
17366 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17367
17368 if (!Failed && !Cond && !InTemplateDefinition) {
17369 SmallString<256> MsgBuffer;
17370 llvm::raw_svector_ostream Msg(MsgBuffer);
17371 bool HasMessage = AssertMessage;
17372 if (AssertMessage) {
17373 std::string Str;
17374 HasMessage =
17376 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17377 !Str.empty();
17378 Msg << Str;
17379 }
17380 Expr *InnerCond = nullptr;
17381 std::string InnerCondDescription;
17382 std::tie(InnerCond, InnerCondDescription) =
17383 findFailedBooleanCondition(Converted.get());
17384 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17385 // Drill down into concept specialization expressions to see why they
17386 // weren't satisfied.
17387 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17388 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17389 ConstraintSatisfaction Satisfaction;
17390 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17391 DiagnoseUnsatisfiedConstraint(Satisfaction);
17392 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17393 && !isa<IntegerLiteral>(InnerCond)) {
17394 Diag(InnerCond->getBeginLoc(),
17395 diag::err_static_assert_requirement_failed)
17396 << InnerCondDescription << !HasMessage << Msg.str()
17397 << InnerCond->getSourceRange();
17398 DiagnoseStaticAssertDetails(InnerCond);
17399 } else {
17400 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17401 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17403 }
17404 Failed = true;
17405 }
17406 } else {
17407 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17408 /*DiscardedValue*/false,
17409 /*IsConstexpr*/true);
17410 if (FullAssertExpr.isInvalid())
17411 Failed = true;
17412 else
17413 AssertExpr = FullAssertExpr.get();
17414 }
17415
17417 AssertExpr, AssertMessage, RParenLoc,
17418 Failed);
17419
17421 return Decl;
17422}
17423
17425 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17426 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17427 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17428 MultiTemplateParamsArg TempParamLists) {
17430
17431 bool IsMemberSpecialization = false;
17432 bool Invalid = false;
17433
17434 if (TemplateParameterList *TemplateParams =
17436 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17437 IsMemberSpecialization, Invalid)) {
17438 if (TemplateParams->size() > 0) {
17439 // This is a declaration of a class template.
17440 if (Invalid)
17441 return true;
17442
17443 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17444 Name, NameLoc, Attr, TemplateParams, AS_public,
17445 /*ModulePrivateLoc=*/SourceLocation(),
17446 FriendLoc, TempParamLists.size() - 1,
17447 TempParamLists.data())
17448 .get();
17449 } else {
17450 // The "template<>" header is extraneous.
17451 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17452 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17453 IsMemberSpecialization = true;
17454 }
17455 }
17456
17457 if (Invalid) return true;
17458
17459 bool isAllExplicitSpecializations = true;
17460 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17461 if (TempParamLists[I]->size()) {
17462 isAllExplicitSpecializations = false;
17463 break;
17464 }
17465 }
17466
17467 // FIXME: don't ignore attributes.
17468
17469 // If it's explicit specializations all the way down, just forget
17470 // about the template header and build an appropriate non-templated
17471 // friend. TODO: for source fidelity, remember the headers.
17473 if (isAllExplicitSpecializations) {
17474 if (SS.isEmpty()) {
17475 bool Owned = false;
17476 bool IsDependent = false;
17477 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17478 Attr, AS_public,
17479 /*ModulePrivateLoc=*/SourceLocation(),
17480 MultiTemplateParamsArg(), Owned, IsDependent,
17481 /*ScopedEnumKWLoc=*/SourceLocation(),
17482 /*ScopedEnumUsesClassTag=*/false,
17483 /*UnderlyingType=*/TypeResult(),
17484 /*IsTypeSpecifier=*/false,
17485 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17486 }
17487
17488 ElaboratedTypeKeyword Keyword
17490 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17491 *Name, NameLoc);
17492 if (T.isNull())
17493 return true;
17494
17496 if (isa<DependentNameType>(T)) {
17499 TL.setElaboratedKeywordLoc(TagLoc);
17500 TL.setQualifierLoc(QualifierLoc);
17501 TL.setNameLoc(NameLoc);
17502 } else {
17504 TL.setElaboratedKeywordLoc(TagLoc);
17505 TL.setQualifierLoc(QualifierLoc);
17506 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17507 }
17508
17510 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17511 EllipsisLoc, TempParamLists);
17512 Friend->setAccess(AS_public);
17514 return Friend;
17515 }
17516
17517 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17518
17519 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
17520 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
17521 // shall not have been introduced by the template-declaration.
17523 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
17524 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
17525 for (UnexpandedParameterPack &U : Unexpanded) {
17526 if (getDepthAndIndex(U).first >= FriendDeclDepth) {
17527 auto *ND = U.first.dyn_cast<NamedDecl *>();
17528 if (!ND)
17529 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
17530 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
17531 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
17532 return true;
17533 }
17534 }
17535
17536 // Handle the case of a templated-scope friend class. e.g.
17537 // template <class T> class A<T>::B;
17538 // FIXME: we don't support these right now.
17539 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17540 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17545 TL.setElaboratedKeywordLoc(TagLoc);
17547 TL.setNameLoc(NameLoc);
17548
17550 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17551 EllipsisLoc, TempParamLists);
17552 Friend->setAccess(AS_public);
17553 Friend->setUnsupportedFriend(true);
17555 return Friend;
17556}
17557
17559 MultiTemplateParamsArg TempParams,
17560 SourceLocation EllipsisLoc) {
17562 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17563
17564 assert(DS.isFriendSpecified());
17566
17567 // C++ [class.friend]p3:
17568 // A friend declaration that does not declare a function shall have one of
17569 // the following forms:
17570 // friend elaborated-type-specifier ;
17571 // friend simple-type-specifier ;
17572 // friend typename-specifier ;
17573 //
17574 // If the friend keyword isn't first, or if the declarations has any type
17575 // qualifiers, then the declaration doesn't have that form.
17577 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17578 if (DS.getTypeQualifiers()) {
17580 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17582 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17584 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17586 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17588 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17589 }
17590
17591 // Try to convert the decl specifier to a type. This works for
17592 // friend templates because ActOnTag never produces a ClassTemplateDecl
17593 // for a TagUseKind::Friend.
17594 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17596 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17597 QualType T = TSI->getType();
17598 if (TheDeclarator.isInvalidType())
17599 return nullptr;
17600
17601 // If '...' is present, the type must contain an unexpanded parameter
17602 // pack, and vice versa.
17603 bool Invalid = false;
17604 if (EllipsisLoc.isInvalid() &&
17606 return nullptr;
17607 if (EllipsisLoc.isValid() &&
17609 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
17610 << TSI->getTypeLoc().getSourceRange();
17611 Invalid = true;
17612 }
17613
17614 if (!T->isElaboratedTypeSpecifier()) {
17615 if (TempParams.size()) {
17616 // C++23 [dcl.pre]p5:
17617 // In a simple-declaration, the optional init-declarator-list can be
17618 // omitted only when declaring a class or enumeration, that is, when
17619 // the decl-specifier-seq contains either a class-specifier, an
17620 // elaborated-type-specifier with a class-key, or an enum-specifier.
17621 //
17622 // The declaration of a template-declaration or explicit-specialization
17623 // is never a member-declaration, so this must be a simple-declaration
17624 // with no init-declarator-list. Therefore, this is ill-formed.
17625 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17626 return nullptr;
17627 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17628 SmallString<16> InsertionText(" ");
17629 InsertionText += RD->getKindName();
17630
17632 ? diag::warn_cxx98_compat_unelaborated_friend_type
17633 : diag::ext_unelaborated_friend_type)
17634 << (unsigned)RD->getTagKind() << T
17636 InsertionText);
17637 } else {
17638 Diag(FriendLoc, getLangOpts().CPlusPlus11
17639 ? diag::warn_cxx98_compat_nonclass_type_friend
17640 : diag::ext_nonclass_type_friend)
17641 << T << DS.getSourceRange();
17642 }
17643 }
17644
17645 // C++98 [class.friend]p1: A friend of a class is a function
17646 // or class that is not a member of the class . . .
17647 // This is fixed in DR77, which just barely didn't make the C++03
17648 // deadline. It's also a very silly restriction that seriously
17649 // affects inner classes and which nobody else seems to implement;
17650 // thus we never diagnose it, not even in -pedantic.
17651 //
17652 // But note that we could warn about it: it's always useless to
17653 // friend one of your own members (it's not, however, worthless to
17654 // friend a member of an arbitrary specialization of your template).
17655
17656 Decl *D;
17657 if (!TempParams.empty())
17658 // TODO: Support variadic friend template decls?
17659 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17660 FriendLoc);
17661 else
17663 TSI, FriendLoc, EllipsisLoc);
17664
17665 if (!D)
17666 return nullptr;
17667
17670
17671 if (Invalid)
17672 D->setInvalidDecl();
17673
17674 return D;
17675}
17676
17678 MultiTemplateParamsArg TemplateParams) {
17679 const DeclSpec &DS = D.getDeclSpec();
17680
17681 assert(DS.isFriendSpecified());
17683
17684 SourceLocation Loc = D.getIdentifierLoc();
17686
17687 // C++ [class.friend]p1
17688 // A friend of a class is a function or class....
17689 // Note that this sees through typedefs, which is intended.
17690 // It *doesn't* see through dependent types, which is correct
17691 // according to [temp.arg.type]p3:
17692 // If a declaration acquires a function type through a
17693 // type dependent on a template-parameter and this causes
17694 // a declaration that does not use the syntactic form of a
17695 // function declarator to have a function type, the program
17696 // is ill-formed.
17697 if (!TInfo->getType()->isFunctionType()) {
17698 Diag(Loc, diag::err_unexpected_friend);
17699
17700 // It might be worthwhile to try to recover by creating an
17701 // appropriate declaration.
17702 return nullptr;
17703 }
17704
17705 // C++ [namespace.memdef]p3
17706 // - If a friend declaration in a non-local class first declares a
17707 // class or function, the friend class or function is a member
17708 // of the innermost enclosing namespace.
17709 // - The name of the friend is not found by simple name lookup
17710 // until a matching declaration is provided in that namespace
17711 // scope (either before or after the class declaration granting
17712 // friendship).
17713 // - If a friend function is called, its name may be found by the
17714 // name lookup that considers functions from namespaces and
17715 // classes associated with the types of the function arguments.
17716 // - When looking for a prior declaration of a class or a function
17717 // declared as a friend, scopes outside the innermost enclosing
17718 // namespace scope are not considered.
17719
17720 CXXScopeSpec &SS = D.getCXXScopeSpec();
17722 assert(NameInfo.getName());
17723
17724 // Check for unexpanded parameter packs.
17728 return nullptr;
17729
17730 // The context we found the declaration in, or in which we should
17731 // create the declaration.
17732 DeclContext *DC;
17733 Scope *DCScope = S;
17734 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17735 RedeclarationKind::ForExternalRedeclaration);
17736
17737 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17738
17739 // There are five cases here.
17740 // - There's no scope specifier and we're in a local class. Only look
17741 // for functions declared in the immediately-enclosing block scope.
17742 // We recover from invalid scope qualifiers as if they just weren't there.
17743 FunctionDecl *FunctionContainingLocalClass = nullptr;
17744 if ((SS.isInvalid() || !SS.isSet()) &&
17745 (FunctionContainingLocalClass =
17746 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17747 // C++11 [class.friend]p11:
17748 // If a friend declaration appears in a local class and the name
17749 // specified is an unqualified name, a prior declaration is
17750 // looked up without considering scopes that are outside the
17751 // innermost enclosing non-class scope. For a friend function
17752 // declaration, if there is no prior declaration, the program is
17753 // ill-formed.
17754
17755 // Find the innermost enclosing non-class scope. This is the block
17756 // scope containing the local class definition (or for a nested class,
17757 // the outer local class).
17758 DCScope = S->getFnParent();
17759
17760 // Look up the function name in the scope.
17762 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17763
17764 if (!Previous.empty()) {
17765 // All possible previous declarations must have the same context:
17766 // either they were declared at block scope or they are members of
17767 // one of the enclosing local classes.
17768 DC = Previous.getRepresentativeDecl()->getDeclContext();
17769 } else {
17770 // This is ill-formed, but provide the context that we would have
17771 // declared the function in, if we were permitted to, for error recovery.
17772 DC = FunctionContainingLocalClass;
17773 }
17775
17776 // - There's no scope specifier, in which case we just go to the
17777 // appropriate scope and look for a function or function template
17778 // there as appropriate.
17779 } else if (SS.isInvalid() || !SS.isSet()) {
17780 // C++11 [namespace.memdef]p3:
17781 // If the name in a friend declaration is neither qualified nor
17782 // a template-id and the declaration is a function or an
17783 // elaborated-type-specifier, the lookup to determine whether
17784 // the entity has been previously declared shall not consider
17785 // any scopes outside the innermost enclosing namespace.
17786
17787 // Find the appropriate context according to the above.
17788 DC = CurContext;
17789
17790 // Skip class contexts. If someone can cite chapter and verse
17791 // for this behavior, that would be nice --- it's what GCC and
17792 // EDG do, and it seems like a reasonable intent, but the spec
17793 // really only says that checks for unqualified existing
17794 // declarations should stop at the nearest enclosing namespace,
17795 // not that they should only consider the nearest enclosing
17796 // namespace.
17797 while (DC->isRecord())
17798 DC = DC->getParent();
17799
17800 DeclContext *LookupDC = DC->getNonTransparentContext();
17801 while (true) {
17802 LookupQualifiedName(Previous, LookupDC);
17803
17804 if (!Previous.empty()) {
17805 DC = LookupDC;
17806 break;
17807 }
17808
17809 if (isTemplateId) {
17810 if (isa<TranslationUnitDecl>(LookupDC)) break;
17811 } else {
17812 if (LookupDC->isFileContext()) break;
17813 }
17814 LookupDC = LookupDC->getParent();
17815 }
17816
17817 DCScope = getScopeForDeclContext(S, DC);
17818
17819 // - There's a non-dependent scope specifier, in which case we
17820 // compute it and do a previous lookup there for a function
17821 // or function template.
17822 } else if (!SS.getScopeRep()->isDependent()) {
17823 DC = computeDeclContext(SS);
17824 if (!DC) return nullptr;
17825
17826 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17827
17829
17830 // C++ [class.friend]p1: A friend of a class is a function or
17831 // class that is not a member of the class . . .
17832 if (DC->Equals(CurContext))
17835 diag::warn_cxx98_compat_friend_is_member :
17836 diag::err_friend_is_member);
17837
17838 // - There's a scope specifier that does not match any template
17839 // parameter lists, in which case we use some arbitrary context,
17840 // create a method or method template, and wait for instantiation.
17841 // - There's a scope specifier that does match some template
17842 // parameter lists, which we don't handle right now.
17843 } else {
17844 DC = CurContext;
17845 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17846 }
17847
17848 if (!DC->isRecord()) {
17849 int DiagArg = -1;
17850 switch (D.getName().getKind()) {
17853 DiagArg = 0;
17854 break;
17856 DiagArg = 1;
17857 break;
17859 DiagArg = 2;
17860 break;
17862 DiagArg = 3;
17863 break;
17869 break;
17870 }
17871 // This implies that it has to be an operator or function.
17872 if (DiagArg >= 0) {
17873 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17874 return nullptr;
17875 }
17876 }
17877
17878 // FIXME: This is an egregious hack to cope with cases where the scope stack
17879 // does not contain the declaration context, i.e., in an out-of-line
17880 // definition of a class.
17881 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17882 if (!DCScope) {
17883 FakeDCScope.setEntity(DC);
17884 DCScope = &FakeDCScope;
17885 }
17886
17887 bool AddToScope = true;
17888 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17889 TemplateParams, AddToScope);
17890 if (!ND) return nullptr;
17891
17892 assert(ND->getLexicalDeclContext() == CurContext);
17893
17894 // If we performed typo correction, we might have added a scope specifier
17895 // and changed the decl context.
17896 DC = ND->getDeclContext();
17897
17898 // Add the function declaration to the appropriate lookup tables,
17899 // adjusting the redeclarations list as necessary. We don't
17900 // want to do this yet if the friending class is dependent.
17901 //
17902 // Also update the scope-based lookup if the target context's
17903 // lookup context is in lexical scope.
17905 DC = DC->getRedeclContext();
17907 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17908 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17909 }
17910
17912 D.getIdentifierLoc(), ND,
17913 DS.getFriendSpecLoc());
17914 FrD->setAccess(AS_public);
17915 CurContext->addDecl(FrD);
17916
17917 if (ND->isInvalidDecl()) {
17918 FrD->setInvalidDecl();
17919 } else {
17920 if (DC->isRecord()) CheckFriendAccess(ND);
17921
17922 FunctionDecl *FD;
17923 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17924 FD = FTD->getTemplatedDecl();
17925 else
17926 FD = cast<FunctionDecl>(ND);
17927
17928 // C++ [class.friend]p6:
17929 // A function may be defined in a friend declaration of a class if and
17930 // only if the class is a non-local class, and the function name is
17931 // unqualified.
17932 if (D.isFunctionDefinition()) {
17933 // Qualified friend function definition.
17934 if (SS.isNotEmpty()) {
17935 // FIXME: We should only do this if the scope specifier names the
17936 // innermost enclosing namespace; otherwise the fixit changes the
17937 // meaning of the code.
17939 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17940
17941 DB << SS.getScopeRep();
17942 if (DC->isFileContext())
17944
17945 // Friend function defined in a local class.
17946 } else if (FunctionContainingLocalClass) {
17947 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17948
17949 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
17950 // a template-id, the function name is not unqualified because these is
17951 // no name. While the wording requires some reading in-between the
17952 // lines, GCC, MSVC, and EDG all consider a friend function
17953 // specialization definitions // to be de facto explicit specialization
17954 // and diagnose them as such.
17955 } else if (isTemplateId) {
17956 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
17957 }
17958 }
17959
17960 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17961 // default argument expression, that declaration shall be a definition
17962 // and shall be the only declaration of the function or function
17963 // template in the translation unit.
17965 // We can't look at FD->getPreviousDecl() because it may not have been set
17966 // if we're in a dependent context. If the function is known to be a
17967 // redeclaration, we will have narrowed Previous down to the right decl.
17968 if (D.isRedeclaration()) {
17969 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17970 Diag(Previous.getRepresentativeDecl()->getLocation(),
17971 diag::note_previous_declaration);
17972 } else if (!D.isFunctionDefinition())
17973 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17974 }
17975
17976 // Mark templated-scope function declarations as unsupported.
17977 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17978 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17979 << SS.getScopeRep() << SS.getRange()
17980 << cast<CXXRecordDecl>(CurContext);
17981 FrD->setUnsupportedFriend(true);
17982 }
17983 }
17984
17986
17987 return ND;
17988}
17989
17991 StringLiteral *Message) {
17993
17994 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17995 if (!Fn) {
17996 Diag(DelLoc, diag::err_deleted_non_function);
17997 return;
17998 }
17999
18000 // Deleted function does not have a body.
18001 Fn->setWillHaveBody(false);
18002
18003 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18004 // Don't consider the implicit declaration we generate for explicit
18005 // specializations. FIXME: Do not generate these implicit declarations.
18006 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18007 Prev->getPreviousDecl()) &&
18008 !Prev->isDefined()) {
18009 Diag(DelLoc, diag::err_deleted_decl_not_first);
18010 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18011 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18012 : diag::note_previous_declaration);
18013 // We can't recover from this; the declaration might have already
18014 // been used.
18015 Fn->setInvalidDecl();
18016 return;
18017 }
18018
18019 // To maintain the invariant that functions are only deleted on their first
18020 // declaration, mark the implicitly-instantiated declaration of the
18021 // explicitly-specialized function as deleted instead of marking the
18022 // instantiated redeclaration.
18023 Fn = Fn->getCanonicalDecl();
18024 }
18025
18026 // dllimport/dllexport cannot be deleted.
18027 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18028 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18029 Fn->setInvalidDecl();
18030 }
18031
18032 // C++11 [basic.start.main]p3:
18033 // A program that defines main as deleted [...] is ill-formed.
18034 if (Fn->isMain())
18035 Diag(DelLoc, diag::err_deleted_main);
18036
18037 // C++11 [dcl.fct.def.delete]p4:
18038 // A deleted function is implicitly inline.
18039 Fn->setImplicitlyInline();
18040 Fn->setDeletedAsWritten(true, Message);
18041}
18042
18044 if (!Dcl || Dcl->isInvalidDecl())
18045 return;
18046
18047 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18048 if (!FD) {
18049 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18050 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18051 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18052 return;
18053 }
18054 }
18055
18056 Diag(DefaultLoc, diag::err_default_special_members)
18057 << getLangOpts().CPlusPlus20;
18058 return;
18059 }
18060
18061 // Reject if this can't possibly be a defaultable function.
18063 if (!DefKind &&
18064 // A dependent function that doesn't locally look defaultable can
18065 // still instantiate to a defaultable function if it's a constructor
18066 // or assignment operator.
18067 (!FD->isDependentContext() ||
18068 (!isa<CXXConstructorDecl>(FD) &&
18069 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18070 Diag(DefaultLoc, diag::err_default_special_members)
18071 << getLangOpts().CPlusPlus20;
18072 return;
18073 }
18074
18075 // Issue compatibility warning. We already warned if the operator is
18076 // 'operator<=>' when parsing the '<=>' token.
18077 if (DefKind.isComparison() &&
18079 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18080 ? diag::warn_cxx17_compat_defaulted_comparison
18081 : diag::ext_defaulted_comparison);
18082 }
18083
18084 FD->setDefaulted();
18085 FD->setExplicitlyDefaulted();
18086 FD->setDefaultLoc(DefaultLoc);
18087
18088 // Defer checking functions that are defaulted in a dependent context.
18089 if (FD->isDependentContext())
18090 return;
18091
18092 // Unset that we will have a body for this function. We might not,
18093 // if it turns out to be trivial, and we don't need this marking now
18094 // that we've marked it as defaulted.
18095 FD->setWillHaveBody(false);
18096
18097 if (DefKind.isComparison()) {
18098 // If this comparison's defaulting occurs within the definition of its
18099 // lexical class context, we have to do the checking when complete.
18100 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18101 if (!RD->isCompleteDefinition())
18102 return;
18103 }
18104
18105 // If this member fn was defaulted on its first declaration, we will have
18106 // already performed the checking in CheckCompletedCXXClass. Such a
18107 // declaration doesn't trigger an implicit definition.
18108 if (isa<CXXMethodDecl>(FD)) {
18109 const FunctionDecl *Primary = FD;
18110 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18111 // Ask the template instantiation pattern that actually had the
18112 // '= default' on it.
18113 Primary = Pattern;
18114 if (Primary->getCanonicalDecl()->isDefaulted())
18115 return;
18116 }
18117
18118 if (DefKind.isComparison()) {
18119 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18120 FD->setInvalidDecl();
18121 else
18122 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18123 } else {
18124 auto *MD = cast<CXXMethodDecl>(FD);
18125
18127 DefaultLoc))
18128 MD->setInvalidDecl();
18129 else
18130 DefineDefaultedFunction(*this, MD, DefaultLoc);
18131 }
18132}
18133
18135 for (Stmt *SubStmt : S->children()) {
18136 if (!SubStmt)
18137 continue;
18138 if (isa<ReturnStmt>(SubStmt))
18139 Self.Diag(SubStmt->getBeginLoc(),
18140 diag::err_return_in_constructor_handler);
18141 if (!isa<Expr>(SubStmt))
18142 SearchForReturnInStmt(Self, SubStmt);
18143 }
18144}
18145
18147 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18148 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18149 SearchForReturnInStmt(*this, Handler);
18150 }
18151}
18152
18154 StringLiteral *DeletedMessage) {
18155 switch (BodyKind) {
18156 case FnBodyKind::Delete:
18157 SetDeclDeleted(D, Loc, DeletedMessage);
18158 break;
18161 break;
18162 case FnBodyKind::Other:
18163 llvm_unreachable(
18164 "Parsed function body should be '= delete;' or '= default;'");
18165 }
18166}
18167
18169 const CXXMethodDecl *Old) {
18170 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18171 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18172
18173 if (OldFT->hasExtParameterInfos()) {
18174 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18175 // A parameter of the overriding method should be annotated with noescape
18176 // if the corresponding parameter of the overridden method is annotated.
18177 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18178 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18179 Diag(New->getParamDecl(I)->getLocation(),
18180 diag::warn_overriding_method_missing_noescape);
18181 Diag(Old->getParamDecl(I)->getLocation(),
18182 diag::note_overridden_marked_noescape);
18183 }
18184 }
18185
18186 // SME attributes must match when overriding a function declaration.
18187 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18188 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18189 << New << New->getType() << Old->getType();
18190 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18191 return true;
18192 }
18193
18194 // Virtual overrides must have the same code_seg.
18195 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18196 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18197 if ((NewCSA || OldCSA) &&
18198 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18199 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18200 Diag(Old->getLocation(), diag::note_previous_declaration);
18201 return true;
18202 }
18203
18204 // Virtual overrides: check for matching effects.
18206 const auto OldFX = Old->getFunctionEffects();
18207 const auto NewFXOrig = New->getFunctionEffects();
18208
18209 if (OldFX != NewFXOrig) {
18210 FunctionEffectSet NewFX(NewFXOrig);
18211 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18213 for (const auto &Diff : Diffs) {
18214 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18216 break;
18218 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18219 << Diff.effectName();
18220 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18221 << Old->getReturnTypeSourceRange();
18222 break;
18224 NewFX.insert(Diff.Old.value(), Errs);
18225 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18226 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18228 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18229 NewFT->getParamTypes(), EPI);
18230 New->setType(ModQT);
18231 break;
18232 }
18233 }
18234 }
18235 if (!Errs.empty())
18237 Old->getLocation());
18238 }
18239 }
18240
18241 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18242
18243 // If the calling conventions match, everything is fine
18244 if (NewCC == OldCC)
18245 return false;
18246
18247 // If the calling conventions mismatch because the new function is static,
18248 // suppress the calling convention mismatch error; the error about static
18249 // function override (err_static_overrides_virtual from
18250 // Sema::CheckFunctionDeclaration) is more clear.
18251 if (New->getStorageClass() == SC_Static)
18252 return false;
18253
18254 Diag(New->getLocation(),
18255 diag::err_conflicting_overriding_cc_attributes)
18256 << New->getDeclName() << New->getType() << Old->getType();
18257 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18258 return true;
18259}
18260
18262 const CXXMethodDecl *Old) {
18263 // CWG2553
18264 // A virtual function shall not be an explicit object member function.
18266 return true;
18267 Diag(New->getParamDecl(0)->getBeginLoc(),
18268 diag::err_explicit_object_parameter_nonmember)
18269 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18270 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18271 New->setInvalidDecl();
18272 return false;
18273}
18274
18276 const CXXMethodDecl *Old) {
18277 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18278 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18279
18280 if (Context.hasSameType(NewTy, OldTy) ||
18281 NewTy->isDependentType() || OldTy->isDependentType())
18282 return false;
18283
18284 // Check if the return types are covariant
18285 QualType NewClassTy, OldClassTy;
18286
18287 /// Both types must be pointers or references to classes.
18288 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18289 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18290 NewClassTy = NewPT->getPointeeType();
18291 OldClassTy = OldPT->getPointeeType();
18292 }
18293 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18294 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18295 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18296 NewClassTy = NewRT->getPointeeType();
18297 OldClassTy = OldRT->getPointeeType();
18298 }
18299 }
18300 }
18301
18302 // The return types aren't either both pointers or references to a class type.
18303 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18304 Diag(New->getLocation(),
18305 diag::err_different_return_type_for_overriding_virtual_function)
18306 << New->getDeclName() << NewTy << OldTy
18307 << New->getReturnTypeSourceRange();
18308 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18309 << Old->getReturnTypeSourceRange();
18310
18311 return true;
18312 }
18313
18314 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18315 // C++14 [class.virtual]p8:
18316 // If the class type in the covariant return type of D::f differs from
18317 // that of B::f, the class type in the return type of D::f shall be
18318 // complete at the point of declaration of D::f or shall be the class
18319 // type D.
18320 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18321 if (!RT->isBeingDefined() &&
18322 RequireCompleteType(New->getLocation(), NewClassTy,
18323 diag::err_covariant_return_incomplete,
18324 New->getDeclName()))
18325 return true;
18326 }
18327
18328 // Check if the new class derives from the old class.
18329 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18330 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18331 << New->getDeclName() << NewTy << OldTy
18332 << New->getReturnTypeSourceRange();
18333 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18334 << Old->getReturnTypeSourceRange();
18335 return true;
18336 }
18337
18338 // Check if we the conversion from derived to base is valid.
18340 NewClassTy, OldClassTy,
18341 diag::err_covariant_return_inaccessible_base,
18342 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18344 New->getDeclName(), nullptr)) {
18345 // FIXME: this note won't trigger for delayed access control
18346 // diagnostics, and it's impossible to get an undelayed error
18347 // here from access control during the original parse because
18348 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18349 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18350 << Old->getReturnTypeSourceRange();
18351 return true;
18352 }
18353 }
18354
18355 // The qualifiers of the return types must be the same.
18356 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18357 Diag(New->getLocation(),
18358 diag::err_covariant_return_type_different_qualifications)
18359 << New->getDeclName() << NewTy << OldTy
18360 << New->getReturnTypeSourceRange();
18361 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18362 << Old->getReturnTypeSourceRange();
18363 return true;
18364 }
18365
18366
18367 // The new class type must have the same or less qualifiers as the old type.
18368 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
18369 Diag(New->getLocation(),
18370 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18371 << New->getDeclName() << NewTy << OldTy
18372 << New->getReturnTypeSourceRange();
18373 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18374 << Old->getReturnTypeSourceRange();
18375 return true;
18376 }
18377
18378 return false;
18379}
18380
18382 SourceLocation EndLoc = InitRange.getEnd();
18383 if (EndLoc.isValid())
18384 Method->setRangeEnd(EndLoc);
18385
18386 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18387 Method->setIsPureVirtual();
18388 return false;
18389 }
18390
18391 if (!Method->isInvalidDecl())
18392 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18393 << Method->getDeclName() << InitRange;
18394 return true;
18395}
18396
18398 if (D->getFriendObjectKind())
18399 Diag(D->getLocation(), diag::err_pure_friend);
18400 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18401 CheckPureMethod(M, ZeroLoc);
18402 else
18403 Diag(D->getLocation(), diag::err_illegal_initializer);
18404}
18405
18406/// Invoked when we are about to parse an initializer for the declaration
18407/// 'Dcl'.
18408///
18409/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18410/// static data member of class X, names should be looked up in the scope of
18411/// class X. If the declaration had a scope specifier, a scope will have
18412/// been created and passed in for this purpose. Otherwise, S will be null.
18414 assert(D && !D->isInvalidDecl());
18415
18416 // We will always have a nested name specifier here, but this declaration
18417 // might not be out of line if the specifier names the current namespace:
18418 // extern int n;
18419 // int ::n = 0;
18420 if (S && D->isOutOfLine())
18422
18425}
18426
18428 assert(D);
18429
18430 if (S && D->isOutOfLine())
18432
18433 if (getLangOpts().CPlusPlus23) {
18434 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18435 // [...]
18436 // - the initializer of a variable that is usable in constant expressions or
18437 // has constant initialization.
18438 if (auto *VD = dyn_cast<VarDecl>(D);
18441 // An expression or conversion is in an 'immediate function context' if it
18442 // is potentially evaluated and either:
18443 // [...]
18444 // - it is a subexpression of a manifestly constant-evaluated expression
18445 // or conversion.
18446 ExprEvalContexts.back().InImmediateFunctionContext = true;
18447 }
18448 }
18449
18450 // Unless the initializer is in an immediate function context (as determined
18451 // above), this will evaluate all contained immediate function calls as
18452 // constant expressions. If the initializer IS an immediate function context,
18453 // the initializer has been determined to be a constant expression, and all
18454 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18455 // it was a constant expression).
18457}
18458
18460 // C++ 6.4p2:
18461 // The declarator shall not specify a function or an array.
18462 // The type-specifier-seq shall not contain typedef and shall not declare a
18463 // new class or enumeration.
18464 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18465 "Parser allowed 'typedef' as storage class of condition decl.");
18466
18467 Decl *Dcl = ActOnDeclarator(S, D);
18468 if (!Dcl)
18469 return true;
18470
18471 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18472 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18473 << D.getSourceRange();
18474 return true;
18475 }
18476
18477 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18478 VD->setCXXCondDecl();
18479
18480 return Dcl;
18481}
18482
18484 if (!ExternalSource)
18485 return;
18486
18488 ExternalSource->ReadUsedVTables(VTables);
18490 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18491 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18492 = VTablesUsed.find(VTables[I].Record);
18493 // Even if a definition wasn't required before, it may be required now.
18494 if (Pos != VTablesUsed.end()) {
18495 if (!Pos->second && VTables[I].DefinitionRequired)
18496 Pos->second = true;
18497 continue;
18498 }
18499
18500 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18501 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18502 }
18503
18504 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18505}
18506
18508 bool DefinitionRequired) {
18509 // Ignore any vtable uses in unevaluated operands or for classes that do
18510 // not have a vtable.
18511 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18513 return;
18514 // Do not mark as used if compiling for the device outside of the target
18515 // region.
18516 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18517 !OpenMP().isInOpenMPDeclareTargetContext() &&
18518 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18519 if (!DefinitionRequired)
18521 return;
18522 }
18523
18524 // Try to insert this class into the map.
18526 Class = Class->getCanonicalDecl();
18527 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18528 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18529 if (!Pos.second) {
18530 // If we already had an entry, check to see if we are promoting this vtable
18531 // to require a definition. If so, we need to reappend to the VTableUses
18532 // list, since we may have already processed the first entry.
18533 if (DefinitionRequired && !Pos.first->second) {
18534 Pos.first->second = true;
18535 } else {
18536 // Otherwise, we can early exit.
18537 return;
18538 }
18539 } else {
18540 // The Microsoft ABI requires that we perform the destructor body
18541 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18542 // the deleting destructor is emitted with the vtable, not with the
18543 // destructor definition as in the Itanium ABI.
18545 CXXDestructorDecl *DD = Class->getDestructor();
18546 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18547 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18548 // If this is an out-of-line declaration, marking it referenced will
18549 // not do anything. Manually call CheckDestructor to look up operator
18550 // delete().
18551 ContextRAII SavedContext(*this, DD);
18552 CheckDestructor(DD);
18553 } else {
18554 MarkFunctionReferenced(Loc, Class->getDestructor());
18555 }
18556 }
18557 }
18558 }
18559
18560 // Local classes need to have their virtual members marked
18561 // immediately. For all other classes, we mark their virtual members
18562 // at the end of the translation unit.
18563 if (Class->isLocalClass())
18564 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18565 else
18566 VTableUses.push_back(std::make_pair(Class, Loc));
18567}
18568
18571 if (VTableUses.empty())
18572 return false;
18573
18574 // Note: The VTableUses vector could grow as a result of marking
18575 // the members of a class as "used", so we check the size each
18576 // time through the loop and prefer indices (which are stable) to
18577 // iterators (which are not).
18578 bool DefinedAnything = false;
18579 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18580 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18581 if (!Class)
18582 continue;
18584 Class->getTemplateSpecializationKind();
18585
18586 SourceLocation Loc = VTableUses[I].second;
18587
18588 bool DefineVTable = true;
18589
18590 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18591 // V-tables for non-template classes with an owning module are always
18592 // uniquely emitted in that module.
18593 if (Class->isInCurrentModuleUnit()) {
18594 DefineVTable = true;
18595 } else if (KeyFunction && !KeyFunction->hasBody()) {
18596 // If this class has a key function, but that key function is
18597 // defined in another translation unit, we don't need to emit the
18598 // vtable even though we're using it.
18599 // The key function is in another translation unit.
18600 DefineVTable = false;
18602 KeyFunction->getTemplateSpecializationKind();
18605 "Instantiations don't have key functions");
18606 (void)TSK;
18607 } else if (!KeyFunction) {
18608 // If we have a class with no key function that is the subject
18609 // of an explicit instantiation declaration, suppress the
18610 // vtable; it will live with the explicit instantiation
18611 // definition.
18612 bool IsExplicitInstantiationDeclaration =
18614 for (auto *R : Class->redecls()) {
18616 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18618 IsExplicitInstantiationDeclaration = true;
18619 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18620 IsExplicitInstantiationDeclaration = false;
18621 break;
18622 }
18623 }
18624
18625 if (IsExplicitInstantiationDeclaration)
18626 DefineVTable = false;
18627 }
18628
18629 // The exception specifications for all virtual members may be needed even
18630 // if we are not providing an authoritative form of the vtable in this TU.
18631 // We may choose to emit it available_externally anyway.
18632 if (!DefineVTable) {
18634 continue;
18635 }
18636
18637 // Mark all of the virtual members of this class as referenced, so
18638 // that we can build a vtable. Then, tell the AST consumer that a
18639 // vtable for this class is required.
18640 DefinedAnything = true;
18642 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18643 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
18645
18646 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18647 // no key function or the key function is inlined. Don't warn in C++ ABIs
18648 // that lack key functions, since the user won't be able to make one.
18650 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18652 const FunctionDecl *KeyFunctionDef = nullptr;
18653 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18654 KeyFunctionDef->isInlined()))
18655 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18656 }
18657 }
18658 VTableUses.clear();
18659
18660 return DefinedAnything;
18661}
18662
18664 const CXXRecordDecl *RD) {
18665 for (const auto *I : RD->methods())
18666 if (I->isVirtual() && !I->isPureVirtual())
18667 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18668}
18669
18671 const CXXRecordDecl *RD,
18672 bool ConstexprOnly) {
18673 // Mark all functions which will appear in RD's vtable as used.
18674 CXXFinalOverriderMap FinalOverriders;
18675 RD->getFinalOverriders(FinalOverriders);
18676 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18677 E = FinalOverriders.end();
18678 I != E; ++I) {
18679 for (OverridingMethods::const_iterator OI = I->second.begin(),
18680 OE = I->second.end();
18681 OI != OE; ++OI) {
18682 assert(OI->second.size() > 0 && "no final overrider");
18683 CXXMethodDecl *Overrider = OI->second.front().Method;
18684
18685 // C++ [basic.def.odr]p2:
18686 // [...] A virtual member function is used if it is not pure. [...]
18687 if (!Overrider->isPureVirtual() &&
18688 (!ConstexprOnly || Overrider->isConstexpr()))
18689 MarkFunctionReferenced(Loc, Overrider);
18690 }
18691 }
18692
18693 // Only classes that have virtual bases need a VTT.
18694 if (RD->getNumVBases() == 0)
18695 return;
18696
18697 for (const auto &I : RD->bases()) {
18698 const auto *Base =
18699 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18700 if (Base->getNumVBases() == 0)
18701 continue;
18703 }
18704}
18705
18706static
18711 Sema &S) {
18712 if (Ctor->isInvalidDecl())
18713 return;
18714
18716
18717 // Target may not be determinable yet, for instance if this is a dependent
18718 // call in an uninstantiated template.
18719 if (Target) {
18720 const FunctionDecl *FNTarget = nullptr;
18721 (void)Target->hasBody(FNTarget);
18722 Target = const_cast<CXXConstructorDecl*>(
18723 cast_or_null<CXXConstructorDecl>(FNTarget));
18724 }
18725
18726 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18727 // Avoid dereferencing a null pointer here.
18728 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18729
18730 if (!Current.insert(Canonical).second)
18731 return;
18732
18733 // We know that beyond here, we aren't chaining into a cycle.
18734 if (!Target || !Target->isDelegatingConstructor() ||
18735 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18736 Valid.insert(Current.begin(), Current.end());
18737 Current.clear();
18738 // We've hit a cycle.
18739 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18740 Current.count(TCanonical)) {
18741 // If we haven't diagnosed this cycle yet, do so now.
18742 if (!Invalid.count(TCanonical)) {
18743 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18744 diag::warn_delegating_ctor_cycle)
18745 << Ctor;
18746
18747 // Don't add a note for a function delegating directly to itself.
18748 if (TCanonical != Canonical)
18749 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18750
18752 while (C->getCanonicalDecl() != Canonical) {
18753 const FunctionDecl *FNTarget = nullptr;
18754 (void)C->getTargetConstructor()->hasBody(FNTarget);
18755 assert(FNTarget && "Ctor cycle through bodiless function");
18756
18757 C = const_cast<CXXConstructorDecl*>(
18758 cast<CXXConstructorDecl>(FNTarget));
18759 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18760 }
18761 }
18762
18763 Invalid.insert(Current.begin(), Current.end());
18764 Current.clear();
18765 } else {
18766 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18767 }
18768}
18769
18770
18773
18774 for (DelegatingCtorDeclsType::iterator
18777 I != E; ++I)
18778 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18779
18780 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18781 (*CI)->setInvalidDecl();
18782}
18783
18784namespace {
18785 /// AST visitor that finds references to the 'this' expression.
18786class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
18787 Sema &S;
18788
18789public:
18790 explicit FindCXXThisExpr(Sema &S) : S(S) {}
18791
18792 bool VisitCXXThisExpr(CXXThisExpr *E) override {
18793 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18794 << E->isImplicit();
18795 return false;
18796 }
18797};
18798}
18799
18801 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18802 if (!TSInfo)
18803 return false;
18804
18805 TypeLoc TL = TSInfo->getTypeLoc();
18807 if (!ProtoTL)
18808 return false;
18809
18810 // C++11 [expr.prim.general]p3:
18811 // [The expression this] shall not appear before the optional
18812 // cv-qualifier-seq and it shall not appear within the declaration of a
18813 // static member function (although its type and value category are defined
18814 // within a static member function as they are within a non-static member
18815 // function). [ Note: this is because declaration matching does not occur
18816 // until the complete declarator is known. - end note ]
18817 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18818 FindCXXThisExpr Finder(*this);
18819
18820 // If the return type came after the cv-qualifier-seq, check it now.
18821 if (Proto->hasTrailingReturn() &&
18822 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18823 return true;
18824
18825 // Check the exception specification.
18827 return true;
18828
18829 // Check the trailing requires clause
18830 if (Expr *E = Method->getTrailingRequiresClause())
18831 if (!Finder.TraverseStmt(E))
18832 return true;
18833
18835}
18836
18838 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18839 if (!TSInfo)
18840 return false;
18841
18842 TypeLoc TL = TSInfo->getTypeLoc();
18844 if (!ProtoTL)
18845 return false;
18846
18847 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18848 FindCXXThisExpr Finder(*this);
18849
18850 switch (Proto->getExceptionSpecType()) {
18851 case EST_Unparsed:
18852 case EST_Uninstantiated:
18853 case EST_Unevaluated:
18854 case EST_BasicNoexcept:
18855 case EST_NoThrow:
18856 case EST_DynamicNone:
18857 case EST_MSAny:
18858 case EST_None:
18859 break;
18860
18862 case EST_NoexceptFalse:
18863 case EST_NoexceptTrue:
18864 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18865 return true;
18866 [[fallthrough]];
18867
18868 case EST_Dynamic:
18869 for (const auto &E : Proto->exceptions()) {
18870 if (!Finder.TraverseType(E))
18871 return true;
18872 }
18873 break;
18874 }
18875
18876 return false;
18877}
18878
18880 FindCXXThisExpr Finder(*this);
18881
18882 // Check attributes.
18883 for (const auto *A : Method->attrs()) {
18884 // FIXME: This should be emitted by tblgen.
18885 Expr *Arg = nullptr;
18886 ArrayRef<Expr *> Args;
18887 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18888 Arg = G->getArg();
18889 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18890 Arg = G->getArg();
18891 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18892 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18893 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18894 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18895 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18896 Arg = ETLF->getSuccessValue();
18897 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18898 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18899 Arg = STLF->getSuccessValue();
18900 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18901 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18902 Arg = LR->getArg();
18903 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18904 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18905 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18906 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18907 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18908 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18909 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18910 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18911 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18912 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18913
18914 if (Arg && !Finder.TraverseStmt(Arg))
18915 return true;
18916
18917 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18918 if (!Finder.TraverseStmt(Args[I]))
18919 return true;
18920 }
18921 }
18922
18923 return false;
18924}
18925
18927 bool IsTopLevel, ExceptionSpecificationType EST,
18928 ArrayRef<ParsedType> DynamicExceptions,
18929 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18930 SmallVectorImpl<QualType> &Exceptions,
18932 Exceptions.clear();
18933 ESI.Type = EST;
18934 if (EST == EST_Dynamic) {
18935 Exceptions.reserve(DynamicExceptions.size());
18936 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18937 // FIXME: Preserve type source info.
18938 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18939
18940 if (IsTopLevel) {
18942 collectUnexpandedParameterPacks(ET, Unexpanded);
18943 if (!Unexpanded.empty()) {
18945 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18946 Unexpanded);
18947 continue;
18948 }
18949 }
18950
18951 // Check that the type is valid for an exception spec, and
18952 // drop it if not.
18953 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18954 Exceptions.push_back(ET);
18955 }
18956 ESI.Exceptions = Exceptions;
18957 return;
18958 }
18959
18960 if (isComputedNoexcept(EST)) {
18961 assert((NoexceptExpr->isTypeDependent() ||
18962 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18963 Context.BoolTy) &&
18964 "Parser should have made sure that the expression is boolean");
18965 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18966 ESI.Type = EST_BasicNoexcept;
18967 return;
18968 }
18969
18970 ESI.NoexceptExpr = NoexceptExpr;
18971 return;
18972 }
18973}
18974
18976 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
18977 ArrayRef<ParsedType> DynamicExceptions,
18978 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
18979 if (!D)
18980 return;
18981
18982 // Dig out the function we're referring to.
18983 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
18984 D = FTD->getTemplatedDecl();
18985
18986 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
18987 if (!FD)
18988 return;
18989
18990 // Check the exception specification.
18993 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
18994 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18995 ESI);
18996
18997 // Update the exception specification on the function type.
18998 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
18999
19000 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19001 if (MD->isStatic())
19003
19004 if (MD->isVirtual()) {
19005 // Check overrides, which we previously had to delay.
19006 for (const CXXMethodDecl *O : MD->overridden_methods())
19008 }
19009 }
19010}
19011
19012/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19013///
19015 SourceLocation DeclStart, Declarator &D,
19016 Expr *BitWidth,
19017 InClassInitStyle InitStyle,
19018 AccessSpecifier AS,
19019 const ParsedAttr &MSPropertyAttr) {
19020 const IdentifierInfo *II = D.getIdentifier();
19021 if (!II) {
19022 Diag(DeclStart, diag::err_anonymous_property);
19023 return nullptr;
19024 }
19025 SourceLocation Loc = D.getIdentifierLoc();
19026
19028 QualType T = TInfo->getType();
19029 if (getLangOpts().CPlusPlus) {
19031
19032 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19034 D.setInvalidType();
19035 T = Context.IntTy;
19037 }
19038 }
19039
19040 DiagnoseFunctionSpecifiers(D.getDeclSpec());
19041
19042 if (D.getDeclSpec().isInlineSpecified())
19043 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19044 << getLangOpts().CPlusPlus17;
19045 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19046 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19047 diag::err_invalid_thread)
19049
19050 // Check to see if this name was declared as a member previously
19051 NamedDecl *PrevDecl = nullptr;
19053 RedeclarationKind::ForVisibleRedeclaration);
19054 LookupName(Previous, S);
19055 switch (Previous.getResultKind()) {
19058 PrevDecl = Previous.getAsSingle<NamedDecl>();
19059 break;
19060
19062 PrevDecl = Previous.getRepresentativeDecl();
19063 break;
19064
19068 break;
19069 }
19070
19071 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19072 // Maybe we will complain about the shadowed template parameter.
19073 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19074 // Just pretend that we didn't see the previous declaration.
19075 PrevDecl = nullptr;
19076 }
19077
19078 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19079 PrevDecl = nullptr;
19080
19081 SourceLocation TSSL = D.getBeginLoc();
19082 MSPropertyDecl *NewPD =
19083 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19084 MSPropertyAttr.getPropertyDataGetter(),
19085 MSPropertyAttr.getPropertyDataSetter());
19087 NewPD->setAccess(AS);
19088
19089 if (NewPD->isInvalidDecl())
19090 Record->setInvalidDecl();
19091
19092 if (D.getDeclSpec().isModulePrivateSpecified())
19093 NewPD->setModulePrivate();
19094
19095 if (NewPD->isInvalidDecl() && PrevDecl) {
19096 // Don't introduce NewFD into scope; there's already something
19097 // with the same name in the same scope.
19098 } else if (II) {
19099 PushOnScopeChains(NewPD, S);
19100 } else
19101 Record->addDecl(NewPD);
19102
19103 return NewPD;
19104}
19105
19107 Declarator &Declarator, unsigned TemplateParameterDepth) {
19108 auto &Info = InventedParameterInfos.emplace_back();
19109 TemplateParameterList *ExplicitParams = nullptr;
19110 ArrayRef<TemplateParameterList *> ExplicitLists =
19112 if (!ExplicitLists.empty()) {
19113 bool IsMemberSpecialization, IsInvalid;
19116 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19117 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19118 /*SuppressDiagnostic=*/true);
19119 }
19120 // C++23 [dcl.fct]p23:
19121 // An abbreviated function template can have a template-head. The invented
19122 // template-parameters are appended to the template-parameter-list after
19123 // the explicitly declared template-parameters.
19124 //
19125 // A template-head must have one or more template-parameters (read:
19126 // 'template<>' is *not* a template-head). Only append the invented
19127 // template parameters if we matched the nested-name-specifier to a non-empty
19128 // TemplateParameterList.
19129 if (ExplicitParams && !ExplicitParams->empty()) {
19130 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19131 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19132 Info.NumExplicitTemplateParams = ExplicitParams->size();
19133 } else {
19134 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19135 Info.NumExplicitTemplateParams = 0;
19136 }
19137}
19138
19140 auto &FSI = InventedParameterInfos.back();
19141 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19142 if (FSI.NumExplicitTemplateParams != 0) {
19143 TemplateParameterList *ExplicitParams =
19147 Context, ExplicitParams->getTemplateLoc(),
19148 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19149 ExplicitParams->getRAngleLoc(),
19150 ExplicitParams->getRequiresClause()));
19151 } else {
19154 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19155 SourceLocation(), /*RequiresClause=*/nullptr));
19156 }
19157 }
19158 InventedParameterInfos.pop_back();
19159}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
NodeId Parent
Definition: ASTDiff.cpp:191
DynTypedNode Node
StringRef P
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1727::IndirectLocalPathEntry::EntryKind Kind
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
int Category
Definition: Format.cpp:3056
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool RefersToRValueRef(Expr *MemRef)
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
#define CheckPolymorphic(Type)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
bool Indirect
Definition: SemaObjC.cpp:760
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
const NestedNameSpecifier * Specifier
StateNode * Previous
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:124
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3410
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3424
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType Char16Ty
Definition: ASTContext.h:1167
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
void Deallocate(void *Ptr) const
Definition: ASTContext.h:760
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1188
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
CanQualType WideCharTy
Definition: ASTContext.h:1164
IdentifierTable & Idents
Definition: ASTContext.h:680
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1392
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2420
QualType AutoDeductTy
Definition: ASTContext.h:1223
CanQualType BoolTy
Definition: ASTContext.h:1161
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3389
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3021
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1162
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3403
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3396
CanQualType IntTy
Definition: ASTContext.h:1169
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3420
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2489
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3385
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3417
CanQualType VoidTy
Definition: ASTContext.h:1160
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3399
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:3182
CanQualType Char32Ty
Definition: ASTContext.h:1168
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3392
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1274
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3406
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CanQualType Char8Ty
Definition: ASTContext.h:1166
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3413
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Wrapper for source info for arrays.
Definition: TypeLoc.h:1593
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1623
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
bool isInherited() const
Definition: Attr.h:98
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition: Attr.h:96
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
AutoTypeKeyword getKeyword() const
Definition: Type.h:6592
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3440
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3518
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3272
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3510
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3281
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4902
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2158
A binding in a decomposition declaration.
Definition: DeclCXX.h:4130
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3465
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1346
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
std::list< CXXBasePath >::iterator paths_iterator
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition: ExprCXX.cpp:1159
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1609
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2795
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:2898
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2624
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2649
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2875
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:2893
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2884
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2790
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2854
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2885
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2925
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2318
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2490
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2803
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2790
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2464
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2988
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1737
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:722
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:2588
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2595
bool isVirtual() const
Definition: DeclCXX.h:2133
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2232
bool isVolatile() const
Definition: DeclCXX.h:2131
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2181
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2665
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2659
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2707
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2254
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2649
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
bool isInstance() const
Definition: DeclCXX.h:2105
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2621
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2407
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2228
bool isStatic() const
Definition: DeclCXX.cpp:2319
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2599
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition: DeclCXX.h:1282
friend_range friends() const
Definition: DeclFriend.h:261
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1353
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:619
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1641
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1013
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:832
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition: DeclCXX.h:1432
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1403
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1382
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:718
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.cpp:1467
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:973
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1368
base_class_range bases()
Definition: DeclCXX.h:620
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:612
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1030
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1313
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:778
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:904
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:922
method_range methods() const
Definition: DeclCXX.h:662
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:943
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1738
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1275
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1290
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:985
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:607
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1226
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:709
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1294
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition: DeclCXX.cpp:738
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2011
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1340
base_class_range vbases()
Definition: DeclCXX.h:637
base_class_iterator vbases_begin()
Definition: DeclCXX.h:644
ctor_range ctors() const
Definition: DeclCXX.h:682
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:879
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1233
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1248
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:870
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1160
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:811
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1414
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1212
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:805
bool hasDefinition() const
Definition: DeclCXX.h:572
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:928
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1019
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:2003
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition: DeclCXX.h:914
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:1006
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2081
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1025
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1426
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1712
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:817
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:858
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:995
bool isInterfaceLike() const
Definition: DeclCXX.cpp:2110
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:937
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1318
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1700
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition: DeclCXX.h:958
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
Represents the this expression in C++.
Definition: ExprCXX.h:1152
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1172
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:108
unsigned getNumHandlers() const
Definition: StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
body_range body()
Definition: Stmt.h:1691
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:391
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:196
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3621
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3685
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:3254
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:1372
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2384
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2233
bool isFileContext() const
Definition: DeclBase.h:2175
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2065
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
bool isTranslationUnit() const
Definition: DeclBase.h:2180
bool isRecord() const
Definition: DeclBase.h:2184
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2010
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1699
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1780
decl_iterator decls_end() const
Definition: DeclBase.h:2366
bool isStdNamespace() const
Definition: DeclBase.cpp:1329
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2364
bool isFunctionOrMethod() const
Definition: DeclBase.h:2156
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1400
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1415
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1754
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2097
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1426
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1636
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:550
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:487
ValueDecl * getDecl()
Definition: Expr.h:1333
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1457
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:691
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:560
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:827
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:825
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:623
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:655
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition: DeclSpec.cpp:453
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_auto
Definition: DeclSpec.h:318
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1519
decl_range decls()
Definition: Stmt.h:1567
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1545
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1054
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:528
void addAttr(Attr *A)
Definition: DeclBase.cpp:1019
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1207
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:572
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1212
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1210
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:254
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2784
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1226
bool isInvalidDecl() const
Definition: DeclBase.h:591
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:882
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1162
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:237
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:597
void setReferenced(bool R=true)
Definition: DeclBase.h:626
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:557
DeclContext * getDeclContext()
Definition: DeclBase.h:451
attr_range attrs() const
Definition: DeclBase.h:538
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void dropAttr()
Definition: DeclBase.h:559
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Kind getKind() const
Definition: DeclBase.h:445
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:874
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:769
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:810
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2339
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2086
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2065
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2652
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2659
bool isInvalidType() const
Definition: DeclSpec.h:2717
A decomposition declaration.
Definition: DeclCXX.h:4189
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4221
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1839
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1837
Represents a C++17 deduced template specialization type.
Definition: Type.h:6609
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2455
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2435
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2444
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Definition: Diagnostic.h:1512
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:793
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseConstructorInitializer(CXXCtorInitializer *Init)
Recursively visit a constructor initializer.
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2355
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2393
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2369
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5695
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3291
Represents an enum.
Definition: Decl.h:3861
enumerator_range enumerators() const
Definition: Decl.h:3994
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
const Expr * getExpr() const
Definition: DeclCXX.h:1921
void setExpr(Expr *E)
Definition: DeclCXX.h:1946
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1945
This represents one expression.
Definition: Expr.h:110
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3097
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3085
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3093
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3231
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4591
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3208
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4581
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3202
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4601
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3118
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3275
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition: Diagnostic.h:114
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:101
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:189
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3103
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3243
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2744
bool isTrivialForCall() const
Definition: Decl.h:2308
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3734
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4075
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4063
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3262
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
bool isImmediateFunction() const
Definition: Decl.cpp:3300
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3124
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3894
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3491
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3752
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
SourceLocation getDefaultLoc() const
Definition: Decl.h:2326
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2317
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4183
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2657
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3634
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3888
param_iterator param_begin()
Definition: Decl.h:2661
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2261
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2414
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4199
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3009
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4127
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2763
bool isStatic() const
Definition: Decl.h:2804
void setTrivial(bool IT)
Definition: Decl.h:2306
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4014
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2288
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3509
bool isImmediateEscalating() const
Definition: Decl.cpp:3275
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3187
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4416
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4000
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2401
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4287
void setDefaulted(bool D=true)
Definition: Decl.h:2314
bool isConsteval() const
Definition: Decl.h:2410
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2338
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2737
void setBody(Stmt *B)
Definition: Decl.cpp:3255
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2279
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3766
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3713
size_t param_size() const
Definition: Decl.h:2665
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
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:3210
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2774
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3158
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2680
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:5044
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition: Type.cpp:5286
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4908
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5573
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5387
unsigned getNumParams() const
Definition: Type.h:5360
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5500
QualType getParamType(unsigned i) const
Definition: Type.h:5362
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5445
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< QualType > exceptions() const
Definition: Type.h:5530
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5545
Declaration of a template function.
Definition: DeclTemplate.h:958
Wrapper for source info for functions.
Definition: TypeLoc.h:1460
unsigned getNumParams() const
Definition: TypeLoc.h:1532
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1538
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1539
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1541
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4547
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
CallingConv getCallConv() const
Definition: Type.h:4659
QualType getReturnType() const
Definition: Type.h:4648
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2165
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2089
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5841
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
void setInherited(bool I)
Definition: Attr.h:155
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2524
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2536
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:515
Describes an C or C++ initializer list.
Definition: Expr.h:5088
unsigned getNumInits() const
Definition: Expr.h:5118
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5134
child_range children()
Definition: Expr.h:5280
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7637
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:3605
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6798
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:980
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1339
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1352
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:672
void push_back(const T &LocalValue)
iterator begin(Source *source, bool LocalOnly=false)
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1023
Represents a linkage specification.
Definition: DeclCXX.h:2957
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:3073
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2999
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:469
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:311
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:408
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
iterator end() const
Definition: Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4258
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3530
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
Expr * getBase() const
Definition: Expr.h:3313
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3431
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1364
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
Describes a module or submodule.
Definition: Module.h:115
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:703
bool isExplicitGlobalModule() const
Definition: Module.h:213
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:699
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represents a C++ namespace alias.
Definition: DeclCXX.h:3143
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3168
Represent a C++ namespace.
Definition: Decl.h:551
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:607
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3128
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition: Decl.h:634
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:653
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
PtrTy get() const
Definition: Ownership.h:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1015
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1019
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1026
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1192
MapType::iterator iterator
MapType::const_iterator const_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4774
Represents a parameter to a function.
Definition: Decl.h:1725
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2987
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1821
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1866
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2992
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3012
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
bool hasInheritedDefaultArg() const
Definition: Decl.h:1870
bool isExplicitObjectParameter() const
Definition: Decl.h:1813
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2922
Expr * getDefaultArg()
Definition: Decl.cpp:2975
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3017
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3023
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1874
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2945
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:485
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:479
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:836
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:916
Wrapper for source info for pointers.
Definition: TypeLoc.h:1333
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
ArrayRef< Expr * > semantics()
Definition: Expr.h:6625
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
QualType withConst() const
Definition: Type.h:1154
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8139
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2885
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1081
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7982
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2641
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:8119
Represents a template name as written in source code.
Definition: TemplateName.h:491
The collection of all-type qualifiers we support.
Definition: Type.h:324
void addAddressSpace(LangAS space)
Definition: Type.h:590
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
void removeConst()
Definition: Type.h:452
void removeAddressSpace()
Definition: Type.h:589
void addConst()
Definition: Type.h:453
void removeVolatile()
Definition: Type.h:462
std::string getAsString() const
LangAS getAddressSpace() const
Definition: Type.h:564
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
Represents a struct/union/class.
Definition: Decl.h:4162
bool hasFlexibleArrayMember() const
Definition: Decl.h:4195
field_iterator field_end() const
Definition: Decl.h:4379
field_range fields() const
Definition: Decl.h:4376
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5072
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4214
bool field_empty() const
Definition: Decl.h:4384
field_iterator field_begin() const
Definition: Decl.cpp:5106
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5080
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3046
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
void setEntity(DeclContext *E)
Definition: Scope.h:393
void AddDecl(Decl *D)
Definition: Scope.h:346
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:370
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
A RAII object to enter scope of a compound statement.
Definition: Sema.h:916
bool isInvalid() const
Definition: Sema.h:7331
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5891
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5923
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5920
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:4995
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:8942
CXXMethodDecl * getMethod() const
Definition: Sema.h:8954
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:13078
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7229
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:11046
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6716
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, ASTContext &Ctx, bool ErrorOnInvalidMessage)
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12643
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9816
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:6074
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1561
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15504
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5835
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9017
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9025
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:9013
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:412
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6652
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, CXXScopeSpec *SS=nullptr)
VariadicCallType
Definition: Sema.h:2315
@ VariadicDoesNotApply
Definition: Sema.h:2320
@ VariadicConstructor
Definition: Sema.h:2319
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:6129
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void PrintContextStack()
Definition: Sema.h:13220
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
Definition: SemaDecl.cpp:7470
SemaOpenMP & OpenMP()
Definition: Sema.h:1126
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:5810
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6114
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:867
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:6051
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:6032
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1190
SemaCUDA & CUDA()
Definition: Sema.h:1071
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17400
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ AR_dependent
Definition: Sema.h:1270
@ AR_accessible
Definition: Sema.h:1268
@ AR_inaccessible
Definition: Sema.h:1269
@ AR_delayed
Definition: Sema.h:1271
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2292
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2161
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6257
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17158
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4844
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition: SemaStmt.cpp:49
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:18415
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1665
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:909
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5821
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1111
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4954
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
AllowFoldKind
Definition: Sema.h:7243
@ AllowFold
Definition: Sema.h:7245
@ NoFold
Definition: Sema.h:7244
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1499
ASTContext & getASTContext() const
Definition: Sema.h:532
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:6058
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:19921
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:6136
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17833
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:692
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:5606
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
@ None
This is not a defaultable comparison operator.
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9486
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:6069
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:817
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2204
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11789
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1589
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7962
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1581
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2180
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:527
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20424
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
@ UPPC_RequiresClause
Definition: Sema.h:13973
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:13928
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:13946
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13937
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:13907
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13931
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13940
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13910
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13913
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:13919
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:525
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:5396
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1390
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:908
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6476
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:8279
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14382
const LangOptions & LangOpts
Definition: Sema.h:907
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17517
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7600
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6036
SemaHLSL & HLSL()
Definition: Sema.h:1076
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11953
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:5402
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:4792
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition: Sema.h:6029
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20072
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
Definition: SemaStmt.cpp:3710
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:6128
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6062
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9582
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1377
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1857
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:12655
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:5392
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14990
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:9588
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15449
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:6492
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:6043
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15373
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true, bool WantSize=false, bool WantAligned=false)
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14940
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5826
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
TrivialABIHandling
Definition: Sema.h:5875
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:5877
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:5880
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7777
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const RecordType * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20021
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2255
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13490
SourceManager & getSourceManager() const
Definition: Sema.h:530
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1342
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:8970
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9736
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
Definition: SemaAttr.cpp:1471
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8302
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
Definition: SemaStmt.cpp:3883
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14945
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_ErrorRecovery
Definition: Sema.h:9384
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14304
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
RedeclarationKind forRedeclarationInCurContext() const
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6054
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
@ CCEK_StaticAssertMessageSize
Call to size() in a static assert message.
Definition: Sema.h:10005
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10003
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:10007
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3095
ASTConsumer & Consumer
Definition: Sema.h:910
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:4227
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9787
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9779
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9783
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5121
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9704
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5704
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:17158
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9119
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:872
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19016
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Definition: SemaAttr.cpp:1480
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
Definition: SemaInit.cpp:7456
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17910
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7917
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1310
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:912
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition: Sema.h:911
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:7301
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7293
@ TPC_TypeAliasTemplate
Definition: Sema.h:11285
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6753
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Definition: SemaExpr.cpp:3598
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5582
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1317
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:2871
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6066
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1581
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8885
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1566
@ OOK_Outside
Definition: Sema.h:3868
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13377
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:296
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:5809
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18091
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5954
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21174
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6088
AbstractDiagSelID
Definition: Sema.h:5755
@ AbstractVariableType
Definition: Sema.h:5759
@ AbstractReturnType
Definition: Sema.h:5757
@ AbstractNone
Definition: Sema.h:5756
@ AbstractFieldType
Definition: Sema.h:5760
@ AbstractArrayType
Definition: Sema.h:5763
@ AbstractParamType
Definition: Sema.h:5758
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:962
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1705
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7966
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14774
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CheckConstexprKind
Definition: Sema.h:5951
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2751
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition: SemaStmt.cpp:451
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition: Sema.h:3003
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
ExprResult ActOnCXXThis(SourceLocation Loc)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6075
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5333
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:590
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3438
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
child_range children()
Definition: Stmt.cpp:295
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
bool isUnevaluated() const
Definition: Expr.h:1907
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3701
StringRef getKindName() const
Definition: Decl.h:3769
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4762
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4756
bool isUnion() const
Definition: Decl.h:3784
TagKind getTagKind() const
Definition: Decl.h:3773
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3732
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:188
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:206
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:611
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1300
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
Represents a template argument.
Definition: TemplateBase.h:61
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:398
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1727
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6666
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6734
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6732
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
unsigned getIndex() const
Definition: Type.h:6348
unsigned getDepth() const
Definition: Type.h:6347
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3549
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5620
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3568
Declaration of an alias template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Represents a declaration of a type.
Definition: Decl.h:3384
const Type * getTypeForDecl() const
Definition: Decl.h:3409
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:170
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1257
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
TypeLocClass getTypeLocClass() const
Definition: TypeLoc.h:116
bool isNull() const
Definition: TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2716
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7907
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7918
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:529
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3196
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6929
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3178
The base class of the type hierarchy.
Definition: Type.h:1828
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2511
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8271
bool isUndeducedAutoType() const
Definition: Type.h:8350
bool isRValueReferenceType() const
Definition: Type.h:8217
bool isArrayType() const
Definition: Type.h:8263
bool isPointerType() const
Definition: Type.h:8191
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3303
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isLValueReferenceType() const
Definition: Type.h:8213
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8484
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2700
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8686
bool isFunctionProtoType() const
Definition: Type.h:2535
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8656
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCObjectType() const
Definition: Type.h:8337
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isStructureOrClassType() const
Definition: Type.cpp:690
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isRecordType() const
Definition: Type.h:8291
bool isUnionType() const
Definition: Type.cpp:704
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1924
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
QualType getUnderlyingType() const
Definition: Decl.h:3482
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4959
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4063
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3417
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3982
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3396
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3885
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3368
Represents a C++ using-declaration.
Definition: DeclCXX.h:3535
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3584
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3576
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3303
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3572
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3562
Represents C++ using-directive.
Definition: DeclCXX.h:3038
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:3090
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3736
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3324
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3347
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3379
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3407
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3243
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2179
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2812
void setCXXCondDecl()
Definition: Decl.h:1563
bool isInlineSpecified() const
Definition: Decl.h:1498
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2547
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2620
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2827
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:908
void setInit(Expr *I)
Definition: Decl.cpp:2449
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2500
void setExceptionVariable(bool EV)
Definition: Decl.h:1441
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2783
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2803
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2815
bool isOverrideSpecified() const
Definition: DeclSpec.h:2802
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2807
bool isFinalSpecified() const
Definition: DeclSpec.h:2805
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2806
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition: ScopeInfo.h:179
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:824
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2350
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:925
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_decltype
Definition: Specifiers.h:89
@ TST_typename_pack_indexing
Definition: Specifiers.h:97
@ TST_decltype_auto
Definition: Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isa(CodeGen::Address addr)
Definition: Address.h:328
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2949
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_ListInit
Direct list-initialization.
Definition: Specifiers.h:274
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
CXXConstructionKind
Definition: ExprCXX.h:1538
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
BinaryOperatorKind
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
StmtResult StmtError()
Definition: Ownership.h:265
@ Result
The result type of a method or function.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:985
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanPassInRegs
The argument of this type can be passed directly in registers.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1102
ComparisonCategoryType
An enumeration representing the different comparison categories types.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:423
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1278
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:236
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6851
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_protected
Definition: Specifiers.h:125
@ AS_none
Definition: Specifiers.h:127
@ AS_private
Definition: Specifiers.h:126
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition: DeclSpec.h:1368
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1428
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1377
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1431
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1529
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1558
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1561
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1467
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1554
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1343
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
SourceRange getSourceRange() const
Definition: DeclSpec.h:1263
enum clang::DeclaratorChunk::@225 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1642
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Holds information about the various types of exception specification.
Definition: Type.h:5164
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5176
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5166
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5169
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5172
Extra information about a function prototype.
Definition: Type.h:5192
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5199
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1045
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12660
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12754
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12751
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12704
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12718
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12722
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7858
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.