[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Sema / SemaDeclCXX.cpp
bloba7ab0948d01bf36bf4c2404c656d1e1db264cfd2
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.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
30 #include "clang/Basic/AttributeCommonInfo.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/Specifiers.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/EnterExpressionEvaluationContext.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Ownership.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/ScopeExit.h"
50 #include "llvm/ADT/SmallString.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Support/SaveAndRestore.h"
53 #include <map>
54 #include <optional>
55 #include <set>
57 using namespace clang;
59 //===----------------------------------------------------------------------===//
60 // CheckDefaultArgumentVisitor
61 //===----------------------------------------------------------------------===//
63 namespace {
64 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
65 /// the default argument of a parameter to determine whether it
66 /// contains any ill-formed subexpressions. For example, this will
67 /// diagnose the use of local variables or parameters within the
68 /// default argument expression.
69 class CheckDefaultArgumentVisitor
70 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
71 Sema &S;
72 const Expr *DefaultArg;
74 public:
75 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
76 : S(S), DefaultArg(DefaultArg) {}
78 bool VisitExpr(const Expr *Node);
79 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
80 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
81 bool VisitLambdaExpr(const LambdaExpr *Lambda);
82 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
85 /// VisitExpr - Visit all of the children of this expression.
86 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
87 bool IsInvalid = false;
88 for (const Stmt *SubStmt : Node->children())
89 IsInvalid |= Visit(SubStmt);
90 return IsInvalid;
93 /// VisitDeclRefExpr - Visit a reference to a declaration, to
94 /// determine whether this declaration can be used in the default
95 /// argument expression.
96 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
97 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
99 if (!isa<VarDecl, BindingDecl>(Decl))
100 return false;
102 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
103 // C++ [dcl.fct.default]p9:
104 // [...] parameters of a function shall not be used in default
105 // argument expressions, even if they are not evaluated. [...]
107 // C++17 [dcl.fct.default]p9 (by CWG 2082):
108 // [...] A parameter shall not appear as a potentially-evaluated
109 // expression in a default argument. [...]
111 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
112 return S.Diag(DRE->getBeginLoc(),
113 diag::err_param_default_argument_references_param)
114 << Param->getDeclName() << DefaultArg->getSourceRange();
115 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
116 // C++ [dcl.fct.default]p7:
117 // Local variables shall not be used in default argument
118 // expressions.
120 // C++17 [dcl.fct.default]p7 (by CWG 2082):
121 // A local variable shall not appear as a potentially-evaluated
122 // expression in a default argument.
124 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
125 // Note: A local variable cannot be odr-used (6.3) in a default
126 // argument.
128 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
129 return S.Diag(DRE->getBeginLoc(),
130 diag::err_param_default_argument_references_local)
131 << Decl << DefaultArg->getSourceRange();
133 return false;
136 /// VisitCXXThisExpr - Visit a C++ "this" expression.
137 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
138 // C++ [dcl.fct.default]p8:
139 // The keyword this shall not be used in a default argument of a
140 // member function.
141 return S.Diag(ThisE->getBeginLoc(),
142 diag::err_param_default_argument_references_this)
143 << ThisE->getSourceRange();
146 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
147 const PseudoObjectExpr *POE) {
148 bool Invalid = false;
149 for (const Expr *E : POE->semantics()) {
150 // Look through bindings.
151 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
152 E = OVE->getSourceExpr();
153 assert(E && "pseudo-object binding without source expression?");
156 Invalid |= Visit(E);
158 return Invalid;
161 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
162 // [expr.prim.lambda.capture]p9
163 // a lambda-expression appearing in a default argument cannot implicitly or
164 // explicitly capture any local entity. Such a lambda-expression can still
165 // have an init-capture if any full-expression in its initializer satisfies
166 // the constraints of an expression appearing in a default argument.
167 bool Invalid = false;
168 for (const LambdaCapture &LC : Lambda->captures()) {
169 if (!Lambda->isInitCapture(&LC))
170 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
171 // Init captures are always VarDecl.
172 auto *D = cast<VarDecl>(LC.getCapturedVar());
173 Invalid |= Visit(D->getInit());
175 return Invalid;
177 } // namespace
179 void
180 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
181 const CXXMethodDecl *Method) {
182 // If we have an MSAny spec already, don't bother.
183 if (!Method || ComputedEST == EST_MSAny)
184 return;
186 const FunctionProtoType *Proto
187 = Method->getType()->getAs<FunctionProtoType>();
188 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
189 if (!Proto)
190 return;
192 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
194 // If we have a throw-all spec at this point, ignore the function.
195 if (ComputedEST == EST_None)
196 return;
198 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
199 EST = EST_BasicNoexcept;
201 switch (EST) {
202 case EST_Unparsed:
203 case EST_Uninstantiated:
204 case EST_Unevaluated:
205 llvm_unreachable("should not see unresolved exception specs here");
207 // If this function can throw any exceptions, make a note of that.
208 case EST_MSAny:
209 case EST_None:
210 // FIXME: Whichever we see last of MSAny and None determines our result.
211 // We should make a consistent, order-independent choice here.
212 ClearExceptions();
213 ComputedEST = EST;
214 return;
215 case EST_NoexceptFalse:
216 ClearExceptions();
217 ComputedEST = EST_None;
218 return;
219 // FIXME: If the call to this decl is using any of its default arguments, we
220 // need to search them for potentially-throwing calls.
221 // If this function has a basic noexcept, it doesn't affect the outcome.
222 case EST_BasicNoexcept:
223 case EST_NoexceptTrue:
224 case EST_NoThrow:
225 return;
226 // If we're still at noexcept(true) and there's a throw() callee,
227 // change to that specification.
228 case EST_DynamicNone:
229 if (ComputedEST == EST_BasicNoexcept)
230 ComputedEST = EST_DynamicNone;
231 return;
232 case EST_DependentNoexcept:
233 llvm_unreachable(
234 "should not generate implicit declarations for dependent cases");
235 case EST_Dynamic:
236 break;
238 assert(EST == EST_Dynamic && "EST case not considered earlier.");
239 assert(ComputedEST != EST_None &&
240 "Shouldn't collect exceptions when throw-all is guaranteed.");
241 ComputedEST = EST_Dynamic;
242 // Record the exceptions in this function's exception specification.
243 for (const auto &E : Proto->exceptions())
244 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
245 Exceptions.push_back(E);
248 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
249 if (!S || ComputedEST == EST_MSAny)
250 return;
252 // FIXME:
254 // C++0x [except.spec]p14:
255 // [An] implicit exception-specification specifies the type-id T if and
256 // only if T is allowed by the exception-specification of a function directly
257 // invoked by f's implicit definition; f shall allow all exceptions if any
258 // function it directly invokes allows all exceptions, and f shall allow no
259 // exceptions if every function it directly invokes allows no exceptions.
261 // Note in particular that if an implicit exception-specification is generated
262 // for a function containing a throw-expression, that specification can still
263 // be noexcept(true).
265 // Note also that 'directly invoked' is not defined in the standard, and there
266 // is no indication that we should only consider potentially-evaluated calls.
268 // Ultimately we should implement the intent of the standard: the exception
269 // specification should be the set of exceptions which can be thrown by the
270 // implicit definition. For now, we assume that any non-nothrow expression can
271 // throw any exception.
273 if (Self->canThrow(S))
274 ComputedEST = EST_None;
277 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
278 SourceLocation EqualLoc) {
279 if (RequireCompleteType(Param->getLocation(), Param->getType(),
280 diag::err_typecheck_decl_incomplete_type))
281 return true;
283 // C++ [dcl.fct.default]p5
284 // A default argument expression is implicitly converted (clause
285 // 4) to the parameter type. The default argument expression has
286 // the same semantic constraints as the initializer expression in
287 // a declaration of a variable of the parameter type, using the
288 // copy-initialization semantics (8.5).
289 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
290 Param);
291 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
292 EqualLoc);
293 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
294 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
295 if (Result.isInvalid())
296 return true;
297 Arg = Result.getAs<Expr>();
299 CheckCompletedExpr(Arg, EqualLoc);
300 Arg = MaybeCreateExprWithCleanups(Arg);
302 return Arg;
305 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
306 SourceLocation EqualLoc) {
307 // Add the default argument to the parameter
308 Param->setDefaultArg(Arg);
310 // We have already instantiated this parameter; provide each of the
311 // instantiations with the uninstantiated default argument.
312 UnparsedDefaultArgInstantiationsMap::iterator InstPos
313 = UnparsedDefaultArgInstantiations.find(Param);
314 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
315 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
316 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
318 // We're done tracking this parameter's instantiations.
319 UnparsedDefaultArgInstantiations.erase(InstPos);
323 /// ActOnParamDefaultArgument - Check whether the default argument
324 /// provided for a function parameter is well-formed. If so, attach it
325 /// to the parameter declaration.
326 void
327 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
328 Expr *DefaultArg) {
329 if (!param || !DefaultArg)
330 return;
332 ParmVarDecl *Param = cast<ParmVarDecl>(param);
333 UnparsedDefaultArgLocs.erase(Param);
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);
342 // Check for unexpanded parameter packs.
343 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))
344 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
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;
357 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
358 if (Result.isInvalid())
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361 DefaultArg = Result.getAs<Expr>();
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);
368 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
371 /// ActOnParamUnparsedDefaultArgument - We've seen a default
372 /// argument for a function parameter, but we can't parse it yet
373 /// because we're inside a class definition. Note that this default
374 /// argument will be parsed later.
375 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
376 SourceLocation EqualLoc,
377 SourceLocation ArgLoc) {
378 if (!param)
379 return;
381 ParmVarDecl *Param = cast<ParmVarDecl>(param);
382 Param->setUnparsedDefaultArg();
383 UnparsedDefaultArgLocs[Param] = ArgLoc;
386 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
387 /// the default argument for the parameter param failed.
388 void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
389 Expr *DefaultArg) {
390 if (!param)
391 return;
393 ParmVarDecl *Param = cast<ParmVarDecl>(param);
394 Param->setInvalidDecl();
395 UnparsedDefaultArgLocs.erase(Param);
396 ExprResult RE;
397 if (DefaultArg) {
398 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
399 Param->getType().getNonReferenceType());
400 } else {
401 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
402 Param->getType().getNonReferenceType());
404 Param->setDefaultArg(RE.get());
407 /// CheckExtraCXXDefaultArguments - Check for any extra default
408 /// arguments in the declarator, which is not a function declaration
409 /// or definition and therefore is not permitted to have default
410 /// arguments. This routine should be invoked for every declarator
411 /// that is not a function declaration or definition.
412 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
413 // C++ [dcl.fct.default]p3
414 // A default argument expression shall be specified only in the
415 // parameter-declaration-clause of a function declaration or in a
416 // template-parameter (14.1). It shall not be specified for a
417 // parameter pack. If it is specified in a
418 // parameter-declaration-clause, it shall not occur within a
419 // declarator or abstract-declarator of a parameter-declaration.
420 bool MightBeFunction = D.isFunctionDeclarationContext();
421 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
422 DeclaratorChunk &chunk = D.getTypeObject(i);
423 if (chunk.Kind == DeclaratorChunk::Function) {
424 if (MightBeFunction) {
425 // This is a function declaration. It can have default arguments, but
426 // keep looking in case its return type is a function type with default
427 // arguments.
428 MightBeFunction = false;
429 continue;
431 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
432 ++argIdx) {
433 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
434 if (Param->hasUnparsedDefaultArg()) {
435 std::unique_ptr<CachedTokens> Toks =
436 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
437 SourceRange SR;
438 if (Toks->size() > 1)
439 SR = SourceRange((*Toks)[1].getLocation(),
440 Toks->back().getLocation());
441 else
442 SR = UnparsedDefaultArgLocs[Param];
443 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
444 << SR;
445 } else if (Param->getDefaultArg()) {
446 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
447 << Param->getDefaultArg()->getSourceRange();
448 Param->setDefaultArg(nullptr);
451 } else if (chunk.Kind != DeclaratorChunk::Paren) {
452 MightBeFunction = false;
457 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
458 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
459 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
463 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
464 /// function, once we already know that they have the same
465 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
466 /// error, false otherwise.
467 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
468 Scope *S) {
469 bool Invalid = false;
471 // The declaration context corresponding to the scope is the semantic
472 // parent, unless this is a local function declaration, in which case
473 // it is that surrounding function.
474 DeclContext *ScopeDC = New->isLocalExternDecl()
475 ? New->getLexicalDeclContext()
476 : New->getDeclContext();
478 // Find the previous declaration for the purpose of default arguments.
479 FunctionDecl *PrevForDefaultArgs = Old;
480 for (/**/; PrevForDefaultArgs;
481 // Don't bother looking back past the latest decl if this is a local
482 // extern declaration; nothing else could work.
483 PrevForDefaultArgs = New->isLocalExternDecl()
484 ? nullptr
485 : PrevForDefaultArgs->getPreviousDecl()) {
486 // Ignore hidden declarations.
487 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
488 continue;
490 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
491 !New->isCXXClassMember()) {
492 // Ignore default arguments of old decl if they are not in
493 // the same scope and this is not an out-of-line definition of
494 // a member function.
495 continue;
498 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
499 // If only one of these is a local function declaration, then they are
500 // declared in different scopes, even though isDeclInScope may think
501 // they're in the same scope. (If both are local, the scope check is
502 // sufficient, and if neither is local, then they are in the same scope.)
503 continue;
506 // We found the right previous declaration.
507 break;
510 // C++ [dcl.fct.default]p4:
511 // For non-template functions, default arguments can be added in
512 // later declarations of a function in the same
513 // scope. Declarations in different scopes have completely
514 // distinct sets of default arguments. That is, declarations in
515 // inner scopes do not acquire default arguments from
516 // declarations in outer scopes, and vice versa. In a given
517 // function declaration, all parameters subsequent to a
518 // parameter with a default argument shall have default
519 // arguments supplied in this or previous declarations. A
520 // default argument shall not be redefined by a later
521 // declaration (not even to the same value).
523 // C++ [dcl.fct.default]p6:
524 // Except for member functions of class templates, the default arguments
525 // in a member function definition that appears outside of the class
526 // definition are added to the set of default arguments provided by the
527 // member function declaration in the class definition.
528 for (unsigned p = 0, NumParams = PrevForDefaultArgs
529 ? PrevForDefaultArgs->getNumParams()
530 : 0;
531 p < NumParams; ++p) {
532 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
533 ParmVarDecl *NewParam = New->getParamDecl(p);
535 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
536 bool NewParamHasDfl = NewParam->hasDefaultArg();
538 if (OldParamHasDfl && NewParamHasDfl) {
539 unsigned DiagDefaultParamID =
540 diag::err_param_default_argument_redefinition;
542 // MSVC accepts that default parameters be redefined for member functions
543 // of template class. The new default parameter's value is ignored.
544 Invalid = true;
545 if (getLangOpts().MicrosoftExt) {
546 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
547 if (MD && MD->getParent()->getDescribedClassTemplate()) {
548 // Merge the old default argument into the new parameter.
549 NewParam->setHasInheritedDefaultArg();
550 if (OldParam->hasUninstantiatedDefaultArg())
551 NewParam->setUninstantiatedDefaultArg(
552 OldParam->getUninstantiatedDefaultArg());
553 else
554 NewParam->setDefaultArg(OldParam->getInit());
555 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
556 Invalid = false;
560 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
561 // hint here. Alternatively, we could walk the type-source information
562 // for NewParam to find the last source location in the type... but it
563 // isn't worth the effort right now. This is the kind of test case that
564 // is hard to get right:
565 // int f(int);
566 // void g(int (*fp)(int) = f);
567 // void g(int (*fp)(int) = &f);
568 Diag(NewParam->getLocation(), DiagDefaultParamID)
569 << NewParam->getDefaultArgRange();
571 // Look for the function declaration where the default argument was
572 // actually written, which may be a declaration prior to Old.
573 for (auto Older = PrevForDefaultArgs;
574 OldParam->hasInheritedDefaultArg(); /**/) {
575 Older = Older->getPreviousDecl();
576 OldParam = Older->getParamDecl(p);
579 Diag(OldParam->getLocation(), diag::note_previous_definition)
580 << OldParam->getDefaultArgRange();
581 } else if (OldParamHasDfl) {
582 // Merge the old default argument into the new parameter unless the new
583 // function is a friend declaration in a template class. In the latter
584 // case the default arguments will be inherited when the friend
585 // declaration will be instantiated.
586 if (New->getFriendObjectKind() == Decl::FOK_None ||
587 !New->getLexicalDeclContext()->isDependentContext()) {
588 // It's important to use getInit() here; getDefaultArg()
589 // strips off any top-level ExprWithCleanups.
590 NewParam->setHasInheritedDefaultArg();
591 if (OldParam->hasUnparsedDefaultArg())
592 NewParam->setUnparsedDefaultArg();
593 else if (OldParam->hasUninstantiatedDefaultArg())
594 NewParam->setUninstantiatedDefaultArg(
595 OldParam->getUninstantiatedDefaultArg());
596 else
597 NewParam->setDefaultArg(OldParam->getInit());
599 } else if (NewParamHasDfl) {
600 if (New->getDescribedFunctionTemplate()) {
601 // Paragraph 4, quoted above, only applies to non-template functions.
602 Diag(NewParam->getLocation(),
603 diag::err_param_default_argument_template_redecl)
604 << NewParam->getDefaultArgRange();
605 Diag(PrevForDefaultArgs->getLocation(),
606 diag::note_template_prev_declaration)
607 << false;
608 } else if (New->getTemplateSpecializationKind()
609 != TSK_ImplicitInstantiation &&
610 New->getTemplateSpecializationKind() != TSK_Undeclared) {
611 // C++ [temp.expr.spec]p21:
612 // Default function arguments shall not be specified in a declaration
613 // or a definition for one of the following explicit specializations:
614 // - the explicit specialization of a function template;
615 // - the explicit specialization of a member function template;
616 // - the explicit specialization of a member function of a class
617 // template where the class template specialization to which the
618 // member function specialization belongs is implicitly
619 // instantiated.
620 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
621 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
622 << New->getDeclName()
623 << NewParam->getDefaultArgRange();
624 } else if (New->getDeclContext()->isDependentContext()) {
625 // C++ [dcl.fct.default]p6 (DR217):
626 // Default arguments for a member function of a class template shall
627 // be specified on the initial declaration of the member function
628 // within the class template.
630 // Reading the tea leaves a bit in DR217 and its reference to DR205
631 // leads me to the conclusion that one cannot add default function
632 // arguments for an out-of-line definition of a member function of a
633 // dependent type.
634 int WhichKind = 2;
635 if (CXXRecordDecl *Record
636 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
637 if (Record->getDescribedClassTemplate())
638 WhichKind = 0;
639 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
640 WhichKind = 1;
641 else
642 WhichKind = 2;
645 Diag(NewParam->getLocation(),
646 diag::err_param_default_argument_member_template_redecl)
647 << WhichKind
648 << NewParam->getDefaultArgRange();
653 // DR1344: If a default argument is added outside a class definition and that
654 // default argument makes the function a special member function, the program
655 // is ill-formed. This can only happen for constructors.
656 if (isa<CXXConstructorDecl>(New) &&
657 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
658 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
659 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
660 if (NewSM != OldSM) {
661 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
662 assert(NewParam->hasDefaultArg());
663 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
664 << NewParam->getDefaultArgRange() << NewSM;
665 Diag(Old->getLocation(), diag::note_previous_declaration);
669 const FunctionDecl *Def;
670 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
671 // template has a constexpr specifier then all its declarations shall
672 // contain the constexpr specifier.
673 if (New->getConstexprKind() != Old->getConstexprKind()) {
674 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
675 << New << static_cast<int>(New->getConstexprKind())
676 << static_cast<int>(Old->getConstexprKind());
677 Diag(Old->getLocation(), diag::note_previous_declaration);
678 Invalid = true;
679 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
680 Old->isDefined(Def) &&
681 // If a friend function is inlined but does not have 'inline'
682 // specifier, it is a definition. Do not report attribute conflict
683 // in this case, redefinition will be diagnosed later.
684 (New->isInlineSpecified() ||
685 New->getFriendObjectKind() == Decl::FOK_None)) {
686 // C++11 [dcl.fcn.spec]p4:
687 // If the definition of a function appears in a translation unit before its
688 // first declaration as inline, the program is ill-formed.
689 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
690 Diag(Def->getLocation(), diag::note_previous_definition);
691 Invalid = true;
694 // C++17 [temp.deduct.guide]p3:
695 // Two deduction guide declarations in the same translation unit
696 // for the same class template shall not have equivalent
697 // parameter-declaration-clauses.
698 if (isa<CXXDeductionGuideDecl>(New) &&
699 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
700 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
701 Diag(Old->getLocation(), diag::note_previous_declaration);
704 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
705 // argument expression, that declaration shall be a definition and shall be
706 // the only declaration of the function or function template in the
707 // translation unit.
708 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
709 functionDeclHasDefaultArgument(Old)) {
710 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
711 Diag(Old->getLocation(), diag::note_previous_declaration);
712 Invalid = true;
715 // C++11 [temp.friend]p4 (DR329):
716 // When a function is defined in a friend function declaration in a class
717 // template, the function is instantiated when the function is odr-used.
718 // The same restrictions on multiple declarations and definitions that
719 // apply to non-template function declarations and definitions also apply
720 // to these implicit definitions.
721 const FunctionDecl *OldDefinition = nullptr;
722 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
723 Old->isDefined(OldDefinition, true))
724 CheckForFunctionRedefinition(New, OldDefinition);
726 return Invalid;
729 void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
730 Diag(Loc, getLangOpts().CPlusPlus26
731 ? diag::warn_cxx23_placeholder_var_definition
732 : diag::ext_placeholder_var_definition);
735 NamedDecl *
736 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
737 MultiTemplateParamsArg TemplateParamLists) {
738 assert(D.isDecompositionDeclarator());
739 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
741 // The syntax only allows a decomposition declarator as a simple-declaration,
742 // a for-range-declaration, or a condition in Clang, but we parse it in more
743 // cases than that.
744 if (!D.mayHaveDecompositionDeclarator()) {
745 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
746 << Decomp.getSourceRange();
747 return nullptr;
750 if (!TemplateParamLists.empty()) {
751 // FIXME: There's no rule against this, but there are also no rules that
752 // would actually make it usable, so we reject it for now.
753 Diag(TemplateParamLists.front()->getTemplateLoc(),
754 diag::err_decomp_decl_template);
755 return nullptr;
758 Diag(Decomp.getLSquareLoc(),
759 !getLangOpts().CPlusPlus17
760 ? diag::ext_decomp_decl
761 : D.getContext() == DeclaratorContext::Condition
762 ? diag::ext_decomp_decl_cond
763 : diag::warn_cxx14_compat_decomp_decl)
764 << Decomp.getSourceRange();
766 // The semantic context is always just the current context.
767 DeclContext *const DC = CurContext;
769 // C++17 [dcl.dcl]/8:
770 // The decl-specifier-seq shall contain only the type-specifier auto
771 // and cv-qualifiers.
772 // C++20 [dcl.dcl]/8:
773 // If decl-specifier-seq contains any decl-specifier other than static,
774 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
775 // C++23 [dcl.pre]/6:
776 // Each decl-specifier in the decl-specifier-seq shall be static,
777 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
778 auto &DS = D.getDeclSpec();
780 // Note: While constrained-auto needs to be checked, we do so separately so
781 // we can emit a better diagnostic.
782 SmallVector<StringRef, 8> BadSpecifiers;
783 SmallVector<SourceLocation, 8> BadSpecifierLocs;
784 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
785 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
786 if (auto SCS = DS.getStorageClassSpec()) {
787 if (SCS == DeclSpec::SCS_static) {
788 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
789 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
790 } else {
791 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
792 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
795 if (auto TSCS = DS.getThreadStorageClassSpec()) {
796 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
797 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
799 if (DS.hasConstexprSpecifier()) {
800 BadSpecifiers.push_back(
801 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
802 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
804 if (DS.isInlineSpecified()) {
805 BadSpecifiers.push_back("inline");
806 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
809 if (!BadSpecifiers.empty()) {
810 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
811 Err << (int)BadSpecifiers.size()
812 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
813 // Don't add FixItHints to remove the specifiers; we do still respect
814 // them when building the underlying variable.
815 for (auto Loc : BadSpecifierLocs)
816 Err << SourceRange(Loc, Loc);
817 } else if (!CPlusPlus20Specifiers.empty()) {
818 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
819 getLangOpts().CPlusPlus20
820 ? diag::warn_cxx17_compat_decomp_decl_spec
821 : diag::ext_decomp_decl_spec);
822 Warn << (int)CPlusPlus20Specifiers.size()
823 << llvm::join(CPlusPlus20Specifiers.begin(),
824 CPlusPlus20Specifiers.end(), " ");
825 for (auto Loc : CPlusPlus20SpecifierLocs)
826 Warn << SourceRange(Loc, Loc);
828 // We can't recover from it being declared as a typedef.
829 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
830 return nullptr;
833 // C++2a [dcl.struct.bind]p1:
834 // A cv that includes volatile is deprecated
835 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
836 getLangOpts().CPlusPlus20)
837 Diag(DS.getVolatileSpecLoc(),
838 diag::warn_deprecated_volatile_structured_binding);
840 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
841 QualType R = TInfo->getType();
843 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
844 UPPC_DeclarationType))
845 D.setInvalidType();
847 // The syntax only allows a single ref-qualifier prior to the decomposition
848 // declarator. No other declarator chunks are permitted. Also check the type
849 // specifier here.
850 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
851 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
852 (D.getNumTypeObjects() == 1 &&
853 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
854 Diag(Decomp.getLSquareLoc(),
855 (D.hasGroupingParens() ||
856 (D.getNumTypeObjects() &&
857 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
858 ? diag::err_decomp_decl_parens
859 : diag::err_decomp_decl_type)
860 << R;
862 // In most cases, there's no actual problem with an explicitly-specified
863 // type, but a function type won't work here, and ActOnVariableDeclarator
864 // shouldn't be called for such a type.
865 if (R->isFunctionType())
866 D.setInvalidType();
869 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
870 if (DS.isConstrainedAuto()) {
871 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
872 assert(TemplRep->Kind == TNK_Concept_template &&
873 "No other template kind should be possible for a constrained auto");
875 SourceRange TemplRange{TemplRep->TemplateNameLoc,
876 TemplRep->RAngleLoc.isValid()
877 ? TemplRep->RAngleLoc
878 : TemplRep->TemplateNameLoc};
879 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
880 << TemplRange << FixItHint::CreateRemoval(TemplRange);
883 // Build the BindingDecls.
884 SmallVector<BindingDecl*, 8> Bindings;
886 // Build the BindingDecls.
887 for (auto &B : D.getDecompositionDeclarator().bindings()) {
888 // Check for name conflicts.
889 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
890 IdentifierInfo *VarName = B.Name;
891 assert(VarName && "Cannot have an unnamed binding declaration");
893 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
894 ForVisibleRedeclaration);
895 LookupName(Previous, S,
896 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
898 // It's not permitted to shadow a template parameter name.
899 if (Previous.isSingleResult() &&
900 Previous.getFoundDecl()->isTemplateParameter()) {
901 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
902 Previous.getFoundDecl());
903 Previous.clear();
906 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
908 // Find the shadowed declaration before filtering for scope.
909 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
910 ? getShadowedDeclaration(BD, Previous)
911 : nullptr;
913 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
914 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
915 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
916 /*AllowInlineNamespace*/false);
918 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
919 DC->isFunctionOrMethod() && VarName->isPlaceholder();
920 if (!Previous.empty()) {
921 if (IsPlaceholder) {
922 bool sameDC = (Previous.end() - 1)
923 ->getDeclContext()
924 ->getRedeclContext()
925 ->Equals(DC->getRedeclContext());
926 if (sameDC &&
927 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
928 Previous.clear();
929 DiagPlaceholderVariableDefinition(B.NameLoc);
931 } else {
932 auto *Old = Previous.getRepresentativeDecl();
933 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
934 Diag(Old->getLocation(), diag::note_previous_definition);
936 } else if (ShadowedDecl && !D.isRedeclaration()) {
937 CheckShadow(BD, ShadowedDecl, Previous);
939 PushOnScopeChains(BD, S, true);
940 Bindings.push_back(BD);
941 ParsingInitForAutoVars.insert(BD);
944 // There are no prior lookup results for the variable itself, because it
945 // is unnamed.
946 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
947 Decomp.getLSquareLoc());
948 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
949 ForVisibleRedeclaration);
951 // Build the variable that holds the non-decomposed object.
952 bool AddToScope = true;
953 NamedDecl *New =
954 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
955 MultiTemplateParamsArg(), AddToScope, Bindings);
956 if (AddToScope) {
957 S->AddDecl(New);
958 CurContext->addHiddenDecl(New);
961 if (isInOpenMPDeclareTargetContext())
962 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
964 return New;
967 static bool checkSimpleDecomposition(
968 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
969 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
970 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
971 if ((int64_t)Bindings.size() != NumElems) {
972 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
973 << DecompType << (unsigned)Bindings.size()
974 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
975 << toString(NumElems, 10) << (NumElems < Bindings.size());
976 return true;
979 unsigned I = 0;
980 for (auto *B : Bindings) {
981 SourceLocation Loc = B->getLocation();
982 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
983 if (E.isInvalid())
984 return true;
985 E = GetInit(Loc, E.get(), I++);
986 if (E.isInvalid())
987 return true;
988 B->setBinding(ElemType, E.get());
991 return false;
994 static bool checkArrayLikeDecomposition(Sema &S,
995 ArrayRef<BindingDecl *> Bindings,
996 ValueDecl *Src, QualType DecompType,
997 const llvm::APSInt &NumElems,
998 QualType ElemType) {
999 return checkSimpleDecomposition(
1000 S, Bindings, Src, DecompType, NumElems, ElemType,
1001 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1002 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1003 if (E.isInvalid())
1004 return ExprError();
1005 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1009 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1010 ValueDecl *Src, QualType DecompType,
1011 const ConstantArrayType *CAT) {
1012 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1013 llvm::APSInt(CAT->getSize()),
1014 CAT->getElementType());
1017 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1018 ValueDecl *Src, QualType DecompType,
1019 const VectorType *VT) {
1020 return checkArrayLikeDecomposition(
1021 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1022 S.Context.getQualifiedType(VT->getElementType(),
1023 DecompType.getQualifiers()));
1026 static bool checkComplexDecomposition(Sema &S,
1027 ArrayRef<BindingDecl *> Bindings,
1028 ValueDecl *Src, QualType DecompType,
1029 const ComplexType *CT) {
1030 return checkSimpleDecomposition(
1031 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1032 S.Context.getQualifiedType(CT->getElementType(),
1033 DecompType.getQualifiers()),
1034 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1035 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1039 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1040 TemplateArgumentListInfo &Args,
1041 const TemplateParameterList *Params) {
1042 SmallString<128> SS;
1043 llvm::raw_svector_ostream OS(SS);
1044 bool First = true;
1045 unsigned I = 0;
1046 for (auto &Arg : Args.arguments()) {
1047 if (!First)
1048 OS << ", ";
1049 Arg.getArgument().print(PrintingPolicy, OS,
1050 TemplateParameterList::shouldIncludeTypeForArgument(
1051 PrintingPolicy, Params, I));
1052 First = false;
1053 I++;
1055 return std::string(OS.str());
1058 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1059 SourceLocation Loc, StringRef Trait,
1060 TemplateArgumentListInfo &Args,
1061 unsigned DiagID) {
1062 auto DiagnoseMissing = [&] {
1063 if (DiagID)
1064 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1065 Args, /*Params*/ nullptr);
1066 return true;
1069 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1070 NamespaceDecl *Std = S.getStdNamespace();
1071 if (!Std)
1072 return DiagnoseMissing();
1074 // Look up the trait itself, within namespace std. We can diagnose various
1075 // problems with this lookup even if we've been asked to not diagnose a
1076 // missing specialization, because this can only fail if the user has been
1077 // declaring their own names in namespace std or we don't support the
1078 // standard library implementation in use.
1079 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1080 Loc, Sema::LookupOrdinaryName);
1081 if (!S.LookupQualifiedName(Result, Std))
1082 return DiagnoseMissing();
1083 if (Result.isAmbiguous())
1084 return true;
1086 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1087 if (!TraitTD) {
1088 Result.suppressDiagnostics();
1089 NamedDecl *Found = *Result.begin();
1090 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1091 S.Diag(Found->getLocation(), diag::note_declared_at);
1092 return true;
1095 // Build the template-id.
1096 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1097 if (TraitTy.isNull())
1098 return true;
1099 if (!S.isCompleteType(Loc, TraitTy)) {
1100 if (DiagID)
1101 S.RequireCompleteType(
1102 Loc, TraitTy, DiagID,
1103 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1104 TraitTD->getTemplateParameters()));
1105 return true;
1108 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1109 assert(RD && "specialization of class template is not a class?");
1111 // Look up the member of the trait type.
1112 S.LookupQualifiedName(TraitMemberLookup, RD);
1113 return TraitMemberLookup.isAmbiguous();
1116 static TemplateArgumentLoc
1117 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1118 uint64_t I) {
1119 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1120 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1123 static TemplateArgumentLoc
1124 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1125 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1128 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1130 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1131 llvm::APSInt &Size) {
1132 EnterExpressionEvaluationContext ContextRAII(
1133 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1135 DeclarationName Value = S.PP.getIdentifierInfo("value");
1136 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1138 // Form template argument list for tuple_size<T>.
1139 TemplateArgumentListInfo Args(Loc, Loc);
1140 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1142 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1143 // it's not tuple-like.
1144 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1145 R.empty())
1146 return IsTupleLike::NotTupleLike;
1148 // If we get this far, we've committed to the tuple interpretation, but
1149 // we can still fail if there actually isn't a usable ::value.
1151 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1152 LookupResult &R;
1153 TemplateArgumentListInfo &Args;
1154 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1155 : R(R), Args(Args) {}
1156 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1157 SourceLocation Loc) override {
1158 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1159 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1160 /*Params*/ nullptr);
1162 } Diagnoser(R, Args);
1164 ExprResult E =
1165 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1166 if (E.isInvalid())
1167 return IsTupleLike::Error;
1169 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1170 if (E.isInvalid())
1171 return IsTupleLike::Error;
1173 return IsTupleLike::TupleLike;
1176 /// \return std::tuple_element<I, T>::type.
1177 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1178 unsigned I, QualType T) {
1179 // Form template argument list for tuple_element<I, T>.
1180 TemplateArgumentListInfo Args(Loc, Loc);
1181 Args.addArgument(
1182 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1183 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1185 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1186 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1187 if (lookupStdTypeTraitMember(
1188 S, R, Loc, "tuple_element", Args,
1189 diag::err_decomp_decl_std_tuple_element_not_specialized))
1190 return QualType();
1192 auto *TD = R.getAsSingle<TypeDecl>();
1193 if (!TD) {
1194 R.suppressDiagnostics();
1195 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1196 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1197 /*Params*/ nullptr);
1198 if (!R.empty())
1199 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1200 return QualType();
1203 return S.Context.getTypeDeclType(TD);
1206 namespace {
1207 struct InitializingBinding {
1208 Sema &S;
1209 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1210 Sema::CodeSynthesisContext Ctx;
1211 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1212 Ctx.PointOfInstantiation = BD->getLocation();
1213 Ctx.Entity = BD;
1214 S.pushCodeSynthesisContext(Ctx);
1216 ~InitializingBinding() {
1217 S.popCodeSynthesisContext();
1222 static bool checkTupleLikeDecomposition(Sema &S,
1223 ArrayRef<BindingDecl *> Bindings,
1224 VarDecl *Src, QualType DecompType,
1225 const llvm::APSInt &TupleSize) {
1226 if ((int64_t)Bindings.size() != TupleSize) {
1227 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1228 << DecompType << (unsigned)Bindings.size()
1229 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1230 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1231 return true;
1234 if (Bindings.empty())
1235 return false;
1237 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1239 // [dcl.decomp]p3:
1240 // The unqualified-id get is looked up in the scope of E by class member
1241 // access lookup ...
1242 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1243 bool UseMemberGet = false;
1244 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1245 if (auto *RD = DecompType->getAsCXXRecordDecl())
1246 S.LookupQualifiedName(MemberGet, RD);
1247 if (MemberGet.isAmbiguous())
1248 return true;
1249 // ... and if that finds at least one declaration that is a function
1250 // template whose first template parameter is a non-type parameter ...
1251 for (NamedDecl *D : MemberGet) {
1252 if (FunctionTemplateDecl *FTD =
1253 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1254 TemplateParameterList *TPL = FTD->getTemplateParameters();
1255 if (TPL->size() != 0 &&
1256 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1257 // ... the initializer is e.get<i>().
1258 UseMemberGet = true;
1259 break;
1265 unsigned I = 0;
1266 for (auto *B : Bindings) {
1267 InitializingBinding InitContext(S, B);
1268 SourceLocation Loc = B->getLocation();
1270 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1271 if (E.isInvalid())
1272 return true;
1274 // e is an lvalue if the type of the entity is an lvalue reference and
1275 // an xvalue otherwise
1276 if (!Src->getType()->isLValueReferenceType())
1277 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1278 E.get(), nullptr, VK_XValue,
1279 FPOptionsOverride());
1281 TemplateArgumentListInfo Args(Loc, Loc);
1282 Args.addArgument(
1283 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1285 if (UseMemberGet) {
1286 // if [lookup of member get] finds at least one declaration, the
1287 // initializer is e.get<i-1>().
1288 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1289 CXXScopeSpec(), SourceLocation(), nullptr,
1290 MemberGet, &Args, nullptr);
1291 if (E.isInvalid())
1292 return true;
1294 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1295 } else {
1296 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1297 // in the associated namespaces.
1298 Expr *Get = UnresolvedLookupExpr::Create(
1299 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1300 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1301 UnresolvedSetIterator(), UnresolvedSetIterator());
1303 Expr *Arg = E.get();
1304 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1306 if (E.isInvalid())
1307 return true;
1308 Expr *Init = E.get();
1310 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1311 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1312 if (T.isNull())
1313 return true;
1315 // each vi is a variable of type "reference to T" initialized with the
1316 // initializer, where the reference is an lvalue reference if the
1317 // initializer is an lvalue and an rvalue reference otherwise
1318 QualType RefType =
1319 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1320 if (RefType.isNull())
1321 return true;
1322 auto *RefVD = VarDecl::Create(
1323 S.Context, Src->getDeclContext(), Loc, Loc,
1324 B->getDeclName().getAsIdentifierInfo(), RefType,
1325 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1326 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1327 RefVD->setTSCSpec(Src->getTSCSpec());
1328 RefVD->setImplicit();
1329 if (Src->isInlineSpecified())
1330 RefVD->setInlineSpecified();
1331 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1333 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1334 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1335 InitializationSequence Seq(S, Entity, Kind, Init);
1336 E = Seq.Perform(S, Entity, Kind, Init);
1337 if (E.isInvalid())
1338 return true;
1339 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1340 if (E.isInvalid())
1341 return true;
1342 RefVD->setInit(E.get());
1343 S.CheckCompleteVariableDeclaration(RefVD);
1345 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1346 DeclarationNameInfo(B->getDeclName(), Loc),
1347 RefVD);
1348 if (E.isInvalid())
1349 return true;
1351 B->setBinding(T, E.get());
1352 I++;
1355 return false;
1358 /// Find the base class to decompose in a built-in decomposition of a class type.
1359 /// This base class search is, unfortunately, not quite like any other that we
1360 /// perform anywhere else in C++.
1361 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1362 const CXXRecordDecl *RD,
1363 CXXCastPath &BasePath) {
1364 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1365 CXXBasePath &Path) {
1366 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1369 const CXXRecordDecl *ClassWithFields = nullptr;
1370 AccessSpecifier AS = AS_public;
1371 if (RD->hasDirectFields())
1372 // [dcl.decomp]p4:
1373 // Otherwise, all of E's non-static data members shall be public direct
1374 // members of E ...
1375 ClassWithFields = RD;
1376 else {
1377 // ... or of ...
1378 CXXBasePaths Paths;
1379 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1380 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1381 // If no classes have fields, just decompose RD itself. (This will work
1382 // if and only if zero bindings were provided.)
1383 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1386 CXXBasePath *BestPath = nullptr;
1387 for (auto &P : Paths) {
1388 if (!BestPath)
1389 BestPath = &P;
1390 else if (!S.Context.hasSameType(P.back().Base->getType(),
1391 BestPath->back().Base->getType())) {
1392 // ... the same ...
1393 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1394 << false << RD << BestPath->back().Base->getType()
1395 << P.back().Base->getType();
1396 return DeclAccessPair();
1397 } else if (P.Access < BestPath->Access) {
1398 BestPath = &P;
1402 // ... unambiguous ...
1403 QualType BaseType = BestPath->back().Base->getType();
1404 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1405 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1406 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1407 return DeclAccessPair();
1410 // ... [accessible, implied by other rules] base class of E.
1411 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1412 *BestPath, diag::err_decomp_decl_inaccessible_base);
1413 AS = BestPath->Access;
1415 ClassWithFields = BaseType->getAsCXXRecordDecl();
1416 S.BuildBasePathArray(Paths, BasePath);
1419 // The above search did not check whether the selected class itself has base
1420 // classes with fields, so check that now.
1421 CXXBasePaths Paths;
1422 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1423 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1424 << (ClassWithFields == RD) << RD << ClassWithFields
1425 << Paths.front().back().Base->getType();
1426 return DeclAccessPair();
1429 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1432 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1433 ValueDecl *Src, QualType DecompType,
1434 const CXXRecordDecl *OrigRD) {
1435 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1436 diag::err_incomplete_type))
1437 return true;
1439 CXXCastPath BasePath;
1440 DeclAccessPair BasePair =
1441 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1442 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1443 if (!RD)
1444 return true;
1445 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1446 DecompType.getQualifiers());
1448 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1449 unsigned NumFields = llvm::count_if(
1450 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1451 assert(Bindings.size() != NumFields);
1452 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1453 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1454 << (NumFields < Bindings.size());
1455 return true;
1458 // all of E's non-static data members shall be [...] well-formed
1459 // when named as e.name in the context of the structured binding,
1460 // E shall not have an anonymous union member, ...
1461 unsigned I = 0;
1462 for (auto *FD : RD->fields()) {
1463 if (FD->isUnnamedBitfield())
1464 continue;
1466 // All the non-static data members are required to be nameable, so they
1467 // must all have names.
1468 if (!FD->getDeclName()) {
1469 if (RD->isLambda()) {
1470 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1471 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1472 return true;
1475 if (FD->isAnonymousStructOrUnion()) {
1476 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1477 << DecompType << FD->getType()->isUnionType();
1478 S.Diag(FD->getLocation(), diag::note_declared_at);
1479 return true;
1482 // FIXME: Are there any other ways we could have an anonymous member?
1485 // We have a real field to bind.
1486 if (I >= Bindings.size())
1487 return DiagnoseBadNumberOfBindings();
1488 auto *B = Bindings[I++];
1489 SourceLocation Loc = B->getLocation();
1491 // The field must be accessible in the context of the structured binding.
1492 // We already checked that the base class is accessible.
1493 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1494 // const_cast here.
1495 S.CheckStructuredBindingMemberAccess(
1496 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1497 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1498 BasePair.getAccess(), FD->getAccess())));
1500 // Initialize the binding to Src.FD.
1501 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1502 if (E.isInvalid())
1503 return true;
1504 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1505 VK_LValue, &BasePath);
1506 if (E.isInvalid())
1507 return true;
1508 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1509 CXXScopeSpec(), FD,
1510 DeclAccessPair::make(FD, FD->getAccess()),
1511 DeclarationNameInfo(FD->getDeclName(), Loc));
1512 if (E.isInvalid())
1513 return true;
1515 // If the type of the member is T, the referenced type is cv T, where cv is
1516 // the cv-qualification of the decomposition expression.
1518 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1519 // 'const' to the type of the field.
1520 Qualifiers Q = DecompType.getQualifiers();
1521 if (FD->isMutable())
1522 Q.removeConst();
1523 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1526 if (I != Bindings.size())
1527 return DiagnoseBadNumberOfBindings();
1529 return false;
1532 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1533 QualType DecompType = DD->getType();
1535 // If the type of the decomposition is dependent, then so is the type of
1536 // each binding.
1537 if (DecompType->isDependentType()) {
1538 for (auto *B : DD->bindings())
1539 B->setType(Context.DependentTy);
1540 return;
1543 DecompType = DecompType.getNonReferenceType();
1544 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1546 // C++1z [dcl.decomp]/2:
1547 // If E is an array type [...]
1548 // As an extension, we also support decomposition of built-in complex and
1549 // vector types.
1550 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1551 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1552 DD->setInvalidDecl();
1553 return;
1555 if (auto *VT = DecompType->getAs<VectorType>()) {
1556 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1557 DD->setInvalidDecl();
1558 return;
1560 if (auto *CT = DecompType->getAs<ComplexType>()) {
1561 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1562 DD->setInvalidDecl();
1563 return;
1566 // C++1z [dcl.decomp]/3:
1567 // if the expression std::tuple_size<E>::value is a well-formed integral
1568 // constant expression, [...]
1569 llvm::APSInt TupleSize(32);
1570 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1571 case IsTupleLike::Error:
1572 DD->setInvalidDecl();
1573 return;
1575 case IsTupleLike::TupleLike:
1576 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1577 DD->setInvalidDecl();
1578 return;
1580 case IsTupleLike::NotTupleLike:
1581 break;
1584 // C++1z [dcl.dcl]/8:
1585 // [E shall be of array or non-union class type]
1586 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1587 if (!RD || RD->isUnion()) {
1588 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1589 << DD << !RD << DecompType;
1590 DD->setInvalidDecl();
1591 return;
1594 // C++1z [dcl.decomp]/4:
1595 // all of E's non-static data members shall be [...] direct members of
1596 // E or of the same unambiguous public base class of E, ...
1597 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1598 DD->setInvalidDecl();
1601 /// Merge the exception specifications of two variable declarations.
1603 /// This is called when there's a redeclaration of a VarDecl. The function
1604 /// checks if the redeclaration might have an exception specification and
1605 /// validates compatibility and merges the specs if necessary.
1606 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1607 // Shortcut if exceptions are disabled.
1608 if (!getLangOpts().CXXExceptions)
1609 return;
1611 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1612 "Should only be called if types are otherwise the same.");
1614 QualType NewType = New->getType();
1615 QualType OldType = Old->getType();
1617 // We're only interested in pointers and references to functions, as well
1618 // as pointers to member functions.
1619 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1620 NewType = R->getPointeeType();
1621 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1622 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1623 NewType = P->getPointeeType();
1624 OldType = OldType->castAs<PointerType>()->getPointeeType();
1625 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1626 NewType = M->getPointeeType();
1627 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1630 if (!NewType->isFunctionProtoType())
1631 return;
1633 // There's lots of special cases for functions. For function pointers, system
1634 // libraries are hopefully not as broken so that we don't need these
1635 // workarounds.
1636 if (CheckEquivalentExceptionSpec(
1637 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1638 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1639 New->setInvalidDecl();
1643 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1644 /// function declaration are well-formed according to C++
1645 /// [dcl.fct.default].
1646 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1647 unsigned NumParams = FD->getNumParams();
1648 unsigned ParamIdx = 0;
1650 // This checking doesn't make sense for explicit specializations; their
1651 // default arguments are determined by the declaration we're specializing,
1652 // not by FD.
1653 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1654 return;
1655 if (auto *FTD = FD->getDescribedFunctionTemplate())
1656 if (FTD->isMemberSpecialization())
1657 return;
1659 // Find first parameter with a default argument
1660 for (; ParamIdx < NumParams; ++ParamIdx) {
1661 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1662 if (Param->hasDefaultArg())
1663 break;
1666 // C++20 [dcl.fct.default]p4:
1667 // In a given function declaration, each parameter subsequent to a parameter
1668 // with a default argument shall have a default argument supplied in this or
1669 // a previous declaration, unless the parameter was expanded from a
1670 // parameter pack, or shall be a function parameter pack.
1671 for (; ParamIdx < NumParams; ++ParamIdx) {
1672 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1673 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1674 !(CurrentInstantiationScope &&
1675 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1676 if (Param->isInvalidDecl())
1677 /* We already complained about this parameter. */;
1678 else if (Param->getIdentifier())
1679 Diag(Param->getLocation(),
1680 diag::err_param_default_argument_missing_name)
1681 << Param->getIdentifier();
1682 else
1683 Diag(Param->getLocation(),
1684 diag::err_param_default_argument_missing);
1689 /// Check that the given type is a literal type. Issue a diagnostic if not,
1690 /// if Kind is Diagnose.
1691 /// \return \c true if a problem has been found (and optionally diagnosed).
1692 template <typename... Ts>
1693 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1694 SourceLocation Loc, QualType T, unsigned DiagID,
1695 Ts &&...DiagArgs) {
1696 if (T->isDependentType())
1697 return false;
1699 switch (Kind) {
1700 case Sema::CheckConstexprKind::Diagnose:
1701 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1702 std::forward<Ts>(DiagArgs)...);
1704 case Sema::CheckConstexprKind::CheckValid:
1705 return !T->isLiteralType(SemaRef.Context);
1708 llvm_unreachable("unknown CheckConstexprKind");
1711 /// Determine whether a destructor cannot be constexpr due to
1712 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1713 const CXXDestructorDecl *DD,
1714 Sema::CheckConstexprKind Kind) {
1715 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1716 const CXXRecordDecl *RD =
1717 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1718 if (!RD || RD->hasConstexprDestructor())
1719 return true;
1721 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1722 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1723 << static_cast<int>(DD->getConstexprKind()) << !FD
1724 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1725 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1726 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1728 return false;
1731 const CXXRecordDecl *RD = DD->getParent();
1732 for (const CXXBaseSpecifier &B : RD->bases())
1733 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1734 return false;
1735 for (const FieldDecl *FD : RD->fields())
1736 if (!Check(FD->getLocation(), FD->getType(), FD))
1737 return false;
1738 return true;
1741 /// Check whether a function's parameter types are all literal types. If so,
1742 /// return true. If not, produce a suitable diagnostic and return false.
1743 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1744 const FunctionDecl *FD,
1745 Sema::CheckConstexprKind Kind) {
1746 unsigned ArgIndex = 0;
1747 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1748 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1749 e = FT->param_type_end();
1750 i != e; ++i, ++ArgIndex) {
1751 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1752 assert(PD && "null in a parameter list");
1753 SourceLocation ParamLoc = PD->getLocation();
1754 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1755 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1756 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1757 FD->isConsteval()))
1758 return false;
1760 return true;
1763 /// Check whether a function's return type is a literal type. If so, return
1764 /// true. If not, produce a suitable diagnostic and return false.
1765 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1766 Sema::CheckConstexprKind Kind) {
1767 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1768 diag::err_constexpr_non_literal_return,
1769 FD->isConsteval()))
1770 return false;
1771 return true;
1774 /// Get diagnostic %select index for tag kind for
1775 /// record diagnostic message.
1776 /// WARNING: Indexes apply to particular diagnostics only!
1778 /// \returns diagnostic %select index.
1779 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1780 switch (Tag) {
1781 case TTK_Struct: return 0;
1782 case TTK_Interface: return 1;
1783 case TTK_Class: return 2;
1784 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1788 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1789 Stmt *Body,
1790 Sema::CheckConstexprKind Kind);
1792 // Check whether a function declaration satisfies the requirements of a
1793 // constexpr function definition or a constexpr constructor definition. If so,
1794 // return true. If not, produce appropriate diagnostics (unless asked not to by
1795 // Kind) and return false.
1797 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1798 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1799 CheckConstexprKind Kind) {
1800 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1801 if (MD && MD->isInstance()) {
1802 // C++11 [dcl.constexpr]p4:
1803 // The definition of a constexpr constructor shall satisfy the following
1804 // constraints:
1805 // - the class shall not have any virtual base classes;
1807 // FIXME: This only applies to constructors and destructors, not arbitrary
1808 // member functions.
1809 const CXXRecordDecl *RD = MD->getParent();
1810 if (RD->getNumVBases()) {
1811 if (Kind == CheckConstexprKind::CheckValid)
1812 return false;
1814 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1815 << isa<CXXConstructorDecl>(NewFD)
1816 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1817 for (const auto &I : RD->vbases())
1818 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1819 << I.getSourceRange();
1820 return false;
1824 if (!isa<CXXConstructorDecl>(NewFD)) {
1825 // C++11 [dcl.constexpr]p3:
1826 // The definition of a constexpr function shall satisfy the following
1827 // constraints:
1828 // - it shall not be virtual; (removed in C++20)
1829 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1830 if (Method && Method->isVirtual()) {
1831 if (getLangOpts().CPlusPlus20) {
1832 if (Kind == CheckConstexprKind::Diagnose)
1833 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1834 } else {
1835 if (Kind == CheckConstexprKind::CheckValid)
1836 return false;
1838 Method = Method->getCanonicalDecl();
1839 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1841 // If it's not obvious why this function is virtual, find an overridden
1842 // function which uses the 'virtual' keyword.
1843 const CXXMethodDecl *WrittenVirtual = Method;
1844 while (!WrittenVirtual->isVirtualAsWritten())
1845 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1846 if (WrittenVirtual != Method)
1847 Diag(WrittenVirtual->getLocation(),
1848 diag::note_overridden_virtual_function);
1849 return false;
1853 // - its return type shall be a literal type;
1854 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1855 return false;
1858 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1859 // A destructor can be constexpr only if the defaulted destructor could be;
1860 // we don't need to check the members and bases if we already know they all
1861 // have constexpr destructors.
1862 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1863 if (Kind == CheckConstexprKind::CheckValid)
1864 return false;
1865 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1866 return false;
1870 // - each of its parameter types shall be a literal type;
1871 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1872 return false;
1874 Stmt *Body = NewFD->getBody();
1875 assert(Body &&
1876 "CheckConstexprFunctionDefinition called on function with no body");
1877 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1880 /// Check the given declaration statement is legal within a constexpr function
1881 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1883 /// \return true if the body is OK (maybe only as an extension), false if we
1884 /// have diagnosed a problem.
1885 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1886 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1887 Sema::CheckConstexprKind Kind) {
1888 // C++11 [dcl.constexpr]p3 and p4:
1889 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1890 // contain only
1891 for (const auto *DclIt : DS->decls()) {
1892 switch (DclIt->getKind()) {
1893 case Decl::StaticAssert:
1894 case Decl::Using:
1895 case Decl::UsingShadow:
1896 case Decl::UsingDirective:
1897 case Decl::UnresolvedUsingTypename:
1898 case Decl::UnresolvedUsingValue:
1899 case Decl::UsingEnum:
1900 // - static_assert-declarations
1901 // - using-declarations,
1902 // - using-directives,
1903 // - using-enum-declaration
1904 continue;
1906 case Decl::Typedef:
1907 case Decl::TypeAlias: {
1908 // - typedef declarations and alias-declarations that do not define
1909 // classes or enumerations,
1910 const auto *TN = cast<TypedefNameDecl>(DclIt);
1911 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1912 // Don't allow variably-modified types in constexpr functions.
1913 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1914 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1915 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1916 << TL.getSourceRange() << TL.getType()
1917 << isa<CXXConstructorDecl>(Dcl);
1919 return false;
1921 continue;
1924 case Decl::Enum:
1925 case Decl::CXXRecord:
1926 // C++1y allows types to be defined, not just declared.
1927 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1928 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1929 SemaRef.Diag(DS->getBeginLoc(),
1930 SemaRef.getLangOpts().CPlusPlus14
1931 ? diag::warn_cxx11_compat_constexpr_type_definition
1932 : diag::ext_constexpr_type_definition)
1933 << isa<CXXConstructorDecl>(Dcl);
1934 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1935 return false;
1938 continue;
1940 case Decl::EnumConstant:
1941 case Decl::IndirectField:
1942 case Decl::ParmVar:
1943 // These can only appear with other declarations which are banned in
1944 // C++11 and permitted in C++1y, so ignore them.
1945 continue;
1947 case Decl::Var:
1948 case Decl::Decomposition: {
1949 // C++1y [dcl.constexpr]p3 allows anything except:
1950 // a definition of a variable of non-literal type or of static or
1951 // thread storage duration or [before C++2a] for which no
1952 // initialization is performed.
1953 const auto *VD = cast<VarDecl>(DclIt);
1954 if (VD->isThisDeclarationADefinition()) {
1955 if (VD->isStaticLocal()) {
1956 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1957 SemaRef.Diag(VD->getLocation(),
1958 SemaRef.getLangOpts().CPlusPlus23
1959 ? diag::warn_cxx20_compat_constexpr_var
1960 : diag::ext_constexpr_static_var)
1961 << isa<CXXConstructorDecl>(Dcl)
1962 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1963 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1964 return false;
1967 if (SemaRef.LangOpts.CPlusPlus23) {
1968 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1969 diag::warn_cxx20_compat_constexpr_var,
1970 isa<CXXConstructorDecl>(Dcl),
1971 /*variable of non-literal type*/ 2);
1972 } else if (CheckLiteralType(
1973 SemaRef, Kind, VD->getLocation(), VD->getType(),
1974 diag::err_constexpr_local_var_non_literal_type,
1975 isa<CXXConstructorDecl>(Dcl))) {
1976 return false;
1978 if (!VD->getType()->isDependentType() &&
1979 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1980 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1981 SemaRef.Diag(
1982 VD->getLocation(),
1983 SemaRef.getLangOpts().CPlusPlus20
1984 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1985 : diag::ext_constexpr_local_var_no_init)
1986 << isa<CXXConstructorDecl>(Dcl);
1987 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1988 return false;
1990 continue;
1993 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1994 SemaRef.Diag(VD->getLocation(),
1995 SemaRef.getLangOpts().CPlusPlus14
1996 ? diag::warn_cxx11_compat_constexpr_local_var
1997 : diag::ext_constexpr_local_var)
1998 << isa<CXXConstructorDecl>(Dcl);
1999 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2000 return false;
2002 continue;
2005 case Decl::NamespaceAlias:
2006 case Decl::Function:
2007 // These are disallowed in C++11 and permitted in C++1y. Allow them
2008 // everywhere as an extension.
2009 if (!Cxx1yLoc.isValid())
2010 Cxx1yLoc = DS->getBeginLoc();
2011 continue;
2013 default:
2014 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2015 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2016 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2018 return false;
2022 return true;
2025 /// Check that the given field is initialized within a constexpr constructor.
2027 /// \param Dcl The constexpr constructor being checked.
2028 /// \param Field The field being checked. This may be a member of an anonymous
2029 /// struct or union nested within the class being checked.
2030 /// \param Inits All declarations, including anonymous struct/union members and
2031 /// indirect members, for which any initialization was provided.
2032 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2033 /// multiple notes for different members to the same error.
2034 /// \param Kind Whether we're diagnosing a constructor as written or determining
2035 /// whether the formal requirements are satisfied.
2036 /// \return \c false if we're checking for validity and the constructor does
2037 /// not satisfy the requirements on a constexpr constructor.
2038 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2039 const FunctionDecl *Dcl,
2040 FieldDecl *Field,
2041 llvm::SmallSet<Decl*, 16> &Inits,
2042 bool &Diagnosed,
2043 Sema::CheckConstexprKind Kind) {
2044 // In C++20 onwards, there's nothing to check for validity.
2045 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2046 SemaRef.getLangOpts().CPlusPlus20)
2047 return true;
2049 if (Field->isInvalidDecl())
2050 return true;
2052 if (Field->isUnnamedBitfield())
2053 return true;
2055 // Anonymous unions with no variant members and empty anonymous structs do not
2056 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2057 // indirect fields don't need initializing.
2058 if (Field->isAnonymousStructOrUnion() &&
2059 (Field->getType()->isUnionType()
2060 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2061 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2062 return true;
2064 if (!Inits.count(Field)) {
2065 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2066 if (!Diagnosed) {
2067 SemaRef.Diag(Dcl->getLocation(),
2068 SemaRef.getLangOpts().CPlusPlus20
2069 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2070 : diag::ext_constexpr_ctor_missing_init);
2071 Diagnosed = true;
2073 SemaRef.Diag(Field->getLocation(),
2074 diag::note_constexpr_ctor_missing_init);
2075 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2076 return false;
2078 } else if (Field->isAnonymousStructOrUnion()) {
2079 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2080 for (auto *I : RD->fields())
2081 // If an anonymous union contains an anonymous struct of which any member
2082 // is initialized, all members must be initialized.
2083 if (!RD->isUnion() || Inits.count(I))
2084 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2085 Kind))
2086 return false;
2088 return true;
2091 /// Check the provided statement is allowed in a constexpr function
2092 /// definition.
2093 static bool
2094 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2095 SmallVectorImpl<SourceLocation> &ReturnStmts,
2096 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2097 SourceLocation &Cxx2bLoc,
2098 Sema::CheckConstexprKind Kind) {
2099 // - its function-body shall be [...] a compound-statement that contains only
2100 switch (S->getStmtClass()) {
2101 case Stmt::NullStmtClass:
2102 // - null statements,
2103 return true;
2105 case Stmt::DeclStmtClass:
2106 // - static_assert-declarations
2107 // - using-declarations,
2108 // - using-directives,
2109 // - typedef declarations and alias-declarations that do not define
2110 // classes or enumerations,
2111 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2112 return false;
2113 return true;
2115 case Stmt::ReturnStmtClass:
2116 // - and exactly one return statement;
2117 if (isa<CXXConstructorDecl>(Dcl)) {
2118 // C++1y allows return statements in constexpr constructors.
2119 if (!Cxx1yLoc.isValid())
2120 Cxx1yLoc = S->getBeginLoc();
2121 return true;
2124 ReturnStmts.push_back(S->getBeginLoc());
2125 return true;
2127 case Stmt::AttributedStmtClass:
2128 // Attributes on a statement don't affect its formal kind and hence don't
2129 // affect its validity in a constexpr function.
2130 return CheckConstexprFunctionStmt(
2131 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2132 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2134 case Stmt::CompoundStmtClass: {
2135 // C++1y allows compound-statements.
2136 if (!Cxx1yLoc.isValid())
2137 Cxx1yLoc = S->getBeginLoc();
2139 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2140 for (auto *BodyIt : CompStmt->body()) {
2141 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2142 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2143 return false;
2145 return true;
2148 case Stmt::IfStmtClass: {
2149 // C++1y allows if-statements.
2150 if (!Cxx1yLoc.isValid())
2151 Cxx1yLoc = S->getBeginLoc();
2153 IfStmt *If = cast<IfStmt>(S);
2154 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2155 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2156 return false;
2157 if (If->getElse() &&
2158 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2159 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2160 return false;
2161 return true;
2164 case Stmt::WhileStmtClass:
2165 case Stmt::DoStmtClass:
2166 case Stmt::ForStmtClass:
2167 case Stmt::CXXForRangeStmtClass:
2168 case Stmt::ContinueStmtClass:
2169 // C++1y allows all of these. We don't allow them as extensions in C++11,
2170 // because they don't make sense without variable mutation.
2171 if (!SemaRef.getLangOpts().CPlusPlus14)
2172 break;
2173 if (!Cxx1yLoc.isValid())
2174 Cxx1yLoc = S->getBeginLoc();
2175 for (Stmt *SubStmt : S->children()) {
2176 if (SubStmt &&
2177 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2178 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2179 return false;
2181 return true;
2183 case Stmt::SwitchStmtClass:
2184 case Stmt::CaseStmtClass:
2185 case Stmt::DefaultStmtClass:
2186 case Stmt::BreakStmtClass:
2187 // C++1y allows switch-statements, and since they don't need variable
2188 // mutation, we can reasonably allow them in C++11 as an extension.
2189 if (!Cxx1yLoc.isValid())
2190 Cxx1yLoc = 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;
2197 return true;
2199 case Stmt::LabelStmtClass:
2200 case Stmt::GotoStmtClass:
2201 if (Cxx2bLoc.isInvalid())
2202 Cxx2bLoc = S->getBeginLoc();
2203 for (Stmt *SubStmt : S->children()) {
2204 if (SubStmt &&
2205 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2206 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2207 return false;
2209 return true;
2211 case Stmt::GCCAsmStmtClass:
2212 case Stmt::MSAsmStmtClass:
2213 // C++2a allows inline assembly statements.
2214 case Stmt::CXXTryStmtClass:
2215 if (Cxx2aLoc.isInvalid())
2216 Cxx2aLoc = S->getBeginLoc();
2217 for (Stmt *SubStmt : S->children()) {
2218 if (SubStmt &&
2219 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2220 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2221 return false;
2223 return true;
2225 case Stmt::CXXCatchStmtClass:
2226 // Do not bother checking the language mode (already covered by the
2227 // try block check).
2228 if (!CheckConstexprFunctionStmt(
2229 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2230 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2231 return false;
2232 return true;
2234 default:
2235 if (!isa<Expr>(S))
2236 break;
2238 // C++1y allows expression-statements.
2239 if (!Cxx1yLoc.isValid())
2240 Cxx1yLoc = S->getBeginLoc();
2241 return true;
2244 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2245 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2246 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2248 return false;
2251 /// Check the body for the given constexpr function declaration only contains
2252 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2254 /// \return true if the body is OK, false if we have found or diagnosed a
2255 /// problem.
2256 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2257 Stmt *Body,
2258 Sema::CheckConstexprKind Kind) {
2259 SmallVector<SourceLocation, 4> ReturnStmts;
2261 if (isa<CXXTryStmt>(Body)) {
2262 // C++11 [dcl.constexpr]p3:
2263 // The definition of a constexpr function shall satisfy the following
2264 // constraints: [...]
2265 // - its function-body shall be = delete, = default, or a
2266 // compound-statement
2268 // C++11 [dcl.constexpr]p4:
2269 // In the definition of a constexpr constructor, [...]
2270 // - its function-body shall not be a function-try-block;
2272 // This restriction is lifted in C++2a, as long as inner statements also
2273 // apply the general constexpr rules.
2274 switch (Kind) {
2275 case Sema::CheckConstexprKind::CheckValid:
2276 if (!SemaRef.getLangOpts().CPlusPlus20)
2277 return false;
2278 break;
2280 case Sema::CheckConstexprKind::Diagnose:
2281 SemaRef.Diag(Body->getBeginLoc(),
2282 !SemaRef.getLangOpts().CPlusPlus20
2283 ? diag::ext_constexpr_function_try_block_cxx20
2284 : diag::warn_cxx17_compat_constexpr_function_try_block)
2285 << isa<CXXConstructorDecl>(Dcl);
2286 break;
2290 // - its function-body shall be [...] a compound-statement that contains only
2291 // [... list of cases ...]
2293 // Note that walking the children here is enough to properly check for
2294 // CompoundStmt and CXXTryStmt body.
2295 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2296 for (Stmt *SubStmt : Body->children()) {
2297 if (SubStmt &&
2298 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2299 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2300 return false;
2303 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2304 // If this is only valid as an extension, report that we don't satisfy the
2305 // constraints of the current language.
2306 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2307 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2308 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2309 return false;
2310 } else if (Cxx2bLoc.isValid()) {
2311 SemaRef.Diag(Cxx2bLoc,
2312 SemaRef.getLangOpts().CPlusPlus23
2313 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2314 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2315 << isa<CXXConstructorDecl>(Dcl);
2316 } else if (Cxx2aLoc.isValid()) {
2317 SemaRef.Diag(Cxx2aLoc,
2318 SemaRef.getLangOpts().CPlusPlus20
2319 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2320 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2321 << isa<CXXConstructorDecl>(Dcl);
2322 } else if (Cxx1yLoc.isValid()) {
2323 SemaRef.Diag(Cxx1yLoc,
2324 SemaRef.getLangOpts().CPlusPlus14
2325 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2326 : diag::ext_constexpr_body_invalid_stmt)
2327 << isa<CXXConstructorDecl>(Dcl);
2330 if (const CXXConstructorDecl *Constructor
2331 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2332 const CXXRecordDecl *RD = Constructor->getParent();
2333 // DR1359:
2334 // - every non-variant non-static data member and base class sub-object
2335 // shall be initialized;
2336 // DR1460:
2337 // - if the class is a union having variant members, exactly one of them
2338 // shall be initialized;
2339 if (RD->isUnion()) {
2340 if (Constructor->getNumCtorInitializers() == 0 &&
2341 RD->hasVariantMembers()) {
2342 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2343 SemaRef.Diag(
2344 Dcl->getLocation(),
2345 SemaRef.getLangOpts().CPlusPlus20
2346 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2347 : diag::ext_constexpr_union_ctor_no_init);
2348 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2349 return false;
2352 } else if (!Constructor->isDependentContext() &&
2353 !Constructor->isDelegatingConstructor()) {
2354 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2356 // Skip detailed checking if we have enough initializers, and we would
2357 // allow at most one initializer per member.
2358 bool AnyAnonStructUnionMembers = false;
2359 unsigned Fields = 0;
2360 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2361 E = RD->field_end(); I != E; ++I, ++Fields) {
2362 if (I->isAnonymousStructOrUnion()) {
2363 AnyAnonStructUnionMembers = true;
2364 break;
2367 // DR1460:
2368 // - if the class is a union-like class, but is not a union, for each of
2369 // its anonymous union members having variant members, exactly one of
2370 // them shall be initialized;
2371 if (AnyAnonStructUnionMembers ||
2372 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2373 // Check initialization of non-static data members. Base classes are
2374 // always initialized so do not need to be checked. Dependent bases
2375 // might not have initializers in the member initializer list.
2376 llvm::SmallSet<Decl*, 16> Inits;
2377 for (const auto *I: Constructor->inits()) {
2378 if (FieldDecl *FD = I->getMember())
2379 Inits.insert(FD);
2380 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2381 Inits.insert(ID->chain_begin(), ID->chain_end());
2384 bool Diagnosed = false;
2385 for (auto *I : RD->fields())
2386 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2387 Kind))
2388 return false;
2391 } else {
2392 if (ReturnStmts.empty()) {
2393 // C++1y doesn't require constexpr functions to contain a 'return'
2394 // statement. We still do, unless the return type might be void, because
2395 // otherwise if there's no return statement, the function cannot
2396 // be used in a core constant expression.
2397 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2398 (Dcl->getReturnType()->isVoidType() ||
2399 Dcl->getReturnType()->isDependentType());
2400 switch (Kind) {
2401 case Sema::CheckConstexprKind::Diagnose:
2402 SemaRef.Diag(Dcl->getLocation(),
2403 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2404 : diag::err_constexpr_body_no_return)
2405 << Dcl->isConsteval();
2406 if (!OK)
2407 return false;
2408 break;
2410 case Sema::CheckConstexprKind::CheckValid:
2411 // The formal requirements don't include this rule in C++14, even
2412 // though the "must be able to produce a constant expression" rules
2413 // still imply it in some cases.
2414 if (!SemaRef.getLangOpts().CPlusPlus14)
2415 return false;
2416 break;
2418 } else if (ReturnStmts.size() > 1) {
2419 switch (Kind) {
2420 case Sema::CheckConstexprKind::Diagnose:
2421 SemaRef.Diag(
2422 ReturnStmts.back(),
2423 SemaRef.getLangOpts().CPlusPlus14
2424 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2425 : diag::ext_constexpr_body_multiple_return);
2426 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2427 SemaRef.Diag(ReturnStmts[I],
2428 diag::note_constexpr_body_previous_return);
2429 break;
2431 case Sema::CheckConstexprKind::CheckValid:
2432 if (!SemaRef.getLangOpts().CPlusPlus14)
2433 return false;
2434 break;
2439 // C++11 [dcl.constexpr]p5:
2440 // if no function argument values exist such that the function invocation
2441 // substitution would produce a constant expression, the program is
2442 // ill-formed; no diagnostic required.
2443 // C++11 [dcl.constexpr]p3:
2444 // - every constructor call and implicit conversion used in initializing the
2445 // return value shall be one of those allowed in a constant expression.
2446 // C++11 [dcl.constexpr]p4:
2447 // - every constructor involved in initializing non-static data members and
2448 // base class sub-objects shall be a constexpr constructor.
2450 // Note that this rule is distinct from the "requirements for a constexpr
2451 // function", so is not checked in CheckValid mode.
2452 SmallVector<PartialDiagnosticAt, 8> Diags;
2453 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2454 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2455 SemaRef.Diag(Dcl->getLocation(),
2456 diag::ext_constexpr_function_never_constant_expr)
2457 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2458 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2459 SemaRef.Diag(Diags[I].first, Diags[I].second);
2460 // Don't return false here: we allow this for compatibility in
2461 // system headers.
2464 return true;
2467 bool Sema::CheckImmediateEscalatingFunctionDefinition(
2468 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2469 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2470 return true;
2471 FD->setBodyContainsImmediateEscalatingExpressions(
2472 FSI->FoundImmediateEscalatingExpression);
2473 if (FSI->FoundImmediateEscalatingExpression) {
2474 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2475 if (it != UndefinedButUsed.end()) {
2476 Diag(it->second, diag::err_immediate_function_used_before_definition)
2477 << it->first;
2478 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2479 if (FD->isImmediateFunction() && !FD->isConsteval())
2480 DiagnoseImmediateEscalatingReason(FD);
2481 return false;
2484 return true;
2487 void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2488 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2489 "expected an immediate function");
2490 assert(FD->hasBody() && "expected the function to have a body");
2491 struct ImmediateEscalatingExpressionsVisitor
2492 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2494 using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>;
2495 Sema &SemaRef;
2497 const FunctionDecl *ImmediateFn;
2498 bool ImmediateFnIsConstructor;
2499 CXXConstructorDecl *CurrentConstructor = nullptr;
2500 CXXCtorInitializer *CurrentInit = nullptr;
2502 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2503 : SemaRef(SemaRef), ImmediateFn(FD),
2504 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2506 bool shouldVisitImplicitCode() const { return true; }
2507 bool shouldVisitLambdaBody() const { return false; }
2509 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2510 SourceLocation Loc = E->getBeginLoc();
2511 SourceRange Range = E->getSourceRange();
2512 if (CurrentConstructor && CurrentInit) {
2513 Loc = CurrentConstructor->getLocation();
2514 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2515 : SourceRange();
2517 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2518 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2519 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2520 << (CurrentInit != nullptr)
2521 << (CurrentInit && !CurrentInit->isWritten())
2522 << (CurrentInit ? CurrentInit->getAnyMember() : nullptr) << Range;
2524 bool TraverseCallExpr(CallExpr *E) {
2525 if (const auto *DR =
2526 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2527 DR && DR->isImmediateEscalating()) {
2528 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2529 return false;
2532 for (Expr *A : E->arguments())
2533 if (!getDerived().TraverseStmt(A))
2534 return false;
2536 return true;
2539 bool VisitDeclRefExpr(DeclRefExpr *E) {
2540 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2541 ReferencedFn && E->isImmediateEscalating()) {
2542 Diag(E, ReferencedFn, /*IsCall=*/false);
2543 return false;
2546 return true;
2549 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2550 CXXConstructorDecl *D = E->getConstructor();
2551 if (E->isImmediateEscalating()) {
2552 Diag(E, D, /*IsCall=*/true);
2553 return false;
2555 return true;
2558 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2559 llvm::SaveAndRestore RAII(CurrentInit, Init);
2560 return Base::TraverseConstructorInitializer(Init);
2563 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2564 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2565 return Base::TraverseCXXConstructorDecl(Ctr);
2568 bool TraverseType(QualType T) { return true; }
2569 bool VisitBlockExpr(BlockExpr *T) { return true; }
2571 } Visitor(*this, FD);
2572 Visitor.TraverseDecl(FD);
2575 /// Get the class that is directly named by the current context. This is the
2576 /// class for which an unqualified-id in this scope could name a constructor
2577 /// or destructor.
2579 /// If the scope specifier denotes a class, this will be that class.
2580 /// If the scope specifier is empty, this will be the class whose
2581 /// member-specification we are currently within. Otherwise, there
2582 /// is no such class.
2583 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2584 assert(getLangOpts().CPlusPlus && "No class names in C!");
2586 if (SS && SS->isInvalid())
2587 return nullptr;
2589 if (SS && SS->isNotEmpty()) {
2590 DeclContext *DC = computeDeclContext(*SS, true);
2591 return dyn_cast_or_null<CXXRecordDecl>(DC);
2594 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2597 /// isCurrentClassName - Determine whether the identifier II is the
2598 /// name of the class type currently being defined. In the case of
2599 /// nested classes, this will only return true if II is the name of
2600 /// the innermost class.
2601 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2602 const CXXScopeSpec *SS) {
2603 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2604 return CurDecl && &II == CurDecl->getIdentifier();
2607 /// Determine whether the identifier II is a typo for the name of
2608 /// the class type currently being defined. If so, update it to the identifier
2609 /// that should have been used.
2610 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2611 assert(getLangOpts().CPlusPlus && "No class names in C!");
2613 if (!getLangOpts().SpellChecking)
2614 return false;
2616 CXXRecordDecl *CurDecl;
2617 if (SS && SS->isSet() && !SS->isInvalid()) {
2618 DeclContext *DC = computeDeclContext(*SS, true);
2619 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2620 } else
2621 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2623 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2624 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2625 < II->getLength()) {
2626 II = CurDecl->getIdentifier();
2627 return true;
2630 return false;
2633 /// Determine whether the given class is a base class of the given
2634 /// class, including looking at dependent bases.
2635 static bool findCircularInheritance(const CXXRecordDecl *Class,
2636 const CXXRecordDecl *Current) {
2637 SmallVector<const CXXRecordDecl*, 8> Queue;
2639 Class = Class->getCanonicalDecl();
2640 while (true) {
2641 for (const auto &I : Current->bases()) {
2642 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2643 if (!Base)
2644 continue;
2646 Base = Base->getDefinition();
2647 if (!Base)
2648 continue;
2650 if (Base->getCanonicalDecl() == Class)
2651 return true;
2653 Queue.push_back(Base);
2656 if (Queue.empty())
2657 return false;
2659 Current = Queue.pop_back_val();
2662 return false;
2665 /// Check the validity of a C++ base class specifier.
2667 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2668 /// and returns NULL otherwise.
2669 CXXBaseSpecifier *
2670 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2671 SourceRange SpecifierRange,
2672 bool Virtual, AccessSpecifier Access,
2673 TypeSourceInfo *TInfo,
2674 SourceLocation EllipsisLoc) {
2675 // In HLSL, unspecified class access is public rather than private.
2676 if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2677 Access == AS_none)
2678 Access = AS_public;
2680 QualType BaseType = TInfo->getType();
2681 if (BaseType->containsErrors()) {
2682 // Already emitted a diagnostic when parsing the error type.
2683 return nullptr;
2685 // C++ [class.union]p1:
2686 // A union shall not have base classes.
2687 if (Class->isUnion()) {
2688 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2689 << SpecifierRange;
2690 return nullptr;
2693 if (EllipsisLoc.isValid() &&
2694 !TInfo->getType()->containsUnexpandedParameterPack()) {
2695 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2696 << TInfo->getTypeLoc().getSourceRange();
2697 EllipsisLoc = SourceLocation();
2700 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2702 if (BaseType->isDependentType()) {
2703 // Make sure that we don't have circular inheritance among our dependent
2704 // bases. For non-dependent bases, the check for completeness below handles
2705 // this.
2706 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2707 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2708 ((BaseDecl = BaseDecl->getDefinition()) &&
2709 findCircularInheritance(Class, BaseDecl))) {
2710 Diag(BaseLoc, diag::err_circular_inheritance)
2711 << BaseType << Context.getTypeDeclType(Class);
2713 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2714 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2715 << BaseType;
2717 return nullptr;
2721 // Make sure that we don't make an ill-formed AST where the type of the
2722 // Class is non-dependent and its attached base class specifier is an
2723 // dependent type, which violates invariants in many clang code paths (e.g.
2724 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2725 // explicitly mark the Class decl invalid. The diagnostic was already
2726 // emitted.
2727 if (!Class->getTypeForDecl()->isDependentType())
2728 Class->setInvalidDecl();
2729 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2730 Class->getTagKind() == TTK_Class,
2731 Access, TInfo, EllipsisLoc);
2734 // Base specifiers must be record types.
2735 if (!BaseType->isRecordType()) {
2736 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2737 return nullptr;
2740 // C++ [class.union]p1:
2741 // A union shall not be used as a base class.
2742 if (BaseType->isUnionType()) {
2743 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2744 return nullptr;
2747 // For the MS ABI, propagate DLL attributes to base class templates.
2748 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2749 Context.getTargetInfo().getTriple().isPS()) {
2750 if (Attr *ClassAttr = getDLLAttr(Class)) {
2751 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2752 BaseType->getAsCXXRecordDecl())) {
2753 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2754 BaseLoc);
2759 // C++ [class.derived]p2:
2760 // The class-name in a base-specifier shall not be an incompletely
2761 // defined class.
2762 if (RequireCompleteType(BaseLoc, BaseType,
2763 diag::err_incomplete_base_class, SpecifierRange)) {
2764 Class->setInvalidDecl();
2765 return nullptr;
2768 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2769 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2770 assert(BaseDecl && "Record type has no declaration");
2771 BaseDecl = BaseDecl->getDefinition();
2772 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2773 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2774 assert(CXXBaseDecl && "Base type is not a C++ type");
2776 // Microsoft docs say:
2777 // "If a base-class has a code_seg attribute, derived classes must have the
2778 // same attribute."
2779 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2780 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2781 if ((DerivedCSA || BaseCSA) &&
2782 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2783 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2784 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2785 << CXXBaseDecl;
2786 return nullptr;
2789 // A class which contains a flexible array member is not suitable for use as a
2790 // base class:
2791 // - If the layout determines that a base comes before another base,
2792 // the flexible array member would index into the subsequent base.
2793 // - If the layout determines that base comes before the derived class,
2794 // the flexible array member would index into the derived class.
2795 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2796 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2797 << CXXBaseDecl->getDeclName();
2798 return nullptr;
2801 // C++ [class]p3:
2802 // If a class is marked final and it appears as a base-type-specifier in
2803 // base-clause, the program is ill-formed.
2804 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2805 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2806 << CXXBaseDecl->getDeclName()
2807 << FA->isSpelledAsSealed();
2808 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2809 << CXXBaseDecl->getDeclName() << FA->getRange();
2810 return nullptr;
2813 if (BaseDecl->isInvalidDecl())
2814 Class->setInvalidDecl();
2816 // Create the base specifier.
2817 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2818 Class->getTagKind() == TTK_Class,
2819 Access, TInfo, EllipsisLoc);
2822 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2823 /// one entry in the base class list of a class specifier, for
2824 /// example:
2825 /// class foo : public bar, virtual private baz {
2826 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2827 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2828 const ParsedAttributesView &Attributes,
2829 bool Virtual, AccessSpecifier Access,
2830 ParsedType basetype, SourceLocation BaseLoc,
2831 SourceLocation EllipsisLoc) {
2832 if (!classdecl)
2833 return true;
2835 AdjustDeclIfTemplate(classdecl);
2836 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2837 if (!Class)
2838 return true;
2840 // We haven't yet attached the base specifiers.
2841 Class->setIsParsingBaseSpecifiers();
2843 // We do not support any C++11 attributes on base-specifiers yet.
2844 // Diagnose any attributes we see.
2845 for (const ParsedAttr &AL : Attributes) {
2846 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2847 continue;
2848 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2849 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2850 << AL << AL.getRange();
2851 else
2852 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2853 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2856 TypeSourceInfo *TInfo = nullptr;
2857 GetTypeFromParser(basetype, &TInfo);
2859 if (EllipsisLoc.isInvalid() &&
2860 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2861 UPPC_BaseType))
2862 return true;
2864 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2865 Virtual, Access, TInfo,
2866 EllipsisLoc))
2867 return BaseSpec;
2868 else
2869 Class->setInvalidDecl();
2871 return true;
2874 /// Use small set to collect indirect bases. As this is only used
2875 /// locally, there's no need to abstract the small size parameter.
2876 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2878 /// Recursively add the bases of Type. Don't add Type itself.
2879 static void
2880 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2881 const QualType &Type)
2883 // Even though the incoming type is a base, it might not be
2884 // a class -- it could be a template parm, for instance.
2885 if (auto Rec = Type->getAs<RecordType>()) {
2886 auto Decl = Rec->getAsCXXRecordDecl();
2888 // Iterate over its bases.
2889 for (const auto &BaseSpec : Decl->bases()) {
2890 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2891 .getUnqualifiedType();
2892 if (Set.insert(Base).second)
2893 // If we've not already seen it, recurse.
2894 NoteIndirectBases(Context, Set, Base);
2899 /// Performs the actual work of attaching the given base class
2900 /// specifiers to a C++ class.
2901 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2902 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2903 if (Bases.empty())
2904 return false;
2906 // Used to keep track of which base types we have already seen, so
2907 // that we can properly diagnose redundant direct base types. Note
2908 // that the key is always the unqualified canonical type of the base
2909 // class.
2910 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2912 // Used to track indirect bases so we can see if a direct base is
2913 // ambiguous.
2914 IndirectBaseSet IndirectBaseTypes;
2916 // Copy non-redundant base specifiers into permanent storage.
2917 unsigned NumGoodBases = 0;
2918 bool Invalid = false;
2919 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2920 QualType NewBaseType
2921 = Context.getCanonicalType(Bases[idx]->getType());
2922 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2924 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2925 if (KnownBase) {
2926 // C++ [class.mi]p3:
2927 // A class shall not be specified as a direct base class of a
2928 // derived class more than once.
2929 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2930 << KnownBase->getType() << Bases[idx]->getSourceRange();
2932 // Delete the duplicate base class specifier; we're going to
2933 // overwrite its pointer later.
2934 Context.Deallocate(Bases[idx]);
2936 Invalid = true;
2937 } else {
2938 // Okay, add this new base class.
2939 KnownBase = Bases[idx];
2940 Bases[NumGoodBases++] = Bases[idx];
2942 if (NewBaseType->isDependentType())
2943 continue;
2944 // Note this base's direct & indirect bases, if there could be ambiguity.
2945 if (Bases.size() > 1)
2946 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2948 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2949 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2950 if (Class->isInterface() &&
2951 (!RD->isInterfaceLike() ||
2952 KnownBase->getAccessSpecifier() != AS_public)) {
2953 // The Microsoft extension __interface does not permit bases that
2954 // are not themselves public interfaces.
2955 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2956 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2957 << RD->getSourceRange();
2958 Invalid = true;
2960 if (RD->hasAttr<WeakAttr>())
2961 Class->addAttr(WeakAttr::CreateImplicit(Context));
2966 // Attach the remaining base class specifiers to the derived class.
2967 Class->setBases(Bases.data(), NumGoodBases);
2969 // Check that the only base classes that are duplicate are virtual.
2970 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2971 // Check whether this direct base is inaccessible due to ambiguity.
2972 QualType BaseType = Bases[idx]->getType();
2974 // Skip all dependent types in templates being used as base specifiers.
2975 // Checks below assume that the base specifier is a CXXRecord.
2976 if (BaseType->isDependentType())
2977 continue;
2979 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2980 .getUnqualifiedType();
2982 if (IndirectBaseTypes.count(CanonicalBase)) {
2983 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2984 /*DetectVirtual=*/true);
2985 bool found
2986 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2987 assert(found);
2988 (void)found;
2990 if (Paths.isAmbiguous(CanonicalBase))
2991 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2992 << BaseType << getAmbiguousPathsDisplayString(Paths)
2993 << Bases[idx]->getSourceRange();
2994 else
2995 assert(Bases[idx]->isVirtual());
2998 // Delete the base class specifier, since its data has been copied
2999 // into the CXXRecordDecl.
3000 Context.Deallocate(Bases[idx]);
3003 return Invalid;
3006 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
3007 /// class, after checking whether there are any duplicate base
3008 /// classes.
3009 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3010 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3011 if (!ClassDecl || Bases.empty())
3012 return;
3014 AdjustDeclIfTemplate(ClassDecl);
3015 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3018 /// Determine whether the type \p Derived is a C++ class that is
3019 /// derived from the type \p Base.
3020 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3021 if (!getLangOpts().CPlusPlus)
3022 return false;
3024 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3025 if (!DerivedRD)
3026 return false;
3028 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3029 if (!BaseRD)
3030 return false;
3032 // If either the base or the derived type is invalid, don't try to
3033 // check whether one is derived from the other.
3034 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3035 return false;
3037 // FIXME: In a modules build, do we need the entire path to be visible for us
3038 // to be able to use the inheritance relationship?
3039 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3040 return false;
3042 return DerivedRD->isDerivedFrom(BaseRD);
3045 /// Determine whether the type \p Derived is a C++ class that is
3046 /// derived from the type \p Base.
3047 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3048 CXXBasePaths &Paths) {
3049 if (!getLangOpts().CPlusPlus)
3050 return false;
3052 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3053 if (!DerivedRD)
3054 return false;
3056 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3057 if (!BaseRD)
3058 return false;
3060 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3061 return false;
3063 return DerivedRD->isDerivedFrom(BaseRD, Paths);
3066 static void BuildBasePathArray(const CXXBasePath &Path,
3067 CXXCastPath &BasePathArray) {
3068 // We first go backward and check if we have a virtual base.
3069 // FIXME: It would be better if CXXBasePath had the base specifier for
3070 // the nearest virtual base.
3071 unsigned Start = 0;
3072 for (unsigned I = Path.size(); I != 0; --I) {
3073 if (Path[I - 1].Base->isVirtual()) {
3074 Start = I - 1;
3075 break;
3079 // Now add all bases.
3080 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3081 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3085 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3086 CXXCastPath &BasePathArray) {
3087 assert(BasePathArray.empty() && "Base path array must be empty!");
3088 assert(Paths.isRecordingPaths() && "Must record paths!");
3089 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3091 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3092 /// conversion (where Derived and Base are class types) is
3093 /// well-formed, meaning that the conversion is unambiguous (and
3094 /// that all of the base classes are accessible). Returns true
3095 /// and emits a diagnostic if the code is ill-formed, returns false
3096 /// otherwise. Loc is the location where this routine should point to
3097 /// if there is an error, and Range is the source range to highlight
3098 /// if there is an error.
3100 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3101 /// diagnostic for the respective type of error will be suppressed, but the
3102 /// check for ill-formed code will still be performed.
3103 bool
3104 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3105 unsigned InaccessibleBaseID,
3106 unsigned AmbiguousBaseConvID,
3107 SourceLocation Loc, SourceRange Range,
3108 DeclarationName Name,
3109 CXXCastPath *BasePath,
3110 bool IgnoreAccess) {
3111 // First, determine whether the path from Derived to Base is
3112 // ambiguous. This is slightly more expensive than checking whether
3113 // the Derived to Base conversion exists, because here we need to
3114 // explore multiple paths to determine if there is an ambiguity.
3115 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3116 /*DetectVirtual=*/false);
3117 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3118 if (!DerivationOkay)
3119 return true;
3121 const CXXBasePath *Path = nullptr;
3122 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3123 Path = &Paths.front();
3125 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3126 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3127 // user to access such bases.
3128 if (!Path && getLangOpts().MSVCCompat) {
3129 for (const CXXBasePath &PossiblePath : Paths) {
3130 if (PossiblePath.size() == 1) {
3131 Path = &PossiblePath;
3132 if (AmbiguousBaseConvID)
3133 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3134 << Base << Derived << Range;
3135 break;
3140 if (Path) {
3141 if (!IgnoreAccess) {
3142 // Check that the base class can be accessed.
3143 switch (
3144 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3145 case AR_inaccessible:
3146 return true;
3147 case AR_accessible:
3148 case AR_dependent:
3149 case AR_delayed:
3150 break;
3154 // Build a base path if necessary.
3155 if (BasePath)
3156 ::BuildBasePathArray(*Path, *BasePath);
3157 return false;
3160 if (AmbiguousBaseConvID) {
3161 // We know that the derived-to-base conversion is ambiguous, and
3162 // we're going to produce a diagnostic. Perform the derived-to-base
3163 // search just one more time to compute all of the possible paths so
3164 // that we can print them out. This is more expensive than any of
3165 // the previous derived-to-base checks we've done, but at this point
3166 // performance isn't as much of an issue.
3167 Paths.clear();
3168 Paths.setRecordingPaths(true);
3169 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3170 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3171 (void)StillOkay;
3173 // Build up a textual representation of the ambiguous paths, e.g.,
3174 // D -> B -> A, that will be used to illustrate the ambiguous
3175 // conversions in the diagnostic. We only print one of the paths
3176 // to each base class subobject.
3177 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3179 Diag(Loc, AmbiguousBaseConvID)
3180 << Derived << Base << PathDisplayStr << Range << Name;
3182 return true;
3185 bool
3186 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3187 SourceLocation Loc, SourceRange Range,
3188 CXXCastPath *BasePath,
3189 bool IgnoreAccess) {
3190 return CheckDerivedToBaseConversion(
3191 Derived, Base, diag::err_upcast_to_inaccessible_base,
3192 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3193 BasePath, IgnoreAccess);
3197 /// Builds a string representing ambiguous paths from a
3198 /// specific derived class to different subobjects of the same base
3199 /// class.
3201 /// This function builds a string that can be used in error messages
3202 /// to show the different paths that one can take through the
3203 /// inheritance hierarchy to go from the derived class to different
3204 /// subobjects of a base class. The result looks something like this:
3205 /// @code
3206 /// struct D -> struct B -> struct A
3207 /// struct D -> struct C -> struct A
3208 /// @endcode
3209 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3210 std::string PathDisplayStr;
3211 std::set<unsigned> DisplayedPaths;
3212 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3213 Path != Paths.end(); ++Path) {
3214 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3215 // We haven't displayed a path to this particular base
3216 // class subobject yet.
3217 PathDisplayStr += "\n ";
3218 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3219 for (CXXBasePath::const_iterator Element = Path->begin();
3220 Element != Path->end(); ++Element)
3221 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3225 return PathDisplayStr;
3228 //===----------------------------------------------------------------------===//
3229 // C++ class member Handling
3230 //===----------------------------------------------------------------------===//
3232 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3233 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3234 SourceLocation ColonLoc,
3235 const ParsedAttributesView &Attrs) {
3236 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3237 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3238 ASLoc, ColonLoc);
3239 CurContext->addHiddenDecl(ASDecl);
3240 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3243 /// CheckOverrideControl - Check C++11 override control semantics.
3244 void Sema::CheckOverrideControl(NamedDecl *D) {
3245 if (D->isInvalidDecl())
3246 return;
3248 // We only care about "override" and "final" declarations.
3249 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3250 return;
3252 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3254 // We can't check dependent instance methods.
3255 if (MD && MD->isInstance() &&
3256 (MD->getParent()->hasAnyDependentBases() ||
3257 MD->getType()->isDependentType()))
3258 return;
3260 if (MD && !MD->isVirtual()) {
3261 // If we have a non-virtual method, check if it hides a virtual method.
3262 // (In that case, it's most likely the method has the wrong type.)
3263 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3264 FindHiddenVirtualMethods(MD, OverloadedMethods);
3266 if (!OverloadedMethods.empty()) {
3267 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3268 Diag(OA->getLocation(),
3269 diag::override_keyword_hides_virtual_member_function)
3270 << "override" << (OverloadedMethods.size() > 1);
3271 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3272 Diag(FA->getLocation(),
3273 diag::override_keyword_hides_virtual_member_function)
3274 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3275 << (OverloadedMethods.size() > 1);
3277 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3278 MD->setInvalidDecl();
3279 return;
3281 // Fall through into the general case diagnostic.
3282 // FIXME: We might want to attempt typo correction here.
3285 if (!MD || !MD->isVirtual()) {
3286 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3287 Diag(OA->getLocation(),
3288 diag::override_keyword_only_allowed_on_virtual_member_functions)
3289 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3290 D->dropAttr<OverrideAttr>();
3292 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3293 Diag(FA->getLocation(),
3294 diag::override_keyword_only_allowed_on_virtual_member_functions)
3295 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3296 << FixItHint::CreateRemoval(FA->getLocation());
3297 D->dropAttr<FinalAttr>();
3299 return;
3302 // C++11 [class.virtual]p5:
3303 // If a function is marked with the virt-specifier override and
3304 // does not override a member function of a base class, the program is
3305 // ill-formed.
3306 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3307 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3308 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3309 << MD->getDeclName();
3312 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3313 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3314 return;
3315 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3316 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3317 return;
3319 SourceLocation Loc = MD->getLocation();
3320 SourceLocation SpellingLoc = Loc;
3321 if (getSourceManager().isMacroArgExpansion(Loc))
3322 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3323 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3324 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3325 return;
3327 if (MD->size_overridden_methods() > 0) {
3328 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3329 unsigned DiagID =
3330 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3331 ? DiagInconsistent
3332 : DiagSuggest;
3333 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3334 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3335 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3337 if (isa<CXXDestructorDecl>(MD))
3338 EmitDiag(
3339 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3340 diag::warn_suggest_destructor_marked_not_override_overriding);
3341 else
3342 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3343 diag::warn_suggest_function_marked_not_override_overriding);
3347 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3348 /// function overrides a virtual member function marked 'final', according to
3349 /// C++11 [class.virtual]p4.
3350 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3351 const CXXMethodDecl *Old) {
3352 FinalAttr *FA = Old->getAttr<FinalAttr>();
3353 if (!FA)
3354 return false;
3356 Diag(New->getLocation(), diag::err_final_function_overridden)
3357 << New->getDeclName()
3358 << FA->isSpelledAsSealed();
3359 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3360 return true;
3363 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3364 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3365 // FIXME: Destruction of ObjC lifetime types has side-effects.
3366 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3367 return !RD->isCompleteDefinition() ||
3368 !RD->hasTrivialDefaultConstructor() ||
3369 !RD->hasTrivialDestructor();
3370 return false;
3373 // Check if there is a field shadowing.
3374 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3375 DeclarationName FieldName,
3376 const CXXRecordDecl *RD,
3377 bool DeclIsField) {
3378 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3379 return;
3381 // To record a shadowed field in a base
3382 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3383 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3384 CXXBasePath &Path) {
3385 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3386 // Record an ambiguous path directly
3387 if (Bases.find(Base) != Bases.end())
3388 return true;
3389 for (const auto Field : Base->lookup(FieldName)) {
3390 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3391 Field->getAccess() != AS_private) {
3392 assert(Field->getAccess() != AS_none);
3393 assert(Bases.find(Base) == Bases.end());
3394 Bases[Base] = Field;
3395 return true;
3398 return false;
3401 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3402 /*DetectVirtual=*/true);
3403 if (!RD->lookupInBases(FieldShadowed, Paths))
3404 return;
3406 for (const auto &P : Paths) {
3407 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3408 auto It = Bases.find(Base);
3409 // Skip duplicated bases
3410 if (It == Bases.end())
3411 continue;
3412 auto BaseField = It->second;
3413 assert(BaseField->getAccess() != AS_private);
3414 if (AS_none !=
3415 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3416 Diag(Loc, diag::warn_shadow_field)
3417 << FieldName << RD << Base << DeclIsField;
3418 Diag(BaseField->getLocation(), diag::note_shadow_field);
3419 Bases.erase(It);
3424 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3425 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3426 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3427 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3428 /// present (but parsing it has been deferred).
3429 NamedDecl *
3430 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3431 MultiTemplateParamsArg TemplateParameterLists,
3432 Expr *BW, const VirtSpecifiers &VS,
3433 InClassInitStyle InitStyle) {
3434 const DeclSpec &DS = D.getDeclSpec();
3435 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3436 DeclarationName Name = NameInfo.getName();
3437 SourceLocation Loc = NameInfo.getLoc();
3439 // For anonymous bitfields, the location should point to the type.
3440 if (Loc.isInvalid())
3441 Loc = D.getBeginLoc();
3443 Expr *BitWidth = static_cast<Expr*>(BW);
3445 assert(isa<CXXRecordDecl>(CurContext));
3446 assert(!DS.isFriendSpecified());
3448 bool isFunc = D.isDeclarationOfFunction();
3449 const ParsedAttr *MSPropertyAttr =
3450 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3452 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3453 // The Microsoft extension __interface only permits public member functions
3454 // and prohibits constructors, destructors, operators, non-public member
3455 // functions, static methods and data members.
3456 unsigned InvalidDecl;
3457 bool ShowDeclName = true;
3458 if (!isFunc &&
3459 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3460 InvalidDecl = 0;
3461 else if (!isFunc)
3462 InvalidDecl = 1;
3463 else if (AS != AS_public)
3464 InvalidDecl = 2;
3465 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3466 InvalidDecl = 3;
3467 else switch (Name.getNameKind()) {
3468 case DeclarationName::CXXConstructorName:
3469 InvalidDecl = 4;
3470 ShowDeclName = false;
3471 break;
3473 case DeclarationName::CXXDestructorName:
3474 InvalidDecl = 5;
3475 ShowDeclName = false;
3476 break;
3478 case DeclarationName::CXXOperatorName:
3479 case DeclarationName::CXXConversionFunctionName:
3480 InvalidDecl = 6;
3481 break;
3483 default:
3484 InvalidDecl = 0;
3485 break;
3488 if (InvalidDecl) {
3489 if (ShowDeclName)
3490 Diag(Loc, diag::err_invalid_member_in_interface)
3491 << (InvalidDecl-1) << Name;
3492 else
3493 Diag(Loc, diag::err_invalid_member_in_interface)
3494 << (InvalidDecl-1) << "";
3495 return nullptr;
3499 // C++ 9.2p6: A member shall not be declared to have automatic storage
3500 // duration (auto, register) or with the extern storage-class-specifier.
3501 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3502 // data members and cannot be applied to names declared const or static,
3503 // and cannot be applied to reference members.
3504 switch (DS.getStorageClassSpec()) {
3505 case DeclSpec::SCS_unspecified:
3506 case DeclSpec::SCS_typedef:
3507 case DeclSpec::SCS_static:
3508 break;
3509 case DeclSpec::SCS_mutable:
3510 if (isFunc) {
3511 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3513 // FIXME: It would be nicer if the keyword was ignored only for this
3514 // declarator. Otherwise we could get follow-up errors.
3515 D.getMutableDeclSpec().ClearStorageClassSpecs();
3517 break;
3518 default:
3519 Diag(DS.getStorageClassSpecLoc(),
3520 diag::err_storageclass_invalid_for_member);
3521 D.getMutableDeclSpec().ClearStorageClassSpecs();
3522 break;
3525 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3526 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3527 !isFunc);
3529 if (DS.hasConstexprSpecifier() && isInstField) {
3530 SemaDiagnosticBuilder B =
3531 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3532 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3533 if (InitStyle == ICIS_NoInit) {
3534 B << 0 << 0;
3535 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3536 B << FixItHint::CreateRemoval(ConstexprLoc);
3537 else {
3538 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3539 D.getMutableDeclSpec().ClearConstexprSpec();
3540 const char *PrevSpec;
3541 unsigned DiagID;
3542 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3543 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3544 (void)Failed;
3545 assert(!Failed && "Making a constexpr member const shouldn't fail");
3547 } else {
3548 B << 1;
3549 const char *PrevSpec;
3550 unsigned DiagID;
3551 if (D.getMutableDeclSpec().SetStorageClassSpec(
3552 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3553 Context.getPrintingPolicy())) {
3554 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3555 "This is the only DeclSpec that should fail to be applied");
3556 B << 1;
3557 } else {
3558 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3559 isInstField = false;
3564 NamedDecl *Member;
3565 if (isInstField) {
3566 CXXScopeSpec &SS = D.getCXXScopeSpec();
3568 // Data members must have identifiers for names.
3569 if (!Name.isIdentifier()) {
3570 Diag(Loc, diag::err_bad_variable_name)
3571 << Name;
3572 return nullptr;
3575 IdentifierInfo *II = Name.getAsIdentifierInfo();
3577 // Member field could not be with "template" keyword.
3578 // So TemplateParameterLists should be empty in this case.
3579 if (TemplateParameterLists.size()) {
3580 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3581 if (TemplateParams->size()) {
3582 // There is no such thing as a member field template.
3583 Diag(D.getIdentifierLoc(), diag::err_template_member)
3584 << II
3585 << SourceRange(TemplateParams->getTemplateLoc(),
3586 TemplateParams->getRAngleLoc());
3587 } else {
3588 // There is an extraneous 'template<>' for this member.
3589 Diag(TemplateParams->getTemplateLoc(),
3590 diag::err_template_member_noparams)
3591 << II
3592 << SourceRange(TemplateParams->getTemplateLoc(),
3593 TemplateParams->getRAngleLoc());
3595 return nullptr;
3598 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3599 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3600 << II
3601 << SourceRange(D.getName().TemplateId->LAngleLoc,
3602 D.getName().TemplateId->RAngleLoc)
3603 << D.getName().TemplateId->LAngleLoc;
3604 D.SetIdentifier(II, Loc);
3607 if (SS.isSet() && !SS.isInvalid()) {
3608 // The user provided a superfluous scope specifier inside a class
3609 // definition:
3611 // class X {
3612 // int X::member;
3613 // };
3614 if (DeclContext *DC = computeDeclContext(SS, false))
3615 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3616 D.getName().getKind() ==
3617 UnqualifiedIdKind::IK_TemplateId);
3618 else
3619 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3620 << Name << SS.getRange();
3622 SS.clear();
3625 if (MSPropertyAttr) {
3626 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3627 BitWidth, InitStyle, AS, *MSPropertyAttr);
3628 if (!Member)
3629 return nullptr;
3630 isInstField = false;
3631 } else {
3632 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3633 BitWidth, InitStyle, AS);
3634 if (!Member)
3635 return nullptr;
3638 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3639 } else {
3640 Member = HandleDeclarator(S, D, TemplateParameterLists);
3641 if (!Member)
3642 return nullptr;
3644 // Non-instance-fields can't have a bitfield.
3645 if (BitWidth) {
3646 if (Member->isInvalidDecl()) {
3647 // don't emit another diagnostic.
3648 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3649 // C++ 9.6p3: A bit-field shall not be a static member.
3650 // "static member 'A' cannot be a bit-field"
3651 Diag(Loc, diag::err_static_not_bitfield)
3652 << Name << BitWidth->getSourceRange();
3653 } else if (isa<TypedefDecl>(Member)) {
3654 // "typedef member 'x' cannot be a bit-field"
3655 Diag(Loc, diag::err_typedef_not_bitfield)
3656 << Name << BitWidth->getSourceRange();
3657 } else {
3658 // A function typedef ("typedef int f(); f a;").
3659 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3660 Diag(Loc, diag::err_not_integral_type_bitfield)
3661 << Name << cast<ValueDecl>(Member)->getType()
3662 << BitWidth->getSourceRange();
3665 BitWidth = nullptr;
3666 Member->setInvalidDecl();
3669 NamedDecl *NonTemplateMember = Member;
3670 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3671 NonTemplateMember = FunTmpl->getTemplatedDecl();
3672 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3673 NonTemplateMember = VarTmpl->getTemplatedDecl();
3675 Member->setAccess(AS);
3677 // If we have declared a member function template or static data member
3678 // template, set the access of the templated declaration as well.
3679 if (NonTemplateMember != Member)
3680 NonTemplateMember->setAccess(AS);
3682 // C++ [temp.deduct.guide]p3:
3683 // A deduction guide [...] for a member class template [shall be
3684 // declared] with the same access [as the template].
3685 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3686 auto *TD = DG->getDeducedTemplate();
3687 // Access specifiers are only meaningful if both the template and the
3688 // deduction guide are from the same scope.
3689 if (AS != TD->getAccess() &&
3690 TD->getDeclContext()->getRedeclContext()->Equals(
3691 DG->getDeclContext()->getRedeclContext())) {
3692 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3693 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3694 << TD->getAccess();
3695 const AccessSpecDecl *LastAccessSpec = nullptr;
3696 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3697 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3698 LastAccessSpec = AccessSpec;
3700 assert(LastAccessSpec && "differing access with no access specifier");
3701 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3702 << AS;
3707 if (VS.isOverrideSpecified())
3708 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3709 if (VS.isFinalSpecified())
3710 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3711 VS.isFinalSpelledSealed()
3712 ? FinalAttr::Keyword_sealed
3713 : FinalAttr::Keyword_final));
3715 if (VS.getLastLocation().isValid()) {
3716 // Update the end location of a method that has a virt-specifiers.
3717 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3718 MD->setRangeEnd(VS.getLastLocation());
3721 CheckOverrideControl(Member);
3723 assert((Name || isInstField) && "No identifier for non-field ?");
3725 if (isInstField) {
3726 FieldDecl *FD = cast<FieldDecl>(Member);
3727 FieldCollector->Add(FD);
3729 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3730 // Remember all explicit private FieldDecls that have a name, no side
3731 // effects and are not part of a dependent type declaration.
3732 if (!FD->isImplicit() && FD->getDeclName() &&
3733 FD->getAccess() == AS_private &&
3734 !FD->hasAttr<UnusedAttr>() &&
3735 !FD->getParent()->isDependentContext() &&
3736 !InitializationHasSideEffects(*FD))
3737 UnusedPrivateFields.insert(FD);
3741 return Member;
3744 namespace {
3745 class UninitializedFieldVisitor
3746 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3747 Sema &S;
3748 // List of Decls to generate a warning on. Also remove Decls that become
3749 // initialized.
3750 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3751 // List of base classes of the record. Classes are removed after their
3752 // initializers.
3753 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3754 // Vector of decls to be removed from the Decl set prior to visiting the
3755 // nodes. These Decls may have been initialized in the prior initializer.
3756 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3757 // If non-null, add a note to the warning pointing back to the constructor.
3758 const CXXConstructorDecl *Constructor;
3759 // Variables to hold state when processing an initializer list. When
3760 // InitList is true, special case initialization of FieldDecls matching
3761 // InitListFieldDecl.
3762 bool InitList;
3763 FieldDecl *InitListFieldDecl;
3764 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3766 public:
3767 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3768 UninitializedFieldVisitor(Sema &S,
3769 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3770 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3771 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3772 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3774 // Returns true if the use of ME is not an uninitialized use.
3775 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3776 bool CheckReferenceOnly) {
3777 llvm::SmallVector<FieldDecl*, 4> Fields;
3778 bool ReferenceField = false;
3779 while (ME) {
3780 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3781 if (!FD)
3782 return false;
3783 Fields.push_back(FD);
3784 if (FD->getType()->isReferenceType())
3785 ReferenceField = true;
3786 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3789 // Binding a reference to an uninitialized field is not an
3790 // uninitialized use.
3791 if (CheckReferenceOnly && !ReferenceField)
3792 return true;
3794 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3795 // Discard the first field since it is the field decl that is being
3796 // initialized.
3797 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3798 UsedFieldIndex.push_back(FD->getFieldIndex());
3800 for (auto UsedIter = UsedFieldIndex.begin(),
3801 UsedEnd = UsedFieldIndex.end(),
3802 OrigIter = InitFieldIndex.begin(),
3803 OrigEnd = InitFieldIndex.end();
3804 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3805 if (*UsedIter < *OrigIter)
3806 return true;
3807 if (*UsedIter > *OrigIter)
3808 break;
3811 return false;
3814 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3815 bool AddressOf) {
3816 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3817 return;
3819 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3820 // or union.
3821 MemberExpr *FieldME = ME;
3823 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3825 Expr *Base = ME;
3826 while (MemberExpr *SubME =
3827 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3829 if (isa<VarDecl>(SubME->getMemberDecl()))
3830 return;
3832 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3833 if (!FD->isAnonymousStructOrUnion())
3834 FieldME = SubME;
3836 if (!FieldME->getType().isPODType(S.Context))
3837 AllPODFields = false;
3839 Base = SubME->getBase();
3842 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3843 Visit(Base);
3844 return;
3847 if (AddressOf && AllPODFields)
3848 return;
3850 ValueDecl* FoundVD = FieldME->getMemberDecl();
3852 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3853 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3854 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3857 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3858 QualType T = BaseCast->getType();
3859 if (T->isPointerType() &&
3860 BaseClasses.count(T->getPointeeType())) {
3861 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3862 << T->getPointeeType() << FoundVD;
3867 if (!Decls.count(FoundVD))
3868 return;
3870 const bool IsReference = FoundVD->getType()->isReferenceType();
3872 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3873 // Special checking for initializer lists.
3874 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3875 return;
3877 } else {
3878 // Prevent double warnings on use of unbounded references.
3879 if (CheckReferenceOnly && !IsReference)
3880 return;
3883 unsigned diag = IsReference
3884 ? diag::warn_reference_field_is_uninit
3885 : diag::warn_field_is_uninit;
3886 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3887 if (Constructor)
3888 S.Diag(Constructor->getLocation(),
3889 diag::note_uninit_in_this_constructor)
3890 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3894 void HandleValue(Expr *E, bool AddressOf) {
3895 E = E->IgnoreParens();
3897 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3898 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3899 AddressOf /*AddressOf*/);
3900 return;
3903 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3904 Visit(CO->getCond());
3905 HandleValue(CO->getTrueExpr(), AddressOf);
3906 HandleValue(CO->getFalseExpr(), AddressOf);
3907 return;
3910 if (BinaryConditionalOperator *BCO =
3911 dyn_cast<BinaryConditionalOperator>(E)) {
3912 Visit(BCO->getCond());
3913 HandleValue(BCO->getFalseExpr(), AddressOf);
3914 return;
3917 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3918 HandleValue(OVE->getSourceExpr(), AddressOf);
3919 return;
3922 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3923 switch (BO->getOpcode()) {
3924 default:
3925 break;
3926 case(BO_PtrMemD):
3927 case(BO_PtrMemI):
3928 HandleValue(BO->getLHS(), AddressOf);
3929 Visit(BO->getRHS());
3930 return;
3931 case(BO_Comma):
3932 Visit(BO->getLHS());
3933 HandleValue(BO->getRHS(), AddressOf);
3934 return;
3938 Visit(E);
3941 void CheckInitListExpr(InitListExpr *ILE) {
3942 InitFieldIndex.push_back(0);
3943 for (auto *Child : ILE->children()) {
3944 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3945 CheckInitListExpr(SubList);
3946 } else {
3947 Visit(Child);
3949 ++InitFieldIndex.back();
3951 InitFieldIndex.pop_back();
3954 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3955 FieldDecl *Field, const Type *BaseClass) {
3956 // Remove Decls that may have been initialized in the previous
3957 // initializer.
3958 for (ValueDecl* VD : DeclsToRemove)
3959 Decls.erase(VD);
3960 DeclsToRemove.clear();
3962 Constructor = FieldConstructor;
3963 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3965 if (ILE && Field) {
3966 InitList = true;
3967 InitListFieldDecl = Field;
3968 InitFieldIndex.clear();
3969 CheckInitListExpr(ILE);
3970 } else {
3971 InitList = false;
3972 Visit(E);
3975 if (Field)
3976 Decls.erase(Field);
3977 if (BaseClass)
3978 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3981 void VisitMemberExpr(MemberExpr *ME) {
3982 // All uses of unbounded reference fields will warn.
3983 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3986 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3987 if (E->getCastKind() == CK_LValueToRValue) {
3988 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3989 return;
3992 Inherited::VisitImplicitCastExpr(E);
3995 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3996 if (E->getConstructor()->isCopyConstructor()) {
3997 Expr *ArgExpr = E->getArg(0);
3998 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3999 if (ILE->getNumInits() == 1)
4000 ArgExpr = ILE->getInit(0);
4001 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4002 if (ICE->getCastKind() == CK_NoOp)
4003 ArgExpr = ICE->getSubExpr();
4004 HandleValue(ArgExpr, false /*AddressOf*/);
4005 return;
4007 Inherited::VisitCXXConstructExpr(E);
4010 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4011 Expr *Callee = E->getCallee();
4012 if (isa<MemberExpr>(Callee)) {
4013 HandleValue(Callee, false /*AddressOf*/);
4014 for (auto *Arg : E->arguments())
4015 Visit(Arg);
4016 return;
4019 Inherited::VisitCXXMemberCallExpr(E);
4022 void VisitCallExpr(CallExpr *E) {
4023 // Treat std::move as a use.
4024 if (E->isCallToStdMove()) {
4025 HandleValue(E->getArg(0), /*AddressOf=*/false);
4026 return;
4029 Inherited::VisitCallExpr(E);
4032 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4033 Expr *Callee = E->getCallee();
4035 if (isa<UnresolvedLookupExpr>(Callee))
4036 return Inherited::VisitCXXOperatorCallExpr(E);
4038 Visit(Callee);
4039 for (auto *Arg : E->arguments())
4040 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4043 void VisitBinaryOperator(BinaryOperator *E) {
4044 // If a field assignment is detected, remove the field from the
4045 // uninitiailized field set.
4046 if (E->getOpcode() == BO_Assign)
4047 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4048 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4049 if (!FD->getType()->isReferenceType())
4050 DeclsToRemove.push_back(FD);
4052 if (E->isCompoundAssignmentOp()) {
4053 HandleValue(E->getLHS(), false /*AddressOf*/);
4054 Visit(E->getRHS());
4055 return;
4058 Inherited::VisitBinaryOperator(E);
4061 void VisitUnaryOperator(UnaryOperator *E) {
4062 if (E->isIncrementDecrementOp()) {
4063 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4064 return;
4066 if (E->getOpcode() == UO_AddrOf) {
4067 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4068 HandleValue(ME->getBase(), true /*AddressOf*/);
4069 return;
4073 Inherited::VisitUnaryOperator(E);
4077 // Diagnose value-uses of fields to initialize themselves, e.g.
4078 // foo(foo)
4079 // where foo is not also a parameter to the constructor.
4080 // Also diagnose across field uninitialized use such as
4081 // x(y), y(x)
4082 // TODO: implement -Wuninitialized and fold this into that framework.
4083 static void DiagnoseUninitializedFields(
4084 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4086 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4087 Constructor->getLocation())) {
4088 return;
4091 if (Constructor->isInvalidDecl())
4092 return;
4094 const CXXRecordDecl *RD = Constructor->getParent();
4096 if (RD->isDependentContext())
4097 return;
4099 // Holds fields that are uninitialized.
4100 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4102 // At the beginning, all fields are uninitialized.
4103 for (auto *I : RD->decls()) {
4104 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4105 UninitializedFields.insert(FD);
4106 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4107 UninitializedFields.insert(IFD->getAnonField());
4111 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4112 for (const auto &I : RD->bases())
4113 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4115 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4116 return;
4118 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4119 UninitializedFields,
4120 UninitializedBaseClasses);
4122 for (const auto *FieldInit : Constructor->inits()) {
4123 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4124 break;
4126 Expr *InitExpr = FieldInit->getInit();
4127 if (!InitExpr)
4128 continue;
4130 if (CXXDefaultInitExpr *Default =
4131 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4132 InitExpr = Default->getExpr();
4133 if (!InitExpr)
4134 continue;
4135 // In class initializers will point to the constructor.
4136 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4137 FieldInit->getAnyMember(),
4138 FieldInit->getBaseClass());
4139 } else {
4140 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4141 FieldInit->getAnyMember(),
4142 FieldInit->getBaseClass());
4146 } // namespace
4148 /// Enter a new C++ default initializer scope. After calling this, the
4149 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4150 /// parsing or instantiating the initializer failed.
4151 void Sema::ActOnStartCXXInClassMemberInitializer() {
4152 // Create a synthetic function scope to represent the call to the constructor
4153 // that notionally surrounds a use of this initializer.
4154 PushFunctionScope();
4157 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4158 if (!D.isFunctionDeclarator())
4159 return;
4160 auto &FTI = D.getFunctionTypeInfo();
4161 if (!FTI.Params)
4162 return;
4163 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4164 FTI.NumParams)) {
4165 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4166 if (ParamDecl->getDeclName())
4167 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4171 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4172 return ActOnRequiresClause(ConstraintExpr);
4175 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4176 if (ConstraintExpr.isInvalid())
4177 return ExprError();
4179 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4180 if (ConstraintExpr.isInvalid())
4181 return ExprError();
4183 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4184 UPPC_RequiresClause))
4185 return ExprError();
4187 return ConstraintExpr;
4190 ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4191 Expr *InitExpr,
4192 SourceLocation InitLoc) {
4193 InitializedEntity Entity =
4194 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4195 InitializationKind Kind =
4196 FD->getInClassInitStyle() == ICIS_ListInit
4197 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4198 InitExpr->getBeginLoc(),
4199 InitExpr->getEndLoc())
4200 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4201 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4202 return Seq.Perform(*this, Entity, Kind, InitExpr);
4205 /// This is invoked after parsing an in-class initializer for a
4206 /// non-static C++ class member, and after instantiating an in-class initializer
4207 /// in a class template. Such actions are deferred until the class is complete.
4208 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4209 SourceLocation InitLoc,
4210 Expr *InitExpr) {
4211 // Pop the notional constructor scope we created earlier.
4212 PopFunctionScopeInfo(nullptr, D);
4214 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4215 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4216 "must set init style when field is created");
4218 if (!InitExpr) {
4219 D->setInvalidDecl();
4220 if (FD)
4221 FD->removeInClassInitializer();
4222 return;
4225 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4226 FD->setInvalidDecl();
4227 FD->removeInClassInitializer();
4228 return;
4231 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4232 /*RecoverUncorrectedTypos=*/true);
4233 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4234 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4235 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4236 // C++11 [class.base.init]p7:
4237 // The initialization of each base and member constitutes a
4238 // full-expression.
4239 if (!Init.isInvalid())
4240 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4241 if (Init.isInvalid()) {
4242 FD->setInvalidDecl();
4243 return;
4247 FD->setInClassInitializer(Init.get());
4250 /// Find the direct and/or virtual base specifiers that
4251 /// correspond to the given base type, for use in base initialization
4252 /// within a constructor.
4253 static bool FindBaseInitializer(Sema &SemaRef,
4254 CXXRecordDecl *ClassDecl,
4255 QualType BaseType,
4256 const CXXBaseSpecifier *&DirectBaseSpec,
4257 const CXXBaseSpecifier *&VirtualBaseSpec) {
4258 // First, check for a direct base class.
4259 DirectBaseSpec = nullptr;
4260 for (const auto &Base : ClassDecl->bases()) {
4261 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4262 // We found a direct base of this type. That's what we're
4263 // initializing.
4264 DirectBaseSpec = &Base;
4265 break;
4269 // Check for a virtual base class.
4270 // FIXME: We might be able to short-circuit this if we know in advance that
4271 // there are no virtual bases.
4272 VirtualBaseSpec = nullptr;
4273 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4274 // We haven't found a base yet; search the class hierarchy for a
4275 // virtual base class.
4276 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4277 /*DetectVirtual=*/false);
4278 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4279 SemaRef.Context.getTypeDeclType(ClassDecl),
4280 BaseType, Paths)) {
4281 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4282 Path != Paths.end(); ++Path) {
4283 if (Path->back().Base->isVirtual()) {
4284 VirtualBaseSpec = Path->back().Base;
4285 break;
4291 return DirectBaseSpec || VirtualBaseSpec;
4294 /// Handle a C++ member initializer using braced-init-list syntax.
4295 MemInitResult
4296 Sema::ActOnMemInitializer(Decl *ConstructorD,
4297 Scope *S,
4298 CXXScopeSpec &SS,
4299 IdentifierInfo *MemberOrBase,
4300 ParsedType TemplateTypeTy,
4301 const DeclSpec &DS,
4302 SourceLocation IdLoc,
4303 Expr *InitList,
4304 SourceLocation EllipsisLoc) {
4305 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4306 DS, IdLoc, InitList,
4307 EllipsisLoc);
4310 /// Handle a C++ member initializer using parentheses syntax.
4311 MemInitResult
4312 Sema::ActOnMemInitializer(Decl *ConstructorD,
4313 Scope *S,
4314 CXXScopeSpec &SS,
4315 IdentifierInfo *MemberOrBase,
4316 ParsedType TemplateTypeTy,
4317 const DeclSpec &DS,
4318 SourceLocation IdLoc,
4319 SourceLocation LParenLoc,
4320 ArrayRef<Expr *> Args,
4321 SourceLocation RParenLoc,
4322 SourceLocation EllipsisLoc) {
4323 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4324 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4325 DS, IdLoc, List, EllipsisLoc);
4328 namespace {
4330 // Callback to only accept typo corrections that can be a valid C++ member
4331 // initializer: either a non-static field member or a base class.
4332 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4333 public:
4334 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4335 : ClassDecl(ClassDecl) {}
4337 bool ValidateCandidate(const TypoCorrection &candidate) override {
4338 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4339 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4340 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4341 return isa<TypeDecl>(ND);
4343 return false;
4346 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4347 return std::make_unique<MemInitializerValidatorCCC>(*this);
4350 private:
4351 CXXRecordDecl *ClassDecl;
4356 bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4357 RecordDecl *ClassDecl,
4358 const IdentifierInfo *Name) {
4359 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4360 DeclContextLookupResult::iterator Found =
4361 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4362 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4363 Elem->isPlaceholderVar(getLangOpts());
4365 // We did not find a placeholder variable
4366 if (Found == Result.end())
4367 return false;
4368 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4369 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4370 const NamedDecl *ND = *It;
4371 if (ND->getDeclContext() != ND->getDeclContext())
4372 break;
4373 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4374 ND->isPlaceholderVar(getLangOpts()))
4375 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4377 return true;
4380 ValueDecl *
4381 Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4382 const IdentifierInfo *MemberOrBase) {
4383 ValueDecl *ND = nullptr;
4384 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4385 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4386 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4387 if (ND) {
4388 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4389 return nullptr;
4390 break;
4392 if (!IsPlaceholder)
4393 return cast<ValueDecl>(D);
4394 ND = cast<ValueDecl>(D);
4397 return ND;
4400 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4401 CXXScopeSpec &SS,
4402 ParsedType TemplateTypeTy,
4403 IdentifierInfo *MemberOrBase) {
4404 if (SS.getScopeRep() || TemplateTypeTy)
4405 return nullptr;
4406 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4409 /// Handle a C++ member initializer.
4410 MemInitResult
4411 Sema::BuildMemInitializer(Decl *ConstructorD,
4412 Scope *S,
4413 CXXScopeSpec &SS,
4414 IdentifierInfo *MemberOrBase,
4415 ParsedType TemplateTypeTy,
4416 const DeclSpec &DS,
4417 SourceLocation IdLoc,
4418 Expr *Init,
4419 SourceLocation EllipsisLoc) {
4420 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4421 /*RecoverUncorrectedTypos=*/true);
4422 if (!Res.isUsable())
4423 return true;
4424 Init = Res.get();
4426 if (!ConstructorD)
4427 return true;
4429 AdjustDeclIfTemplate(ConstructorD);
4431 CXXConstructorDecl *Constructor
4432 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4433 if (!Constructor) {
4434 // The user wrote a constructor initializer on a function that is
4435 // not a C++ constructor. Ignore the error for now, because we may
4436 // have more member initializers coming; we'll diagnose it just
4437 // once in ActOnMemInitializers.
4438 return true;
4441 CXXRecordDecl *ClassDecl = Constructor->getParent();
4443 // C++ [class.base.init]p2:
4444 // Names in a mem-initializer-id are looked up in the scope of the
4445 // constructor's class and, if not found in that scope, are looked
4446 // up in the scope containing the constructor's definition.
4447 // [Note: if the constructor's class contains a member with the
4448 // same name as a direct or virtual base class of the class, a
4449 // mem-initializer-id naming the member or base class and composed
4450 // of a single identifier refers to the class member. A
4451 // mem-initializer-id for the hidden base class may be specified
4452 // using a qualified name. ]
4454 // Look for a member, first.
4455 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4456 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4457 if (EllipsisLoc.isValid())
4458 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4459 << MemberOrBase
4460 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4462 return BuildMemberInitializer(Member, Init, IdLoc);
4464 // It didn't name a member, so see if it names a class.
4465 QualType BaseType;
4466 TypeSourceInfo *TInfo = nullptr;
4468 if (TemplateTypeTy) {
4469 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4470 if (BaseType.isNull())
4471 return true;
4472 } else if (DS.getTypeSpecType() == TST_decltype) {
4473 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4474 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4475 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4476 return true;
4477 } else {
4478 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4479 LookupParsedName(R, S, &SS);
4481 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4482 if (!TyD) {
4483 if (R.isAmbiguous()) return true;
4485 // We don't want access-control diagnostics here.
4486 R.suppressDiagnostics();
4488 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4489 bool NotUnknownSpecialization = false;
4490 DeclContext *DC = computeDeclContext(SS, false);
4491 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4492 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4494 if (!NotUnknownSpecialization) {
4495 // When the scope specifier can refer to a member of an unknown
4496 // specialization, we take it as a type name.
4497 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4498 SS.getWithLocInContext(Context),
4499 *MemberOrBase, IdLoc);
4500 if (BaseType.isNull())
4501 return true;
4503 TInfo = Context.CreateTypeSourceInfo(BaseType);
4504 DependentNameTypeLoc TL =
4505 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4506 if (!TL.isNull()) {
4507 TL.setNameLoc(IdLoc);
4508 TL.setElaboratedKeywordLoc(SourceLocation());
4509 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4512 R.clear();
4513 R.setLookupName(MemberOrBase);
4517 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4518 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4519 auto *TempSpec = cast<TemplateSpecializationType>(
4520 UnqualifiedBase->getInjectedClassNameSpecialization());
4521 TemplateName TN = TempSpec->getTemplateName();
4522 for (auto const &Base : ClassDecl->bases()) {
4523 auto BaseTemplate =
4524 Base.getType()->getAs<TemplateSpecializationType>();
4525 if (BaseTemplate && Context.hasSameTemplateName(
4526 BaseTemplate->getTemplateName(), TN)) {
4527 Diag(IdLoc, diag::ext_unqualified_base_class)
4528 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4529 BaseType = Base.getType();
4530 break;
4536 // If no results were found, try to correct typos.
4537 TypoCorrection Corr;
4538 MemInitializerValidatorCCC CCC(ClassDecl);
4539 if (R.empty() && BaseType.isNull() &&
4540 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4541 CCC, CTK_ErrorRecovery, ClassDecl))) {
4542 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4543 // We have found a non-static data member with a similar
4544 // name to what was typed; complain and initialize that
4545 // member.
4546 diagnoseTypo(Corr,
4547 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4548 << MemberOrBase << true);
4549 return BuildMemberInitializer(Member, Init, IdLoc);
4550 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4551 const CXXBaseSpecifier *DirectBaseSpec;
4552 const CXXBaseSpecifier *VirtualBaseSpec;
4553 if (FindBaseInitializer(*this, ClassDecl,
4554 Context.getTypeDeclType(Type),
4555 DirectBaseSpec, VirtualBaseSpec)) {
4556 // We have found a direct or virtual base class with a
4557 // similar name to what was typed; complain and initialize
4558 // that base class.
4559 diagnoseTypo(Corr,
4560 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4561 << MemberOrBase << false,
4562 PDiag() /*Suppress note, we provide our own.*/);
4564 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4565 : VirtualBaseSpec;
4566 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4567 << BaseSpec->getType() << BaseSpec->getSourceRange();
4569 TyD = Type;
4574 if (!TyD && BaseType.isNull()) {
4575 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4576 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4577 return true;
4581 if (BaseType.isNull()) {
4582 BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
4583 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4584 TInfo = Context.CreateTypeSourceInfo(BaseType);
4585 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4586 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4587 TL.setElaboratedKeywordLoc(SourceLocation());
4588 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4592 if (!TInfo)
4593 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4595 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4598 MemInitResult
4599 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4600 SourceLocation IdLoc) {
4601 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4602 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4603 assert((DirectMember || IndirectMember) &&
4604 "Member must be a FieldDecl or IndirectFieldDecl");
4606 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4607 return true;
4609 if (Member->isInvalidDecl())
4610 return true;
4612 MultiExprArg Args;
4613 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4614 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4615 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4616 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4617 } else {
4618 // Template instantiation doesn't reconstruct ParenListExprs for us.
4619 Args = Init;
4622 SourceRange InitRange = Init->getSourceRange();
4624 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4625 // Can't check initialization for a member of dependent type or when
4626 // any of the arguments are type-dependent expressions.
4627 DiscardCleanupsInEvaluationContext();
4628 } else {
4629 bool InitList = false;
4630 if (isa<InitListExpr>(Init)) {
4631 InitList = true;
4632 Args = Init;
4635 // Initialize the member.
4636 InitializedEntity MemberEntity =
4637 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4638 : InitializedEntity::InitializeMember(IndirectMember,
4639 nullptr);
4640 InitializationKind Kind =
4641 InitList ? InitializationKind::CreateDirectList(
4642 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4643 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4644 InitRange.getEnd());
4646 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4647 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4648 nullptr);
4649 if (!MemberInit.isInvalid()) {
4650 // C++11 [class.base.init]p7:
4651 // The initialization of each base and member constitutes a
4652 // full-expression.
4653 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4654 /*DiscardedValue*/ false);
4657 if (MemberInit.isInvalid()) {
4658 // Args were sensible expressions but we couldn't initialize the member
4659 // from them. Preserve them in a RecoveryExpr instead.
4660 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4661 Member->getType())
4662 .get();
4663 if (!Init)
4664 return true;
4665 } else {
4666 Init = MemberInit.get();
4670 if (DirectMember) {
4671 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4672 InitRange.getBegin(), Init,
4673 InitRange.getEnd());
4674 } else {
4675 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4676 InitRange.getBegin(), Init,
4677 InitRange.getEnd());
4681 MemInitResult
4682 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4683 CXXRecordDecl *ClassDecl) {
4684 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4685 if (!LangOpts.CPlusPlus11)
4686 return Diag(NameLoc, diag::err_delegating_ctor)
4687 << TInfo->getTypeLoc().getSourceRange();
4688 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4690 bool InitList = true;
4691 MultiExprArg Args = Init;
4692 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4693 InitList = false;
4694 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4697 SourceRange InitRange = Init->getSourceRange();
4698 // Initialize the object.
4699 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4700 QualType(ClassDecl->getTypeForDecl(), 0));
4701 InitializationKind Kind =
4702 InitList ? InitializationKind::CreateDirectList(
4703 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4704 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4705 InitRange.getEnd());
4706 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4707 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4708 Args, nullptr);
4709 if (!DelegationInit.isInvalid()) {
4710 assert((DelegationInit.get()->containsErrors() ||
4711 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4712 "Delegating constructor with no target?");
4714 // C++11 [class.base.init]p7:
4715 // The initialization of each base and member constitutes a
4716 // full-expression.
4717 DelegationInit = ActOnFinishFullExpr(
4718 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4721 if (DelegationInit.isInvalid()) {
4722 DelegationInit =
4723 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4724 QualType(ClassDecl->getTypeForDecl(), 0));
4725 if (DelegationInit.isInvalid())
4726 return true;
4727 } else {
4728 // If we are in a dependent context, template instantiation will
4729 // perform this type-checking again. Just save the arguments that we
4730 // received in a ParenListExpr.
4731 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4732 // of the information that we have about the base
4733 // initializer. However, deconstructing the ASTs is a dicey process,
4734 // and this approach is far more likely to get the corner cases right.
4735 if (CurContext->isDependentContext())
4736 DelegationInit = Init;
4739 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4740 DelegationInit.getAs<Expr>(),
4741 InitRange.getEnd());
4744 MemInitResult
4745 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4746 Expr *Init, CXXRecordDecl *ClassDecl,
4747 SourceLocation EllipsisLoc) {
4748 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4750 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4751 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4752 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4754 // C++ [class.base.init]p2:
4755 // [...] Unless the mem-initializer-id names a nonstatic data
4756 // member of the constructor's class or a direct or virtual base
4757 // of that class, the mem-initializer is ill-formed. A
4758 // mem-initializer-list can initialize a base class using any
4759 // name that denotes that base class type.
4761 // We can store the initializers in "as-written" form and delay analysis until
4762 // instantiation if the constructor is dependent. But not for dependent
4763 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4764 bool Dependent = CurContext->isDependentContext() &&
4765 (BaseType->isDependentType() || Init->isTypeDependent());
4767 SourceRange InitRange = Init->getSourceRange();
4768 if (EllipsisLoc.isValid()) {
4769 // This is a pack expansion.
4770 if (!BaseType->containsUnexpandedParameterPack()) {
4771 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4772 << SourceRange(BaseLoc, InitRange.getEnd());
4774 EllipsisLoc = SourceLocation();
4776 } else {
4777 // Check for any unexpanded parameter packs.
4778 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4779 return true;
4781 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4782 return true;
4785 // Check for direct and virtual base classes.
4786 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4787 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4788 if (!Dependent) {
4789 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4790 BaseType))
4791 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4793 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4794 VirtualBaseSpec);
4796 // C++ [base.class.init]p2:
4797 // Unless the mem-initializer-id names a nonstatic data member of the
4798 // constructor's class or a direct or virtual base of that class, the
4799 // mem-initializer is ill-formed.
4800 if (!DirectBaseSpec && !VirtualBaseSpec) {
4801 // If the class has any dependent bases, then it's possible that
4802 // one of those types will resolve to the same type as
4803 // BaseType. Therefore, just treat this as a dependent base
4804 // class initialization. FIXME: Should we try to check the
4805 // initialization anyway? It seems odd.
4806 if (ClassDecl->hasAnyDependentBases())
4807 Dependent = true;
4808 else
4809 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4810 << BaseType << Context.getTypeDeclType(ClassDecl)
4811 << BaseTInfo->getTypeLoc().getSourceRange();
4815 if (Dependent) {
4816 DiscardCleanupsInEvaluationContext();
4818 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4819 /*IsVirtual=*/false,
4820 InitRange.getBegin(), Init,
4821 InitRange.getEnd(), EllipsisLoc);
4824 // C++ [base.class.init]p2:
4825 // If a mem-initializer-id is ambiguous because it designates both
4826 // a direct non-virtual base class and an inherited virtual base
4827 // class, the mem-initializer is ill-formed.
4828 if (DirectBaseSpec && VirtualBaseSpec)
4829 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4830 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4832 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4833 if (!BaseSpec)
4834 BaseSpec = VirtualBaseSpec;
4836 // Initialize the base.
4837 bool InitList = true;
4838 MultiExprArg Args = Init;
4839 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4840 InitList = false;
4841 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4844 InitializedEntity BaseEntity =
4845 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4846 InitializationKind Kind =
4847 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4848 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4849 InitRange.getEnd());
4850 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4851 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4852 if (!BaseInit.isInvalid()) {
4853 // C++11 [class.base.init]p7:
4854 // The initialization of each base and member constitutes a
4855 // full-expression.
4856 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4857 /*DiscardedValue*/ false);
4860 if (BaseInit.isInvalid()) {
4861 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4862 Args, BaseType);
4863 if (BaseInit.isInvalid())
4864 return true;
4865 } else {
4866 // If we are in a dependent context, template instantiation will
4867 // perform this type-checking again. Just save the arguments that we
4868 // received in a ParenListExpr.
4869 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4870 // of the information that we have about the base
4871 // initializer. However, deconstructing the ASTs is a dicey process,
4872 // and this approach is far more likely to get the corner cases right.
4873 if (CurContext->isDependentContext())
4874 BaseInit = Init;
4877 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4878 BaseSpec->isVirtual(),
4879 InitRange.getBegin(),
4880 BaseInit.getAs<Expr>(),
4881 InitRange.getEnd(), EllipsisLoc);
4884 // Create a static_cast\<T&&>(expr).
4885 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4886 QualType TargetType =
4887 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4888 SourceLocation(), DeclarationName());
4889 SourceLocation ExprLoc = E->getBeginLoc();
4890 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4891 TargetType, ExprLoc);
4893 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4894 SourceRange(ExprLoc, ExprLoc),
4895 E->getSourceRange()).get();
4898 /// ImplicitInitializerKind - How an implicit base or member initializer should
4899 /// initialize its base or member.
4900 enum ImplicitInitializerKind {
4901 IIK_Default,
4902 IIK_Copy,
4903 IIK_Move,
4904 IIK_Inherit
4907 static bool
4908 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4909 ImplicitInitializerKind ImplicitInitKind,
4910 CXXBaseSpecifier *BaseSpec,
4911 bool IsInheritedVirtualBase,
4912 CXXCtorInitializer *&CXXBaseInit) {
4913 InitializedEntity InitEntity
4914 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4915 IsInheritedVirtualBase);
4917 ExprResult BaseInit;
4919 switch (ImplicitInitKind) {
4920 case IIK_Inherit:
4921 case IIK_Default: {
4922 InitializationKind InitKind
4923 = InitializationKind::CreateDefault(Constructor->getLocation());
4924 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4925 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4926 break;
4929 case IIK_Move:
4930 case IIK_Copy: {
4931 bool Moving = ImplicitInitKind == IIK_Move;
4932 ParmVarDecl *Param = Constructor->getParamDecl(0);
4933 QualType ParamType = Param->getType().getNonReferenceType();
4935 Expr *CopyCtorArg =
4936 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4937 SourceLocation(), Param, false,
4938 Constructor->getLocation(), ParamType,
4939 VK_LValue, nullptr);
4941 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4943 // Cast to the base class to avoid ambiguities.
4944 QualType ArgTy =
4945 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4946 ParamType.getQualifiers());
4948 if (Moving) {
4949 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4952 CXXCastPath BasePath;
4953 BasePath.push_back(BaseSpec);
4954 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4955 CK_UncheckedDerivedToBase,
4956 Moving ? VK_XValue : VK_LValue,
4957 &BasePath).get();
4959 InitializationKind InitKind
4960 = InitializationKind::CreateDirect(Constructor->getLocation(),
4961 SourceLocation(), SourceLocation());
4962 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4963 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4964 break;
4968 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4969 if (BaseInit.isInvalid())
4970 return true;
4972 CXXBaseInit =
4973 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4974 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4975 SourceLocation()),
4976 BaseSpec->isVirtual(),
4977 SourceLocation(),
4978 BaseInit.getAs<Expr>(),
4979 SourceLocation(),
4980 SourceLocation());
4982 return false;
4985 static bool RefersToRValueRef(Expr *MemRef) {
4986 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4987 return Referenced->getType()->isRValueReferenceType();
4990 static bool
4991 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4992 ImplicitInitializerKind ImplicitInitKind,
4993 FieldDecl *Field, IndirectFieldDecl *Indirect,
4994 CXXCtorInitializer *&CXXMemberInit) {
4995 if (Field->isInvalidDecl())
4996 return true;
4998 SourceLocation Loc = Constructor->getLocation();
5000 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5001 bool Moving = ImplicitInitKind == IIK_Move;
5002 ParmVarDecl *Param = Constructor->getParamDecl(0);
5003 QualType ParamType = Param->getType().getNonReferenceType();
5005 // Suppress copying zero-width bitfields.
5006 if (Field->isZeroLengthBitField(SemaRef.Context))
5007 return false;
5009 Expr *MemberExprBase =
5010 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
5011 SourceLocation(), Param, false,
5012 Loc, ParamType, VK_LValue, nullptr);
5014 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5016 if (Moving) {
5017 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5020 // Build a reference to this field within the parameter.
5021 CXXScopeSpec SS;
5022 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5023 Sema::LookupMemberName);
5024 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5025 : cast<ValueDecl>(Field), AS_public);
5026 MemberLookup.resolveKind();
5027 ExprResult CtorArg
5028 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5029 ParamType, Loc,
5030 /*IsArrow=*/false,
5032 /*TemplateKWLoc=*/SourceLocation(),
5033 /*FirstQualifierInScope=*/nullptr,
5034 MemberLookup,
5035 /*TemplateArgs=*/nullptr,
5036 /*S*/nullptr);
5037 if (CtorArg.isInvalid())
5038 return true;
5040 // C++11 [class.copy]p15:
5041 // - if a member m has rvalue reference type T&&, it is direct-initialized
5042 // with static_cast<T&&>(x.m);
5043 if (RefersToRValueRef(CtorArg.get())) {
5044 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5047 InitializedEntity Entity =
5048 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5049 /*Implicit*/ true)
5050 : InitializedEntity::InitializeMember(Field, nullptr,
5051 /*Implicit*/ true);
5053 // Direct-initialize to use the copy constructor.
5054 InitializationKind InitKind =
5055 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
5057 Expr *CtorArgE = CtorArg.getAs<Expr>();
5058 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5059 ExprResult MemberInit =
5060 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5061 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5062 if (MemberInit.isInvalid())
5063 return true;
5065 if (Indirect)
5066 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5067 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5068 else
5069 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5070 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5071 return false;
5074 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5075 "Unhandled implicit init kind!");
5077 QualType FieldBaseElementType =
5078 SemaRef.Context.getBaseElementType(Field->getType());
5080 if (FieldBaseElementType->isRecordType()) {
5081 InitializedEntity InitEntity =
5082 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5083 /*Implicit*/ true)
5084 : InitializedEntity::InitializeMember(Field, nullptr,
5085 /*Implicit*/ true);
5086 InitializationKind InitKind =
5087 InitializationKind::CreateDefault(Loc);
5089 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5090 ExprResult MemberInit =
5091 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5093 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5094 if (MemberInit.isInvalid())
5095 return true;
5097 if (Indirect)
5098 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5099 Indirect, Loc,
5100 Loc,
5101 MemberInit.get(),
5102 Loc);
5103 else
5104 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5105 Field, Loc, Loc,
5106 MemberInit.get(),
5107 Loc);
5108 return false;
5111 if (!Field->getParent()->isUnion()) {
5112 if (FieldBaseElementType->isReferenceType()) {
5113 SemaRef.Diag(Constructor->getLocation(),
5114 diag::err_uninitialized_member_in_ctor)
5115 << (int)Constructor->isImplicit()
5116 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5117 << 0 << Field->getDeclName();
5118 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5119 return true;
5122 if (FieldBaseElementType.isConstQualified()) {
5123 SemaRef.Diag(Constructor->getLocation(),
5124 diag::err_uninitialized_member_in_ctor)
5125 << (int)Constructor->isImplicit()
5126 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5127 << 1 << Field->getDeclName();
5128 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5129 return true;
5133 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5134 // ARC and Weak:
5135 // Default-initialize Objective-C pointers to NULL.
5136 CXXMemberInit
5137 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5138 Loc, Loc,
5139 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5140 Loc);
5141 return false;
5144 // Nothing to initialize.
5145 CXXMemberInit = nullptr;
5146 return false;
5149 namespace {
5150 struct BaseAndFieldInfo {
5151 Sema &S;
5152 CXXConstructorDecl *Ctor;
5153 bool AnyErrorsInInits;
5154 ImplicitInitializerKind IIK;
5155 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5156 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5157 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5159 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5160 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5161 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5162 if (Ctor->getInheritedConstructor())
5163 IIK = IIK_Inherit;
5164 else if (Generated && Ctor->isCopyConstructor())
5165 IIK = IIK_Copy;
5166 else if (Generated && Ctor->isMoveConstructor())
5167 IIK = IIK_Move;
5168 else
5169 IIK = IIK_Default;
5172 bool isImplicitCopyOrMove() const {
5173 switch (IIK) {
5174 case IIK_Copy:
5175 case IIK_Move:
5176 return true;
5178 case IIK_Default:
5179 case IIK_Inherit:
5180 return false;
5183 llvm_unreachable("Invalid ImplicitInitializerKind!");
5186 bool addFieldInitializer(CXXCtorInitializer *Init) {
5187 AllToInit.push_back(Init);
5189 // Check whether this initializer makes the field "used".
5190 if (Init->getInit()->HasSideEffects(S.Context))
5191 S.UnusedPrivateFields.remove(Init->getAnyMember());
5193 return false;
5196 bool isInactiveUnionMember(FieldDecl *Field) {
5197 RecordDecl *Record = Field->getParent();
5198 if (!Record->isUnion())
5199 return false;
5201 if (FieldDecl *Active =
5202 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5203 return Active != Field->getCanonicalDecl();
5205 // In an implicit copy or move constructor, ignore any in-class initializer.
5206 if (isImplicitCopyOrMove())
5207 return true;
5209 // If there's no explicit initialization, the field is active only if it
5210 // has an in-class initializer...
5211 if (Field->hasInClassInitializer())
5212 return false;
5213 // ... or it's an anonymous struct or union whose class has an in-class
5214 // initializer.
5215 if (!Field->isAnonymousStructOrUnion())
5216 return true;
5217 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5218 return !FieldRD->hasInClassInitializer();
5221 /// Determine whether the given field is, or is within, a union member
5222 /// that is inactive (because there was an initializer given for a different
5223 /// member of the union, or because the union was not initialized at all).
5224 bool isWithinInactiveUnionMember(FieldDecl *Field,
5225 IndirectFieldDecl *Indirect) {
5226 if (!Indirect)
5227 return isInactiveUnionMember(Field);
5229 for (auto *C : Indirect->chain()) {
5230 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5231 if (Field && isInactiveUnionMember(Field))
5232 return true;
5234 return false;
5239 /// Determine whether the given type is an incomplete or zero-lenfgth
5240 /// array type.
5241 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5242 if (T->isIncompleteArrayType())
5243 return true;
5245 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5246 if (!ArrayT->getSize())
5247 return true;
5249 T = ArrayT->getElementType();
5252 return false;
5255 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5256 FieldDecl *Field,
5257 IndirectFieldDecl *Indirect = nullptr) {
5258 if (Field->isInvalidDecl())
5259 return false;
5261 // Overwhelmingly common case: we have a direct initializer for this field.
5262 if (CXXCtorInitializer *Init =
5263 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5264 return Info.addFieldInitializer(Init);
5266 // C++11 [class.base.init]p8:
5267 // if the entity is a non-static data member that has a
5268 // brace-or-equal-initializer and either
5269 // -- the constructor's class is a union and no other variant member of that
5270 // union is designated by a mem-initializer-id or
5271 // -- the constructor's class is not a union, and, if the entity is a member
5272 // of an anonymous union, no other member of that union is designated by
5273 // a mem-initializer-id,
5274 // the entity is initialized as specified in [dcl.init].
5276 // We also apply the same rules to handle anonymous structs within anonymous
5277 // unions.
5278 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5279 return false;
5281 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5282 ExprResult DIE =
5283 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5284 if (DIE.isInvalid())
5285 return true;
5287 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5288 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5290 CXXCtorInitializer *Init;
5291 if (Indirect)
5292 Init = new (SemaRef.Context)
5293 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5294 SourceLocation(), DIE.get(), SourceLocation());
5295 else
5296 Init = new (SemaRef.Context)
5297 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5298 SourceLocation(), DIE.get(), SourceLocation());
5299 return Info.addFieldInitializer(Init);
5302 // Don't initialize incomplete or zero-length arrays.
5303 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5304 return false;
5306 // Don't try to build an implicit initializer if there were semantic
5307 // errors in any of the initializers (and therefore we might be
5308 // missing some that the user actually wrote).
5309 if (Info.AnyErrorsInInits)
5310 return false;
5312 CXXCtorInitializer *Init = nullptr;
5313 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5314 Indirect, Init))
5315 return true;
5317 if (!Init)
5318 return false;
5320 return Info.addFieldInitializer(Init);
5323 bool
5324 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5325 CXXCtorInitializer *Initializer) {
5326 assert(Initializer->isDelegatingInitializer());
5327 Constructor->setNumCtorInitializers(1);
5328 CXXCtorInitializer **initializer =
5329 new (Context) CXXCtorInitializer*[1];
5330 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5331 Constructor->setCtorInitializers(initializer);
5333 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5334 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5335 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5338 DelegatingCtorDecls.push_back(Constructor);
5340 DiagnoseUninitializedFields(*this, Constructor);
5342 return false;
5345 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5346 ArrayRef<CXXCtorInitializer *> Initializers) {
5347 if (Constructor->isDependentContext()) {
5348 // Just store the initializers as written, they will be checked during
5349 // instantiation.
5350 if (!Initializers.empty()) {
5351 Constructor->setNumCtorInitializers(Initializers.size());
5352 CXXCtorInitializer **baseOrMemberInitializers =
5353 new (Context) CXXCtorInitializer*[Initializers.size()];
5354 memcpy(baseOrMemberInitializers, Initializers.data(),
5355 Initializers.size() * sizeof(CXXCtorInitializer*));
5356 Constructor->setCtorInitializers(baseOrMemberInitializers);
5359 // Let template instantiation know whether we had errors.
5360 if (AnyErrors)
5361 Constructor->setInvalidDecl();
5363 return false;
5366 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5368 // We need to build the initializer AST according to order of construction
5369 // and not what user specified in the Initializers list.
5370 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5371 if (!ClassDecl)
5372 return true;
5374 bool HadError = false;
5376 for (unsigned i = 0; i < Initializers.size(); i++) {
5377 CXXCtorInitializer *Member = Initializers[i];
5379 if (Member->isBaseInitializer())
5380 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5381 else {
5382 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5384 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5385 for (auto *C : F->chain()) {
5386 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5387 if (FD && FD->getParent()->isUnion())
5388 Info.ActiveUnionMember.insert(std::make_pair(
5389 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5391 } else if (FieldDecl *FD = Member->getMember()) {
5392 if (FD->getParent()->isUnion())
5393 Info.ActiveUnionMember.insert(std::make_pair(
5394 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5399 // Keep track of the direct virtual bases.
5400 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5401 for (auto &I : ClassDecl->bases()) {
5402 if (I.isVirtual())
5403 DirectVBases.insert(&I);
5406 // Push virtual bases before others.
5407 for (auto &VBase : ClassDecl->vbases()) {
5408 if (CXXCtorInitializer *Value
5409 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5410 // [class.base.init]p7, per DR257:
5411 // A mem-initializer where the mem-initializer-id names a virtual base
5412 // class is ignored during execution of a constructor of any class that
5413 // is not the most derived class.
5414 if (ClassDecl->isAbstract()) {
5415 // FIXME: Provide a fixit to remove the base specifier. This requires
5416 // tracking the location of the associated comma for a base specifier.
5417 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5418 << VBase.getType() << ClassDecl;
5419 DiagnoseAbstractType(ClassDecl);
5422 Info.AllToInit.push_back(Value);
5423 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5424 // [class.base.init]p8, per DR257:
5425 // If a given [...] base class is not named by a mem-initializer-id
5426 // [...] and the entity is not a virtual base class of an abstract
5427 // class, then [...] the entity is default-initialized.
5428 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5429 CXXCtorInitializer *CXXBaseInit;
5430 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5431 &VBase, IsInheritedVirtualBase,
5432 CXXBaseInit)) {
5433 HadError = true;
5434 continue;
5437 Info.AllToInit.push_back(CXXBaseInit);
5441 // Non-virtual bases.
5442 for (auto &Base : ClassDecl->bases()) {
5443 // Virtuals are in the virtual base list and already constructed.
5444 if (Base.isVirtual())
5445 continue;
5447 if (CXXCtorInitializer *Value
5448 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5449 Info.AllToInit.push_back(Value);
5450 } else if (!AnyErrors) {
5451 CXXCtorInitializer *CXXBaseInit;
5452 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5453 &Base, /*IsInheritedVirtualBase=*/false,
5454 CXXBaseInit)) {
5455 HadError = true;
5456 continue;
5459 Info.AllToInit.push_back(CXXBaseInit);
5463 // Fields.
5464 for (auto *Mem : ClassDecl->decls()) {
5465 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5466 // C++ [class.bit]p2:
5467 // A declaration for a bit-field that omits the identifier declares an
5468 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5469 // initialized.
5470 if (F->isUnnamedBitfield())
5471 continue;
5473 // If we're not generating the implicit copy/move constructor, then we'll
5474 // handle anonymous struct/union fields based on their individual
5475 // indirect fields.
5476 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5477 continue;
5479 if (CollectFieldInitializer(*this, Info, F))
5480 HadError = true;
5481 continue;
5484 // Beyond this point, we only consider default initialization.
5485 if (Info.isImplicitCopyOrMove())
5486 continue;
5488 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5489 if (F->getType()->isIncompleteArrayType()) {
5490 assert(ClassDecl->hasFlexibleArrayMember() &&
5491 "Incomplete array type is not valid");
5492 continue;
5495 // Initialize each field of an anonymous struct individually.
5496 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5497 HadError = true;
5499 continue;
5503 unsigned NumInitializers = Info.AllToInit.size();
5504 if (NumInitializers > 0) {
5505 Constructor->setNumCtorInitializers(NumInitializers);
5506 CXXCtorInitializer **baseOrMemberInitializers =
5507 new (Context) CXXCtorInitializer*[NumInitializers];
5508 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5509 NumInitializers * sizeof(CXXCtorInitializer*));
5510 Constructor->setCtorInitializers(baseOrMemberInitializers);
5512 // Constructors implicitly reference the base and member
5513 // destructors.
5514 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5515 Constructor->getParent());
5518 return HadError;
5521 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5522 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5523 const RecordDecl *RD = RT->getDecl();
5524 if (RD->isAnonymousStructOrUnion()) {
5525 for (auto *Field : RD->fields())
5526 PopulateKeysForFields(Field, IdealInits);
5527 return;
5530 IdealInits.push_back(Field->getCanonicalDecl());
5533 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5534 return Context.getCanonicalType(BaseType).getTypePtr();
5537 static const void *GetKeyForMember(ASTContext &Context,
5538 CXXCtorInitializer *Member) {
5539 if (!Member->isAnyMemberInitializer())
5540 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5542 return Member->getAnyMember()->getCanonicalDecl();
5545 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5546 const CXXCtorInitializer *Previous,
5547 const CXXCtorInitializer *Current) {
5548 if (Previous->isAnyMemberInitializer())
5549 Diag << 0 << Previous->getAnyMember();
5550 else
5551 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5553 if (Current->isAnyMemberInitializer())
5554 Diag << 0 << Current->getAnyMember();
5555 else
5556 Diag << 1 << Current->getTypeSourceInfo()->getType();
5559 static void DiagnoseBaseOrMemInitializerOrder(
5560 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5561 ArrayRef<CXXCtorInitializer *> Inits) {
5562 if (Constructor->getDeclContext()->isDependentContext())
5563 return;
5565 // Don't check initializers order unless the warning is enabled at the
5566 // location of at least one initializer.
5567 bool ShouldCheckOrder = false;
5568 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5569 CXXCtorInitializer *Init = Inits[InitIndex];
5570 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5571 Init->getSourceLocation())) {
5572 ShouldCheckOrder = true;
5573 break;
5576 if (!ShouldCheckOrder)
5577 return;
5579 // Build the list of bases and members in the order that they'll
5580 // actually be initialized. The explicit initializers should be in
5581 // this same order but may be missing things.
5582 SmallVector<const void*, 32> IdealInitKeys;
5584 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5586 // 1. Virtual bases.
5587 for (const auto &VBase : ClassDecl->vbases())
5588 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5590 // 2. Non-virtual bases.
5591 for (const auto &Base : ClassDecl->bases()) {
5592 if (Base.isVirtual())
5593 continue;
5594 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5597 // 3. Direct fields.
5598 for (auto *Field : ClassDecl->fields()) {
5599 if (Field->isUnnamedBitfield())
5600 continue;
5602 PopulateKeysForFields(Field, IdealInitKeys);
5605 unsigned NumIdealInits = IdealInitKeys.size();
5606 unsigned IdealIndex = 0;
5608 // Track initializers that are in an incorrect order for either a warning or
5609 // note if multiple ones occur.
5610 SmallVector<unsigned> WarnIndexes;
5611 // Correlates the index of an initializer in the init-list to the index of
5612 // the field/base in the class.
5613 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5615 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5616 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5618 // Scan forward to try to find this initializer in the idealized
5619 // initializers list.
5620 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5621 if (InitKey == IdealInitKeys[IdealIndex])
5622 break;
5624 // If we didn't find this initializer, it must be because we
5625 // scanned past it on a previous iteration. That can only
5626 // happen if we're out of order; emit a warning.
5627 if (IdealIndex == NumIdealInits && InitIndex) {
5628 WarnIndexes.push_back(InitIndex);
5630 // Move back to the initializer's location in the ideal list.
5631 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5632 if (InitKey == IdealInitKeys[IdealIndex])
5633 break;
5635 assert(IdealIndex < NumIdealInits &&
5636 "initializer not found in initializer list");
5638 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5641 if (WarnIndexes.empty())
5642 return;
5644 // Sort based on the ideal order, first in the pair.
5645 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5647 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5648 // emit the diagnostic before we can try adding notes.
5650 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5651 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5652 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5653 : diag::warn_some_initializers_out_of_order);
5655 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5656 if (CorrelatedInitOrder[I].second == I)
5657 continue;
5658 // Ideally we would be using InsertFromRange here, but clang doesn't
5659 // appear to handle InsertFromRange correctly when the source range is
5660 // modified by another fix-it.
5661 D << FixItHint::CreateReplacement(
5662 Inits[I]->getSourceRange(),
5663 Lexer::getSourceText(
5664 CharSourceRange::getTokenRange(
5665 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5666 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5669 // If there is only 1 item out of order, the warning expects the name and
5670 // type of each being added to it.
5671 if (WarnIndexes.size() == 1) {
5672 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5673 Inits[WarnIndexes.front()]);
5674 return;
5677 // More than 1 item to warn, create notes letting the user know which ones
5678 // are bad.
5679 for (unsigned WarnIndex : WarnIndexes) {
5680 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5681 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5682 diag::note_initializer_out_of_order);
5683 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5684 D << PrevInit->getSourceRange();
5688 namespace {
5689 bool CheckRedundantInit(Sema &S,
5690 CXXCtorInitializer *Init,
5691 CXXCtorInitializer *&PrevInit) {
5692 if (!PrevInit) {
5693 PrevInit = Init;
5694 return false;
5697 if (FieldDecl *Field = Init->getAnyMember())
5698 S.Diag(Init->getSourceLocation(),
5699 diag::err_multiple_mem_initialization)
5700 << Field->getDeclName()
5701 << Init->getSourceRange();
5702 else {
5703 const Type *BaseClass = Init->getBaseClass();
5704 assert(BaseClass && "neither field nor base");
5705 S.Diag(Init->getSourceLocation(),
5706 diag::err_multiple_base_initialization)
5707 << QualType(BaseClass, 0)
5708 << Init->getSourceRange();
5710 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5711 << 0 << PrevInit->getSourceRange();
5713 return true;
5716 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5717 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5719 bool CheckRedundantUnionInit(Sema &S,
5720 CXXCtorInitializer *Init,
5721 RedundantUnionMap &Unions) {
5722 FieldDecl *Field = Init->getAnyMember();
5723 RecordDecl *Parent = Field->getParent();
5724 NamedDecl *Child = Field;
5726 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5727 if (Parent->isUnion()) {
5728 UnionEntry &En = Unions[Parent];
5729 if (En.first && En.first != Child) {
5730 S.Diag(Init->getSourceLocation(),
5731 diag::err_multiple_mem_union_initialization)
5732 << Field->getDeclName()
5733 << Init->getSourceRange();
5734 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5735 << 0 << En.second->getSourceRange();
5736 return true;
5738 if (!En.first) {
5739 En.first = Child;
5740 En.second = Init;
5742 if (!Parent->isAnonymousStructOrUnion())
5743 return false;
5746 Child = Parent;
5747 Parent = cast<RecordDecl>(Parent->getDeclContext());
5750 return false;
5752 } // namespace
5754 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5755 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5756 SourceLocation ColonLoc,
5757 ArrayRef<CXXCtorInitializer*> MemInits,
5758 bool AnyErrors) {
5759 if (!ConstructorDecl)
5760 return;
5762 AdjustDeclIfTemplate(ConstructorDecl);
5764 CXXConstructorDecl *Constructor
5765 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5767 if (!Constructor) {
5768 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5769 return;
5772 // Mapping for the duplicate initializers check.
5773 // For member initializers, this is keyed with a FieldDecl*.
5774 // For base initializers, this is keyed with a Type*.
5775 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5777 // Mapping for the inconsistent anonymous-union initializers check.
5778 RedundantUnionMap MemberUnions;
5780 bool HadError = false;
5781 for (unsigned i = 0; i < MemInits.size(); i++) {
5782 CXXCtorInitializer *Init = MemInits[i];
5784 // Set the source order index.
5785 Init->setSourceOrder(i);
5787 if (Init->isAnyMemberInitializer()) {
5788 const void *Key = GetKeyForMember(Context, Init);
5789 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5790 CheckRedundantUnionInit(*this, Init, MemberUnions))
5791 HadError = true;
5792 } else if (Init->isBaseInitializer()) {
5793 const void *Key = GetKeyForMember(Context, Init);
5794 if (CheckRedundantInit(*this, Init, Members[Key]))
5795 HadError = true;
5796 } else {
5797 assert(Init->isDelegatingInitializer());
5798 // This must be the only initializer
5799 if (MemInits.size() != 1) {
5800 Diag(Init->getSourceLocation(),
5801 diag::err_delegating_initializer_alone)
5802 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5803 // We will treat this as being the only initializer.
5805 SetDelegatingInitializer(Constructor, MemInits[i]);
5806 // Return immediately as the initializer is set.
5807 return;
5811 if (HadError)
5812 return;
5814 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5816 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5818 DiagnoseUninitializedFields(*this, Constructor);
5821 void
5822 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5823 CXXRecordDecl *ClassDecl) {
5824 // Ignore dependent contexts. Also ignore unions, since their members never
5825 // have destructors implicitly called.
5826 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5827 return;
5829 // FIXME: all the access-control diagnostics are positioned on the
5830 // field/base declaration. That's probably good; that said, the
5831 // user might reasonably want to know why the destructor is being
5832 // emitted, and we currently don't say.
5834 // Non-static data members.
5835 for (auto *Field : ClassDecl->fields()) {
5836 if (Field->isInvalidDecl())
5837 continue;
5839 // Don't destroy incomplete or zero-length arrays.
5840 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5841 continue;
5843 QualType FieldType = Context.getBaseElementType(Field->getType());
5845 const RecordType* RT = FieldType->getAs<RecordType>();
5846 if (!RT)
5847 continue;
5849 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5850 if (FieldClassDecl->isInvalidDecl())
5851 continue;
5852 if (FieldClassDecl->hasIrrelevantDestructor())
5853 continue;
5854 // The destructor for an implicit anonymous union member is never invoked.
5855 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5856 continue;
5858 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5859 // Dtor might still be missing, e.g because it's invalid.
5860 if (!Dtor)
5861 continue;
5862 CheckDestructorAccess(Field->getLocation(), Dtor,
5863 PDiag(diag::err_access_dtor_field)
5864 << Field->getDeclName()
5865 << FieldType);
5867 MarkFunctionReferenced(Location, Dtor);
5868 DiagnoseUseOfDecl(Dtor, Location);
5871 // We only potentially invoke the destructors of potentially constructed
5872 // subobjects.
5873 bool VisitVirtualBases = !ClassDecl->isAbstract();
5875 // If the destructor exists and has already been marked used in the MS ABI,
5876 // then virtual base destructors have already been checked and marked used.
5877 // Skip checking them again to avoid duplicate diagnostics.
5878 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5879 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5880 if (Dtor && Dtor->isUsed())
5881 VisitVirtualBases = false;
5884 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5886 // Bases.
5887 for (const auto &Base : ClassDecl->bases()) {
5888 const RecordType *RT = Base.getType()->getAs<RecordType>();
5889 if (!RT)
5890 continue;
5892 // Remember direct virtual bases.
5893 if (Base.isVirtual()) {
5894 if (!VisitVirtualBases)
5895 continue;
5896 DirectVirtualBases.insert(RT);
5899 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5900 // If our base class is invalid, we probably can't get its dtor anyway.
5901 if (BaseClassDecl->isInvalidDecl())
5902 continue;
5903 if (BaseClassDecl->hasIrrelevantDestructor())
5904 continue;
5906 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5907 // Dtor might still be missing, e.g because it's invalid.
5908 if (!Dtor)
5909 continue;
5911 // FIXME: caret should be on the start of the class name
5912 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5913 PDiag(diag::err_access_dtor_base)
5914 << Base.getType() << Base.getSourceRange(),
5915 Context.getTypeDeclType(ClassDecl));
5917 MarkFunctionReferenced(Location, Dtor);
5918 DiagnoseUseOfDecl(Dtor, Location);
5921 if (VisitVirtualBases)
5922 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5923 &DirectVirtualBases);
5926 void Sema::MarkVirtualBaseDestructorsReferenced(
5927 SourceLocation Location, CXXRecordDecl *ClassDecl,
5928 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5929 // Virtual bases.
5930 for (const auto &VBase : ClassDecl->vbases()) {
5931 // Bases are always records in a well-formed non-dependent class.
5932 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5934 // Ignore already visited direct virtual bases.
5935 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5936 continue;
5938 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5939 // If our base class is invalid, we probably can't get its dtor anyway.
5940 if (BaseClassDecl->isInvalidDecl())
5941 continue;
5942 if (BaseClassDecl->hasIrrelevantDestructor())
5943 continue;
5945 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5946 // Dtor might still be missing, e.g because it's invalid.
5947 if (!Dtor)
5948 continue;
5949 if (CheckDestructorAccess(
5950 ClassDecl->getLocation(), Dtor,
5951 PDiag(diag::err_access_dtor_vbase)
5952 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5953 Context.getTypeDeclType(ClassDecl)) ==
5954 AR_accessible) {
5955 CheckDerivedToBaseConversion(
5956 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5957 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5958 SourceRange(), DeclarationName(), nullptr);
5961 MarkFunctionReferenced(Location, Dtor);
5962 DiagnoseUseOfDecl(Dtor, Location);
5966 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5967 if (!CDtorDecl)
5968 return;
5970 if (CXXConstructorDecl *Constructor
5971 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5972 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5973 DiagnoseUninitializedFields(*this, Constructor);
5977 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5978 if (!getLangOpts().CPlusPlus)
5979 return false;
5981 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5982 if (!RD)
5983 return false;
5985 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5986 // class template specialization here, but doing so breaks a lot of code.
5988 // We can't answer whether something is abstract until it has a
5989 // definition. If it's currently being defined, we'll walk back
5990 // over all the declarations when we have a full definition.
5991 const CXXRecordDecl *Def = RD->getDefinition();
5992 if (!Def || Def->isBeingDefined())
5993 return false;
5995 return RD->isAbstract();
5998 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5999 TypeDiagnoser &Diagnoser) {
6000 if (!isAbstractType(Loc, T))
6001 return false;
6003 T = Context.getBaseElementType(T);
6004 Diagnoser.diagnose(*this, Loc, T);
6005 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6006 return true;
6009 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6010 // Check if we've already emitted the list of pure virtual functions
6011 // for this class.
6012 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
6013 return;
6015 // If the diagnostic is suppressed, don't emit the notes. We're only
6016 // going to emit them once, so try to attach them to a diagnostic we're
6017 // actually going to show.
6018 if (Diags.isLastDiagnosticIgnored())
6019 return;
6021 CXXFinalOverriderMap FinalOverriders;
6022 RD->getFinalOverriders(FinalOverriders);
6024 // Keep a set of seen pure methods so we won't diagnose the same method
6025 // more than once.
6026 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6028 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6029 MEnd = FinalOverriders.end();
6030 M != MEnd;
6031 ++M) {
6032 for (OverridingMethods::iterator SO = M->second.begin(),
6033 SOEnd = M->second.end();
6034 SO != SOEnd; ++SO) {
6035 // C++ [class.abstract]p4:
6036 // A class is abstract if it contains or inherits at least one
6037 // pure virtual function for which the final overrider is pure
6038 // virtual.
6041 if (SO->second.size() != 1)
6042 continue;
6044 if (!SO->second.front().Method->isPure())
6045 continue;
6047 if (!SeenPureMethods.insert(SO->second.front().Method).second)
6048 continue;
6050 Diag(SO->second.front().Method->getLocation(),
6051 diag::note_pure_virtual_function)
6052 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6056 if (!PureVirtualClassDiagSet)
6057 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
6058 PureVirtualClassDiagSet->insert(RD);
6061 namespace {
6062 struct AbstractUsageInfo {
6063 Sema &S;
6064 CXXRecordDecl *Record;
6065 CanQualType AbstractType;
6066 bool Invalid;
6068 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6069 : S(S), Record(Record),
6070 AbstractType(S.Context.getCanonicalType(
6071 S.Context.getTypeDeclType(Record))),
6072 Invalid(false) {}
6074 void DiagnoseAbstractType() {
6075 if (Invalid) return;
6076 S.DiagnoseAbstractType(Record);
6077 Invalid = true;
6080 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6083 struct CheckAbstractUsage {
6084 AbstractUsageInfo &Info;
6085 const NamedDecl *Ctx;
6087 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6088 : Info(Info), Ctx(Ctx) {}
6090 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6091 switch (TL.getTypeLocClass()) {
6092 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6093 #define TYPELOC(CLASS, PARENT) \
6094 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6095 #include "clang/AST/TypeLocNodes.def"
6099 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6100 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
6101 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6102 if (!TL.getParam(I))
6103 continue;
6105 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6106 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6110 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6111 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
6114 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6115 // Visit the type parameters from a permissive context.
6116 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6117 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6118 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6119 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6120 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6121 // TODO: other template argument types?
6125 // Visit pointee types from a permissive context.
6126 #define CheckPolymorphic(Type) \
6127 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6128 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6130 CheckPolymorphic(PointerTypeLoc)
6131 CheckPolymorphic(ReferenceTypeLoc)
6132 CheckPolymorphic(MemberPointerTypeLoc)
6133 CheckPolymorphic(BlockPointerTypeLoc)
6134 CheckPolymorphic(AtomicTypeLoc)
6136 /// Handle all the types we haven't given a more specific
6137 /// implementation for above.
6138 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6139 // Every other kind of type that we haven't called out already
6140 // that has an inner type is either (1) sugar or (2) contains that
6141 // inner type in some way as a subobject.
6142 if (TypeLoc Next = TL.getNextTypeLoc())
6143 return Visit(Next, Sel);
6145 // If there's no inner type and we're in a permissive context,
6146 // don't diagnose.
6147 if (Sel == Sema::AbstractNone) return;
6149 // Check whether the type matches the abstract type.
6150 QualType T = TL.getType();
6151 if (T->isArrayType()) {
6152 Sel = Sema::AbstractArrayType;
6153 T = Info.S.Context.getBaseElementType(T);
6155 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6156 if (CT != Info.AbstractType) return;
6158 // It matched; do some magic.
6159 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6160 if (Sel == Sema::AbstractArrayType) {
6161 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6162 << T << TL.getSourceRange();
6163 } else {
6164 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6165 << Sel << T << TL.getSourceRange();
6167 Info.DiagnoseAbstractType();
6171 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6172 Sema::AbstractDiagSelID Sel) {
6173 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6178 /// Check for invalid uses of an abstract type in a function declaration.
6179 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6180 FunctionDecl *FD) {
6181 // Only definitions are required to refer to complete and
6182 // non-abstract types.
6183 if (!FD->doesThisDeclarationHaveABody())
6184 return;
6186 // For safety's sake, just ignore it if we don't have type source
6187 // information. This should never happen for non-implicit methods,
6188 // but...
6189 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6190 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6193 /// Check for invalid uses of an abstract type in a variable0 declaration.
6194 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6195 VarDecl *VD) {
6196 // No need to do the check on definitions, which require that
6197 // the type is complete.
6198 if (VD->isThisDeclarationADefinition())
6199 return;
6201 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6202 Sema::AbstractVariableType);
6205 /// Check for invalid uses of an abstract type within a class definition.
6206 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6207 CXXRecordDecl *RD) {
6208 for (auto *D : RD->decls()) {
6209 if (D->isImplicit()) continue;
6211 // Step through friends to the befriended declaration.
6212 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6213 D = FD->getFriendDecl();
6214 if (!D) continue;
6217 // Functions and function templates.
6218 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6219 CheckAbstractClassUsage(Info, FD);
6220 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6221 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6223 // Fields and static variables.
6224 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6225 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6226 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6227 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6228 CheckAbstractClassUsage(Info, VD);
6229 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6230 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6232 // Nested classes and class templates.
6233 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6234 CheckAbstractClassUsage(Info, RD);
6235 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6236 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6241 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6242 Attr *ClassAttr = getDLLAttr(Class);
6243 if (!ClassAttr)
6244 return;
6246 assert(ClassAttr->getKind() == attr::DLLExport);
6248 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6250 if (TSK == TSK_ExplicitInstantiationDeclaration)
6251 // Don't go any further if this is just an explicit instantiation
6252 // declaration.
6253 return;
6255 // Add a context note to explain how we got to any diagnostics produced below.
6256 struct MarkingClassDllexported {
6257 Sema &S;
6258 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6259 SourceLocation AttrLoc)
6260 : S(S) {
6261 Sema::CodeSynthesisContext Ctx;
6262 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6263 Ctx.PointOfInstantiation = AttrLoc;
6264 Ctx.Entity = Class;
6265 S.pushCodeSynthesisContext(Ctx);
6267 ~MarkingClassDllexported() {
6268 S.popCodeSynthesisContext();
6270 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6272 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6273 S.MarkVTableUsed(Class->getLocation(), Class, true);
6275 for (Decl *Member : Class->decls()) {
6276 // Skip members that were not marked exported.
6277 if (!Member->hasAttr<DLLExportAttr>())
6278 continue;
6280 // Defined static variables that are members of an exported base
6281 // class must be marked export too.
6282 auto *VD = dyn_cast<VarDecl>(Member);
6283 if (VD && VD->getStorageClass() == SC_Static &&
6284 TSK == TSK_ImplicitInstantiation)
6285 S.MarkVariableReferenced(VD->getLocation(), VD);
6287 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6288 if (!MD)
6289 continue;
6291 if (MD->isUserProvided()) {
6292 // Instantiate non-default class member functions ...
6294 // .. except for certain kinds of template specializations.
6295 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6296 continue;
6298 // If this is an MS ABI dllexport default constructor, instantiate any
6299 // default arguments.
6300 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6301 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6302 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6303 S.InstantiateDefaultCtorDefaultArgs(CD);
6307 S.MarkFunctionReferenced(Class->getLocation(), MD);
6309 // The function will be passed to the consumer when its definition is
6310 // encountered.
6311 } else if (MD->isExplicitlyDefaulted()) {
6312 // Synthesize and instantiate explicitly defaulted methods.
6313 S.MarkFunctionReferenced(Class->getLocation(), MD);
6315 if (TSK != TSK_ExplicitInstantiationDefinition) {
6316 // Except for explicit instantiation defs, we will not see the
6317 // definition again later, so pass it to the consumer now.
6318 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6320 } else if (!MD->isTrivial() ||
6321 MD->isCopyAssignmentOperator() ||
6322 MD->isMoveAssignmentOperator()) {
6323 // Synthesize and instantiate non-trivial implicit methods, and the copy
6324 // and move assignment operators. The latter are exported even if they
6325 // are trivial, because the address of an operator can be taken and
6326 // should compare equal across libraries.
6327 S.MarkFunctionReferenced(Class->getLocation(), MD);
6329 // There is no later point when we will see the definition of this
6330 // function, so pass it to the consumer now.
6331 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6336 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6337 CXXRecordDecl *Class) {
6338 // Only the MS ABI has default constructor closures, so we don't need to do
6339 // this semantic checking anywhere else.
6340 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6341 return;
6343 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6344 for (Decl *Member : Class->decls()) {
6345 // Look for exported default constructors.
6346 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6347 if (!CD || !CD->isDefaultConstructor())
6348 continue;
6349 auto *Attr = CD->getAttr<DLLExportAttr>();
6350 if (!Attr)
6351 continue;
6353 // If the class is non-dependent, mark the default arguments as ODR-used so
6354 // that we can properly codegen the constructor closure.
6355 if (!Class->isDependentContext()) {
6356 for (ParmVarDecl *PD : CD->parameters()) {
6357 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6358 S.DiscardCleanupsInEvaluationContext();
6362 if (LastExportedDefaultCtor) {
6363 S.Diag(LastExportedDefaultCtor->getLocation(),
6364 diag::err_attribute_dll_ambiguous_default_ctor)
6365 << Class;
6366 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6367 << CD->getDeclName();
6368 return;
6370 LastExportedDefaultCtor = CD;
6374 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6375 CXXRecordDecl *Class) {
6376 bool ErrorReported = false;
6377 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6378 ClassTemplateDecl *TD) {
6379 if (ErrorReported)
6380 return;
6381 S.Diag(TD->getLocation(),
6382 diag::err_cuda_device_builtin_surftex_cls_template)
6383 << /*surface*/ 0 << TD;
6384 ErrorReported = true;
6387 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6388 if (!TD) {
6389 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6390 if (!SD) {
6391 S.Diag(Class->getLocation(),
6392 diag::err_cuda_device_builtin_surftex_ref_decl)
6393 << /*surface*/ 0 << Class;
6394 S.Diag(Class->getLocation(),
6395 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6396 << Class;
6397 return;
6399 TD = SD->getSpecializedTemplate();
6402 TemplateParameterList *Params = TD->getTemplateParameters();
6403 unsigned N = Params->size();
6405 if (N != 2) {
6406 reportIllegalClassTemplate(S, TD);
6407 S.Diag(TD->getLocation(),
6408 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6409 << TD << 2;
6411 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6412 reportIllegalClassTemplate(S, TD);
6413 S.Diag(TD->getLocation(),
6414 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6415 << TD << /*1st*/ 0 << /*type*/ 0;
6417 if (N > 1) {
6418 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6419 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6420 reportIllegalClassTemplate(S, TD);
6421 S.Diag(TD->getLocation(),
6422 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6423 << TD << /*2nd*/ 1 << /*integer*/ 1;
6428 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6429 CXXRecordDecl *Class) {
6430 bool ErrorReported = false;
6431 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6432 ClassTemplateDecl *TD) {
6433 if (ErrorReported)
6434 return;
6435 S.Diag(TD->getLocation(),
6436 diag::err_cuda_device_builtin_surftex_cls_template)
6437 << /*texture*/ 1 << TD;
6438 ErrorReported = true;
6441 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6442 if (!TD) {
6443 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6444 if (!SD) {
6445 S.Diag(Class->getLocation(),
6446 diag::err_cuda_device_builtin_surftex_ref_decl)
6447 << /*texture*/ 1 << Class;
6448 S.Diag(Class->getLocation(),
6449 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6450 << Class;
6451 return;
6453 TD = SD->getSpecializedTemplate();
6456 TemplateParameterList *Params = TD->getTemplateParameters();
6457 unsigned N = Params->size();
6459 if (N != 3) {
6460 reportIllegalClassTemplate(S, TD);
6461 S.Diag(TD->getLocation(),
6462 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6463 << TD << 3;
6465 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6466 reportIllegalClassTemplate(S, TD);
6467 S.Diag(TD->getLocation(),
6468 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6469 << TD << /*1st*/ 0 << /*type*/ 0;
6471 if (N > 1) {
6472 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6473 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6474 reportIllegalClassTemplate(S, TD);
6475 S.Diag(TD->getLocation(),
6476 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6477 << TD << /*2nd*/ 1 << /*integer*/ 1;
6480 if (N > 2) {
6481 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6482 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6483 reportIllegalClassTemplate(S, TD);
6484 S.Diag(TD->getLocation(),
6485 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6486 << TD << /*3rd*/ 2 << /*integer*/ 1;
6491 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6492 // Mark any compiler-generated routines with the implicit code_seg attribute.
6493 for (auto *Method : Class->methods()) {
6494 if (Method->isUserProvided())
6495 continue;
6496 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6497 Method->addAttr(A);
6501 /// Check class-level dllimport/dllexport attribute.
6502 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6503 Attr *ClassAttr = getDLLAttr(Class);
6505 // MSVC inherits DLL attributes to partial class template specializations.
6506 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6507 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6508 if (Attr *TemplateAttr =
6509 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6510 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6511 A->setInherited(true);
6512 ClassAttr = A;
6517 if (!ClassAttr)
6518 return;
6520 // MSVC allows imported or exported template classes that have UniqueExternal
6521 // linkage. This occurs when the template class has been instantiated with
6522 // a template parameter which itself has internal linkage.
6523 // We drop the attribute to avoid exporting or importing any members.
6524 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6525 Context.getTargetInfo().getTriple().isPS()) &&
6526 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6527 Class->dropAttr<DLLExportAttr>();
6528 Class->dropAttr<DLLImportAttr>();
6529 return;
6532 if (!Class->isExternallyVisible()) {
6533 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6534 << Class << ClassAttr;
6535 return;
6538 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6539 !ClassAttr->isInherited()) {
6540 // Diagnose dll attributes on members of class with dll attribute.
6541 for (Decl *Member : Class->decls()) {
6542 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6543 continue;
6544 InheritableAttr *MemberAttr = getDLLAttr(Member);
6545 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6546 continue;
6548 Diag(MemberAttr->getLocation(),
6549 diag::err_attribute_dll_member_of_dll_class)
6550 << MemberAttr << ClassAttr;
6551 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6552 Member->setInvalidDecl();
6556 if (Class->getDescribedClassTemplate())
6557 // Don't inherit dll attribute until the template is instantiated.
6558 return;
6560 // The class is either imported or exported.
6561 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6563 // Check if this was a dllimport attribute propagated from a derived class to
6564 // a base class template specialization. We don't apply these attributes to
6565 // static data members.
6566 const bool PropagatedImport =
6567 !ClassExported &&
6568 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6570 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6572 // Ignore explicit dllexport on explicit class template instantiation
6573 // declarations, except in MinGW mode.
6574 if (ClassExported && !ClassAttr->isInherited() &&
6575 TSK == TSK_ExplicitInstantiationDeclaration &&
6576 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6577 Class->dropAttr<DLLExportAttr>();
6578 return;
6581 // Force declaration of implicit members so they can inherit the attribute.
6582 ForceDeclarationOfImplicitMembers(Class);
6584 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6585 // seem to be true in practice?
6587 for (Decl *Member : Class->decls()) {
6588 VarDecl *VD = dyn_cast<VarDecl>(Member);
6589 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6591 // Only methods and static fields inherit the attributes.
6592 if (!VD && !MD)
6593 continue;
6595 if (MD) {
6596 // Don't process deleted methods.
6597 if (MD->isDeleted())
6598 continue;
6600 if (MD->isInlined()) {
6601 // MinGW does not import or export inline methods. But do it for
6602 // template instantiations.
6603 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6604 TSK != TSK_ExplicitInstantiationDeclaration &&
6605 TSK != TSK_ExplicitInstantiationDefinition)
6606 continue;
6608 // MSVC versions before 2015 don't export the move assignment operators
6609 // and move constructor, so don't attempt to import/export them if
6610 // we have a definition.
6611 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6612 if ((MD->isMoveAssignmentOperator() ||
6613 (Ctor && Ctor->isMoveConstructor())) &&
6614 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6615 continue;
6617 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6618 // operator is exported anyway.
6619 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6620 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6621 continue;
6625 // Don't apply dllimport attributes to static data members of class template
6626 // instantiations when the attribute is propagated from a derived class.
6627 if (VD && PropagatedImport)
6628 continue;
6630 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6631 continue;
6633 if (!getDLLAttr(Member)) {
6634 InheritableAttr *NewAttr = nullptr;
6636 // Do not export/import inline function when -fno-dllexport-inlines is
6637 // passed. But add attribute for later local static var check.
6638 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6639 TSK != TSK_ExplicitInstantiationDeclaration &&
6640 TSK != TSK_ExplicitInstantiationDefinition) {
6641 if (ClassExported) {
6642 NewAttr = ::new (getASTContext())
6643 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6644 } else {
6645 NewAttr = ::new (getASTContext())
6646 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6648 } else {
6649 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6652 NewAttr->setInherited(true);
6653 Member->addAttr(NewAttr);
6655 if (MD) {
6656 // Propagate DLLAttr to friend re-declarations of MD that have already
6657 // been constructed.
6658 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6659 FD = FD->getPreviousDecl()) {
6660 if (FD->getFriendObjectKind() == Decl::FOK_None)
6661 continue;
6662 assert(!getDLLAttr(FD) &&
6663 "friend re-decl should not already have a DLLAttr");
6664 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6665 NewAttr->setInherited(true);
6666 FD->addAttr(NewAttr);
6672 if (ClassExported)
6673 DelayedDllExportClasses.push_back(Class);
6676 /// Perform propagation of DLL attributes from a derived class to a
6677 /// templated base class for MS compatibility.
6678 void Sema::propagateDLLAttrToBaseClassTemplate(
6679 CXXRecordDecl *Class, Attr *ClassAttr,
6680 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6681 if (getDLLAttr(
6682 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6683 // If the base class template has a DLL attribute, don't try to change it.
6684 return;
6687 auto TSK = BaseTemplateSpec->getSpecializationKind();
6688 if (!getDLLAttr(BaseTemplateSpec) &&
6689 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6690 TSK == TSK_ImplicitInstantiation)) {
6691 // The template hasn't been instantiated yet (or it has, but only as an
6692 // explicit instantiation declaration or implicit instantiation, which means
6693 // we haven't codegenned any members yet), so propagate the attribute.
6694 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6695 NewAttr->setInherited(true);
6696 BaseTemplateSpec->addAttr(NewAttr);
6698 // If this was an import, mark that we propagated it from a derived class to
6699 // a base class template specialization.
6700 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6701 ImportAttr->setPropagatedToBaseTemplate();
6703 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6704 // needs to be run again to work see the new attribute. Otherwise this will
6705 // get run whenever the template is instantiated.
6706 if (TSK != TSK_Undeclared)
6707 checkClassLevelDLLAttribute(BaseTemplateSpec);
6709 return;
6712 if (getDLLAttr(BaseTemplateSpec)) {
6713 // The template has already been specialized or instantiated with an
6714 // attribute, explicitly or through propagation. We should not try to change
6715 // it.
6716 return;
6719 // The template was previously instantiated or explicitly specialized without
6720 // a dll attribute, It's too late for us to add an attribute, so warn that
6721 // this is unsupported.
6722 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6723 << BaseTemplateSpec->isExplicitSpecialization();
6724 Diag(ClassAttr->getLocation(), diag::note_attribute);
6725 if (BaseTemplateSpec->isExplicitSpecialization()) {
6726 Diag(BaseTemplateSpec->getLocation(),
6727 diag::note_template_class_explicit_specialization_was_here)
6728 << BaseTemplateSpec;
6729 } else {
6730 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6731 diag::note_template_class_instantiation_was_here)
6732 << BaseTemplateSpec;
6736 /// Determine the kind of defaulting that would be done for a given function.
6738 /// If the function is both a default constructor and a copy / move constructor
6739 /// (due to having a default argument for the first parameter), this picks
6740 /// CXXDefaultConstructor.
6742 /// FIXME: Check that case is properly handled by all callers.
6743 Sema::DefaultedFunctionKind
6744 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6745 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6746 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6747 if (Ctor->isDefaultConstructor())
6748 return Sema::CXXDefaultConstructor;
6750 if (Ctor->isCopyConstructor())
6751 return Sema::CXXCopyConstructor;
6753 if (Ctor->isMoveConstructor())
6754 return Sema::CXXMoveConstructor;
6757 if (MD->isCopyAssignmentOperator())
6758 return Sema::CXXCopyAssignment;
6760 if (MD->isMoveAssignmentOperator())
6761 return Sema::CXXMoveAssignment;
6763 if (isa<CXXDestructorDecl>(FD))
6764 return Sema::CXXDestructor;
6767 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6768 case OO_EqualEqual:
6769 return DefaultedComparisonKind::Equal;
6771 case OO_ExclaimEqual:
6772 return DefaultedComparisonKind::NotEqual;
6774 case OO_Spaceship:
6775 // No point allowing this if <=> doesn't exist in the current language mode.
6776 if (!getLangOpts().CPlusPlus20)
6777 break;
6778 return DefaultedComparisonKind::ThreeWay;
6780 case OO_Less:
6781 case OO_LessEqual:
6782 case OO_Greater:
6783 case OO_GreaterEqual:
6784 // No point allowing this if <=> doesn't exist in the current language mode.
6785 if (!getLangOpts().CPlusPlus20)
6786 break;
6787 return DefaultedComparisonKind::Relational;
6789 default:
6790 break;
6793 // Not defaultable.
6794 return DefaultedFunctionKind();
6797 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6798 SourceLocation DefaultLoc) {
6799 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6800 if (DFK.isComparison())
6801 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6803 switch (DFK.asSpecialMember()) {
6804 case Sema::CXXDefaultConstructor:
6805 S.DefineImplicitDefaultConstructor(DefaultLoc,
6806 cast<CXXConstructorDecl>(FD));
6807 break;
6808 case Sema::CXXCopyConstructor:
6809 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6810 break;
6811 case Sema::CXXCopyAssignment:
6812 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6813 break;
6814 case Sema::CXXDestructor:
6815 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6816 break;
6817 case Sema::CXXMoveConstructor:
6818 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6819 break;
6820 case Sema::CXXMoveAssignment:
6821 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6822 break;
6823 case Sema::CXXInvalid:
6824 llvm_unreachable("Invalid special member.");
6828 /// Determine whether a type is permitted to be passed or returned in
6829 /// registers, per C++ [class.temporary]p3.
6830 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6831 TargetInfo::CallingConvKind CCK) {
6832 if (D->isDependentType() || D->isInvalidDecl())
6833 return false;
6835 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6836 // The PS4 platform ABI follows the behavior of Clang 3.2.
6837 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6838 return !D->hasNonTrivialDestructorForCall() &&
6839 !D->hasNonTrivialCopyConstructorForCall();
6841 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6842 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6843 bool DtorIsTrivialForCall = false;
6845 // If a class has at least one eligible, trivial copy constructor, it
6846 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6848 // Note: This permits classes with non-trivial copy or move ctors to be
6849 // passed in registers, so long as they *also* have a trivial copy ctor,
6850 // which is non-conforming.
6851 if (D->needsImplicitCopyConstructor()) {
6852 if (!D->defaultedCopyConstructorIsDeleted()) {
6853 if (D->hasTrivialCopyConstructor())
6854 CopyCtorIsTrivial = true;
6855 if (D->hasTrivialCopyConstructorForCall())
6856 CopyCtorIsTrivialForCall = true;
6858 } else {
6859 for (const CXXConstructorDecl *CD : D->ctors()) {
6860 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6861 !CD->isIneligibleOrNotSelected()) {
6862 if (CD->isTrivial())
6863 CopyCtorIsTrivial = true;
6864 if (CD->isTrivialForCall())
6865 CopyCtorIsTrivialForCall = true;
6870 if (D->needsImplicitDestructor()) {
6871 if (!D->defaultedDestructorIsDeleted() &&
6872 D->hasTrivialDestructorForCall())
6873 DtorIsTrivialForCall = true;
6874 } else if (const auto *DD = D->getDestructor()) {
6875 if (!DD->isDeleted() && DD->isTrivialForCall())
6876 DtorIsTrivialForCall = true;
6879 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6880 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6881 return true;
6883 // If a class has a destructor, we'd really like to pass it indirectly
6884 // because it allows us to elide copies. Unfortunately, MSVC makes that
6885 // impossible for small types, which it will pass in a single register or
6886 // stack slot. Most objects with dtors are large-ish, so handle that early.
6887 // We can't call out all large objects as being indirect because there are
6888 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6889 // how we pass large POD types.
6891 // Note: This permits small classes with nontrivial destructors to be
6892 // passed in registers, which is non-conforming.
6893 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6894 uint64_t TypeSize = isAArch64 ? 128 : 64;
6896 if (CopyCtorIsTrivial &&
6897 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6898 return true;
6899 return false;
6902 // Per C++ [class.temporary]p3, the relevant condition is:
6903 // each copy constructor, move constructor, and destructor of X is
6904 // either trivial or deleted, and X has at least one non-deleted copy
6905 // or move constructor
6906 bool HasNonDeletedCopyOrMove = false;
6908 if (D->needsImplicitCopyConstructor() &&
6909 !D->defaultedCopyConstructorIsDeleted()) {
6910 if (!D->hasTrivialCopyConstructorForCall())
6911 return false;
6912 HasNonDeletedCopyOrMove = true;
6915 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6916 !D->defaultedMoveConstructorIsDeleted()) {
6917 if (!D->hasTrivialMoveConstructorForCall())
6918 return false;
6919 HasNonDeletedCopyOrMove = true;
6922 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6923 !D->hasTrivialDestructorForCall())
6924 return false;
6926 for (const CXXMethodDecl *MD : D->methods()) {
6927 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6928 continue;
6930 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6931 if (CD && CD->isCopyOrMoveConstructor())
6932 HasNonDeletedCopyOrMove = true;
6933 else if (!isa<CXXDestructorDecl>(MD))
6934 continue;
6936 if (!MD->isTrivialForCall())
6937 return false;
6940 return HasNonDeletedCopyOrMove;
6943 /// Report an error regarding overriding, along with any relevant
6944 /// overridden methods.
6946 /// \param DiagID the primary error to report.
6947 /// \param MD the overriding method.
6948 static bool
6949 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6950 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6951 bool IssuedDiagnostic = false;
6952 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6953 if (Report(O)) {
6954 if (!IssuedDiagnostic) {
6955 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6956 IssuedDiagnostic = true;
6958 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6961 return IssuedDiagnostic;
6964 /// Perform semantic checks on a class definition that has been
6965 /// completing, introducing implicitly-declared members, checking for
6966 /// abstract types, etc.
6968 /// \param S The scope in which the class was parsed. Null if we didn't just
6969 /// parse a class definition.
6970 /// \param Record The completed class.
6971 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6972 if (!Record)
6973 return;
6975 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6976 AbstractUsageInfo Info(*this, Record);
6977 CheckAbstractClassUsage(Info, Record);
6980 // If this is not an aggregate type and has no user-declared constructor,
6981 // complain about any non-static data members of reference or const scalar
6982 // type, since they will never get initializers.
6983 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6984 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6985 !Record->isLambda()) {
6986 bool Complained = false;
6987 for (const auto *F : Record->fields()) {
6988 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6989 continue;
6991 if (F->getType()->isReferenceType() ||
6992 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6993 if (!Complained) {
6994 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6995 << Record->getTagKind() << Record;
6996 Complained = true;
6999 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7000 << F->getType()->isReferenceType()
7001 << F->getDeclName();
7006 if (Record->getIdentifier()) {
7007 // C++ [class.mem]p13:
7008 // If T is the name of a class, then each of the following shall have a
7009 // name different from T:
7010 // - every member of every anonymous union that is a member of class T.
7012 // C++ [class.mem]p14:
7013 // In addition, if class T has a user-declared constructor (12.1), every
7014 // non-static data member of class T shall have a name different from T.
7015 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7016 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7017 ++I) {
7018 NamedDecl *D = (*I)->getUnderlyingDecl();
7019 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7020 Record->hasUserDeclaredConstructor()) ||
7021 isa<IndirectFieldDecl>(D)) {
7022 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7023 << D->getDeclName();
7024 break;
7029 // Warn if the class has virtual methods but non-virtual public destructor.
7030 if (Record->isPolymorphic() && !Record->isDependentType()) {
7031 CXXDestructorDecl *dtor = Record->getDestructor();
7032 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7033 !Record->hasAttr<FinalAttr>())
7034 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7035 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7038 if (Record->isAbstract()) {
7039 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7040 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7041 << FA->isSpelledAsSealed();
7042 DiagnoseAbstractType(Record);
7046 // Warn if the class has a final destructor but is not itself marked final.
7047 if (!Record->hasAttr<FinalAttr>()) {
7048 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7049 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7050 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7051 << FA->isSpelledAsSealed()
7052 << FixItHint::CreateInsertion(
7053 getLocForEndOfToken(Record->getLocation()),
7054 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7055 Diag(Record->getLocation(),
7056 diag::note_final_dtor_non_final_class_silence)
7057 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7062 // See if trivial_abi has to be dropped.
7063 if (Record->hasAttr<TrivialABIAttr>())
7064 checkIllFormedTrivialABIStruct(*Record);
7066 // Set HasTrivialSpecialMemberForCall if the record has attribute
7067 // "trivial_abi".
7068 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7070 if (HasTrivialABI)
7071 Record->setHasTrivialSpecialMemberForCall();
7073 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7074 // We check these last because they can depend on the properties of the
7075 // primary comparison functions (==, <=>).
7076 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7078 // Perform checks that can't be done until we know all the properties of a
7079 // member function (whether it's defaulted, deleted, virtual, overriding,
7080 // ...).
7081 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7082 // A static function cannot override anything.
7083 if (MD->getStorageClass() == SC_Static) {
7084 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7085 [](const CXXMethodDecl *) { return true; }))
7086 return;
7089 // A deleted function cannot override a non-deleted function and vice
7090 // versa.
7091 if (ReportOverrides(*this,
7092 MD->isDeleted() ? diag::err_deleted_override
7093 : diag::err_non_deleted_override,
7094 MD, [&](const CXXMethodDecl *V) {
7095 return MD->isDeleted() != V->isDeleted();
7096 })) {
7097 if (MD->isDefaulted() && MD->isDeleted())
7098 // Explain why this defaulted function was deleted.
7099 DiagnoseDeletedDefaultedFunction(MD);
7100 return;
7103 // A consteval function cannot override a non-consteval function and vice
7104 // versa.
7105 if (ReportOverrides(*this,
7106 MD->isConsteval() ? diag::err_consteval_override
7107 : diag::err_non_consteval_override,
7108 MD, [&](const CXXMethodDecl *V) {
7109 return MD->isConsteval() != V->isConsteval();
7110 })) {
7111 if (MD->isDefaulted() && MD->isDeleted())
7112 // Explain why this defaulted function was deleted.
7113 DiagnoseDeletedDefaultedFunction(MD);
7114 return;
7118 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7119 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7120 return false;
7122 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7123 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7124 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7125 DefaultedSecondaryComparisons.push_back(FD);
7126 return true;
7129 CheckExplicitlyDefaultedFunction(S, FD);
7130 return false;
7133 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7134 // Check whether the explicitly-defaulted members are valid.
7135 bool Incomplete = CheckForDefaultedFunction(M);
7137 // Skip the rest of the checks for a member of a dependent class.
7138 if (Record->isDependentType())
7139 return;
7141 // For an explicitly defaulted or deleted special member, we defer
7142 // determining triviality until the class is complete. That time is now!
7143 CXXSpecialMember CSM = getSpecialMember(M);
7144 if (!M->isImplicit() && !M->isUserProvided()) {
7145 if (CSM != CXXInvalid) {
7146 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7147 // Inform the class that we've finished declaring this member.
7148 Record->finishedDefaultedOrDeletedMember(M);
7149 M->setTrivialForCall(
7150 HasTrivialABI ||
7151 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
7152 Record->setTrivialForCallFlags(M);
7156 // Set triviality for the purpose of calls if this is a user-provided
7157 // copy/move constructor or destructor.
7158 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
7159 CSM == CXXDestructor) && M->isUserProvided()) {
7160 M->setTrivialForCall(HasTrivialABI);
7161 Record->setTrivialForCallFlags(M);
7164 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7165 M->hasAttr<DLLExportAttr>()) {
7166 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7167 M->isTrivial() &&
7168 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
7169 CSM == CXXDestructor))
7170 M->dropAttr<DLLExportAttr>();
7172 if (M->hasAttr<DLLExportAttr>()) {
7173 // Define after any fields with in-class initializers have been parsed.
7174 DelayedDllExportMemberFunctions.push_back(M);
7178 // Define defaulted constexpr virtual functions that override a base class
7179 // function right away.
7180 // FIXME: We can defer doing this until the vtable is marked as used.
7181 if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
7182 M->isConstexpr() && M->size_overridden_methods())
7183 DefineDefaultedFunction(*this, M, M->getLocation());
7185 if (!Incomplete)
7186 CheckCompletedMemberFunction(M);
7189 // Check the destructor before any other member function. We need to
7190 // determine whether it's trivial in order to determine whether the claas
7191 // type is a literal type, which is a prerequisite for determining whether
7192 // other special member functions are valid and whether they're implicitly
7193 // 'constexpr'.
7194 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7195 CompleteMemberFunction(Dtor);
7197 bool HasMethodWithOverrideControl = false,
7198 HasOverridingMethodWithoutOverrideControl = false;
7199 for (auto *D : Record->decls()) {
7200 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7201 // FIXME: We could do this check for dependent types with non-dependent
7202 // bases.
7203 if (!Record->isDependentType()) {
7204 // See if a method overloads virtual methods in a base
7205 // class without overriding any.
7206 if (!M->isStatic())
7207 DiagnoseHiddenVirtualMethods(M);
7208 if (M->hasAttr<OverrideAttr>())
7209 HasMethodWithOverrideControl = true;
7210 else if (M->size_overridden_methods() > 0)
7211 HasOverridingMethodWithoutOverrideControl = true;
7214 if (!isa<CXXDestructorDecl>(M))
7215 CompleteMemberFunction(M);
7216 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7217 CheckForDefaultedFunction(
7218 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7222 if (HasOverridingMethodWithoutOverrideControl) {
7223 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7224 for (auto *M : Record->methods())
7225 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7228 // Check the defaulted secondary comparisons after any other member functions.
7229 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7230 CheckExplicitlyDefaultedFunction(S, FD);
7232 // If this is a member function, we deferred checking it until now.
7233 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7234 CheckCompletedMemberFunction(MD);
7237 // ms_struct is a request to use the same ABI rules as MSVC. Check
7238 // whether this class uses any C++ features that are implemented
7239 // completely differently in MSVC, and if so, emit a diagnostic.
7240 // That diagnostic defaults to an error, but we allow projects to
7241 // map it down to a warning (or ignore it). It's a fairly common
7242 // practice among users of the ms_struct pragma to mass-annotate
7243 // headers, sweeping up a bunch of types that the project doesn't
7244 // really rely on MSVC-compatible layout for. We must therefore
7245 // support "ms_struct except for C++ stuff" as a secondary ABI.
7246 // Don't emit this diagnostic if the feature was enabled as a
7247 // language option (as opposed to via a pragma or attribute), as
7248 // the option -mms-bitfields otherwise essentially makes it impossible
7249 // to build C++ code, unless this diagnostic is turned off.
7250 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7251 (Record->isPolymorphic() || Record->getNumBases())) {
7252 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7255 checkClassLevelDLLAttribute(Record);
7256 checkClassLevelCodeSegAttribute(Record);
7258 bool ClangABICompat4 =
7259 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7260 TargetInfo::CallingConvKind CCK =
7261 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7262 bool CanPass = canPassInRegisters(*this, Record, CCK);
7264 // Do not change ArgPassingRestrictions if it has already been set to
7265 // APK_CanNeverPassInRegs.
7266 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7267 Record->setArgPassingRestrictions(CanPass
7268 ? RecordDecl::APK_CanPassInRegs
7269 : RecordDecl::APK_CannotPassInRegs);
7271 // If canPassInRegisters returns true despite the record having a non-trivial
7272 // destructor, the record is destructed in the callee. This happens only when
7273 // the record or one of its subobjects has a field annotated with trivial_abi
7274 // or a field qualified with ObjC __strong/__weak.
7275 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7276 Record->setParamDestroyedInCallee(true);
7277 else if (Record->hasNonTrivialDestructor())
7278 Record->setParamDestroyedInCallee(CanPass);
7280 if (getLangOpts().ForceEmitVTables) {
7281 // If we want to emit all the vtables, we need to mark it as used. This
7282 // is especially required for cases like vtable assumption loads.
7283 MarkVTableUsed(Record->getInnerLocStart(), Record);
7286 if (getLangOpts().CUDA) {
7287 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7288 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7289 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7290 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7294 /// Look up the special member function that would be called by a special
7295 /// member function for a subobject of class type.
7297 /// \param Class The class type of the subobject.
7298 /// \param CSM The kind of special member function.
7299 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7300 /// \param ConstRHS True if this is a copy operation with a const object
7301 /// on its RHS, that is, if the argument to the outer special member
7302 /// function is 'const' and this is not a field marked 'mutable'.
7303 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7304 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7305 unsigned FieldQuals, bool ConstRHS) {
7306 unsigned LHSQuals = 0;
7307 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7308 LHSQuals = FieldQuals;
7310 unsigned RHSQuals = FieldQuals;
7311 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7312 RHSQuals = 0;
7313 else if (ConstRHS)
7314 RHSQuals |= Qualifiers::Const;
7316 return S.LookupSpecialMember(Class, CSM,
7317 RHSQuals & Qualifiers::Const,
7318 RHSQuals & Qualifiers::Volatile,
7319 false,
7320 LHSQuals & Qualifiers::Const,
7321 LHSQuals & Qualifiers::Volatile);
7324 class Sema::InheritedConstructorInfo {
7325 Sema &S;
7326 SourceLocation UseLoc;
7328 /// A mapping from the base classes through which the constructor was
7329 /// inherited to the using shadow declaration in that base class (or a null
7330 /// pointer if the constructor was declared in that base class).
7331 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7332 InheritedFromBases;
7334 public:
7335 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7336 ConstructorUsingShadowDecl *Shadow)
7337 : S(S), UseLoc(UseLoc) {
7338 bool DiagnosedMultipleConstructedBases = false;
7339 CXXRecordDecl *ConstructedBase = nullptr;
7340 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7342 // Find the set of such base class subobjects and check that there's a
7343 // unique constructed subobject.
7344 for (auto *D : Shadow->redecls()) {
7345 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7346 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7347 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7349 InheritedFromBases.insert(
7350 std::make_pair(DNominatedBase->getCanonicalDecl(),
7351 DShadow->getNominatedBaseClassShadowDecl()));
7352 if (DShadow->constructsVirtualBase())
7353 InheritedFromBases.insert(
7354 std::make_pair(DConstructedBase->getCanonicalDecl(),
7355 DShadow->getConstructedBaseClassShadowDecl()));
7356 else
7357 assert(DNominatedBase == DConstructedBase);
7359 // [class.inhctor.init]p2:
7360 // If the constructor was inherited from multiple base class subobjects
7361 // of type B, the program is ill-formed.
7362 if (!ConstructedBase) {
7363 ConstructedBase = DConstructedBase;
7364 ConstructedBaseIntroducer = D->getIntroducer();
7365 } else if (ConstructedBase != DConstructedBase &&
7366 !Shadow->isInvalidDecl()) {
7367 if (!DiagnosedMultipleConstructedBases) {
7368 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7369 << Shadow->getTargetDecl();
7370 S.Diag(ConstructedBaseIntroducer->getLocation(),
7371 diag::note_ambiguous_inherited_constructor_using)
7372 << ConstructedBase;
7373 DiagnosedMultipleConstructedBases = true;
7375 S.Diag(D->getIntroducer()->getLocation(),
7376 diag::note_ambiguous_inherited_constructor_using)
7377 << DConstructedBase;
7381 if (DiagnosedMultipleConstructedBases)
7382 Shadow->setInvalidDecl();
7385 /// Find the constructor to use for inherited construction of a base class,
7386 /// and whether that base class constructor inherits the constructor from a
7387 /// virtual base class (in which case it won't actually invoke it).
7388 std::pair<CXXConstructorDecl *, bool>
7389 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7390 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7391 if (It == InheritedFromBases.end())
7392 return std::make_pair(nullptr, false);
7394 // This is an intermediary class.
7395 if (It->second)
7396 return std::make_pair(
7397 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7398 It->second->constructsVirtualBase());
7400 // This is the base class from which the constructor was inherited.
7401 return std::make_pair(Ctor, false);
7405 /// Is the special member function which would be selected to perform the
7406 /// specified operation on the specified class type a constexpr constructor?
7407 static bool
7408 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7409 Sema::CXXSpecialMember CSM, unsigned Quals,
7410 bool ConstRHS,
7411 CXXConstructorDecl *InheritedCtor = nullptr,
7412 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7413 // Suppress duplicate constraint checking here, in case a constraint check
7414 // caused us to decide to do this. Any truely recursive checks will get
7415 // caught during these checks anyway.
7416 Sema::SatisfactionStackResetRAII SSRAII{S};
7418 // If we're inheriting a constructor, see if we need to call it for this base
7419 // class.
7420 if (InheritedCtor) {
7421 assert(CSM == Sema::CXXDefaultConstructor);
7422 auto BaseCtor =
7423 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7424 if (BaseCtor)
7425 return BaseCtor->isConstexpr();
7428 if (CSM == Sema::CXXDefaultConstructor)
7429 return ClassDecl->hasConstexprDefaultConstructor();
7430 if (CSM == Sema::CXXDestructor)
7431 return ClassDecl->hasConstexprDestructor();
7433 Sema::SpecialMemberOverloadResult SMOR =
7434 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7435 if (!SMOR.getMethod())
7436 // A constructor we wouldn't select can't be "involved in initializing"
7437 // anything.
7438 return true;
7439 return SMOR.getMethod()->isConstexpr();
7442 /// Determine whether the specified special member function would be constexpr
7443 /// if it were implicitly defined.
7444 static bool defaultedSpecialMemberIsConstexpr(
7445 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7446 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7447 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7448 if (!S.getLangOpts().CPlusPlus11)
7449 return false;
7451 // C++11 [dcl.constexpr]p4:
7452 // In the definition of a constexpr constructor [...]
7453 bool Ctor = true;
7454 switch (CSM) {
7455 case Sema::CXXDefaultConstructor:
7456 if (Inherited)
7457 break;
7458 // Since default constructor lookup is essentially trivial (and cannot
7459 // involve, for instance, template instantiation), we compute whether a
7460 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7462 // This is important for performance; we need to know whether the default
7463 // constructor is constexpr to determine whether the type is a literal type.
7464 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7466 case Sema::CXXCopyConstructor:
7467 case Sema::CXXMoveConstructor:
7468 // For copy or move constructors, we need to perform overload resolution.
7469 break;
7471 case Sema::CXXCopyAssignment:
7472 case Sema::CXXMoveAssignment:
7473 if (!S.getLangOpts().CPlusPlus14)
7474 return false;
7475 // In C++1y, we need to perform overload resolution.
7476 Ctor = false;
7477 break;
7479 case Sema::CXXDestructor:
7480 return ClassDecl->defaultedDestructorIsConstexpr();
7482 case Sema::CXXInvalid:
7483 return false;
7486 // -- if the class is a non-empty union, or for each non-empty anonymous
7487 // union member of a non-union class, exactly one non-static data member
7488 // shall be initialized; [DR1359]
7490 // If we squint, this is guaranteed, since exactly one non-static data member
7491 // will be initialized (if the constructor isn't deleted), we just don't know
7492 // which one.
7493 if (Ctor && ClassDecl->isUnion())
7494 return CSM == Sema::CXXDefaultConstructor
7495 ? ClassDecl->hasInClassInitializer() ||
7496 !ClassDecl->hasVariantMembers()
7497 : true;
7499 // -- the class shall not have any virtual base classes;
7500 if (Ctor && ClassDecl->getNumVBases())
7501 return false;
7503 // C++1y [class.copy]p26:
7504 // -- [the class] is a literal type, and
7505 if (!Ctor && !ClassDecl->isLiteral())
7506 return false;
7508 // -- every constructor involved in initializing [...] base class
7509 // sub-objects shall be a constexpr constructor;
7510 // -- the assignment operator selected to copy/move each direct base
7511 // class is a constexpr function, and
7512 for (const auto &B : ClassDecl->bases()) {
7513 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7514 if (!BaseType)
7515 continue;
7516 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7517 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7518 InheritedCtor, Inherited))
7519 return false;
7522 // -- every constructor involved in initializing non-static data members
7523 // [...] shall be a constexpr constructor;
7524 // -- every non-static data member and base class sub-object shall be
7525 // initialized
7526 // -- for each non-static data member of X that is of class type (or array
7527 // thereof), the assignment operator selected to copy/move that member is
7528 // a constexpr function
7529 for (const auto *F : ClassDecl->fields()) {
7530 if (F->isInvalidDecl())
7531 continue;
7532 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7533 continue;
7534 QualType BaseType = S.Context.getBaseElementType(F->getType());
7535 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7536 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7537 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7538 BaseType.getCVRQualifiers(),
7539 ConstArg && !F->isMutable()))
7540 return false;
7541 } else if (CSM == Sema::CXXDefaultConstructor) {
7542 return false;
7546 // All OK, it's constexpr!
7547 return true;
7550 namespace {
7551 /// RAII object to register a defaulted function as having its exception
7552 /// specification computed.
7553 struct ComputingExceptionSpec {
7554 Sema &S;
7556 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7557 : S(S) {
7558 Sema::CodeSynthesisContext Ctx;
7559 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7560 Ctx.PointOfInstantiation = Loc;
7561 Ctx.Entity = FD;
7562 S.pushCodeSynthesisContext(Ctx);
7564 ~ComputingExceptionSpec() {
7565 S.popCodeSynthesisContext();
7570 static Sema::ImplicitExceptionSpecification
7571 ComputeDefaultedSpecialMemberExceptionSpec(
7572 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7573 Sema::InheritedConstructorInfo *ICI);
7575 static Sema::ImplicitExceptionSpecification
7576 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7577 FunctionDecl *FD,
7578 Sema::DefaultedComparisonKind DCK);
7580 static Sema::ImplicitExceptionSpecification
7581 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7582 auto DFK = S.getDefaultedFunctionKind(FD);
7583 if (DFK.isSpecialMember())
7584 return ComputeDefaultedSpecialMemberExceptionSpec(
7585 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7586 if (DFK.isComparison())
7587 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7588 DFK.asComparison());
7590 auto *CD = cast<CXXConstructorDecl>(FD);
7591 assert(CD->getInheritedConstructor() &&
7592 "only defaulted functions and inherited constructors have implicit "
7593 "exception specs");
7594 Sema::InheritedConstructorInfo ICI(
7595 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7596 return ComputeDefaultedSpecialMemberExceptionSpec(
7597 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7600 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7601 CXXMethodDecl *MD) {
7602 FunctionProtoType::ExtProtoInfo EPI;
7604 // Build an exception specification pointing back at this member.
7605 EPI.ExceptionSpec.Type = EST_Unevaluated;
7606 EPI.ExceptionSpec.SourceDecl = MD;
7608 // Set the calling convention to the default for C++ instance methods.
7609 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7610 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7611 /*IsCXXMethod=*/true));
7612 return EPI;
7615 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7616 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7617 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7618 return;
7620 // Evaluate the exception specification.
7621 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7622 auto ESI = IES.getExceptionSpec();
7624 // Update the type of the special member to use it.
7625 UpdateExceptionSpec(FD, ESI);
7628 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7629 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7631 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7632 if (!DefKind) {
7633 assert(FD->getDeclContext()->isDependentContext());
7634 return;
7637 if (DefKind.isComparison())
7638 UnusedPrivateFields.clear();
7640 if (DefKind.isSpecialMember()
7641 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7642 DefKind.asSpecialMember(),
7643 FD->getDefaultLoc())
7644 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7645 FD->setInvalidDecl();
7648 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7649 CXXSpecialMember CSM,
7650 SourceLocation DefaultLoc) {
7651 CXXRecordDecl *RD = MD->getParent();
7653 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7654 "not an explicitly-defaulted special member");
7656 // Defer all checking for special members of a dependent type.
7657 if (RD->isDependentType())
7658 return false;
7660 // Whether this was the first-declared instance of the constructor.
7661 // This affects whether we implicitly add an exception spec and constexpr.
7662 bool First = MD == MD->getCanonicalDecl();
7664 bool HadError = false;
7666 // C++11 [dcl.fct.def.default]p1:
7667 // A function that is explicitly defaulted shall
7668 // -- be a special member function [...] (checked elsewhere),
7669 // -- have the same type (except for ref-qualifiers, and except that a
7670 // copy operation can take a non-const reference) as an implicit
7671 // declaration, and
7672 // -- not have default arguments.
7673 // C++2a changes the second bullet to instead delete the function if it's
7674 // defaulted on its first declaration, unless it's "an assignment operator,
7675 // and its return type differs or its parameter type is not a reference".
7676 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7677 bool ShouldDeleteForTypeMismatch = false;
7678 unsigned ExpectedParams = 1;
7679 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7680 ExpectedParams = 0;
7681 if (MD->getNumParams() != ExpectedParams) {
7682 // This checks for default arguments: a copy or move constructor with a
7683 // default argument is classified as a default constructor, and assignment
7684 // operations and destructors can't have default arguments.
7685 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7686 << CSM << MD->getSourceRange();
7687 HadError = true;
7688 } else if (MD->isVariadic()) {
7689 if (DeleteOnTypeMismatch)
7690 ShouldDeleteForTypeMismatch = true;
7691 else {
7692 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7693 << CSM << MD->getSourceRange();
7694 HadError = true;
7698 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7700 bool CanHaveConstParam = false;
7701 if (CSM == CXXCopyConstructor)
7702 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7703 else if (CSM == CXXCopyAssignment)
7704 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7706 QualType ReturnType = Context.VoidTy;
7707 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7708 // Check for return type matching.
7709 ReturnType = Type->getReturnType();
7711 QualType DeclType = Context.getTypeDeclType(RD);
7712 DeclType = Context.getElaboratedType(ETK_None, nullptr, DeclType, nullptr);
7713 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7714 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7716 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7717 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7718 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7719 HadError = true;
7722 // A defaulted special member cannot have cv-qualifiers.
7723 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7724 if (DeleteOnTypeMismatch)
7725 ShouldDeleteForTypeMismatch = true;
7726 else {
7727 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7728 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7729 HadError = true;
7734 // Check for parameter type matching.
7735 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7736 bool HasConstParam = false;
7737 if (ExpectedParams && ArgType->isReferenceType()) {
7738 // Argument must be reference to possibly-const T.
7739 QualType ReferentType = ArgType->getPointeeType();
7740 HasConstParam = ReferentType.isConstQualified();
7742 if (ReferentType.isVolatileQualified()) {
7743 if (DeleteOnTypeMismatch)
7744 ShouldDeleteForTypeMismatch = true;
7745 else {
7746 Diag(MD->getLocation(),
7747 diag::err_defaulted_special_member_volatile_param) << CSM;
7748 HadError = true;
7752 if (HasConstParam && !CanHaveConstParam) {
7753 if (DeleteOnTypeMismatch)
7754 ShouldDeleteForTypeMismatch = true;
7755 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7756 Diag(MD->getLocation(),
7757 diag::err_defaulted_special_member_copy_const_param)
7758 << (CSM == CXXCopyAssignment);
7759 // FIXME: Explain why this special member can't be const.
7760 HadError = true;
7761 } else {
7762 Diag(MD->getLocation(),
7763 diag::err_defaulted_special_member_move_const_param)
7764 << (CSM == CXXMoveAssignment);
7765 HadError = true;
7768 } else if (ExpectedParams) {
7769 // A copy assignment operator can take its argument by value, but a
7770 // defaulted one cannot.
7771 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7772 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7773 HadError = true;
7776 // C++11 [dcl.fct.def.default]p2:
7777 // An explicitly-defaulted function may be declared constexpr only if it
7778 // would have been implicitly declared as constexpr,
7779 // Do not apply this rule to members of class templates, since core issue 1358
7780 // makes such functions always instantiate to constexpr functions. For
7781 // functions which cannot be constexpr (for non-constructors in C++11 and for
7782 // destructors in C++14 and C++17), this is checked elsewhere.
7784 // FIXME: This should not apply if the member is deleted.
7785 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7786 HasConstParam);
7788 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7789 // If the instantiated template specialization of a constexpr function
7790 // template or member function of a class template would fail to satisfy
7791 // the requirements for a constexpr function or constexpr constructor, that
7792 // specialization is still a constexpr function or constexpr constructor,
7793 // even though a call to such a function cannot appear in a constant
7794 // expression.
7795 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7796 Constexpr = true;
7798 if ((getLangOpts().CPlusPlus20 ||
7799 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7800 : isa<CXXConstructorDecl>(MD))) &&
7801 MD->isConstexpr() && !Constexpr &&
7802 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7803 Diag(MD->getBeginLoc(), MD->isConsteval()
7804 ? diag::err_incorrect_defaulted_consteval
7805 : diag::err_incorrect_defaulted_constexpr)
7806 << CSM;
7807 // FIXME: Explain why the special member can't be constexpr.
7808 HadError = true;
7811 if (First) {
7812 // C++2a [dcl.fct.def.default]p3:
7813 // If a function is explicitly defaulted on its first declaration, it is
7814 // implicitly considered to be constexpr if the implicit declaration
7815 // would be.
7816 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7817 ? ConstexprSpecKind::Consteval
7818 : ConstexprSpecKind::Constexpr)
7819 : ConstexprSpecKind::Unspecified);
7821 if (!Type->hasExceptionSpec()) {
7822 // C++2a [except.spec]p3:
7823 // If a declaration of a function does not have a noexcept-specifier
7824 // [and] is defaulted on its first declaration, [...] the exception
7825 // specification is as specified below
7826 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7827 EPI.ExceptionSpec.Type = EST_Unevaluated;
7828 EPI.ExceptionSpec.SourceDecl = MD;
7829 MD->setType(Context.getFunctionType(
7830 ReturnType, llvm::ArrayRef(&ArgType, ExpectedParams), EPI));
7834 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7835 if (First) {
7836 SetDeclDeleted(MD, MD->getLocation());
7837 if (!inTemplateInstantiation() && !HadError) {
7838 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7839 if (ShouldDeleteForTypeMismatch) {
7840 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7841 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7842 /*Diagnose*/ true) &&
7843 DefaultLoc.isValid()) {
7844 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7845 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7848 if (ShouldDeleteForTypeMismatch && !HadError) {
7849 Diag(MD->getLocation(),
7850 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7852 } else {
7853 // C++11 [dcl.fct.def.default]p4:
7854 // [For a] user-provided explicitly-defaulted function [...] if such a
7855 // function is implicitly defined as deleted, the program is ill-formed.
7856 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7857 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7858 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7859 HadError = true;
7863 return HadError;
7866 namespace {
7867 /// Helper class for building and checking a defaulted comparison.
7869 /// Defaulted functions are built in two phases:
7871 /// * First, the set of operations that the function will perform are
7872 /// identified, and some of them are checked. If any of the checked
7873 /// operations is invalid in certain ways, the comparison function is
7874 /// defined as deleted and no body is built.
7875 /// * Then, if the function is not defined as deleted, the body is built.
7877 /// This is accomplished by performing two visitation steps over the eventual
7878 /// body of the function.
7879 template<typename Derived, typename ResultList, typename Result,
7880 typename Subobject>
7881 class DefaultedComparisonVisitor {
7882 public:
7883 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7885 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7886 DefaultedComparisonKind DCK)
7887 : S(S), RD(RD), FD(FD), DCK(DCK) {
7888 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7889 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7890 // UnresolvedSet to avoid this copy.
7891 Fns.assign(Info->getUnqualifiedLookups().begin(),
7892 Info->getUnqualifiedLookups().end());
7896 ResultList visit() {
7897 // The type of an lvalue naming a parameter of this function.
7898 QualType ParamLvalType =
7899 FD->getParamDecl(0)->getType().getNonReferenceType();
7901 ResultList Results;
7903 switch (DCK) {
7904 case DefaultedComparisonKind::None:
7905 llvm_unreachable("not a defaulted comparison");
7907 case DefaultedComparisonKind::Equal:
7908 case DefaultedComparisonKind::ThreeWay:
7909 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7910 return Results;
7912 case DefaultedComparisonKind::NotEqual:
7913 case DefaultedComparisonKind::Relational:
7914 Results.add(getDerived().visitExpandedSubobject(
7915 ParamLvalType, getDerived().getCompleteObject()));
7916 return Results;
7918 llvm_unreachable("");
7921 protected:
7922 Derived &getDerived() { return static_cast<Derived&>(*this); }
7924 /// Visit the expanded list of subobjects of the given type, as specified in
7925 /// C++2a [class.compare.default].
7927 /// \return \c true if the ResultList object said we're done, \c false if not.
7928 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7929 Qualifiers Quals) {
7930 // C++2a [class.compare.default]p4:
7931 // The direct base class subobjects of C
7932 for (CXXBaseSpecifier &Base : Record->bases())
7933 if (Results.add(getDerived().visitSubobject(
7934 S.Context.getQualifiedType(Base.getType(), Quals),
7935 getDerived().getBase(&Base))))
7936 return true;
7938 // followed by the non-static data members of C
7939 for (FieldDecl *Field : Record->fields()) {
7940 // C++23 [class.bit]p2:
7941 // Unnamed bit-fields are not members ...
7942 if (Field->isUnnamedBitfield())
7943 continue;
7944 // Recursively expand anonymous structs.
7945 if (Field->isAnonymousStructOrUnion()) {
7946 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7947 Quals))
7948 return true;
7949 continue;
7952 // Figure out the type of an lvalue denoting this field.
7953 Qualifiers FieldQuals = Quals;
7954 if (Field->isMutable())
7955 FieldQuals.removeConst();
7956 QualType FieldType =
7957 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7959 if (Results.add(getDerived().visitSubobject(
7960 FieldType, getDerived().getField(Field))))
7961 return true;
7964 // form a list of subobjects.
7965 return false;
7968 Result visitSubobject(QualType Type, Subobject Subobj) {
7969 // In that list, any subobject of array type is recursively expanded
7970 const ArrayType *AT = S.Context.getAsArrayType(Type);
7971 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7972 return getDerived().visitSubobjectArray(CAT->getElementType(),
7973 CAT->getSize(), Subobj);
7974 return getDerived().visitExpandedSubobject(Type, Subobj);
7977 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7978 Subobject Subobj) {
7979 return getDerived().visitSubobject(Type, Subobj);
7982 protected:
7983 Sema &S;
7984 CXXRecordDecl *RD;
7985 FunctionDecl *FD;
7986 DefaultedComparisonKind DCK;
7987 UnresolvedSet<16> Fns;
7990 /// Information about a defaulted comparison, as determined by
7991 /// DefaultedComparisonAnalyzer.
7992 struct DefaultedComparisonInfo {
7993 bool Deleted = false;
7994 bool Constexpr = true;
7995 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7997 static DefaultedComparisonInfo deleted() {
7998 DefaultedComparisonInfo Deleted;
7999 Deleted.Deleted = true;
8000 return Deleted;
8003 bool add(const DefaultedComparisonInfo &R) {
8004 Deleted |= R.Deleted;
8005 Constexpr &= R.Constexpr;
8006 Category = commonComparisonType(Category, R.Category);
8007 return Deleted;
8011 /// An element in the expanded list of subobjects of a defaulted comparison, as
8012 /// specified in C++2a [class.compare.default]p4.
8013 struct DefaultedComparisonSubobject {
8014 enum { CompleteObject, Member, Base } Kind;
8015 NamedDecl *Decl;
8016 SourceLocation Loc;
8019 /// A visitor over the notional body of a defaulted comparison that determines
8020 /// whether that body would be deleted or constexpr.
8021 class DefaultedComparisonAnalyzer
8022 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8023 DefaultedComparisonInfo,
8024 DefaultedComparisonInfo,
8025 DefaultedComparisonSubobject> {
8026 public:
8027 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8029 private:
8030 DiagnosticKind Diagnose;
8032 public:
8033 using Base = DefaultedComparisonVisitor;
8034 using Result = DefaultedComparisonInfo;
8035 using Subobject = DefaultedComparisonSubobject;
8037 friend Base;
8039 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8040 DefaultedComparisonKind DCK,
8041 DiagnosticKind Diagnose = NoDiagnostics)
8042 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8044 Result visit() {
8045 if ((DCK == DefaultedComparisonKind::Equal ||
8046 DCK == DefaultedComparisonKind::ThreeWay) &&
8047 RD->hasVariantMembers()) {
8048 // C++2a [class.compare.default]p2 [P2002R0]:
8049 // A defaulted comparison operator function for class C is defined as
8050 // deleted if [...] C has variant members.
8051 if (Diagnose == ExplainDeleted) {
8052 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8053 << FD << RD->isUnion() << RD;
8055 return Result::deleted();
8058 return Base::visit();
8061 private:
8062 Subobject getCompleteObject() {
8063 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8066 Subobject getBase(CXXBaseSpecifier *Base) {
8067 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8068 Base->getBaseTypeLoc()};
8071 Subobject getField(FieldDecl *Field) {
8072 return Subobject{Subobject::Member, Field, Field->getLocation()};
8075 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8076 // C++2a [class.compare.default]p2 [P2002R0]:
8077 // A defaulted <=> or == operator function for class C is defined as
8078 // deleted if any non-static data member of C is of reference type
8079 if (Type->isReferenceType()) {
8080 if (Diagnose == ExplainDeleted) {
8081 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8082 << FD << RD;
8084 return Result::deleted();
8087 // [...] Let xi be an lvalue denoting the ith element [...]
8088 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8089 Expr *Args[] = {&Xi, &Xi};
8091 // All operators start by trying to apply that same operator recursively.
8092 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8093 assert(OO != OO_None && "not an overloaded operator!");
8094 return visitBinaryOperator(OO, Args, Subobj);
8097 Result
8098 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8099 Subobject Subobj,
8100 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8101 // Note that there is no need to consider rewritten candidates here if
8102 // we've already found there is no viable 'operator<=>' candidate (and are
8103 // considering synthesizing a '<=>' from '==' and '<').
8104 OverloadCandidateSet CandidateSet(
8105 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8106 OverloadCandidateSet::OperatorRewriteInfo(
8107 OO, FD->getLocation(),
8108 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8110 /// C++2a [class.compare.default]p1 [P2002R0]:
8111 /// [...] the defaulted function itself is never a candidate for overload
8112 /// resolution [...]
8113 CandidateSet.exclude(FD);
8115 if (Args[0]->getType()->isOverloadableType())
8116 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8117 else
8118 // FIXME: We determine whether this is a valid expression by checking to
8119 // see if there's a viable builtin operator candidate for it. That isn't
8120 // really what the rules ask us to do, but should give the right results.
8121 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8123 Result R;
8125 OverloadCandidateSet::iterator Best;
8126 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8127 case OR_Success: {
8128 // C++2a [class.compare.secondary]p2 [P2002R0]:
8129 // The operator function [...] is defined as deleted if [...] the
8130 // candidate selected by overload resolution is not a rewritten
8131 // candidate.
8132 if ((DCK == DefaultedComparisonKind::NotEqual ||
8133 DCK == DefaultedComparisonKind::Relational) &&
8134 !Best->RewriteKind) {
8135 if (Diagnose == ExplainDeleted) {
8136 if (Best->Function) {
8137 S.Diag(Best->Function->getLocation(),
8138 diag::note_defaulted_comparison_not_rewritten_callee)
8139 << FD;
8140 } else {
8141 assert(Best->Conversions.size() == 2 &&
8142 Best->Conversions[0].isUserDefined() &&
8143 "non-user-defined conversion from class to built-in "
8144 "comparison");
8145 S.Diag(Best->Conversions[0]
8146 .UserDefined.FoundConversionFunction.getDecl()
8147 ->getLocation(),
8148 diag::note_defaulted_comparison_not_rewritten_conversion)
8149 << FD;
8152 return Result::deleted();
8155 // Throughout C++2a [class.compare]: if overload resolution does not
8156 // result in a usable function, the candidate function is defined as
8157 // deleted. This requires that we selected an accessible function.
8159 // Note that this only considers the access of the function when named
8160 // within the type of the subobject, and not the access path for any
8161 // derived-to-base conversion.
8162 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8163 if (ArgClass && Best->FoundDecl.getDecl() &&
8164 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8165 QualType ObjectType = Subobj.Kind == Subobject::Member
8166 ? Args[0]->getType()
8167 : S.Context.getRecordType(RD);
8168 if (!S.isMemberAccessibleForDeletion(
8169 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8170 Diagnose == ExplainDeleted
8171 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8172 << FD << Subobj.Kind << Subobj.Decl
8173 : S.PDiag()))
8174 return Result::deleted();
8177 bool NeedsDeducing =
8178 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8180 if (FunctionDecl *BestFD = Best->Function) {
8181 // C++2a [class.compare.default]p3 [P2002R0]:
8182 // A defaulted comparison function is constexpr-compatible if
8183 // [...] no overlod resolution performed [...] results in a
8184 // non-constexpr function.
8185 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8186 // If it's not constexpr, explain why not.
8187 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8188 if (Subobj.Kind != Subobject::CompleteObject)
8189 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8190 << Subobj.Kind << Subobj.Decl;
8191 S.Diag(BestFD->getLocation(),
8192 diag::note_defaulted_comparison_not_constexpr_here);
8193 // Bail out after explaining; we don't want any more notes.
8194 return Result::deleted();
8196 R.Constexpr &= BestFD->isConstexpr();
8198 if (NeedsDeducing) {
8199 // If any callee has an undeduced return type, deduce it now.
8200 // FIXME: It's not clear how a failure here should be handled. For
8201 // now, we produce an eager diagnostic, because that is forward
8202 // compatible with most (all?) other reasonable options.
8203 if (BestFD->getReturnType()->isUndeducedType() &&
8204 S.DeduceReturnType(BestFD, FD->getLocation(),
8205 /*Diagnose=*/false)) {
8206 // Don't produce a duplicate error when asked to explain why the
8207 // comparison is deleted: we diagnosed that when initially checking
8208 // the defaulted operator.
8209 if (Diagnose == NoDiagnostics) {
8210 S.Diag(
8211 FD->getLocation(),
8212 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8213 << Subobj.Kind << Subobj.Decl;
8214 S.Diag(
8215 Subobj.Loc,
8216 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8217 << Subobj.Kind << Subobj.Decl;
8218 S.Diag(BestFD->getLocation(),
8219 diag::note_defaulted_comparison_cannot_deduce_callee)
8220 << Subobj.Kind << Subobj.Decl;
8222 return Result::deleted();
8224 auto *Info = S.Context.CompCategories.lookupInfoForType(
8225 BestFD->getCallResultType());
8226 if (!Info) {
8227 if (Diagnose == ExplainDeleted) {
8228 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8229 << Subobj.Kind << Subobj.Decl
8230 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8231 S.Diag(BestFD->getLocation(),
8232 diag::note_defaulted_comparison_cannot_deduce_callee)
8233 << Subobj.Kind << Subobj.Decl;
8235 return Result::deleted();
8237 R.Category = Info->Kind;
8239 } else {
8240 QualType T = Best->BuiltinParamTypes[0];
8241 assert(T == Best->BuiltinParamTypes[1] &&
8242 "builtin comparison for different types?");
8243 assert(Best->BuiltinParamTypes[2].isNull() &&
8244 "invalid builtin comparison");
8246 if (NeedsDeducing) {
8247 std::optional<ComparisonCategoryType> Cat =
8248 getComparisonCategoryForBuiltinCmp(T);
8249 assert(Cat && "no category for builtin comparison?");
8250 R.Category = *Cat;
8254 // Note that we might be rewriting to a different operator. That call is
8255 // not considered until we come to actually build the comparison function.
8256 break;
8259 case OR_Ambiguous:
8260 if (Diagnose == ExplainDeleted) {
8261 unsigned Kind = 0;
8262 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8263 Kind = OO == OO_EqualEqual ? 1 : 2;
8264 CandidateSet.NoteCandidates(
8265 PartialDiagnosticAt(
8266 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8267 << FD << Kind << Subobj.Kind << Subobj.Decl),
8268 S, OCD_AmbiguousCandidates, Args);
8270 R = Result::deleted();
8271 break;
8273 case OR_Deleted:
8274 if (Diagnose == ExplainDeleted) {
8275 if ((DCK == DefaultedComparisonKind::NotEqual ||
8276 DCK == DefaultedComparisonKind::Relational) &&
8277 !Best->RewriteKind) {
8278 S.Diag(Best->Function->getLocation(),
8279 diag::note_defaulted_comparison_not_rewritten_callee)
8280 << FD;
8281 } else {
8282 S.Diag(Subobj.Loc,
8283 diag::note_defaulted_comparison_calls_deleted)
8284 << FD << Subobj.Kind << Subobj.Decl;
8285 S.NoteDeletedFunction(Best->Function);
8288 R = Result::deleted();
8289 break;
8291 case OR_No_Viable_Function:
8292 // If there's no usable candidate, we're done unless we can rewrite a
8293 // '<=>' in terms of '==' and '<'.
8294 if (OO == OO_Spaceship &&
8295 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8296 // For any kind of comparison category return type, we need a usable
8297 // '==' and a usable '<'.
8298 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8299 &CandidateSet)))
8300 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8301 break;
8304 if (Diagnose == ExplainDeleted) {
8305 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8306 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8307 << Subobj.Kind << Subobj.Decl;
8309 // For a three-way comparison, list both the candidates for the
8310 // original operator and the candidates for the synthesized operator.
8311 if (SpaceshipCandidates) {
8312 SpaceshipCandidates->NoteCandidates(
8313 S, Args,
8314 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8315 Args, FD->getLocation()));
8316 S.Diag(Subobj.Loc,
8317 diag::note_defaulted_comparison_no_viable_function_synthesized)
8318 << (OO == OO_EqualEqual ? 0 : 1);
8321 CandidateSet.NoteCandidates(
8322 S, Args,
8323 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8324 FD->getLocation()));
8326 R = Result::deleted();
8327 break;
8330 return R;
8334 /// A list of statements.
8335 struct StmtListResult {
8336 bool IsInvalid = false;
8337 llvm::SmallVector<Stmt*, 16> Stmts;
8339 bool add(const StmtResult &S) {
8340 IsInvalid |= S.isInvalid();
8341 if (IsInvalid)
8342 return true;
8343 Stmts.push_back(S.get());
8344 return false;
8348 /// A visitor over the notional body of a defaulted comparison that synthesizes
8349 /// the actual body.
8350 class DefaultedComparisonSynthesizer
8351 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8352 StmtListResult, StmtResult,
8353 std::pair<ExprResult, ExprResult>> {
8354 SourceLocation Loc;
8355 unsigned ArrayDepth = 0;
8357 public:
8358 using Base = DefaultedComparisonVisitor;
8359 using ExprPair = std::pair<ExprResult, ExprResult>;
8361 friend Base;
8363 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8364 DefaultedComparisonKind DCK,
8365 SourceLocation BodyLoc)
8366 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8368 /// Build a suitable function body for this defaulted comparison operator.
8369 StmtResult build() {
8370 Sema::CompoundScopeRAII CompoundScope(S);
8372 StmtListResult Stmts = visit();
8373 if (Stmts.IsInvalid)
8374 return StmtError();
8376 ExprResult RetVal;
8377 switch (DCK) {
8378 case DefaultedComparisonKind::None:
8379 llvm_unreachable("not a defaulted comparison");
8381 case DefaultedComparisonKind::Equal: {
8382 // C++2a [class.eq]p3:
8383 // [...] compar[e] the corresponding elements [...] until the first
8384 // index i where xi == yi yields [...] false. If no such index exists,
8385 // V is true. Otherwise, V is false.
8387 // Join the comparisons with '&&'s and return the result. Use a right
8388 // fold (traversing the conditions right-to-left), because that
8389 // short-circuits more naturally.
8390 auto OldStmts = std::move(Stmts.Stmts);
8391 Stmts.Stmts.clear();
8392 ExprResult CmpSoFar;
8393 // Finish a particular comparison chain.
8394 auto FinishCmp = [&] {
8395 if (Expr *Prior = CmpSoFar.get()) {
8396 // Convert the last expression to 'return ...;'
8397 if (RetVal.isUnset() && Stmts.Stmts.empty())
8398 RetVal = CmpSoFar;
8399 // Convert any prior comparison to 'if (!(...)) return false;'
8400 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8401 return true;
8402 CmpSoFar = ExprResult();
8404 return false;
8406 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8407 Expr *E = dyn_cast<Expr>(EAsStmt);
8408 if (!E) {
8409 // Found an array comparison.
8410 if (FinishCmp() || Stmts.add(EAsStmt))
8411 return StmtError();
8412 continue;
8415 if (CmpSoFar.isUnset()) {
8416 CmpSoFar = E;
8417 continue;
8419 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8420 if (CmpSoFar.isInvalid())
8421 return StmtError();
8423 if (FinishCmp())
8424 return StmtError();
8425 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8426 // If no such index exists, V is true.
8427 if (RetVal.isUnset())
8428 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8429 break;
8432 case DefaultedComparisonKind::ThreeWay: {
8433 // Per C++2a [class.spaceship]p3, as a fallback add:
8434 // return static_cast<R>(std::strong_ordering::equal);
8435 QualType StrongOrdering = S.CheckComparisonCategoryType(
8436 ComparisonCategoryType::StrongOrdering, Loc,
8437 Sema::ComparisonCategoryUsage::DefaultedOperator);
8438 if (StrongOrdering.isNull())
8439 return StmtError();
8440 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8441 .getValueInfo(ComparisonCategoryResult::Equal)
8442 ->VD;
8443 RetVal = getDecl(EqualVD);
8444 if (RetVal.isInvalid())
8445 return StmtError();
8446 RetVal = buildStaticCastToR(RetVal.get());
8447 break;
8450 case DefaultedComparisonKind::NotEqual:
8451 case DefaultedComparisonKind::Relational:
8452 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8453 break;
8456 // Build the final return statement.
8457 if (RetVal.isInvalid())
8458 return StmtError();
8459 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8460 if (ReturnStmt.isInvalid())
8461 return StmtError();
8462 Stmts.Stmts.push_back(ReturnStmt.get());
8464 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8467 private:
8468 ExprResult getDecl(ValueDecl *VD) {
8469 return S.BuildDeclarationNameExpr(
8470 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8473 ExprResult getParam(unsigned I) {
8474 ParmVarDecl *PD = FD->getParamDecl(I);
8475 return getDecl(PD);
8478 ExprPair getCompleteObject() {
8479 unsigned Param = 0;
8480 ExprResult LHS;
8481 if (isa<CXXMethodDecl>(FD)) {
8482 // LHS is '*this'.
8483 LHS = S.ActOnCXXThis(Loc);
8484 if (!LHS.isInvalid())
8485 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8486 } else {
8487 LHS = getParam(Param++);
8489 ExprResult RHS = getParam(Param++);
8490 assert(Param == FD->getNumParams());
8491 return {LHS, RHS};
8494 ExprPair getBase(CXXBaseSpecifier *Base) {
8495 ExprPair Obj = getCompleteObject();
8496 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8497 return {ExprError(), ExprError()};
8498 CXXCastPath Path = {Base};
8499 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8500 CK_DerivedToBase, VK_LValue, &Path),
8501 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8502 CK_DerivedToBase, VK_LValue, &Path)};
8505 ExprPair getField(FieldDecl *Field) {
8506 ExprPair Obj = getCompleteObject();
8507 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8508 return {ExprError(), ExprError()};
8510 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8511 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8512 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8513 CXXScopeSpec(), Field, Found, NameInfo),
8514 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8515 CXXScopeSpec(), Field, Found, NameInfo)};
8518 // FIXME: When expanding a subobject, register a note in the code synthesis
8519 // stack to say which subobject we're comparing.
8521 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8522 if (Cond.isInvalid())
8523 return StmtError();
8525 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8526 if (NotCond.isInvalid())
8527 return StmtError();
8529 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8530 assert(!False.isInvalid() && "should never fail");
8531 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8532 if (ReturnFalse.isInvalid())
8533 return StmtError();
8535 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8536 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8537 Sema::ConditionKind::Boolean),
8538 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8541 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8542 ExprPair Subobj) {
8543 QualType SizeType = S.Context.getSizeType();
8544 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8546 // Build 'size_t i$n = 0'.
8547 IdentifierInfo *IterationVarName = nullptr;
8549 SmallString<8> Str;
8550 llvm::raw_svector_ostream OS(Str);
8551 OS << "i" << ArrayDepth;
8552 IterationVarName = &S.Context.Idents.get(OS.str());
8554 VarDecl *IterationVar = VarDecl::Create(
8555 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8556 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8557 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8558 IterationVar->setInit(
8559 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8560 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8562 auto IterRef = [&] {
8563 ExprResult Ref = S.BuildDeclarationNameExpr(
8564 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8565 IterationVar);
8566 assert(!Ref.isInvalid() && "can't reference our own variable?");
8567 return Ref.get();
8570 // Build 'i$n != Size'.
8571 ExprResult Cond = S.CreateBuiltinBinOp(
8572 Loc, BO_NE, IterRef(),
8573 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8574 assert(!Cond.isInvalid() && "should never fail");
8576 // Build '++i$n'.
8577 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8578 assert(!Inc.isInvalid() && "should never fail");
8580 // Build 'a[i$n]' and 'b[i$n]'.
8581 auto Index = [&](ExprResult E) {
8582 if (E.isInvalid())
8583 return ExprError();
8584 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8586 Subobj.first = Index(Subobj.first);
8587 Subobj.second = Index(Subobj.second);
8589 // Compare the array elements.
8590 ++ArrayDepth;
8591 StmtResult Substmt = visitSubobject(Type, Subobj);
8592 --ArrayDepth;
8594 if (Substmt.isInvalid())
8595 return StmtError();
8597 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8598 // For outer levels or for an 'operator<=>' we already have a suitable
8599 // statement that returns as necessary.
8600 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8601 assert(DCK == DefaultedComparisonKind::Equal &&
8602 "should have non-expression statement");
8603 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8604 if (Substmt.isInvalid())
8605 return StmtError();
8608 // Build 'for (...) ...'
8609 return S.ActOnForStmt(Loc, Loc, Init,
8610 S.ActOnCondition(nullptr, Loc, Cond.get(),
8611 Sema::ConditionKind::Boolean),
8612 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8613 Substmt.get());
8616 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8617 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8618 return StmtError();
8620 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8621 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8622 ExprResult Op;
8623 if (Type->isOverloadableType())
8624 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8625 Obj.second.get(), /*PerformADL=*/true,
8626 /*AllowRewrittenCandidates=*/true, FD);
8627 else
8628 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8629 if (Op.isInvalid())
8630 return StmtError();
8632 switch (DCK) {
8633 case DefaultedComparisonKind::None:
8634 llvm_unreachable("not a defaulted comparison");
8636 case DefaultedComparisonKind::Equal:
8637 // Per C++2a [class.eq]p2, each comparison is individually contextually
8638 // converted to bool.
8639 Op = S.PerformContextuallyConvertToBool(Op.get());
8640 if (Op.isInvalid())
8641 return StmtError();
8642 return Op.get();
8644 case DefaultedComparisonKind::ThreeWay: {
8645 // Per C++2a [class.spaceship]p3, form:
8646 // if (R cmp = static_cast<R>(op); cmp != 0)
8647 // return cmp;
8648 QualType R = FD->getReturnType();
8649 Op = buildStaticCastToR(Op.get());
8650 if (Op.isInvalid())
8651 return StmtError();
8653 // R cmp = ...;
8654 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8655 VarDecl *VD =
8656 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8657 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8658 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8659 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8661 // cmp != 0
8662 ExprResult VDRef = getDecl(VD);
8663 if (VDRef.isInvalid())
8664 return StmtError();
8665 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8666 Expr *Zero =
8667 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8668 ExprResult Comp;
8669 if (VDRef.get()->getType()->isOverloadableType())
8670 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8671 true, FD);
8672 else
8673 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8674 if (Comp.isInvalid())
8675 return StmtError();
8676 Sema::ConditionResult Cond = S.ActOnCondition(
8677 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8678 if (Cond.isInvalid())
8679 return StmtError();
8681 // return cmp;
8682 VDRef = getDecl(VD);
8683 if (VDRef.isInvalid())
8684 return StmtError();
8685 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8686 if (ReturnStmt.isInvalid())
8687 return StmtError();
8689 // if (...)
8690 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8691 Loc, ReturnStmt.get(),
8692 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8695 case DefaultedComparisonKind::NotEqual:
8696 case DefaultedComparisonKind::Relational:
8697 // C++2a [class.compare.secondary]p2:
8698 // Otherwise, the operator function yields x @ y.
8699 return Op.get();
8701 llvm_unreachable("");
8704 /// Build "static_cast<R>(E)".
8705 ExprResult buildStaticCastToR(Expr *E) {
8706 QualType R = FD->getReturnType();
8707 assert(!R->isUndeducedType() && "type should have been deduced already");
8709 // Don't bother forming a no-op cast in the common case.
8710 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8711 return E;
8712 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8713 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8714 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8719 /// Perform the unqualified lookups that might be needed to form a defaulted
8720 /// comparison function for the given operator.
8721 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8722 UnresolvedSetImpl &Operators,
8723 OverloadedOperatorKind Op) {
8724 auto Lookup = [&](OverloadedOperatorKind OO) {
8725 Self.LookupOverloadedOperatorName(OO, S, Operators);
8728 // Every defaulted operator looks up itself.
8729 Lookup(Op);
8730 // ... and the rewritten form of itself, if any.
8731 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8732 Lookup(ExtraOp);
8734 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8735 // synthesize a three-way comparison from '<' and '=='. In a dependent
8736 // context, we also need to look up '==' in case we implicitly declare a
8737 // defaulted 'operator=='.
8738 if (Op == OO_Spaceship) {
8739 Lookup(OO_ExclaimEqual);
8740 Lookup(OO_Less);
8741 Lookup(OO_EqualEqual);
8745 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8746 DefaultedComparisonKind DCK) {
8747 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8749 // Perform any unqualified lookups we're going to need to default this
8750 // function.
8751 if (S) {
8752 UnresolvedSet<32> Operators;
8753 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8754 FD->getOverloadedOperator());
8755 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8756 Context, Operators.pairs()));
8759 // C++2a [class.compare.default]p1:
8760 // A defaulted comparison operator function for some class C shall be a
8761 // non-template function declared in the member-specification of C that is
8762 // -- a non-static const non-volatile member of C having one parameter of
8763 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8764 // -- a friend of C having two parameters of type const C& or two
8765 // parameters of type C.
8767 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8768 bool IsMethod = isa<CXXMethodDecl>(FD);
8769 if (IsMethod) {
8770 auto *MD = cast<CXXMethodDecl>(FD);
8771 assert(!MD->isStatic() && "comparison function cannot be a static member");
8773 if (MD->getRefQualifier() == RQ_RValue) {
8774 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8776 // Remove the ref qualifier to recover.
8777 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8778 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8779 EPI.RefQualifier = RQ_None;
8780 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8781 FPT->getParamTypes(), EPI));
8784 // If we're out-of-class, this is the class we're comparing.
8785 if (!RD)
8786 RD = MD->getParent();
8788 if (!MD->isConst()) {
8789 SourceLocation InsertLoc;
8790 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8791 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8792 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8793 // corresponding defaulted 'operator<=>' already.
8794 if (!MD->isImplicit()) {
8795 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8796 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8799 // Add the 'const' to the type to recover.
8800 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8801 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8802 EPI.TypeQuals.addConst();
8803 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8804 FPT->getParamTypes(), EPI));
8807 if (MD->isVolatile()) {
8808 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8810 // Remove the 'volatile' from the type to recover.
8811 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8812 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8813 EPI.TypeQuals.removeVolatile();
8814 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8815 FPT->getParamTypes(), EPI));
8819 if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8820 // Let's not worry about using a variadic template pack here -- who would do
8821 // such a thing?
8822 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8823 << int(IsMethod) << int(DCK);
8824 return true;
8827 const ParmVarDecl *KnownParm = nullptr;
8828 for (const ParmVarDecl *Param : FD->parameters()) {
8829 QualType ParmTy = Param->getType();
8831 if (!KnownParm) {
8832 auto CTy = ParmTy;
8833 // Is it `T const &`?
8834 bool Ok = !IsMethod;
8835 QualType ExpectedTy;
8836 if (RD)
8837 ExpectedTy = Context.getRecordType(RD);
8838 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8839 CTy = Ref->getPointeeType();
8840 if (RD)
8841 ExpectedTy.addConst();
8842 Ok = true;
8845 // Is T a class?
8846 if (!Ok) {
8847 } else if (RD) {
8848 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8849 Ok = false;
8850 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8851 RD = cast<CXXRecordDecl>(CRD);
8852 } else {
8853 Ok = false;
8856 if (Ok) {
8857 KnownParm = Param;
8858 } else {
8859 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8860 // corresponding defaulted 'operator<=>' already.
8861 if (!FD->isImplicit()) {
8862 if (RD) {
8863 QualType PlainTy = Context.getRecordType(RD);
8864 QualType RefTy =
8865 Context.getLValueReferenceType(PlainTy.withConst());
8866 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8867 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8868 << Param->getSourceRange();
8869 } else {
8870 assert(!IsMethod && "should know expected type for method");
8871 Diag(FD->getLocation(),
8872 diag::err_defaulted_comparison_param_unknown)
8873 << int(DCK) << ParmTy << Param->getSourceRange();
8876 return true;
8878 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8879 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8880 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8881 << ParmTy << Param->getSourceRange();
8882 return true;
8886 assert(RD && "must have determined class");
8887 if (IsMethod) {
8888 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8889 // In-class, must be a friend decl.
8890 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8891 } else {
8892 // Out of class, require the defaulted comparison to be a friend (of a
8893 // complete type).
8894 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8895 diag::err_defaulted_comparison_not_friend, int(DCK),
8896 int(1)))
8897 return true;
8899 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8900 return FD->getCanonicalDecl() ==
8901 F->getFriendDecl()->getCanonicalDecl();
8902 })) {
8903 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8904 << int(DCK) << int(0) << RD;
8905 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8906 return true;
8910 // C++2a [class.eq]p1, [class.rel]p1:
8911 // A [defaulted comparison other than <=>] shall have a declared return
8912 // type bool.
8913 if (DCK != DefaultedComparisonKind::ThreeWay &&
8914 !FD->getDeclaredReturnType()->isDependentType() &&
8915 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8916 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8917 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8918 << FD->getReturnTypeSourceRange();
8919 return true;
8921 // C++2a [class.spaceship]p2 [P2002R0]:
8922 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8923 // R shall not contain a placeholder type.
8924 if (QualType RT = FD->getDeclaredReturnType();
8925 DCK == DefaultedComparisonKind::ThreeWay &&
8926 RT->getContainedDeducedType() &&
8927 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
8928 RT->getContainedAutoType()->isConstrained())) {
8929 Diag(FD->getLocation(),
8930 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8931 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8932 << FD->getReturnTypeSourceRange();
8933 return true;
8936 // For a defaulted function in a dependent class, defer all remaining checks
8937 // until instantiation.
8938 if (RD->isDependentType())
8939 return false;
8941 // Determine whether the function should be defined as deleted.
8942 DefaultedComparisonInfo Info =
8943 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8945 bool First = FD == FD->getCanonicalDecl();
8947 if (!First) {
8948 if (Info.Deleted) {
8949 // C++11 [dcl.fct.def.default]p4:
8950 // [For a] user-provided explicitly-defaulted function [...] if such a
8951 // function is implicitly defined as deleted, the program is ill-formed.
8953 // This is really just a consequence of the general rule that you can
8954 // only delete a function on its first declaration.
8955 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8956 << FD->isImplicit() << (int)DCK;
8957 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8958 DefaultedComparisonAnalyzer::ExplainDeleted)
8959 .visit();
8960 return true;
8962 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8963 // C++20 [class.compare.default]p1:
8964 // [...] A definition of a comparison operator as defaulted that appears
8965 // in a class shall be the first declaration of that function.
8966 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8967 << (int)DCK;
8968 Diag(FD->getCanonicalDecl()->getLocation(),
8969 diag::note_previous_declaration);
8970 return true;
8974 // If we want to delete the function, then do so; there's nothing else to
8975 // check in that case.
8976 if (Info.Deleted) {
8977 SetDeclDeleted(FD, FD->getLocation());
8978 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8979 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8980 << (int)DCK;
8981 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8982 DefaultedComparisonAnalyzer::ExplainDeleted)
8983 .visit();
8984 if (FD->getDefaultLoc().isValid())
8985 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8986 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8988 return false;
8991 // C++2a [class.spaceship]p2:
8992 // The return type is deduced as the common comparison type of R0, R1, ...
8993 if (DCK == DefaultedComparisonKind::ThreeWay &&
8994 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8995 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8996 if (RetLoc.isInvalid())
8997 RetLoc = FD->getBeginLoc();
8998 // FIXME: Should we really care whether we have the complete type and the
8999 // 'enumerator' constants here? A forward declaration seems sufficient.
9000 QualType Cat = CheckComparisonCategoryType(
9001 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9002 if (Cat.isNull())
9003 return true;
9004 Context.adjustDeducedFunctionResultType(
9005 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9008 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9009 // An explicitly-defaulted function that is not defined as deleted may be
9010 // declared constexpr or consteval only if it is constexpr-compatible.
9011 // C++2a [class.compare.default]p3 [P2002R0]:
9012 // A defaulted comparison function is constexpr-compatible if it satisfies
9013 // the requirements for a constexpr function [...]
9014 // The only relevant requirements are that the parameter and return types are
9015 // literal types. The remaining conditions are checked by the analyzer.
9017 // We support P2448R2 in language modes earlier than C++23 as an extension.
9018 // The concept of constexpr-compatible was removed.
9019 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9020 // A function explicitly defaulted on its first declaration is implicitly
9021 // inline, and is implicitly constexpr if it is constexpr-suitable.
9022 // C++23 [dcl.constexpr]p3
9023 // A function is constexpr-suitable if
9024 // - it is not a coroutine, and
9025 // - if the function is a constructor or destructor, its class does not
9026 // have any virtual base classes.
9027 if (FD->isConstexpr()) {
9028 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
9029 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
9030 !Info.Constexpr) {
9031 Diag(FD->getBeginLoc(),
9032 getLangOpts().CPlusPlus23
9033 ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch
9034 : diag::ext_defaulted_comparison_constexpr_mismatch)
9035 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9036 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9037 DefaultedComparisonAnalyzer::ExplainConstexpr)
9038 .visit();
9042 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9043 // If a constexpr-compatible function is explicitly defaulted on its first
9044 // declaration, it is implicitly considered to be constexpr.
9045 // FIXME: Only applying this to the first declaration seems problematic, as
9046 // simple reorderings can affect the meaning of the program.
9047 if (First && !FD->isConstexpr() && Info.Constexpr)
9048 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9050 // C++2a [except.spec]p3:
9051 // If a declaration of a function does not have a noexcept-specifier
9052 // [and] is defaulted on its first declaration, [...] the exception
9053 // specification is as specified below
9054 if (FD->getExceptionSpecType() == EST_None) {
9055 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9056 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9057 EPI.ExceptionSpec.Type = EST_Unevaluated;
9058 EPI.ExceptionSpec.SourceDecl = FD;
9059 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9060 FPT->getParamTypes(), EPI));
9063 return false;
9066 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9067 FunctionDecl *Spaceship) {
9068 Sema::CodeSynthesisContext Ctx;
9069 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9070 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9071 Ctx.Entity = Spaceship;
9072 pushCodeSynthesisContext(Ctx);
9074 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9075 EqualEqual->setImplicit();
9077 popCodeSynthesisContext();
9080 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9081 DefaultedComparisonKind DCK) {
9082 assert(FD->isDefaulted() && !FD->isDeleted() &&
9083 !FD->doesThisDeclarationHaveABody());
9084 if (FD->willHaveBody() || FD->isInvalidDecl())
9085 return;
9087 SynthesizedFunctionScope Scope(*this, FD);
9089 // Add a context note for diagnostics produced after this point.
9090 Scope.addContextNote(UseLoc);
9093 // Build and set up the function body.
9094 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9095 // the type of the class being compared.
9096 auto PT = FD->getParamDecl(0)->getType();
9097 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9098 SourceLocation BodyLoc =
9099 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9100 StmtResult Body =
9101 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9102 if (Body.isInvalid()) {
9103 FD->setInvalidDecl();
9104 return;
9106 FD->setBody(Body.get());
9107 FD->markUsed(Context);
9110 // The exception specification is needed because we are defining the
9111 // function. Note that this will reuse the body we just built.
9112 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
9114 if (ASTMutationListener *L = getASTMutationListener())
9115 L->CompletedImplicitDefinition(FD);
9118 static Sema::ImplicitExceptionSpecification
9119 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9120 FunctionDecl *FD,
9121 Sema::DefaultedComparisonKind DCK) {
9122 ComputingExceptionSpec CES(S, FD, Loc);
9123 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9125 if (FD->isInvalidDecl())
9126 return ExceptSpec;
9128 // The common case is that we just defined the comparison function. In that
9129 // case, just look at whether the body can throw.
9130 if (FD->hasBody()) {
9131 ExceptSpec.CalledStmt(FD->getBody());
9132 } else {
9133 // Otherwise, build a body so we can check it. This should ideally only
9134 // happen when we're not actually marking the function referenced. (This is
9135 // only really important for efficiency: we don't want to build and throw
9136 // away bodies for comparison functions more than we strictly need to.)
9138 // Pretend to synthesize the function body in an unevaluated context.
9139 // Note that we can't actually just go ahead and define the function here:
9140 // we are not permitted to mark its callees as referenced.
9141 Sema::SynthesizedFunctionScope Scope(S, FD);
9142 EnterExpressionEvaluationContext Context(
9143 S, Sema::ExpressionEvaluationContext::Unevaluated);
9145 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9146 SourceLocation BodyLoc =
9147 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9148 StmtResult Body =
9149 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9150 if (!Body.isInvalid())
9151 ExceptSpec.CalledStmt(Body.get());
9153 // FIXME: Can we hold onto this body and just transform it to potentially
9154 // evaluated when we're asked to define the function rather than rebuilding
9155 // it? Either that, or we should only build the bits of the body that we
9156 // need (the expressions, not the statements).
9159 return ExceptSpec;
9162 void Sema::CheckDelayedMemberExceptionSpecs() {
9163 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9164 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9166 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9167 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
9169 // Perform any deferred checking of exception specifications for virtual
9170 // destructors.
9171 for (auto &Check : Overriding)
9172 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9174 // Perform any deferred checking of exception specifications for befriended
9175 // special members.
9176 for (auto &Check : Equivalent)
9177 CheckEquivalentExceptionSpec(Check.second, Check.first);
9180 namespace {
9181 /// CRTP base class for visiting operations performed by a special member
9182 /// function (or inherited constructor).
9183 template<typename Derived>
9184 struct SpecialMemberVisitor {
9185 Sema &S;
9186 CXXMethodDecl *MD;
9187 Sema::CXXSpecialMember CSM;
9188 Sema::InheritedConstructorInfo *ICI;
9190 // Properties of the special member, computed for convenience.
9191 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9193 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
9194 Sema::InheritedConstructorInfo *ICI)
9195 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9196 switch (CSM) {
9197 case Sema::CXXDefaultConstructor:
9198 case Sema::CXXCopyConstructor:
9199 case Sema::CXXMoveConstructor:
9200 IsConstructor = true;
9201 break;
9202 case Sema::CXXCopyAssignment:
9203 case Sema::CXXMoveAssignment:
9204 IsAssignment = true;
9205 break;
9206 case Sema::CXXDestructor:
9207 break;
9208 case Sema::CXXInvalid:
9209 llvm_unreachable("invalid special member kind");
9212 if (MD->getNumParams()) {
9213 if (const ReferenceType *RT =
9214 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
9215 ConstArg = RT->getPointeeType().isConstQualified();
9219 Derived &getDerived() { return static_cast<Derived&>(*this); }
9221 /// Is this a "move" special member?
9222 bool isMove() const {
9223 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
9226 /// Look up the corresponding special member in the given class.
9227 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9228 unsigned Quals, bool IsMutable) {
9229 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9230 ConstArg && !IsMutable);
9233 /// Look up the constructor for the specified base class to see if it's
9234 /// overridden due to this being an inherited constructor.
9235 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9236 if (!ICI)
9237 return {};
9238 assert(CSM == Sema::CXXDefaultConstructor);
9239 auto *BaseCtor =
9240 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9241 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9242 return MD;
9243 return {};
9246 /// A base or member subobject.
9247 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9249 /// Get the location to use for a subobject in diagnostics.
9250 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9251 // FIXME: For an indirect virtual base, the direct base leading to
9252 // the indirect virtual base would be a more useful choice.
9253 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9254 return B->getBaseTypeLoc();
9255 else
9256 return Subobj.get<FieldDecl*>()->getLocation();
9259 enum BasesToVisit {
9260 /// Visit all non-virtual (direct) bases.
9261 VisitNonVirtualBases,
9262 /// Visit all direct bases, virtual or not.
9263 VisitDirectBases,
9264 /// Visit all non-virtual bases, and all virtual bases if the class
9265 /// is not abstract.
9266 VisitPotentiallyConstructedBases,
9267 /// Visit all direct or virtual bases.
9268 VisitAllBases
9271 // Visit the bases and members of the class.
9272 bool visit(BasesToVisit Bases) {
9273 CXXRecordDecl *RD = MD->getParent();
9275 if (Bases == VisitPotentiallyConstructedBases)
9276 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9278 for (auto &B : RD->bases())
9279 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9280 getDerived().visitBase(&B))
9281 return true;
9283 if (Bases == VisitAllBases)
9284 for (auto &B : RD->vbases())
9285 if (getDerived().visitBase(&B))
9286 return true;
9288 for (auto *F : RD->fields())
9289 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9290 getDerived().visitField(F))
9291 return true;
9293 return false;
9298 namespace {
9299 struct SpecialMemberDeletionInfo
9300 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9301 bool Diagnose;
9303 SourceLocation Loc;
9305 bool AllFieldsAreConst;
9307 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9308 Sema::CXXSpecialMember CSM,
9309 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9310 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9311 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9313 bool inUnion() const { return MD->getParent()->isUnion(); }
9315 Sema::CXXSpecialMember getEffectiveCSM() {
9316 return ICI ? Sema::CXXInvalid : CSM;
9319 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9321 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9322 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9324 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9325 bool shouldDeleteForField(FieldDecl *FD);
9326 bool shouldDeleteForAllConstMembers();
9328 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9329 unsigned Quals);
9330 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9331 Sema::SpecialMemberOverloadResult SMOR,
9332 bool IsDtorCallInCtor);
9334 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9338 /// Is the given special member inaccessible when used on the given
9339 /// sub-object.
9340 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9341 CXXMethodDecl *target) {
9342 /// If we're operating on a base class, the object type is the
9343 /// type of this special member.
9344 QualType objectTy;
9345 AccessSpecifier access = target->getAccess();
9346 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9347 objectTy = S.Context.getTypeDeclType(MD->getParent());
9348 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9350 // If we're operating on a field, the object type is the type of the field.
9351 } else {
9352 objectTy = S.Context.getTypeDeclType(target->getParent());
9355 return S.isMemberAccessibleForDeletion(
9356 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9359 /// Check whether we should delete a special member due to the implicit
9360 /// definition containing a call to a special member of a subobject.
9361 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9362 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9363 bool IsDtorCallInCtor) {
9364 CXXMethodDecl *Decl = SMOR.getMethod();
9365 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9367 int DiagKind = -1;
9369 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9370 DiagKind = !Decl ? 0 : 1;
9371 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9372 DiagKind = 2;
9373 else if (!isAccessible(Subobj, Decl))
9374 DiagKind = 3;
9375 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9376 !Decl->isTrivial()) {
9377 // A member of a union must have a trivial corresponding special member.
9378 // As a weird special case, a destructor call from a union's constructor
9379 // must be accessible and non-deleted, but need not be trivial. Such a
9380 // destructor is never actually called, but is semantically checked as
9381 // if it were.
9382 if (CSM == Sema::CXXDefaultConstructor) {
9383 // [class.default.ctor]p2:
9384 // A defaulted default constructor for class X is defined as deleted if
9385 // - X is a union that has a variant member with a non-trivial default
9386 // constructor and no variant member of X has a default member
9387 // initializer
9388 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9389 if (!RD->hasInClassInitializer())
9390 DiagKind = 4;
9391 } else {
9392 DiagKind = 4;
9396 if (DiagKind == -1)
9397 return false;
9399 if (Diagnose) {
9400 if (Field) {
9401 S.Diag(Field->getLocation(),
9402 diag::note_deleted_special_member_class_subobject)
9403 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9404 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9405 } else {
9406 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9407 S.Diag(Base->getBeginLoc(),
9408 diag::note_deleted_special_member_class_subobject)
9409 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9410 << Base->getType() << DiagKind << IsDtorCallInCtor
9411 << /*IsObjCPtr*/false;
9414 if (DiagKind == 1)
9415 S.NoteDeletedFunction(Decl);
9416 // FIXME: Explain inaccessibility if DiagKind == 3.
9419 return true;
9422 /// Check whether we should delete a special member function due to having a
9423 /// direct or virtual base class or non-static data member of class type M.
9424 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9425 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9426 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9427 bool IsMutable = Field && Field->isMutable();
9429 // C++11 [class.ctor]p5:
9430 // -- any direct or virtual base class, or non-static data member with no
9431 // brace-or-equal-initializer, has class type M (or array thereof) and
9432 // either M has no default constructor or overload resolution as applied
9433 // to M's default constructor results in an ambiguity or in a function
9434 // that is deleted or inaccessible
9435 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9436 // -- a direct or virtual base class B that cannot be copied/moved because
9437 // overload resolution, as applied to B's corresponding special member,
9438 // results in an ambiguity or a function that is deleted or inaccessible
9439 // from the defaulted special member
9440 // C++11 [class.dtor]p5:
9441 // -- any direct or virtual base class [...] has a type with a destructor
9442 // that is deleted or inaccessible
9443 if (!(CSM == Sema::CXXDefaultConstructor &&
9444 Field && Field->hasInClassInitializer()) &&
9445 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9446 false))
9447 return true;
9449 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9450 // -- any direct or virtual base class or non-static data member has a
9451 // type with a destructor that is deleted or inaccessible
9452 if (IsConstructor) {
9453 Sema::SpecialMemberOverloadResult SMOR =
9454 S.LookupSpecialMember(Class, Sema::CXXDestructor,
9455 false, false, false, false, false);
9456 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9457 return true;
9460 return false;
9463 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9464 FieldDecl *FD, QualType FieldType) {
9465 // The defaulted special functions are defined as deleted if this is a variant
9466 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9467 // type under ARC.
9468 if (!FieldType.hasNonTrivialObjCLifetime())
9469 return false;
9471 // Don't make the defaulted default constructor defined as deleted if the
9472 // member has an in-class initializer.
9473 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9474 return false;
9476 if (Diagnose) {
9477 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9478 S.Diag(FD->getLocation(),
9479 diag::note_deleted_special_member_class_subobject)
9480 << getEffectiveCSM() << ParentClass << /*IsField*/true
9481 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9484 return true;
9487 /// Check whether we should delete a special member function due to the class
9488 /// having a particular direct or virtual base class.
9489 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9490 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9491 // If program is correct, BaseClass cannot be null, but if it is, the error
9492 // must be reported elsewhere.
9493 if (!BaseClass)
9494 return false;
9495 // If we have an inheriting constructor, check whether we're calling an
9496 // inherited constructor instead of a default constructor.
9497 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9498 if (auto *BaseCtor = SMOR.getMethod()) {
9499 // Note that we do not check access along this path; other than that,
9500 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9501 // FIXME: Check that the base has a usable destructor! Sink this into
9502 // shouldDeleteForClassSubobject.
9503 if (BaseCtor->isDeleted() && Diagnose) {
9504 S.Diag(Base->getBeginLoc(),
9505 diag::note_deleted_special_member_class_subobject)
9506 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9507 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9508 << /*IsObjCPtr*/false;
9509 S.NoteDeletedFunction(BaseCtor);
9511 return BaseCtor->isDeleted();
9513 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9516 /// Check whether we should delete a special member function due to the class
9517 /// having a particular non-static data member.
9518 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9519 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9520 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9522 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9523 return true;
9525 if (CSM == Sema::CXXDefaultConstructor) {
9526 // For a default constructor, all references must be initialized in-class
9527 // and, if a union, it must have a non-const member.
9528 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9529 if (Diagnose)
9530 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9531 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9532 return true;
9534 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9535 // data member of const-qualified type (or array thereof) with no
9536 // brace-or-equal-initializer is not const-default-constructible.
9537 if (!inUnion() && FieldType.isConstQualified() &&
9538 !FD->hasInClassInitializer() &&
9539 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9540 if (Diagnose)
9541 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9542 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9543 return true;
9546 if (inUnion() && !FieldType.isConstQualified())
9547 AllFieldsAreConst = false;
9548 } else if (CSM == Sema::CXXCopyConstructor) {
9549 // For a copy constructor, data members must not be of rvalue reference
9550 // type.
9551 if (FieldType->isRValueReferenceType()) {
9552 if (Diagnose)
9553 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9554 << MD->getParent() << FD << FieldType;
9555 return true;
9557 } else if (IsAssignment) {
9558 // For an assignment operator, data members must not be of reference type.
9559 if (FieldType->isReferenceType()) {
9560 if (Diagnose)
9561 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9562 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9563 return true;
9565 if (!FieldRecord && FieldType.isConstQualified()) {
9566 // C++11 [class.copy]p23:
9567 // -- a non-static data member of const non-class type (or array thereof)
9568 if (Diagnose)
9569 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9570 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9571 return true;
9575 if (FieldRecord) {
9576 // Some additional restrictions exist on the variant members.
9577 if (!inUnion() && FieldRecord->isUnion() &&
9578 FieldRecord->isAnonymousStructOrUnion()) {
9579 bool AllVariantFieldsAreConst = true;
9581 // FIXME: Handle anonymous unions declared within anonymous unions.
9582 for (auto *UI : FieldRecord->fields()) {
9583 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9585 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9586 return true;
9588 if (!UnionFieldType.isConstQualified())
9589 AllVariantFieldsAreConst = false;
9591 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9592 if (UnionFieldRecord &&
9593 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9594 UnionFieldType.getCVRQualifiers()))
9595 return true;
9598 // At least one member in each anonymous union must be non-const
9599 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9600 !FieldRecord->field_empty()) {
9601 if (Diagnose)
9602 S.Diag(FieldRecord->getLocation(),
9603 diag::note_deleted_default_ctor_all_const)
9604 << !!ICI << MD->getParent() << /*anonymous union*/1;
9605 return true;
9608 // Don't check the implicit member of the anonymous union type.
9609 // This is technically non-conformant but supported, and we have a
9610 // diagnostic for this elsewhere.
9611 return false;
9614 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9615 FieldType.getCVRQualifiers()))
9616 return true;
9619 return false;
9622 /// C++11 [class.ctor] p5:
9623 /// A defaulted default constructor for a class X is defined as deleted if
9624 /// X is a union and all of its variant members are of const-qualified type.
9625 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9626 // This is a silly definition, because it gives an empty union a deleted
9627 // default constructor. Don't do that.
9628 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9629 bool AnyFields = false;
9630 for (auto *F : MD->getParent()->fields())
9631 if ((AnyFields = !F->isUnnamedBitfield()))
9632 break;
9633 if (!AnyFields)
9634 return false;
9635 if (Diagnose)
9636 S.Diag(MD->getParent()->getLocation(),
9637 diag::note_deleted_default_ctor_all_const)
9638 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9639 return true;
9641 return false;
9644 /// Determine whether a defaulted special member function should be defined as
9645 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9646 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9647 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9648 InheritedConstructorInfo *ICI,
9649 bool Diagnose) {
9650 if (MD->isInvalidDecl())
9651 return false;
9652 CXXRecordDecl *RD = MD->getParent();
9653 assert(!RD->isDependentType() && "do deletion after instantiation");
9654 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9655 return false;
9657 // C++11 [expr.lambda.prim]p19:
9658 // The closure type associated with a lambda-expression has a
9659 // deleted (8.4.3) default constructor and a deleted copy
9660 // assignment operator.
9661 // C++2a adds back these operators if the lambda has no lambda-capture.
9662 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9663 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9664 if (Diagnose)
9665 Diag(RD->getLocation(), diag::note_lambda_decl);
9666 return true;
9669 // For an anonymous struct or union, the copy and assignment special members
9670 // will never be used, so skip the check. For an anonymous union declared at
9671 // namespace scope, the constructor and destructor are used.
9672 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9673 RD->isAnonymousStructOrUnion())
9674 return false;
9676 // C++11 [class.copy]p7, p18:
9677 // If the class definition declares a move constructor or move assignment
9678 // operator, an implicitly declared copy constructor or copy assignment
9679 // operator is defined as deleted.
9680 if (MD->isImplicit() &&
9681 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9682 CXXMethodDecl *UserDeclaredMove = nullptr;
9684 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9685 // deletion of the corresponding copy operation, not both copy operations.
9686 // MSVC 2015 has adopted the standards conforming behavior.
9687 bool DeletesOnlyMatchingCopy =
9688 getLangOpts().MSVCCompat &&
9689 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9691 if (RD->hasUserDeclaredMoveConstructor() &&
9692 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9693 if (!Diagnose) return true;
9695 // Find any user-declared move constructor.
9696 for (auto *I : RD->ctors()) {
9697 if (I->isMoveConstructor()) {
9698 UserDeclaredMove = I;
9699 break;
9702 assert(UserDeclaredMove);
9703 } else if (RD->hasUserDeclaredMoveAssignment() &&
9704 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9705 if (!Diagnose) return true;
9707 // Find any user-declared move assignment operator.
9708 for (auto *I : RD->methods()) {
9709 if (I->isMoveAssignmentOperator()) {
9710 UserDeclaredMove = I;
9711 break;
9714 assert(UserDeclaredMove);
9717 if (UserDeclaredMove) {
9718 Diag(UserDeclaredMove->getLocation(),
9719 diag::note_deleted_copy_user_declared_move)
9720 << (CSM == CXXCopyAssignment) << RD
9721 << UserDeclaredMove->isMoveAssignmentOperator();
9722 return true;
9726 // Do access control from the special member function
9727 ContextRAII MethodContext(*this, MD);
9729 // C++11 [class.dtor]p5:
9730 // -- for a virtual destructor, lookup of the non-array deallocation function
9731 // results in an ambiguity or in a function that is deleted or inaccessible
9732 if (CSM == CXXDestructor && MD->isVirtual()) {
9733 FunctionDecl *OperatorDelete = nullptr;
9734 DeclarationName Name =
9735 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9736 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9737 OperatorDelete, /*Diagnose*/false)) {
9738 if (Diagnose)
9739 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9740 return true;
9744 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9746 // Per DR1611, do not consider virtual bases of constructors of abstract
9747 // classes, since we are not going to construct them.
9748 // Per DR1658, do not consider virtual bases of destructors of abstract
9749 // classes either.
9750 // Per DR2180, for assignment operators we only assign (and thus only
9751 // consider) direct bases.
9752 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9753 : SMI.VisitPotentiallyConstructedBases))
9754 return true;
9756 if (SMI.shouldDeleteForAllConstMembers())
9757 return true;
9759 if (getLangOpts().CUDA) {
9760 // We should delete the special member in CUDA mode if target inference
9761 // failed.
9762 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9763 // is treated as certain special member, which may not reflect what special
9764 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9765 // expects CSM to match MD, therefore recalculate CSM.
9766 assert(ICI || CSM == getSpecialMember(MD));
9767 auto RealCSM = CSM;
9768 if (ICI)
9769 RealCSM = getSpecialMember(MD);
9771 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9772 SMI.ConstArg, Diagnose);
9775 return false;
9778 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9779 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9780 assert(DFK && "not a defaultable function");
9781 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9783 if (DFK.isSpecialMember()) {
9784 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9785 nullptr, /*Diagnose=*/true);
9786 } else {
9787 DefaultedComparisonAnalyzer(
9788 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9789 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9790 .visit();
9794 /// Perform lookup for a special member of the specified kind, and determine
9795 /// whether it is trivial. If the triviality can be determined without the
9796 /// lookup, skip it. This is intended for use when determining whether a
9797 /// special member of a containing object is trivial, and thus does not ever
9798 /// perform overload resolution for default constructors.
9800 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9801 /// member that was most likely to be intended to be trivial, if any.
9803 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9804 /// determine whether the special member is trivial.
9805 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9806 Sema::CXXSpecialMember CSM, unsigned Quals,
9807 bool ConstRHS,
9808 Sema::TrivialABIHandling TAH,
9809 CXXMethodDecl **Selected) {
9810 if (Selected)
9811 *Selected = nullptr;
9813 switch (CSM) {
9814 case Sema::CXXInvalid:
9815 llvm_unreachable("not a special member");
9817 case Sema::CXXDefaultConstructor:
9818 // C++11 [class.ctor]p5:
9819 // A default constructor is trivial if:
9820 // - all the [direct subobjects] have trivial default constructors
9822 // Note, no overload resolution is performed in this case.
9823 if (RD->hasTrivialDefaultConstructor())
9824 return true;
9826 if (Selected) {
9827 // If there's a default constructor which could have been trivial, dig it
9828 // out. Otherwise, if there's any user-provided default constructor, point
9829 // to that as an example of why there's not a trivial one.
9830 CXXConstructorDecl *DefCtor = nullptr;
9831 if (RD->needsImplicitDefaultConstructor())
9832 S.DeclareImplicitDefaultConstructor(RD);
9833 for (auto *CI : RD->ctors()) {
9834 if (!CI->isDefaultConstructor())
9835 continue;
9836 DefCtor = CI;
9837 if (!DefCtor->isUserProvided())
9838 break;
9841 *Selected = DefCtor;
9844 return false;
9846 case Sema::CXXDestructor:
9847 // C++11 [class.dtor]p5:
9848 // A destructor is trivial if:
9849 // - all the direct [subobjects] have trivial destructors
9850 if (RD->hasTrivialDestructor() ||
9851 (TAH == Sema::TAH_ConsiderTrivialABI &&
9852 RD->hasTrivialDestructorForCall()))
9853 return true;
9855 if (Selected) {
9856 if (RD->needsImplicitDestructor())
9857 S.DeclareImplicitDestructor(RD);
9858 *Selected = RD->getDestructor();
9861 return false;
9863 case Sema::CXXCopyConstructor:
9864 // C++11 [class.copy]p12:
9865 // A copy constructor is trivial if:
9866 // - the constructor selected to copy each direct [subobject] is trivial
9867 if (RD->hasTrivialCopyConstructor() ||
9868 (TAH == Sema::TAH_ConsiderTrivialABI &&
9869 RD->hasTrivialCopyConstructorForCall())) {
9870 if (Quals == Qualifiers::Const)
9871 // We must either select the trivial copy constructor or reach an
9872 // ambiguity; no need to actually perform overload resolution.
9873 return true;
9874 } else if (!Selected) {
9875 return false;
9877 // In C++98, we are not supposed to perform overload resolution here, but we
9878 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9879 // cases like B as having a non-trivial copy constructor:
9880 // struct A { template<typename T> A(T&); };
9881 // struct B { mutable A a; };
9882 goto NeedOverloadResolution;
9884 case Sema::CXXCopyAssignment:
9885 // C++11 [class.copy]p25:
9886 // A copy assignment operator is trivial if:
9887 // - the assignment operator selected to copy each direct [subobject] is
9888 // trivial
9889 if (RD->hasTrivialCopyAssignment()) {
9890 if (Quals == Qualifiers::Const)
9891 return true;
9892 } else if (!Selected) {
9893 return false;
9895 // In C++98, we are not supposed to perform overload resolution here, but we
9896 // treat that as a language defect.
9897 goto NeedOverloadResolution;
9899 case Sema::CXXMoveConstructor:
9900 case Sema::CXXMoveAssignment:
9901 NeedOverloadResolution:
9902 Sema::SpecialMemberOverloadResult SMOR =
9903 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9905 // The standard doesn't describe how to behave if the lookup is ambiguous.
9906 // We treat it as not making the member non-trivial, just like the standard
9907 // mandates for the default constructor. This should rarely matter, because
9908 // the member will also be deleted.
9909 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9910 return true;
9912 if (!SMOR.getMethod()) {
9913 assert(SMOR.getKind() ==
9914 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9915 return false;
9918 // We deliberately don't check if we found a deleted special member. We're
9919 // not supposed to!
9920 if (Selected)
9921 *Selected = SMOR.getMethod();
9923 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9924 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9925 return SMOR.getMethod()->isTrivialForCall();
9926 return SMOR.getMethod()->isTrivial();
9929 llvm_unreachable("unknown special method kind");
9932 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9933 for (auto *CI : RD->ctors())
9934 if (!CI->isImplicit())
9935 return CI;
9937 // Look for constructor templates.
9938 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9939 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9940 if (CXXConstructorDecl *CD =
9941 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9942 return CD;
9945 return nullptr;
9948 /// The kind of subobject we are checking for triviality. The values of this
9949 /// enumeration are used in diagnostics.
9950 enum TrivialSubobjectKind {
9951 /// The subobject is a base class.
9952 TSK_BaseClass,
9953 /// The subobject is a non-static data member.
9954 TSK_Field,
9955 /// The object is actually the complete object.
9956 TSK_CompleteObject
9959 /// Check whether the special member selected for a given type would be trivial.
9960 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9961 QualType SubType, bool ConstRHS,
9962 Sema::CXXSpecialMember CSM,
9963 TrivialSubobjectKind Kind,
9964 Sema::TrivialABIHandling TAH, bool Diagnose) {
9965 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9966 if (!SubRD)
9967 return true;
9969 CXXMethodDecl *Selected;
9970 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9971 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9972 return true;
9974 if (Diagnose) {
9975 if (ConstRHS)
9976 SubType.addConst();
9978 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9979 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9980 << Kind << SubType.getUnqualifiedType();
9981 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9982 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9983 } else if (!Selected)
9984 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9985 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9986 else if (Selected->isUserProvided()) {
9987 if (Kind == TSK_CompleteObject)
9988 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9989 << Kind << SubType.getUnqualifiedType() << CSM;
9990 else {
9991 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9992 << Kind << SubType.getUnqualifiedType() << CSM;
9993 S.Diag(Selected->getLocation(), diag::note_declared_at);
9995 } else {
9996 if (Kind != TSK_CompleteObject)
9997 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9998 << Kind << SubType.getUnqualifiedType() << CSM;
10000 // Explain why the defaulted or deleted special member isn't trivial.
10001 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
10002 Diagnose);
10006 return false;
10009 /// Check whether the members of a class type allow a special member to be
10010 /// trivial.
10011 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10012 Sema::CXXSpecialMember CSM,
10013 bool ConstArg,
10014 Sema::TrivialABIHandling TAH,
10015 bool Diagnose) {
10016 for (const auto *FI : RD->fields()) {
10017 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
10018 continue;
10020 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10022 // Pretend anonymous struct or union members are members of this class.
10023 if (FI->isAnonymousStructOrUnion()) {
10024 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10025 CSM, ConstArg, TAH, Diagnose))
10026 return false;
10027 continue;
10030 // C++11 [class.ctor]p5:
10031 // A default constructor is trivial if [...]
10032 // -- no non-static data member of its class has a
10033 // brace-or-equal-initializer
10034 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
10035 if (Diagnose)
10036 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10037 << FI;
10038 return false;
10041 // Objective C ARC 4.3.5:
10042 // [...] nontrivally ownership-qualified types are [...] not trivially
10043 // default constructible, copy constructible, move constructible, copy
10044 // assignable, move assignable, or destructible [...]
10045 if (FieldType.hasNonTrivialObjCLifetime()) {
10046 if (Diagnose)
10047 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10048 << RD << FieldType.getObjCLifetime();
10049 return false;
10052 bool ConstRHS = ConstArg && !FI->isMutable();
10053 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10054 CSM, TSK_Field, TAH, Diagnose))
10055 return false;
10058 return true;
10061 /// Diagnose why the specified class does not have a trivial special member of
10062 /// the given kind.
10063 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
10064 QualType Ty = Context.getRecordType(RD);
10066 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
10067 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10068 TSK_CompleteObject, TAH_IgnoreTrivialABI,
10069 /*Diagnose*/true);
10072 /// Determine whether a defaulted or deleted special member function is trivial,
10073 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10074 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10075 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
10076 TrivialABIHandling TAH, bool Diagnose) {
10077 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
10079 CXXRecordDecl *RD = MD->getParent();
10081 bool ConstArg = false;
10083 // C++11 [class.copy]p12, p25: [DR1593]
10084 // A [special member] is trivial if [...] its parameter-type-list is
10085 // equivalent to the parameter-type-list of an implicit declaration [...]
10086 switch (CSM) {
10087 case CXXDefaultConstructor:
10088 case CXXDestructor:
10089 // Trivial default constructors and destructors cannot have parameters.
10090 break;
10092 case CXXCopyConstructor:
10093 case CXXCopyAssignment: {
10094 const ParmVarDecl *Param0 = MD->getParamDecl(0);
10095 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10097 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10098 // if they are not user-provided and their parameter-type-list is equivalent
10099 // to the parameter-type-list of an implicit declaration. This maintains the
10100 // behavior before dr2171 was implemented.
10102 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10103 // trivial, if they are not user-provided, regardless of the qualifiers on
10104 // the reference type.
10105 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10106 LangOptions::ClangABI::Ver14;
10107 if (!RT ||
10108 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10109 ClangABICompat14)) {
10110 if (Diagnose)
10111 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10112 << Param0->getSourceRange() << Param0->getType()
10113 << Context.getLValueReferenceType(
10114 Context.getRecordType(RD).withConst());
10115 return false;
10118 ConstArg = RT->getPointeeType().isConstQualified();
10119 break;
10122 case CXXMoveConstructor:
10123 case CXXMoveAssignment: {
10124 // Trivial move operations always have non-cv-qualified parameters.
10125 const ParmVarDecl *Param0 = MD->getParamDecl(0);
10126 const RValueReferenceType *RT =
10127 Param0->getType()->getAs<RValueReferenceType>();
10128 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10129 if (Diagnose)
10130 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10131 << Param0->getSourceRange() << Param0->getType()
10132 << Context.getRValueReferenceType(Context.getRecordType(RD));
10133 return false;
10135 break;
10138 case CXXInvalid:
10139 llvm_unreachable("not a special member");
10142 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10143 if (Diagnose)
10144 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10145 diag::note_nontrivial_default_arg)
10146 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10147 return false;
10149 if (MD->isVariadic()) {
10150 if (Diagnose)
10151 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10152 return false;
10155 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10156 // A copy/move [constructor or assignment operator] is trivial if
10157 // -- the [member] selected to copy/move each direct base class subobject
10158 // is trivial
10160 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10161 // A [default constructor or destructor] is trivial if
10162 // -- all the direct base classes have trivial [default constructors or
10163 // destructors]
10164 for (const auto &BI : RD->bases())
10165 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10166 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10167 return false;
10169 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10170 // A copy/move [constructor or assignment operator] for a class X is
10171 // trivial if
10172 // -- for each non-static data member of X that is of class type (or array
10173 // thereof), the constructor selected to copy/move that member is
10174 // trivial
10176 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10177 // A [default constructor or destructor] is trivial if
10178 // -- for all of the non-static data members of its class that are of class
10179 // type (or array thereof), each such class has a trivial [default
10180 // constructor or destructor]
10181 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10182 return false;
10184 // C++11 [class.dtor]p5:
10185 // A destructor is trivial if [...]
10186 // -- the destructor is not virtual
10187 if (CSM == CXXDestructor && MD->isVirtual()) {
10188 if (Diagnose)
10189 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10190 return false;
10193 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10194 // A [special member] for class X is trivial if [...]
10195 // -- class X has no virtual functions and no virtual base classes
10196 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
10197 if (!Diagnose)
10198 return false;
10200 if (RD->getNumVBases()) {
10201 // Check for virtual bases. We already know that the corresponding
10202 // member in all bases is trivial, so vbases must all be direct.
10203 CXXBaseSpecifier &BS = *RD->vbases_begin();
10204 assert(BS.isVirtual());
10205 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10206 return false;
10209 // Must have a virtual method.
10210 for (const auto *MI : RD->methods()) {
10211 if (MI->isVirtual()) {
10212 SourceLocation MLoc = MI->getBeginLoc();
10213 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10214 return false;
10218 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10221 // Looks like it's trivial!
10222 return true;
10225 namespace {
10226 struct FindHiddenVirtualMethod {
10227 Sema *S;
10228 CXXMethodDecl *Method;
10229 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10230 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10232 private:
10233 /// Check whether any most overridden method from MD in Methods
10234 static bool CheckMostOverridenMethods(
10235 const CXXMethodDecl *MD,
10236 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10237 if (MD->size_overridden_methods() == 0)
10238 return Methods.count(MD->getCanonicalDecl());
10239 for (const CXXMethodDecl *O : MD->overridden_methods())
10240 if (CheckMostOverridenMethods(O, Methods))
10241 return true;
10242 return false;
10245 public:
10246 /// Member lookup function that determines whether a given C++
10247 /// method overloads virtual methods in a base class without overriding any,
10248 /// to be used with CXXRecordDecl::lookupInBases().
10249 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10250 RecordDecl *BaseRecord =
10251 Specifier->getType()->castAs<RecordType>()->getDecl();
10253 DeclarationName Name = Method->getDeclName();
10254 assert(Name.getNameKind() == DeclarationName::Identifier);
10256 bool foundSameNameMethod = false;
10257 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10258 for (Path.Decls = BaseRecord->lookup(Name).begin();
10259 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10260 NamedDecl *D = *Path.Decls;
10261 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10262 MD = MD->getCanonicalDecl();
10263 foundSameNameMethod = true;
10264 // Interested only in hidden virtual methods.
10265 if (!MD->isVirtual())
10266 continue;
10267 // If the method we are checking overrides a method from its base
10268 // don't warn about the other overloaded methods. Clang deviates from
10269 // GCC by only diagnosing overloads of inherited virtual functions that
10270 // do not override any other virtual functions in the base. GCC's
10271 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10272 // function from a base class. These cases may be better served by a
10273 // warning (not specific to virtual functions) on call sites when the
10274 // call would select a different function from the base class, were it
10275 // visible.
10276 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10277 if (!S->IsOverload(Method, MD, false))
10278 return true;
10279 // Collect the overload only if its hidden.
10280 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10281 overloadedMethods.push_back(MD);
10285 if (foundSameNameMethod)
10286 OverloadedMethods.append(overloadedMethods.begin(),
10287 overloadedMethods.end());
10288 return foundSameNameMethod;
10291 } // end anonymous namespace
10293 /// Add the most overridden methods from MD to Methods
10294 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10295 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10296 if (MD->size_overridden_methods() == 0)
10297 Methods.insert(MD->getCanonicalDecl());
10298 else
10299 for (const CXXMethodDecl *O : MD->overridden_methods())
10300 AddMostOverridenMethods(O, Methods);
10303 /// Check if a method overloads virtual methods in a base class without
10304 /// overriding any.
10305 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10306 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10307 if (!MD->getDeclName().isIdentifier())
10308 return;
10310 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10311 /*bool RecordPaths=*/false,
10312 /*bool DetectVirtual=*/false);
10313 FindHiddenVirtualMethod FHVM;
10314 FHVM.Method = MD;
10315 FHVM.S = this;
10317 // Keep the base methods that were overridden or introduced in the subclass
10318 // by 'using' in a set. A base method not in this set is hidden.
10319 CXXRecordDecl *DC = MD->getParent();
10320 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10321 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10322 NamedDecl *ND = *I;
10323 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10324 ND = shad->getTargetDecl();
10325 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10326 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10329 if (DC->lookupInBases(FHVM, Paths))
10330 OverloadedMethods = FHVM.OverloadedMethods;
10333 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10334 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10335 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10336 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10337 PartialDiagnostic PD = PDiag(
10338 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10339 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10340 Diag(overloadedMD->getLocation(), PD);
10344 /// Diagnose methods which overload virtual methods in a base class
10345 /// without overriding any.
10346 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10347 if (MD->isInvalidDecl())
10348 return;
10350 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10351 return;
10353 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10354 FindHiddenVirtualMethods(MD, OverloadedMethods);
10355 if (!OverloadedMethods.empty()) {
10356 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10357 << MD << (OverloadedMethods.size() > 1);
10359 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10363 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10364 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10365 // No diagnostics if this is a template instantiation.
10366 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10367 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10368 diag::ext_cannot_use_trivial_abi) << &RD;
10369 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10370 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10372 RD.dropAttr<TrivialABIAttr>();
10375 // Ill-formed if the copy and move constructors are deleted.
10376 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10377 // If the type is dependent, then assume it might have
10378 // implicit copy or move ctor because we won't know yet at this point.
10379 if (RD.isDependentType())
10380 return true;
10381 if (RD.needsImplicitCopyConstructor() &&
10382 !RD.defaultedCopyConstructorIsDeleted())
10383 return true;
10384 if (RD.needsImplicitMoveConstructor() &&
10385 !RD.defaultedMoveConstructorIsDeleted())
10386 return true;
10387 for (const CXXConstructorDecl *CD : RD.ctors())
10388 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10389 return true;
10390 return false;
10393 if (!HasNonDeletedCopyOrMoveConstructor()) {
10394 PrintDiagAndRemoveAttr(0);
10395 return;
10398 // Ill-formed if the struct has virtual functions.
10399 if (RD.isPolymorphic()) {
10400 PrintDiagAndRemoveAttr(1);
10401 return;
10404 for (const auto &B : RD.bases()) {
10405 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10406 // virtual base.
10407 if (!B.getType()->isDependentType() &&
10408 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10409 PrintDiagAndRemoveAttr(2);
10410 return;
10413 if (B.isVirtual()) {
10414 PrintDiagAndRemoveAttr(3);
10415 return;
10419 for (const auto *FD : RD.fields()) {
10420 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10421 // non-trivial for the purpose of calls.
10422 QualType FT = FD->getType();
10423 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10424 PrintDiagAndRemoveAttr(4);
10425 return;
10428 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10429 if (!RT->isDependentType() &&
10430 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10431 PrintDiagAndRemoveAttr(5);
10432 return;
10437 void Sema::ActOnFinishCXXMemberSpecification(
10438 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10439 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10440 if (!TagDecl)
10441 return;
10443 AdjustDeclIfTemplate(TagDecl);
10445 for (const ParsedAttr &AL : AttrList) {
10446 if (AL.getKind() != ParsedAttr::AT_Visibility)
10447 continue;
10448 AL.setInvalid();
10449 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10452 ActOnFields(S, RLoc, TagDecl,
10453 llvm::ArrayRef(
10454 // strict aliasing violation!
10455 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10456 FieldCollector->getCurNumFields()),
10457 LBrac, RBrac, AttrList);
10459 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10462 /// Find the equality comparison functions that should be implicitly declared
10463 /// in a given class definition, per C++2a [class.compare.default]p3.
10464 static void findImplicitlyDeclaredEqualityComparisons(
10465 ASTContext &Ctx, CXXRecordDecl *RD,
10466 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10467 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10468 if (!RD->lookup(EqEq).empty())
10469 // Member operator== explicitly declared: no implicit operator==s.
10470 return;
10472 // Traverse friends looking for an '==' or a '<=>'.
10473 for (FriendDecl *Friend : RD->friends()) {
10474 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10475 if (!FD) continue;
10477 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10478 // Friend operator== explicitly declared: no implicit operator==s.
10479 Spaceships.clear();
10480 return;
10483 if (FD->getOverloadedOperator() == OO_Spaceship &&
10484 FD->isExplicitlyDefaulted())
10485 Spaceships.push_back(FD);
10488 // Look for members named 'operator<=>'.
10489 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10490 for (NamedDecl *ND : RD->lookup(Cmp)) {
10491 // Note that we could find a non-function here (either a function template
10492 // or a using-declaration). Neither case results in an implicit
10493 // 'operator=='.
10494 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10495 if (FD->isExplicitlyDefaulted())
10496 Spaceships.push_back(FD);
10500 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10501 /// special functions, such as the default constructor, copy
10502 /// constructor, or destructor, to the given C++ class (C++
10503 /// [special]p1). This routine can only be executed just before the
10504 /// definition of the class is complete.
10505 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10506 // Don't add implicit special members to templated classes.
10507 // FIXME: This means unqualified lookups for 'operator=' within a class
10508 // template don't work properly.
10509 if (!ClassDecl->isDependentType()) {
10510 if (ClassDecl->needsImplicitDefaultConstructor()) {
10511 ++getASTContext().NumImplicitDefaultConstructors;
10513 if (ClassDecl->hasInheritedConstructor())
10514 DeclareImplicitDefaultConstructor(ClassDecl);
10517 if (ClassDecl->needsImplicitCopyConstructor()) {
10518 ++getASTContext().NumImplicitCopyConstructors;
10520 // If the properties or semantics of the copy constructor couldn't be
10521 // determined while the class was being declared, force a declaration
10522 // of it now.
10523 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10524 ClassDecl->hasInheritedConstructor())
10525 DeclareImplicitCopyConstructor(ClassDecl);
10526 // For the MS ABI we need to know whether the copy ctor is deleted. A
10527 // prerequisite for deleting the implicit copy ctor is that the class has
10528 // a move ctor or move assignment that is either user-declared or whose
10529 // semantics are inherited from a subobject. FIXME: We should provide a
10530 // more direct way for CodeGen to ask whether the constructor was deleted.
10531 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10532 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10533 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10534 ClassDecl->hasUserDeclaredMoveAssignment() ||
10535 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10536 DeclareImplicitCopyConstructor(ClassDecl);
10539 if (getLangOpts().CPlusPlus11 &&
10540 ClassDecl->needsImplicitMoveConstructor()) {
10541 ++getASTContext().NumImplicitMoveConstructors;
10543 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10544 ClassDecl->hasInheritedConstructor())
10545 DeclareImplicitMoveConstructor(ClassDecl);
10548 if (ClassDecl->needsImplicitCopyAssignment()) {
10549 ++getASTContext().NumImplicitCopyAssignmentOperators;
10551 // If we have a dynamic class, then the copy assignment operator may be
10552 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10553 // it shows up in the right place in the vtable and that we diagnose
10554 // problems with the implicit exception specification.
10555 if (ClassDecl->isDynamicClass() ||
10556 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10557 ClassDecl->hasInheritedAssignment())
10558 DeclareImplicitCopyAssignment(ClassDecl);
10561 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10562 ++getASTContext().NumImplicitMoveAssignmentOperators;
10564 // Likewise for the move assignment operator.
10565 if (ClassDecl->isDynamicClass() ||
10566 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10567 ClassDecl->hasInheritedAssignment())
10568 DeclareImplicitMoveAssignment(ClassDecl);
10571 if (ClassDecl->needsImplicitDestructor()) {
10572 ++getASTContext().NumImplicitDestructors;
10574 // If we have a dynamic class, then the destructor may be virtual, so we
10575 // have to declare the destructor immediately. This ensures that, e.g., it
10576 // shows up in the right place in the vtable and that we diagnose problems
10577 // with the implicit exception specification.
10578 if (ClassDecl->isDynamicClass() ||
10579 ClassDecl->needsOverloadResolutionForDestructor())
10580 DeclareImplicitDestructor(ClassDecl);
10584 // C++2a [class.compare.default]p3:
10585 // If the member-specification does not explicitly declare any member or
10586 // friend named operator==, an == operator function is declared implicitly
10587 // for each defaulted three-way comparison operator function defined in
10588 // the member-specification
10589 // FIXME: Consider doing this lazily.
10590 // We do this during the initial parse for a class template, not during
10591 // instantiation, so that we can handle unqualified lookups for 'operator=='
10592 // when parsing the template.
10593 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10594 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10595 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10596 DefaultedSpaceships);
10597 for (auto *FD : DefaultedSpaceships)
10598 DeclareImplicitEqualityComparison(ClassDecl, FD);
10602 unsigned
10603 Sema::ActOnReenterTemplateScope(Decl *D,
10604 llvm::function_ref<Scope *()> EnterScope) {
10605 if (!D)
10606 return 0;
10607 AdjustDeclIfTemplate(D);
10609 // In order to get name lookup right, reenter template scopes in order from
10610 // outermost to innermost.
10611 SmallVector<TemplateParameterList *, 4> ParameterLists;
10612 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10614 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10615 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10616 ParameterLists.push_back(DD->getTemplateParameterList(i));
10618 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10619 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10620 ParameterLists.push_back(FTD->getTemplateParameters());
10621 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10622 LookupDC = VD->getDeclContext();
10624 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10625 ParameterLists.push_back(VTD->getTemplateParameters());
10626 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10627 ParameterLists.push_back(PSD->getTemplateParameters());
10629 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10630 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10631 ParameterLists.push_back(TD->getTemplateParameterList(i));
10633 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10634 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10635 ParameterLists.push_back(CTD->getTemplateParameters());
10636 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10637 ParameterLists.push_back(PSD->getTemplateParameters());
10640 // FIXME: Alias declarations and concepts.
10642 unsigned Count = 0;
10643 Scope *InnermostTemplateScope = nullptr;
10644 for (TemplateParameterList *Params : ParameterLists) {
10645 // Ignore explicit specializations; they don't contribute to the template
10646 // depth.
10647 if (Params->size() == 0)
10648 continue;
10650 InnermostTemplateScope = EnterScope();
10651 for (NamedDecl *Param : *Params) {
10652 if (Param->getDeclName()) {
10653 InnermostTemplateScope->AddDecl(Param);
10654 IdResolver.AddDecl(Param);
10657 ++Count;
10660 // Associate the new template scopes with the corresponding entities.
10661 if (InnermostTemplateScope) {
10662 assert(LookupDC && "no enclosing DeclContext for template lookup");
10663 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10666 return Count;
10669 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10670 if (!RecordD) return;
10671 AdjustDeclIfTemplate(RecordD);
10672 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10673 PushDeclContext(S, Record);
10676 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10677 if (!RecordD) return;
10678 PopDeclContext();
10681 /// This is used to implement the constant expression evaluation part of the
10682 /// attribute enable_if extension. There is nothing in standard C++ which would
10683 /// require reentering parameters.
10684 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10685 if (!Param)
10686 return;
10688 S->AddDecl(Param);
10689 if (Param->getDeclName())
10690 IdResolver.AddDecl(Param);
10693 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10694 /// parsing a top-level (non-nested) C++ class, and we are now
10695 /// parsing those parts of the given Method declaration that could
10696 /// not be parsed earlier (C++ [class.mem]p2), such as default
10697 /// arguments. This action should enter the scope of the given
10698 /// Method declaration as if we had just parsed the qualified method
10699 /// name. However, it should not bring the parameters into scope;
10700 /// that will be performed by ActOnDelayedCXXMethodParameter.
10701 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10704 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10705 /// C++ method declaration. We're (re-)introducing the given
10706 /// function parameter into scope for use in parsing later parts of
10707 /// the method declaration. For example, we could see an
10708 /// ActOnParamDefaultArgument event for this parameter.
10709 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10710 if (!ParamD)
10711 return;
10713 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10715 S->AddDecl(Param);
10716 if (Param->getDeclName())
10717 IdResolver.AddDecl(Param);
10720 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10721 /// processing the delayed method declaration for Method. The method
10722 /// declaration is now considered finished. There may be a separate
10723 /// ActOnStartOfFunctionDef action later (not necessarily
10724 /// immediately!) for this method, if it was also defined inside the
10725 /// class body.
10726 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10727 if (!MethodD)
10728 return;
10730 AdjustDeclIfTemplate(MethodD);
10732 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10734 // Now that we have our default arguments, check the constructor
10735 // again. It could produce additional diagnostics or affect whether
10736 // the class has implicitly-declared destructors, among other
10737 // things.
10738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10739 CheckConstructor(Constructor);
10741 // Check the default arguments, which we may have added.
10742 if (!Method->isInvalidDecl())
10743 CheckCXXDefaultArguments(Method);
10746 // Emit the given diagnostic for each non-address-space qualifier.
10747 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10748 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10749 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10750 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10751 bool DiagOccured = false;
10752 FTI.MethodQualifiers->forEachQualifier(
10753 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10754 SourceLocation SL) {
10755 // This diagnostic should be emitted on any qualifier except an addr
10756 // space qualifier. However, forEachQualifier currently doesn't visit
10757 // addr space qualifiers, so there's no way to write this condition
10758 // right now; we just diagnose on everything.
10759 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10760 DiagOccured = true;
10762 if (DiagOccured)
10763 D.setInvalidType();
10767 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10768 /// the well-formedness of the constructor declarator @p D with type @p
10769 /// R. If there are any errors in the declarator, this routine will
10770 /// emit diagnostics and set the invalid bit to true. In any case, the type
10771 /// will be updated to reflect a well-formed type for the constructor and
10772 /// returned.
10773 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10774 StorageClass &SC) {
10775 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10777 // C++ [class.ctor]p3:
10778 // A constructor shall not be virtual (10.3) or static (9.4). A
10779 // constructor can be invoked for a const, volatile or const
10780 // volatile object. A constructor shall not be declared const,
10781 // volatile, or const volatile (9.3.2).
10782 if (isVirtual) {
10783 if (!D.isInvalidType())
10784 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10785 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10786 << SourceRange(D.getIdentifierLoc());
10787 D.setInvalidType();
10789 if (SC == SC_Static) {
10790 if (!D.isInvalidType())
10791 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10792 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10793 << SourceRange(D.getIdentifierLoc());
10794 D.setInvalidType();
10795 SC = SC_None;
10798 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10799 diagnoseIgnoredQualifiers(
10800 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10801 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10802 D.getDeclSpec().getRestrictSpecLoc(),
10803 D.getDeclSpec().getAtomicSpecLoc());
10804 D.setInvalidType();
10807 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10809 // C++0x [class.ctor]p4:
10810 // A constructor shall not be declared with a ref-qualifier.
10811 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10812 if (FTI.hasRefQualifier()) {
10813 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10814 << FTI.RefQualifierIsLValueRef
10815 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10816 D.setInvalidType();
10819 // Rebuild the function type "R" without any type qualifiers (in
10820 // case any of the errors above fired) and with "void" as the
10821 // return type, since constructors don't have return types.
10822 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10823 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10824 return R;
10826 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10827 EPI.TypeQuals = Qualifiers();
10828 EPI.RefQualifier = RQ_None;
10830 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10833 /// CheckConstructor - Checks a fully-formed constructor for
10834 /// well-formedness, issuing any diagnostics required. Returns true if
10835 /// the constructor declarator is invalid.
10836 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10837 CXXRecordDecl *ClassDecl
10838 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10839 if (!ClassDecl)
10840 return Constructor->setInvalidDecl();
10842 // C++ [class.copy]p3:
10843 // A declaration of a constructor for a class X is ill-formed if
10844 // its first parameter is of type (optionally cv-qualified) X and
10845 // either there are no other parameters or else all other
10846 // parameters have default arguments.
10847 if (!Constructor->isInvalidDecl() &&
10848 Constructor->hasOneParamOrDefaultArgs() &&
10849 Constructor->getTemplateSpecializationKind() !=
10850 TSK_ImplicitInstantiation) {
10851 QualType ParamType = Constructor->getParamDecl(0)->getType();
10852 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10853 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10854 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10855 const char *ConstRef
10856 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10857 : " const &";
10858 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10859 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10861 // FIXME: Rather that making the constructor invalid, we should endeavor
10862 // to fix the type.
10863 Constructor->setInvalidDecl();
10868 /// CheckDestructor - Checks a fully-formed destructor definition for
10869 /// well-formedness, issuing any diagnostics required. Returns true
10870 /// on error.
10871 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10872 CXXRecordDecl *RD = Destructor->getParent();
10874 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10875 SourceLocation Loc;
10877 if (!Destructor->isImplicit())
10878 Loc = Destructor->getLocation();
10879 else
10880 Loc = RD->getLocation();
10882 // If we have a virtual destructor, look up the deallocation function
10883 if (FunctionDecl *OperatorDelete =
10884 FindDeallocationFunctionForDestructor(Loc, RD)) {
10885 Expr *ThisArg = nullptr;
10887 // If the notional 'delete this' expression requires a non-trivial
10888 // conversion from 'this' to the type of a destroying operator delete's
10889 // first parameter, perform that conversion now.
10890 if (OperatorDelete->isDestroyingOperatorDelete()) {
10891 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10892 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10893 // C++ [class.dtor]p13:
10894 // ... as if for the expression 'delete this' appearing in a
10895 // non-virtual destructor of the destructor's class.
10896 ContextRAII SwitchContext(*this, Destructor);
10897 ExprResult This =
10898 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10899 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10900 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10901 if (This.isInvalid()) {
10902 // FIXME: Register this as a context note so that it comes out
10903 // in the right order.
10904 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10905 return true;
10907 ThisArg = This.get();
10911 DiagnoseUseOfDecl(OperatorDelete, Loc);
10912 MarkFunctionReferenced(Loc, OperatorDelete);
10913 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10917 return false;
10920 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10921 /// the well-formednes of the destructor declarator @p D with type @p
10922 /// R. If there are any errors in the declarator, this routine will
10923 /// emit diagnostics and set the declarator to invalid. Even if this happens,
10924 /// will be updated to reflect a well-formed type for the destructor and
10925 /// returned.
10926 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10927 StorageClass& SC) {
10928 // C++ [class.dtor]p1:
10929 // [...] A typedef-name that names a class is a class-name
10930 // (7.1.3); however, a typedef-name that names a class shall not
10931 // be used as the identifier in the declarator for a destructor
10932 // declaration.
10933 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10934 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10935 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10936 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10937 else if (const TemplateSpecializationType *TST =
10938 DeclaratorType->getAs<TemplateSpecializationType>())
10939 if (TST->isTypeAlias())
10940 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10941 << DeclaratorType << 1;
10943 // C++ [class.dtor]p2:
10944 // A destructor is used to destroy objects of its class type. A
10945 // destructor takes no parameters, and no return type can be
10946 // specified for it (not even void). The address of a destructor
10947 // shall not be taken. A destructor shall not be static. A
10948 // destructor can be invoked for a const, volatile or const
10949 // volatile object. A destructor shall not be declared const,
10950 // volatile or const volatile (9.3.2).
10951 if (SC == SC_Static) {
10952 if (!D.isInvalidType())
10953 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10954 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10955 << SourceRange(D.getIdentifierLoc())
10956 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10958 SC = SC_None;
10960 if (!D.isInvalidType()) {
10961 // Destructors don't have return types, but the parser will
10962 // happily parse something like:
10964 // class X {
10965 // float ~X();
10966 // };
10968 // The return type will be eliminated later.
10969 if (D.getDeclSpec().hasTypeSpecifier())
10970 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10971 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10972 << SourceRange(D.getIdentifierLoc());
10973 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10974 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10975 SourceLocation(),
10976 D.getDeclSpec().getConstSpecLoc(),
10977 D.getDeclSpec().getVolatileSpecLoc(),
10978 D.getDeclSpec().getRestrictSpecLoc(),
10979 D.getDeclSpec().getAtomicSpecLoc());
10980 D.setInvalidType();
10984 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10986 // C++0x [class.dtor]p2:
10987 // A destructor shall not be declared with a ref-qualifier.
10988 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10989 if (FTI.hasRefQualifier()) {
10990 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10991 << FTI.RefQualifierIsLValueRef
10992 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10993 D.setInvalidType();
10996 // Make sure we don't have any parameters.
10997 if (FTIHasNonVoidParameters(FTI)) {
10998 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11000 // Delete the parameters.
11001 FTI.freeParams();
11002 D.setInvalidType();
11005 // Make sure the destructor isn't variadic.
11006 if (FTI.isVariadic) {
11007 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11008 D.setInvalidType();
11011 // Rebuild the function type "R" without any type qualifiers or
11012 // parameters (in case any of the errors above fired) and with
11013 // "void" as the return type, since destructors don't have return
11014 // types.
11015 if (!D.isInvalidType())
11016 return R;
11018 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11019 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11020 EPI.Variadic = false;
11021 EPI.TypeQuals = Qualifiers();
11022 EPI.RefQualifier = RQ_None;
11023 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
11026 static void extendLeft(SourceRange &R, SourceRange Before) {
11027 if (Before.isInvalid())
11028 return;
11029 R.setBegin(Before.getBegin());
11030 if (R.getEnd().isInvalid())
11031 R.setEnd(Before.getEnd());
11034 static void extendRight(SourceRange &R, SourceRange After) {
11035 if (After.isInvalid())
11036 return;
11037 if (R.getBegin().isInvalid())
11038 R.setBegin(After.getBegin());
11039 R.setEnd(After.getEnd());
11042 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11043 /// well-formednes of the conversion function declarator @p D with
11044 /// type @p R. If there are any errors in the declarator, this routine
11045 /// will emit diagnostics and return true. Otherwise, it will return
11046 /// false. Either way, the type @p R will be updated to reflect a
11047 /// well-formed type for the conversion operator.
11048 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11049 StorageClass& SC) {
11050 // C++ [class.conv.fct]p1:
11051 // Neither parameter types nor return type can be specified. The
11052 // type of a conversion function (8.3.5) is "function taking no
11053 // parameter returning conversion-type-id."
11054 if (SC == SC_Static) {
11055 if (!D.isInvalidType())
11056 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11057 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11058 << D.getName().getSourceRange();
11059 D.setInvalidType();
11060 SC = SC_None;
11063 TypeSourceInfo *ConvTSI = nullptr;
11064 QualType ConvType =
11065 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11067 const DeclSpec &DS = D.getDeclSpec();
11068 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11069 // Conversion functions don't have return types, but the parser will
11070 // happily parse something like:
11072 // class X {
11073 // float operator bool();
11074 // };
11076 // The return type will be changed later anyway.
11077 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11078 << SourceRange(DS.getTypeSpecTypeLoc())
11079 << SourceRange(D.getIdentifierLoc());
11080 D.setInvalidType();
11081 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11082 // It's also plausible that the user writes type qualifiers in the wrong
11083 // place, such as:
11084 // struct S { const operator int(); };
11085 // FIXME: we could provide a fixit to move the qualifiers onto the
11086 // conversion type.
11087 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11088 << SourceRange(D.getIdentifierLoc()) << 0;
11089 D.setInvalidType();
11092 const auto *Proto = R->castAs<FunctionProtoType>();
11094 // Make sure we don't have any parameters.
11095 if (Proto->getNumParams() > 0) {
11096 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11098 // Delete the parameters.
11099 D.getFunctionTypeInfo().freeParams();
11100 D.setInvalidType();
11101 } else if (Proto->isVariadic()) {
11102 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11103 D.setInvalidType();
11106 // Diagnose "&operator bool()" and other such nonsense. This
11107 // is actually a gcc extension which we don't support.
11108 if (Proto->getReturnType() != ConvType) {
11109 bool NeedsTypedef = false;
11110 SourceRange Before, After;
11112 // Walk the chunks and extract information on them for our diagnostic.
11113 bool PastFunctionChunk = false;
11114 for (auto &Chunk : D.type_objects()) {
11115 switch (Chunk.Kind) {
11116 case DeclaratorChunk::Function:
11117 if (!PastFunctionChunk) {
11118 if (Chunk.Fun.HasTrailingReturnType) {
11119 TypeSourceInfo *TRT = nullptr;
11120 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11121 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11123 PastFunctionChunk = true;
11124 break;
11126 [[fallthrough]];
11127 case DeclaratorChunk::Array:
11128 NeedsTypedef = true;
11129 extendRight(After, Chunk.getSourceRange());
11130 break;
11132 case DeclaratorChunk::Pointer:
11133 case DeclaratorChunk::BlockPointer:
11134 case DeclaratorChunk::Reference:
11135 case DeclaratorChunk::MemberPointer:
11136 case DeclaratorChunk::Pipe:
11137 extendLeft(Before, Chunk.getSourceRange());
11138 break;
11140 case DeclaratorChunk::Paren:
11141 extendLeft(Before, Chunk.Loc);
11142 extendRight(After, Chunk.EndLoc);
11143 break;
11147 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11148 After.isValid() ? After.getBegin() :
11149 D.getIdentifierLoc();
11150 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11151 DB << Before << After;
11153 if (!NeedsTypedef) {
11154 DB << /*don't need a typedef*/0;
11156 // If we can provide a correct fix-it hint, do so.
11157 if (After.isInvalid() && ConvTSI) {
11158 SourceLocation InsertLoc =
11159 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
11160 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11161 << FixItHint::CreateInsertionFromRange(
11162 InsertLoc, CharSourceRange::getTokenRange(Before))
11163 << FixItHint::CreateRemoval(Before);
11165 } else if (!Proto->getReturnType()->isDependentType()) {
11166 DB << /*typedef*/1 << Proto->getReturnType();
11167 } else if (getLangOpts().CPlusPlus11) {
11168 DB << /*alias template*/2 << Proto->getReturnType();
11169 } else {
11170 DB << /*might not be fixable*/3;
11173 // Recover by incorporating the other type chunks into the result type.
11174 // Note, this does *not* change the name of the function. This is compatible
11175 // with the GCC extension:
11176 // struct S { &operator int(); } s;
11177 // int &r = s.operator int(); // ok in GCC
11178 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11179 ConvType = Proto->getReturnType();
11182 // C++ [class.conv.fct]p4:
11183 // The conversion-type-id shall not represent a function type nor
11184 // an array type.
11185 if (ConvType->isArrayType()) {
11186 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11187 ConvType = Context.getPointerType(ConvType);
11188 D.setInvalidType();
11189 } else if (ConvType->isFunctionType()) {
11190 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11191 ConvType = Context.getPointerType(ConvType);
11192 D.setInvalidType();
11195 // Rebuild the function type "R" without any parameters (in case any
11196 // of the errors above fired) and with the conversion type as the
11197 // return type.
11198 if (D.isInvalidType())
11199 R = Context.getFunctionType(ConvType, std::nullopt,
11200 Proto->getExtProtoInfo());
11202 // C++0x explicit conversion operators.
11203 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11204 Diag(DS.getExplicitSpecLoc(),
11205 getLangOpts().CPlusPlus11
11206 ? diag::warn_cxx98_compat_explicit_conversion_functions
11207 : diag::ext_explicit_conversion_functions)
11208 << SourceRange(DS.getExplicitSpecRange());
11211 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11212 /// the declaration of the given C++ conversion function. This routine
11213 /// is responsible for recording the conversion function in the C++
11214 /// class, if possible.
11215 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11216 assert(Conversion && "Expected to receive a conversion function declaration");
11218 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11220 // Make sure we aren't redeclaring the conversion function.
11221 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11222 // C++ [class.conv.fct]p1:
11223 // [...] A conversion function is never used to convert a
11224 // (possibly cv-qualified) object to the (possibly cv-qualified)
11225 // same object type (or a reference to it), to a (possibly
11226 // cv-qualified) base class of that type (or a reference to it),
11227 // or to (possibly cv-qualified) void.
11228 QualType ClassType
11229 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11230 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11231 ConvType = ConvTypeRef->getPointeeType();
11232 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11233 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11234 /* Suppress diagnostics for instantiations. */;
11235 else if (Conversion->size_overridden_methods() != 0)
11236 /* Suppress diagnostics for overriding virtual function in a base class. */;
11237 else if (ConvType->isRecordType()) {
11238 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11239 if (ConvType == ClassType)
11240 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11241 << ClassType;
11242 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11243 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11244 << ClassType << ConvType;
11245 } else if (ConvType->isVoidType()) {
11246 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11247 << ClassType << ConvType;
11250 if (FunctionTemplateDecl *ConversionTemplate
11251 = Conversion->getDescribedFunctionTemplate())
11252 return ConversionTemplate;
11254 return Conversion;
11257 namespace {
11258 /// Utility class to accumulate and print a diagnostic listing the invalid
11259 /// specifier(s) on a declaration.
11260 struct BadSpecifierDiagnoser {
11261 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11262 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11263 ~BadSpecifierDiagnoser() {
11264 Diagnostic << Specifiers;
11267 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11268 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11270 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11271 return check(SpecLoc,
11272 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11274 void check(SourceLocation SpecLoc, const char *Spec) {
11275 if (SpecLoc.isInvalid()) return;
11276 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11277 if (!Specifiers.empty()) Specifiers += " ";
11278 Specifiers += Spec;
11281 Sema &S;
11282 Sema::SemaDiagnosticBuilder Diagnostic;
11283 std::string Specifiers;
11287 /// Check the validity of a declarator that we parsed for a deduction-guide.
11288 /// These aren't actually declarators in the grammar, so we need to check that
11289 /// the user didn't specify any pieces that are not part of the deduction-guide
11290 /// grammar. Return true on invalid deduction-guide.
11291 bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11292 StorageClass &SC) {
11293 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11294 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11295 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11297 // C++ [temp.deduct.guide]p3:
11298 // A deduction-gide shall be declared in the same scope as the
11299 // corresponding class template.
11300 if (!CurContext->getRedeclContext()->Equals(
11301 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11302 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11303 << GuidedTemplateDecl;
11304 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
11307 auto &DS = D.getMutableDeclSpec();
11308 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11309 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11310 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11311 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11312 BadSpecifierDiagnoser Diagnoser(
11313 *this, D.getIdentifierLoc(),
11314 diag::err_deduction_guide_invalid_specifier);
11316 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11317 DS.ClearStorageClassSpecs();
11318 SC = SC_None;
11320 // 'explicit' is permitted.
11321 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11322 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11323 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11324 DS.ClearConstexprSpec();
11326 Diagnoser.check(DS.getConstSpecLoc(), "const");
11327 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11328 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11329 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11330 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11331 DS.ClearTypeQualifiers();
11333 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11334 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11335 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11336 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11337 DS.ClearTypeSpecType();
11340 if (D.isInvalidType())
11341 return true;
11343 // Check the declarator is simple enough.
11344 bool FoundFunction = false;
11345 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11346 if (Chunk.Kind == DeclaratorChunk::Paren)
11347 continue;
11348 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11349 Diag(D.getDeclSpec().getBeginLoc(),
11350 diag::err_deduction_guide_with_complex_decl)
11351 << D.getSourceRange();
11352 break;
11354 if (!Chunk.Fun.hasTrailingReturnType())
11355 return Diag(D.getName().getBeginLoc(),
11356 diag::err_deduction_guide_no_trailing_return_type);
11358 // Check that the return type is written as a specialization of
11359 // the template specified as the deduction-guide's name.
11360 // The template name may not be qualified. [temp.deduct.guide]
11361 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11362 TypeSourceInfo *TSI = nullptr;
11363 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11364 assert(TSI && "deduction guide has valid type but invalid return type?");
11365 bool AcceptableReturnType = false;
11366 bool MightInstantiateToSpecialization = false;
11367 if (auto RetTST =
11368 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11369 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11370 bool TemplateMatches =
11371 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11372 auto TKind = SpecifiedName.getKind();
11373 // A Using TemplateName can't actually be valid (either it's qualified, or
11374 // we're in the wrong scope). But we have diagnosed these problems
11375 // already.
11376 bool SimplyWritten = TKind == TemplateName::Template ||
11377 TKind == TemplateName::UsingTemplate;
11378 if (SimplyWritten && TemplateMatches)
11379 AcceptableReturnType = true;
11380 else {
11381 // This could still instantiate to the right type, unless we know it
11382 // names the wrong class template.
11383 auto *TD = SpecifiedName.getAsTemplateDecl();
11384 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11385 !TemplateMatches);
11387 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11388 MightInstantiateToSpecialization = true;
11391 if (!AcceptableReturnType)
11392 return Diag(TSI->getTypeLoc().getBeginLoc(),
11393 diag::err_deduction_guide_bad_trailing_return_type)
11394 << GuidedTemplate << TSI->getType()
11395 << MightInstantiateToSpecialization
11396 << TSI->getTypeLoc().getSourceRange();
11398 // Keep going to check that we don't have any inner declarator pieces (we
11399 // could still have a function returning a pointer to a function).
11400 FoundFunction = true;
11403 if (D.isFunctionDefinition())
11404 // we can still create a valid deduction guide here.
11405 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11406 return false;
11409 //===----------------------------------------------------------------------===//
11410 // Namespace Handling
11411 //===----------------------------------------------------------------------===//
11413 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11414 /// reopened.
11415 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11416 SourceLocation Loc,
11417 IdentifierInfo *II, bool *IsInline,
11418 NamespaceDecl *PrevNS) {
11419 assert(*IsInline != PrevNS->isInline());
11421 // 'inline' must appear on the original definition, but not necessarily
11422 // on all extension definitions, so the note should point to the first
11423 // definition to avoid confusion.
11424 PrevNS = PrevNS->getFirstDecl();
11426 if (PrevNS->isInline())
11427 // The user probably just forgot the 'inline', so suggest that it
11428 // be added back.
11429 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11430 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11431 else
11432 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11434 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11435 *IsInline = PrevNS->isInline();
11438 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11439 /// definition.
11440 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11441 SourceLocation InlineLoc,
11442 SourceLocation NamespaceLoc,
11443 SourceLocation IdentLoc, IdentifierInfo *II,
11444 SourceLocation LBrace,
11445 const ParsedAttributesView &AttrList,
11446 UsingDirectiveDecl *&UD, bool IsNested) {
11447 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11448 // For anonymous namespace, take the location of the left brace.
11449 SourceLocation Loc = II ? IdentLoc : LBrace;
11450 bool IsInline = InlineLoc.isValid();
11451 bool IsInvalid = false;
11452 bool IsStd = false;
11453 bool AddToKnown = false;
11454 Scope *DeclRegionScope = NamespcScope->getParent();
11456 NamespaceDecl *PrevNS = nullptr;
11457 if (II) {
11458 // C++ [namespace.std]p7:
11459 // A translation unit shall not declare namespace std to be an inline
11460 // namespace (9.8.2).
11462 // Precondition: the std namespace is in the file scope and is declared to
11463 // be inline
11464 auto DiagnoseInlineStdNS = [&]() {
11465 assert(IsInline && II->isStr("std") &&
11466 CurContext->getRedeclContext()->isTranslationUnit() &&
11467 "Precondition of DiagnoseInlineStdNS not met");
11468 Diag(InlineLoc, diag::err_inline_namespace_std)
11469 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11470 IsInline = false;
11472 // C++ [namespace.def]p2:
11473 // The identifier in an original-namespace-definition shall not
11474 // have been previously defined in the declarative region in
11475 // which the original-namespace-definition appears. The
11476 // identifier in an original-namespace-definition is the name of
11477 // the namespace. Subsequently in that declarative region, it is
11478 // treated as an original-namespace-name.
11480 // Since namespace names are unique in their scope, and we don't
11481 // look through using directives, just look for any ordinary names
11482 // as if by qualified name lookup.
11483 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11484 ForExternalRedeclaration);
11485 LookupQualifiedName(R, CurContext->getRedeclContext());
11486 NamedDecl *PrevDecl =
11487 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11488 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11490 if (PrevNS) {
11491 // This is an extended namespace definition.
11492 if (IsInline && II->isStr("std") &&
11493 CurContext->getRedeclContext()->isTranslationUnit())
11494 DiagnoseInlineStdNS();
11495 else if (IsInline != PrevNS->isInline())
11496 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11497 &IsInline, PrevNS);
11498 } else if (PrevDecl) {
11499 // This is an invalid name redefinition.
11500 Diag(Loc, diag::err_redefinition_different_kind)
11501 << II;
11502 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11503 IsInvalid = true;
11504 // Continue on to push Namespc as current DeclContext and return it.
11505 } else if (II->isStr("std") &&
11506 CurContext->getRedeclContext()->isTranslationUnit()) {
11507 if (IsInline)
11508 DiagnoseInlineStdNS();
11509 // This is the first "real" definition of the namespace "std", so update
11510 // our cache of the "std" namespace to point at this definition.
11511 PrevNS = getStdNamespace();
11512 IsStd = true;
11513 AddToKnown = !IsInline;
11514 } else {
11515 // We've seen this namespace for the first time.
11516 AddToKnown = !IsInline;
11518 } else {
11519 // Anonymous namespaces.
11521 // Determine whether the parent already has an anonymous namespace.
11522 DeclContext *Parent = CurContext->getRedeclContext();
11523 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11524 PrevNS = TU->getAnonymousNamespace();
11525 } else {
11526 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11527 PrevNS = ND->getAnonymousNamespace();
11530 if (PrevNS && IsInline != PrevNS->isInline())
11531 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11532 &IsInline, PrevNS);
11535 NamespaceDecl *Namespc = NamespaceDecl::Create(
11536 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11537 if (IsInvalid)
11538 Namespc->setInvalidDecl();
11540 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11541 AddPragmaAttributes(DeclRegionScope, Namespc);
11543 // FIXME: Should we be merging attributes?
11544 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11545 PushNamespaceVisibilityAttr(Attr, Loc);
11547 if (IsStd)
11548 StdNamespace = Namespc;
11549 if (AddToKnown)
11550 KnownNamespaces[Namespc] = false;
11552 if (II) {
11553 PushOnScopeChains(Namespc, DeclRegionScope);
11554 } else {
11555 // Link the anonymous namespace into its parent.
11556 DeclContext *Parent = CurContext->getRedeclContext();
11557 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11558 TU->setAnonymousNamespace(Namespc);
11559 } else {
11560 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11563 CurContext->addDecl(Namespc);
11565 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11566 // behaves as if it were replaced by
11567 // namespace unique { /* empty body */ }
11568 // using namespace unique;
11569 // namespace unique { namespace-body }
11570 // where all occurrences of 'unique' in a translation unit are
11571 // replaced by the same identifier and this identifier differs
11572 // from all other identifiers in the entire program.
11574 // We just create the namespace with an empty name and then add an
11575 // implicit using declaration, just like the standard suggests.
11577 // CodeGen enforces the "universally unique" aspect by giving all
11578 // declarations semantically contained within an anonymous
11579 // namespace internal linkage.
11581 if (!PrevNS) {
11582 UD = UsingDirectiveDecl::Create(Context, Parent,
11583 /* 'using' */ LBrace,
11584 /* 'namespace' */ SourceLocation(),
11585 /* qualifier */ NestedNameSpecifierLoc(),
11586 /* identifier */ SourceLocation(),
11587 Namespc,
11588 /* Ancestor */ Parent);
11589 UD->setImplicit();
11590 Parent->addDecl(UD);
11594 ActOnDocumentableDecl(Namespc);
11596 // Although we could have an invalid decl (i.e. the namespace name is a
11597 // redefinition), push it as current DeclContext and try to continue parsing.
11598 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11599 // for the namespace has the declarations that showed up in that particular
11600 // namespace definition.
11601 PushDeclContext(NamespcScope, Namespc);
11602 return Namespc;
11605 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11606 /// is a namespace alias, returns the namespace it points to.
11607 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11608 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11609 return AD->getNamespace();
11610 return dyn_cast_or_null<NamespaceDecl>(D);
11613 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11614 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11615 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11616 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11617 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11618 Namespc->setRBraceLoc(RBrace);
11619 PopDeclContext();
11620 if (Namespc->hasAttr<VisibilityAttr>())
11621 PopPragmaVisibility(true, RBrace);
11622 // If this namespace contains an export-declaration, export it now.
11623 if (DeferredExportedNamespaces.erase(Namespc))
11624 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11627 CXXRecordDecl *Sema::getStdBadAlloc() const {
11628 return cast_or_null<CXXRecordDecl>(
11629 StdBadAlloc.get(Context.getExternalSource()));
11632 EnumDecl *Sema::getStdAlignValT() const {
11633 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11636 NamespaceDecl *Sema::getStdNamespace() const {
11637 return cast_or_null<NamespaceDecl>(
11638 StdNamespace.get(Context.getExternalSource()));
11640 namespace {
11642 enum UnsupportedSTLSelect {
11643 USS_InvalidMember,
11644 USS_MissingMember,
11645 USS_NonTrivial,
11646 USS_Other
11649 struct InvalidSTLDiagnoser {
11650 Sema &S;
11651 SourceLocation Loc;
11652 QualType TyForDiags;
11654 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11655 const VarDecl *VD = nullptr) {
11657 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11658 << TyForDiags << ((int)Sel);
11659 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11660 assert(!Name.empty());
11661 D << Name;
11664 if (Sel == USS_InvalidMember) {
11665 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11666 << VD << VD->getSourceRange();
11668 return QualType();
11671 } // namespace
11673 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11674 SourceLocation Loc,
11675 ComparisonCategoryUsage Usage) {
11676 assert(getLangOpts().CPlusPlus &&
11677 "Looking for comparison category type outside of C++.");
11679 // Use an elaborated type for diagnostics which has a name containing the
11680 // prepended 'std' namespace but not any inline namespace names.
11681 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11682 auto *NNS =
11683 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11684 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11687 // Check if we've already successfully checked the comparison category type
11688 // before. If so, skip checking it again.
11689 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11690 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11691 // The only thing we need to check is that the type has a reachable
11692 // definition in the current context.
11693 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11694 return QualType();
11696 return Info->getType();
11699 // If lookup failed
11700 if (!Info) {
11701 std::string NameForDiags = "std::";
11702 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11703 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11704 << NameForDiags << (int)Usage;
11705 return QualType();
11708 assert(Info->Kind == Kind);
11709 assert(Info->Record);
11711 // Update the Record decl in case we encountered a forward declaration on our
11712 // first pass. FIXME: This is a bit of a hack.
11713 if (Info->Record->hasDefinition())
11714 Info->Record = Info->Record->getDefinition();
11716 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11717 return QualType();
11719 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11721 if (!Info->Record->isTriviallyCopyable())
11722 return UnsupportedSTLError(USS_NonTrivial);
11724 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11725 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11726 // Tolerate empty base classes.
11727 if (Base->isEmpty())
11728 continue;
11729 // Reject STL implementations which have at least one non-empty base.
11730 return UnsupportedSTLError();
11733 // Check that the STL has implemented the types using a single integer field.
11734 // This expectation allows better codegen for builtin operators. We require:
11735 // (1) The class has exactly one field.
11736 // (2) The field is an integral or enumeration type.
11737 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11738 if (std::distance(FIt, FEnd) != 1 ||
11739 !FIt->getType()->isIntegralOrEnumerationType()) {
11740 return UnsupportedSTLError();
11743 // Build each of the require values and store them in Info.
11744 for (ComparisonCategoryResult CCR :
11745 ComparisonCategories::getPossibleResultsForType(Kind)) {
11746 StringRef MemName = ComparisonCategories::getResultString(CCR);
11747 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11749 if (!ValInfo)
11750 return UnsupportedSTLError(USS_MissingMember, MemName);
11752 VarDecl *VD = ValInfo->VD;
11753 assert(VD && "should not be null!");
11755 // Attempt to diagnose reasons why the STL definition of this type
11756 // might be foobar, including it failing to be a constant expression.
11757 // TODO Handle more ways the lookup or result can be invalid.
11758 if (!VD->isStaticDataMember() ||
11759 !VD->isUsableInConstantExpressions(Context))
11760 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11762 // Attempt to evaluate the var decl as a constant expression and extract
11763 // the value of its first field as a ICE. If this fails, the STL
11764 // implementation is not supported.
11765 if (!ValInfo->hasValidIntValue())
11766 return UnsupportedSTLError();
11768 MarkVariableReferenced(Loc, VD);
11771 // We've successfully built the required types and expressions. Update
11772 // the cache and return the newly cached value.
11773 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11774 return Info->getType();
11777 /// Retrieve the special "std" namespace, which may require us to
11778 /// implicitly define the namespace.
11779 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11780 if (!StdNamespace) {
11781 // The "std" namespace has not yet been defined, so build one implicitly.
11782 StdNamespace = NamespaceDecl::Create(
11783 Context, Context.getTranslationUnitDecl(),
11784 /*Inline=*/false, SourceLocation(), SourceLocation(),
11785 &PP.getIdentifierTable().get("std"),
11786 /*PrevDecl=*/nullptr, /*Nested=*/false);
11787 getStdNamespace()->setImplicit(true);
11788 // We want the created NamespaceDecl to be available for redeclaration
11789 // lookups, but not for regular name lookups.
11790 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
11791 getStdNamespace()->clearIdentifierNamespace();
11794 return getStdNamespace();
11797 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11798 assert(getLangOpts().CPlusPlus &&
11799 "Looking for std::initializer_list outside of C++.");
11801 // We're looking for implicit instantiations of
11802 // template <typename E> class std::initializer_list.
11804 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11805 return false;
11807 ClassTemplateDecl *Template = nullptr;
11808 const TemplateArgument *Arguments = nullptr;
11810 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11812 ClassTemplateSpecializationDecl *Specialization =
11813 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11814 if (!Specialization)
11815 return false;
11817 Template = Specialization->getSpecializedTemplate();
11818 Arguments = Specialization->getTemplateArgs().data();
11819 } else if (const TemplateSpecializationType *TST =
11820 Ty->getAs<TemplateSpecializationType>()) {
11821 Template = dyn_cast_or_null<ClassTemplateDecl>(
11822 TST->getTemplateName().getAsTemplateDecl());
11823 Arguments = TST->template_arguments().begin();
11825 if (!Template)
11826 return false;
11828 if (!StdInitializerList) {
11829 // Haven't recognized std::initializer_list yet, maybe this is it.
11830 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11831 if (TemplateClass->getIdentifier() !=
11832 &PP.getIdentifierTable().get("initializer_list") ||
11833 !getStdNamespace()->InEnclosingNamespaceSetOf(
11834 TemplateClass->getDeclContext()))
11835 return false;
11836 // This is a template called std::initializer_list, but is it the right
11837 // template?
11838 TemplateParameterList *Params = Template->getTemplateParameters();
11839 if (Params->getMinRequiredArguments() != 1)
11840 return false;
11841 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11842 return false;
11844 // It's the right template.
11845 StdInitializerList = Template;
11848 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11849 return false;
11851 // This is an instance of std::initializer_list. Find the argument type.
11852 if (Element)
11853 *Element = Arguments[0].getAsType();
11854 return true;
11857 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11858 NamespaceDecl *Std = S.getStdNamespace();
11859 if (!Std) {
11860 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11861 return nullptr;
11864 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11865 Loc, Sema::LookupOrdinaryName);
11866 if (!S.LookupQualifiedName(Result, Std)) {
11867 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11868 return nullptr;
11870 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11871 if (!Template) {
11872 Result.suppressDiagnostics();
11873 // We found something weird. Complain about the first thing we found.
11874 NamedDecl *Found = *Result.begin();
11875 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11876 return nullptr;
11879 // We found some template called std::initializer_list. Now verify that it's
11880 // correct.
11881 TemplateParameterList *Params = Template->getTemplateParameters();
11882 if (Params->getMinRequiredArguments() != 1 ||
11883 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11884 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11885 return nullptr;
11888 return Template;
11891 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11892 if (!StdInitializerList) {
11893 StdInitializerList = LookupStdInitializerList(*this, Loc);
11894 if (!StdInitializerList)
11895 return QualType();
11898 TemplateArgumentListInfo Args(Loc, Loc);
11899 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11900 Context.getTrivialTypeSourceInfo(Element,
11901 Loc)));
11902 return Context.getElaboratedType(
11903 ElaboratedTypeKeyword::ETK_None,
11904 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
11905 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11908 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11909 // C++ [dcl.init.list]p2:
11910 // A constructor is an initializer-list constructor if its first parameter
11911 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11912 // std::initializer_list<E> for some type E, and either there are no other
11913 // parameters or else all other parameters have default arguments.
11914 if (!Ctor->hasOneParamOrDefaultArgs())
11915 return false;
11917 QualType ArgType = Ctor->getParamDecl(0)->getType();
11918 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11919 ArgType = RT->getPointeeType().getUnqualifiedType();
11921 return isStdInitializerList(ArgType, nullptr);
11924 /// Determine whether a using statement is in a context where it will be
11925 /// apply in all contexts.
11926 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11927 switch (CurContext->getDeclKind()) {
11928 case Decl::TranslationUnit:
11929 return true;
11930 case Decl::LinkageSpec:
11931 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11932 default:
11933 return false;
11937 namespace {
11939 // Callback to only accept typo corrections that are namespaces.
11940 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11941 public:
11942 bool ValidateCandidate(const TypoCorrection &candidate) override {
11943 if (NamedDecl *ND = candidate.getCorrectionDecl())
11944 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11945 return false;
11948 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11949 return std::make_unique<NamespaceValidatorCCC>(*this);
11955 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11956 CXXScopeSpec &SS,
11957 SourceLocation IdentLoc,
11958 IdentifierInfo *Ident) {
11959 R.clear();
11960 NamespaceValidatorCCC CCC{};
11961 if (TypoCorrection Corrected =
11962 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11963 Sema::CTK_ErrorRecovery)) {
11964 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11965 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11966 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11967 Ident->getName().equals(CorrectedStr);
11968 S.diagnoseTypo(Corrected,
11969 S.PDiag(diag::err_using_directive_member_suggest)
11970 << Ident << DC << DroppedSpecifier << SS.getRange(),
11971 S.PDiag(diag::note_namespace_defined_here));
11972 } else {
11973 S.diagnoseTypo(Corrected,
11974 S.PDiag(diag::err_using_directive_suggest) << Ident,
11975 S.PDiag(diag::note_namespace_defined_here));
11977 R.addDecl(Corrected.getFoundDecl());
11978 return true;
11980 return false;
11983 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11984 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11985 SourceLocation IdentLoc,
11986 IdentifierInfo *NamespcName,
11987 const ParsedAttributesView &AttrList) {
11988 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11989 assert(NamespcName && "Invalid NamespcName.");
11990 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11992 // This can only happen along a recovery path.
11993 while (S->isTemplateParamScope())
11994 S = S->getParent();
11995 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11997 UsingDirectiveDecl *UDir = nullptr;
11998 NestedNameSpecifier *Qualifier = nullptr;
11999 if (SS.isSet())
12000 Qualifier = SS.getScopeRep();
12002 // Lookup namespace name.
12003 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12004 LookupParsedName(R, S, &SS);
12005 if (R.isAmbiguous())
12006 return nullptr;
12008 if (R.empty()) {
12009 R.clear();
12010 // Allow "using namespace std;" or "using namespace ::std;" even if
12011 // "std" hasn't been defined yet, for GCC compatibility.
12012 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12013 NamespcName->isStr("std")) {
12014 Diag(IdentLoc, diag::ext_using_undefined_std);
12015 R.addDecl(getOrCreateStdNamespace());
12016 R.resolveKind();
12018 // Otherwise, attempt typo correction.
12019 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12022 if (!R.empty()) {
12023 NamedDecl *Named = R.getRepresentativeDecl();
12024 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12025 assert(NS && "expected namespace decl");
12027 // The use of a nested name specifier may trigger deprecation warnings.
12028 DiagnoseUseOfDecl(Named, IdentLoc);
12030 // C++ [namespace.udir]p1:
12031 // A using-directive specifies that the names in the nominated
12032 // namespace can be used in the scope in which the
12033 // using-directive appears after the using-directive. During
12034 // unqualified name lookup (3.4.1), the names appear as if they
12035 // were declared in the nearest enclosing namespace which
12036 // contains both the using-directive and the nominated
12037 // namespace. [Note: in this context, "contains" means "contains
12038 // directly or indirectly". ]
12040 // Find enclosing context containing both using-directive and
12041 // nominated namespace.
12042 DeclContext *CommonAncestor = NS;
12043 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12044 CommonAncestor = CommonAncestor->getParent();
12046 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12047 SS.getWithLocInContext(Context),
12048 IdentLoc, Named, CommonAncestor);
12050 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12051 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12052 Diag(IdentLoc, diag::warn_using_directive_in_header);
12055 PushUsingDirective(S, UDir);
12056 } else {
12057 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12060 if (UDir)
12061 ProcessDeclAttributeList(S, UDir, AttrList);
12063 return UDir;
12066 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12067 // If the scope has an associated entity and the using directive is at
12068 // namespace or translation unit scope, add the UsingDirectiveDecl into
12069 // its lookup structure so qualified name lookup can find it.
12070 DeclContext *Ctx = S->getEntity();
12071 if (Ctx && !Ctx->isFunctionOrMethod())
12072 Ctx->addDecl(UDir);
12073 else
12074 // Otherwise, it is at block scope. The using-directives will affect lookup
12075 // only to the end of the scope.
12076 S->PushUsingDirective(UDir);
12079 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12080 SourceLocation UsingLoc,
12081 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12082 UnqualifiedId &Name,
12083 SourceLocation EllipsisLoc,
12084 const ParsedAttributesView &AttrList) {
12085 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12087 if (SS.isEmpty()) {
12088 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12089 return nullptr;
12092 switch (Name.getKind()) {
12093 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12094 case UnqualifiedIdKind::IK_Identifier:
12095 case UnqualifiedIdKind::IK_OperatorFunctionId:
12096 case UnqualifiedIdKind::IK_LiteralOperatorId:
12097 case UnqualifiedIdKind::IK_ConversionFunctionId:
12098 break;
12100 case UnqualifiedIdKind::IK_ConstructorName:
12101 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12102 // C++11 inheriting constructors.
12103 Diag(Name.getBeginLoc(),
12104 getLangOpts().CPlusPlus11
12105 ? diag::warn_cxx98_compat_using_decl_constructor
12106 : diag::err_using_decl_constructor)
12107 << SS.getRange();
12109 if (getLangOpts().CPlusPlus11) break;
12111 return nullptr;
12113 case UnqualifiedIdKind::IK_DestructorName:
12114 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12115 return nullptr;
12117 case UnqualifiedIdKind::IK_TemplateId:
12118 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12119 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12120 return nullptr;
12122 case UnqualifiedIdKind::IK_DeductionGuideName:
12123 llvm_unreachable("cannot parse qualified deduction guide name");
12126 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12127 DeclarationName TargetName = TargetNameInfo.getName();
12128 if (!TargetName)
12129 return nullptr;
12131 // Warn about access declarations.
12132 if (UsingLoc.isInvalid()) {
12133 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12134 ? diag::err_access_decl
12135 : diag::warn_access_decl_deprecated)
12136 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12139 if (EllipsisLoc.isInvalid()) {
12140 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
12141 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
12142 return nullptr;
12143 } else {
12144 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12145 !TargetNameInfo.containsUnexpandedParameterPack()) {
12146 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12147 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12148 EllipsisLoc = SourceLocation();
12152 NamedDecl *UD =
12153 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12154 SS, TargetNameInfo, EllipsisLoc, AttrList,
12155 /*IsInstantiation*/ false,
12156 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12157 if (UD)
12158 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12160 return UD;
12163 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12164 SourceLocation UsingLoc,
12165 SourceLocation EnumLoc,
12166 SourceLocation IdentLoc,
12167 IdentifierInfo &II, CXXScopeSpec *SS) {
12168 assert(!SS->isInvalid() && "ScopeSpec is invalid");
12169 TypeSourceInfo *TSI = nullptr;
12170 QualType EnumTy = GetTypeFromParser(
12171 getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12172 /*HasTrailingDot=*/false,
12173 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12174 /*WantNontrivialTypeSourceInfo=*/true),
12175 &TSI);
12176 if (EnumTy.isNull()) {
12177 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12178 ? diag::err_using_enum_is_dependent
12179 : diag::err_unknown_typename)
12180 << II.getName()
12181 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12182 return nullptr;
12185 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12186 if (!Enum) {
12187 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12188 return nullptr;
12191 if (auto *Def = Enum->getDefinition())
12192 Enum = Def;
12194 if (TSI == nullptr)
12195 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12197 auto *UD =
12198 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12200 if (UD)
12201 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12203 return UD;
12206 /// Determine whether a using declaration considers the given
12207 /// declarations as "equivalent", e.g., if they are redeclarations of
12208 /// the same entity or are both typedefs of the same type.
12209 static bool
12210 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12211 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12212 return true;
12214 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12215 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12216 return Context.hasSameType(TD1->getUnderlyingType(),
12217 TD2->getUnderlyingType());
12219 // Two using_if_exists using-declarations are equivalent if both are
12220 // unresolved.
12221 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12222 isa<UnresolvedUsingIfExistsDecl>(D2))
12223 return true;
12225 return false;
12229 /// Determines whether to create a using shadow decl for a particular
12230 /// decl, given the set of decls existing prior to this using lookup.
12231 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12232 const LookupResult &Previous,
12233 UsingShadowDecl *&PrevShadow) {
12234 // Diagnose finding a decl which is not from a base class of the
12235 // current class. We do this now because there are cases where this
12236 // function will silently decide not to build a shadow decl, which
12237 // will pre-empt further diagnostics.
12239 // We don't need to do this in C++11 because we do the check once on
12240 // the qualifier.
12242 // FIXME: diagnose the following if we care enough:
12243 // struct A { int foo; };
12244 // struct B : A { using A::foo; };
12245 // template <class T> struct C : A {};
12246 // template <class T> struct D : C<T> { using B::foo; } // <---
12247 // This is invalid (during instantiation) in C++03 because B::foo
12248 // resolves to the using decl in B, which is not a base class of D<T>.
12249 // We can't diagnose it immediately because C<T> is an unknown
12250 // specialization. The UsingShadowDecl in D<T> then points directly
12251 // to A::foo, which will look well-formed when we instantiate.
12252 // The right solution is to not collapse the shadow-decl chain.
12253 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12254 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12255 DeclContext *OrigDC = Orig->getDeclContext();
12257 // Handle enums and anonymous structs.
12258 if (isa<EnumDecl>(OrigDC))
12259 OrigDC = OrigDC->getParent();
12260 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12261 while (OrigRec->isAnonymousStructOrUnion())
12262 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12264 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12265 if (OrigDC == CurContext) {
12266 Diag(Using->getLocation(),
12267 diag::err_using_decl_nested_name_specifier_is_current_class)
12268 << Using->getQualifierLoc().getSourceRange();
12269 Diag(Orig->getLocation(), diag::note_using_decl_target);
12270 Using->setInvalidDecl();
12271 return true;
12274 Diag(Using->getQualifierLoc().getBeginLoc(),
12275 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12276 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12277 << Using->getQualifierLoc().getSourceRange();
12278 Diag(Orig->getLocation(), diag::note_using_decl_target);
12279 Using->setInvalidDecl();
12280 return true;
12284 if (Previous.empty()) return false;
12286 NamedDecl *Target = Orig;
12287 if (isa<UsingShadowDecl>(Target))
12288 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12290 // If the target happens to be one of the previous declarations, we
12291 // don't have a conflict.
12293 // FIXME: but we might be increasing its access, in which case we
12294 // should redeclare it.
12295 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12296 bool FoundEquivalentDecl = false;
12297 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12298 I != E; ++I) {
12299 NamedDecl *D = (*I)->getUnderlyingDecl();
12300 // We can have UsingDecls in our Previous results because we use the same
12301 // LookupResult for checking whether the UsingDecl itself is a valid
12302 // redeclaration.
12303 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12304 continue;
12306 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12307 // C++ [class.mem]p19:
12308 // If T is the name of a class, then [every named member other than
12309 // a non-static data member] shall have a name different from T
12310 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12311 !isa<IndirectFieldDecl>(Target) &&
12312 !isa<UnresolvedUsingValueDecl>(Target) &&
12313 DiagnoseClassNameShadow(
12314 CurContext,
12315 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12316 return true;
12319 if (IsEquivalentForUsingDecl(Context, D, Target)) {
12320 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12321 PrevShadow = Shadow;
12322 FoundEquivalentDecl = true;
12323 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12324 // We don't conflict with an existing using shadow decl of an equivalent
12325 // declaration, but we're not a redeclaration of it.
12326 FoundEquivalentDecl = true;
12329 if (isVisible(D))
12330 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12333 if (FoundEquivalentDecl)
12334 return false;
12336 // Always emit a diagnostic for a mismatch between an unresolved
12337 // using_if_exists and a resolved using declaration in either direction.
12338 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12339 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12340 if (!NonTag && !Tag)
12341 return false;
12342 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12343 Diag(Target->getLocation(), diag::note_using_decl_target);
12344 Diag((NonTag ? NonTag : Tag)->getLocation(),
12345 diag::note_using_decl_conflict);
12346 BUD->setInvalidDecl();
12347 return true;
12350 if (FunctionDecl *FD = Target->getAsFunction()) {
12351 NamedDecl *OldDecl = nullptr;
12352 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12353 /*IsForUsingDecl*/ true)) {
12354 case Ovl_Overload:
12355 return false;
12357 case Ovl_NonFunction:
12358 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12359 break;
12361 // We found a decl with the exact signature.
12362 case Ovl_Match:
12363 // If we're in a record, we want to hide the target, so we
12364 // return true (without a diagnostic) to tell the caller not to
12365 // build a shadow decl.
12366 if (CurContext->isRecord())
12367 return true;
12369 // If we're not in a record, this is an error.
12370 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12371 break;
12374 Diag(Target->getLocation(), diag::note_using_decl_target);
12375 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12376 BUD->setInvalidDecl();
12377 return true;
12380 // Target is not a function.
12382 if (isa<TagDecl>(Target)) {
12383 // No conflict between a tag and a non-tag.
12384 if (!Tag) return false;
12386 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12387 Diag(Target->getLocation(), diag::note_using_decl_target);
12388 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12389 BUD->setInvalidDecl();
12390 return true;
12393 // No conflict between a tag and a non-tag.
12394 if (!NonTag) return false;
12396 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12397 Diag(Target->getLocation(), diag::note_using_decl_target);
12398 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12399 BUD->setInvalidDecl();
12400 return true;
12403 /// Determine whether a direct base class is a virtual base class.
12404 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12405 if (!Derived->getNumVBases())
12406 return false;
12407 for (auto &B : Derived->bases())
12408 if (B.getType()->getAsCXXRecordDecl() == Base)
12409 return B.isVirtual();
12410 llvm_unreachable("not a direct base class");
12413 /// Builds a shadow declaration corresponding to a 'using' declaration.
12414 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12415 NamedDecl *Orig,
12416 UsingShadowDecl *PrevDecl) {
12417 // If we resolved to another shadow declaration, just coalesce them.
12418 NamedDecl *Target = Orig;
12419 if (isa<UsingShadowDecl>(Target)) {
12420 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12421 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12424 NamedDecl *NonTemplateTarget = Target;
12425 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12426 NonTemplateTarget = TargetTD->getTemplatedDecl();
12428 UsingShadowDecl *Shadow;
12429 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12430 UsingDecl *Using = cast<UsingDecl>(BUD);
12431 bool IsVirtualBase =
12432 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12433 Using->getQualifier()->getAsRecordDecl());
12434 Shadow = ConstructorUsingShadowDecl::Create(
12435 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12436 } else {
12437 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12438 Target->getDeclName(), BUD, Target);
12440 BUD->addShadowDecl(Shadow);
12442 Shadow->setAccess(BUD->getAccess());
12443 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12444 Shadow->setInvalidDecl();
12446 Shadow->setPreviousDecl(PrevDecl);
12448 if (S)
12449 PushOnScopeChains(Shadow, S);
12450 else
12451 CurContext->addDecl(Shadow);
12454 return Shadow;
12457 /// Hides a using shadow declaration. This is required by the current
12458 /// using-decl implementation when a resolvable using declaration in a
12459 /// class is followed by a declaration which would hide or override
12460 /// one or more of the using decl's targets; for example:
12462 /// struct Base { void foo(int); };
12463 /// struct Derived : Base {
12464 /// using Base::foo;
12465 /// void foo(int);
12466 /// };
12468 /// The governing language is C++03 [namespace.udecl]p12:
12470 /// When a using-declaration brings names from a base class into a
12471 /// derived class scope, member functions in the derived class
12472 /// override and/or hide member functions with the same name and
12473 /// parameter types in a base class (rather than conflicting).
12475 /// There are two ways to implement this:
12476 /// (1) optimistically create shadow decls when they're not hidden
12477 /// by existing declarations, or
12478 /// (2) don't create any shadow decls (or at least don't make them
12479 /// visible) until we've fully parsed/instantiated the class.
12480 /// The problem with (1) is that we might have to retroactively remove
12481 /// a shadow decl, which requires several O(n) operations because the
12482 /// decl structures are (very reasonably) not designed for removal.
12483 /// (2) avoids this but is very fiddly and phase-dependent.
12484 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12485 if (Shadow->getDeclName().getNameKind() ==
12486 DeclarationName::CXXConversionFunctionName)
12487 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12489 // Remove it from the DeclContext...
12490 Shadow->getDeclContext()->removeDecl(Shadow);
12492 // ...and the scope, if applicable...
12493 if (S) {
12494 S->RemoveDecl(Shadow);
12495 IdResolver.RemoveDecl(Shadow);
12498 // ...and the using decl.
12499 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12501 // TODO: complain somehow if Shadow was used. It shouldn't
12502 // be possible for this to happen, because...?
12505 /// Find the base specifier for a base class with the given type.
12506 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12507 QualType DesiredBase,
12508 bool &AnyDependentBases) {
12509 // Check whether the named type is a direct base class.
12510 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12511 .getUnqualifiedType();
12512 for (auto &Base : Derived->bases()) {
12513 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12514 if (CanonicalDesiredBase == BaseType)
12515 return &Base;
12516 if (BaseType->isDependentType())
12517 AnyDependentBases = true;
12519 return nullptr;
12522 namespace {
12523 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12524 public:
12525 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12526 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12527 : HasTypenameKeyword(HasTypenameKeyword),
12528 IsInstantiation(IsInstantiation), OldNNS(NNS),
12529 RequireMemberOf(RequireMemberOf) {}
12531 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12532 NamedDecl *ND = Candidate.getCorrectionDecl();
12534 // Keywords are not valid here.
12535 if (!ND || isa<NamespaceDecl>(ND))
12536 return false;
12538 // Completely unqualified names are invalid for a 'using' declaration.
12539 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12540 return false;
12542 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12543 // reject.
12545 if (RequireMemberOf) {
12546 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12547 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12548 // No-one ever wants a using-declaration to name an injected-class-name
12549 // of a base class, unless they're declaring an inheriting constructor.
12550 ASTContext &Ctx = ND->getASTContext();
12551 if (!Ctx.getLangOpts().CPlusPlus11)
12552 return false;
12553 QualType FoundType = Ctx.getRecordType(FoundRecord);
12555 // Check that the injected-class-name is named as a member of its own
12556 // type; we don't want to suggest 'using Derived::Base;', since that
12557 // means something else.
12558 NestedNameSpecifier *Specifier =
12559 Candidate.WillReplaceSpecifier()
12560 ? Candidate.getCorrectionSpecifier()
12561 : OldNNS;
12562 if (!Specifier->getAsType() ||
12563 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12564 return false;
12566 // Check that this inheriting constructor declaration actually names a
12567 // direct base class of the current class.
12568 bool AnyDependentBases = false;
12569 if (!findDirectBaseWithType(RequireMemberOf,
12570 Ctx.getRecordType(FoundRecord),
12571 AnyDependentBases) &&
12572 !AnyDependentBases)
12573 return false;
12574 } else {
12575 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12576 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12577 return false;
12579 // FIXME: Check that the base class member is accessible?
12581 } else {
12582 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12583 if (FoundRecord && FoundRecord->isInjectedClassName())
12584 return false;
12587 if (isa<TypeDecl>(ND))
12588 return HasTypenameKeyword || !IsInstantiation;
12590 return !HasTypenameKeyword;
12593 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12594 return std::make_unique<UsingValidatorCCC>(*this);
12597 private:
12598 bool HasTypenameKeyword;
12599 bool IsInstantiation;
12600 NestedNameSpecifier *OldNNS;
12601 CXXRecordDecl *RequireMemberOf;
12603 } // end anonymous namespace
12605 /// Remove decls we can't actually see from a lookup being used to declare
12606 /// shadow using decls.
12608 /// \param S - The scope of the potential shadow decl
12609 /// \param Previous - The lookup of a potential shadow decl's name.
12610 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12611 // It is really dumb that we have to do this.
12612 LookupResult::Filter F = Previous.makeFilter();
12613 while (F.hasNext()) {
12614 NamedDecl *D = F.next();
12615 if (!isDeclInScope(D, CurContext, S))
12616 F.erase();
12617 // If we found a local extern declaration that's not ordinarily visible,
12618 // and this declaration is being added to a non-block scope, ignore it.
12619 // We're only checking for scope conflicts here, not also for violations
12620 // of the linkage rules.
12621 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12622 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12623 F.erase();
12625 F.done();
12628 /// Builds a using declaration.
12630 /// \param IsInstantiation - Whether this call arises from an
12631 /// instantiation of an unresolved using declaration. We treat
12632 /// the lookup differently for these declarations.
12633 NamedDecl *Sema::BuildUsingDeclaration(
12634 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12635 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12636 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12637 const ParsedAttributesView &AttrList, bool IsInstantiation,
12638 bool IsUsingIfExists) {
12639 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12640 SourceLocation IdentLoc = NameInfo.getLoc();
12641 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12643 // FIXME: We ignore attributes for now.
12645 // For an inheriting constructor declaration, the name of the using
12646 // declaration is the name of a constructor in this class, not in the
12647 // base class.
12648 DeclarationNameInfo UsingName = NameInfo;
12649 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12650 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12651 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12652 Context.getCanonicalType(Context.getRecordType(RD))));
12654 // Do the redeclaration lookup in the current scope.
12655 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12656 ForVisibleRedeclaration);
12657 Previous.setHideTags(false);
12658 if (S) {
12659 LookupName(Previous, S);
12661 FilterUsingLookup(S, Previous);
12662 } else {
12663 assert(IsInstantiation && "no scope in non-instantiation");
12664 if (CurContext->isRecord())
12665 LookupQualifiedName(Previous, CurContext);
12666 else {
12667 // No redeclaration check is needed here; in non-member contexts we
12668 // diagnosed all possible conflicts with other using-declarations when
12669 // building the template:
12671 // For a dependent non-type using declaration, the only valid case is
12672 // if we instantiate to a single enumerator. We check for conflicts
12673 // between shadow declarations we introduce, and we check in the template
12674 // definition for conflicts between a non-type using declaration and any
12675 // other declaration, which together covers all cases.
12677 // A dependent typename using declaration will never successfully
12678 // instantiate, since it will always name a class member, so we reject
12679 // that in the template definition.
12683 // Check for invalid redeclarations.
12684 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12685 SS, IdentLoc, Previous))
12686 return nullptr;
12688 // 'using_if_exists' doesn't make sense on an inherited constructor.
12689 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12690 DeclarationName::CXXConstructorName) {
12691 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12692 return nullptr;
12695 DeclContext *LookupContext = computeDeclContext(SS);
12696 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12697 if (!LookupContext || EllipsisLoc.isValid()) {
12698 NamedDecl *D;
12699 // Dependent scope, or an unexpanded pack
12700 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12701 SS, NameInfo, IdentLoc))
12702 return nullptr;
12704 if (HasTypenameKeyword) {
12705 // FIXME: not all declaration name kinds are legal here
12706 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12707 UsingLoc, TypenameLoc,
12708 QualifierLoc,
12709 IdentLoc, NameInfo.getName(),
12710 EllipsisLoc);
12711 } else {
12712 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12713 QualifierLoc, NameInfo, EllipsisLoc);
12715 D->setAccess(AS);
12716 CurContext->addDecl(D);
12717 ProcessDeclAttributeList(S, D, AttrList);
12718 return D;
12721 auto Build = [&](bool Invalid) {
12722 UsingDecl *UD =
12723 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12724 UsingName, HasTypenameKeyword);
12725 UD->setAccess(AS);
12726 CurContext->addDecl(UD);
12727 ProcessDeclAttributeList(S, UD, AttrList);
12728 UD->setInvalidDecl(Invalid);
12729 return UD;
12731 auto BuildInvalid = [&]{ return Build(true); };
12732 auto BuildValid = [&]{ return Build(false); };
12734 if (RequireCompleteDeclContext(SS, LookupContext))
12735 return BuildInvalid();
12737 // Look up the target name.
12738 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12740 // Unlike most lookups, we don't always want to hide tag
12741 // declarations: tag names are visible through the using declaration
12742 // even if hidden by ordinary names, *except* in a dependent context
12743 // where they may be used by two-phase lookup.
12744 if (!IsInstantiation)
12745 R.setHideTags(false);
12747 // For the purposes of this lookup, we have a base object type
12748 // equal to that of the current context.
12749 if (CurContext->isRecord()) {
12750 R.setBaseObjectType(
12751 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12754 LookupQualifiedName(R, LookupContext);
12756 // Validate the context, now we have a lookup
12757 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12758 IdentLoc, &R))
12759 return nullptr;
12761 if (R.empty() && IsUsingIfExists)
12762 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12763 UsingName.getName()),
12764 AS_public);
12766 // Try to correct typos if possible. If constructor name lookup finds no
12767 // results, that means the named class has no explicit constructors, and we
12768 // suppressed declaring implicit ones (probably because it's dependent or
12769 // invalid).
12770 if (R.empty() &&
12771 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12772 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12773 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12774 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12775 auto *II = NameInfo.getName().getAsIdentifierInfo();
12776 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12777 CurContext->isStdNamespace() &&
12778 isa<TranslationUnitDecl>(LookupContext) &&
12779 getSourceManager().isInSystemHeader(UsingLoc))
12780 return nullptr;
12781 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12782 dyn_cast<CXXRecordDecl>(CurContext));
12783 if (TypoCorrection Corrected =
12784 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12785 CTK_ErrorRecovery)) {
12786 // We reject candidates where DroppedSpecifier == true, hence the
12787 // literal '0' below.
12788 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12789 << NameInfo.getName() << LookupContext << 0
12790 << SS.getRange());
12792 // If we picked a correction with no attached Decl we can't do anything
12793 // useful with it, bail out.
12794 NamedDecl *ND = Corrected.getCorrectionDecl();
12795 if (!ND)
12796 return BuildInvalid();
12798 // If we corrected to an inheriting constructor, handle it as one.
12799 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12800 if (RD && RD->isInjectedClassName()) {
12801 // The parent of the injected class name is the class itself.
12802 RD = cast<CXXRecordDecl>(RD->getParent());
12804 // Fix up the information we'll use to build the using declaration.
12805 if (Corrected.WillReplaceSpecifier()) {
12806 NestedNameSpecifierLocBuilder Builder;
12807 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12808 QualifierLoc.getSourceRange());
12809 QualifierLoc = Builder.getWithLocInContext(Context);
12812 // In this case, the name we introduce is the name of a derived class
12813 // constructor.
12814 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12815 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12816 Context.getCanonicalType(Context.getRecordType(CurClass))));
12817 UsingName.setNamedTypeInfo(nullptr);
12818 for (auto *Ctor : LookupConstructors(RD))
12819 R.addDecl(Ctor);
12820 R.resolveKind();
12821 } else {
12822 // FIXME: Pick up all the declarations if we found an overloaded
12823 // function.
12824 UsingName.setName(ND->getDeclName());
12825 R.addDecl(ND);
12827 } else {
12828 Diag(IdentLoc, diag::err_no_member)
12829 << NameInfo.getName() << LookupContext << SS.getRange();
12830 return BuildInvalid();
12834 if (R.isAmbiguous())
12835 return BuildInvalid();
12837 if (HasTypenameKeyword) {
12838 // If we asked for a typename and got a non-type decl, error out.
12839 if (!R.getAsSingle<TypeDecl>() &&
12840 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12841 Diag(IdentLoc, diag::err_using_typename_non_type);
12842 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12843 Diag((*I)->getUnderlyingDecl()->getLocation(),
12844 diag::note_using_decl_target);
12845 return BuildInvalid();
12847 } else {
12848 // If we asked for a non-typename and we got a type, error out,
12849 // but only if this is an instantiation of an unresolved using
12850 // decl. Otherwise just silently find the type name.
12851 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12852 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12853 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12854 return BuildInvalid();
12858 // C++14 [namespace.udecl]p6:
12859 // A using-declaration shall not name a namespace.
12860 if (R.getAsSingle<NamespaceDecl>()) {
12861 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12862 << SS.getRange();
12863 return BuildInvalid();
12866 UsingDecl *UD = BuildValid();
12868 // Some additional rules apply to inheriting constructors.
12869 if (UsingName.getName().getNameKind() ==
12870 DeclarationName::CXXConstructorName) {
12871 // Suppress access diagnostics; the access check is instead performed at the
12872 // point of use for an inheriting constructor.
12873 R.suppressDiagnostics();
12874 if (CheckInheritingConstructorUsingDecl(UD))
12875 return UD;
12878 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12879 UsingShadowDecl *PrevDecl = nullptr;
12880 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12881 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12884 return UD;
12887 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12888 SourceLocation UsingLoc,
12889 SourceLocation EnumLoc,
12890 SourceLocation NameLoc,
12891 TypeSourceInfo *EnumType,
12892 EnumDecl *ED) {
12893 bool Invalid = false;
12895 if (CurContext->getRedeclContext()->isRecord()) {
12896 /// In class scope, check if this is a duplicate, for better a diagnostic.
12897 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12898 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12899 ForVisibleRedeclaration);
12901 LookupName(Previous, S);
12903 for (NamedDecl *D : Previous)
12904 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12905 if (UED->getEnumDecl() == ED) {
12906 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12907 << SourceRange(EnumLoc, NameLoc);
12908 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12909 Invalid = true;
12910 break;
12914 if (RequireCompleteEnumDecl(ED, NameLoc))
12915 Invalid = true;
12917 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12918 EnumLoc, NameLoc, EnumType);
12919 UD->setAccess(AS);
12920 CurContext->addDecl(UD);
12922 if (Invalid) {
12923 UD->setInvalidDecl();
12924 return UD;
12927 // Create the shadow decls for each enumerator
12928 for (EnumConstantDecl *EC : ED->enumerators()) {
12929 UsingShadowDecl *PrevDecl = nullptr;
12930 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12931 LookupResult Previous(*this, DNI, LookupOrdinaryName,
12932 ForVisibleRedeclaration);
12933 LookupName(Previous, S);
12934 FilterUsingLookup(S, Previous);
12936 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12937 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12940 return UD;
12943 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12944 ArrayRef<NamedDecl *> Expansions) {
12945 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12946 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12947 isa<UsingPackDecl>(InstantiatedFrom));
12949 auto *UPD =
12950 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12951 UPD->setAccess(InstantiatedFrom->getAccess());
12952 CurContext->addDecl(UPD);
12953 return UPD;
12956 /// Additional checks for a using declaration referring to a constructor name.
12957 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12958 assert(!UD->hasTypename() && "expecting a constructor name");
12960 const Type *SourceType = UD->getQualifier()->getAsType();
12961 assert(SourceType &&
12962 "Using decl naming constructor doesn't have type in scope spec.");
12963 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12965 // Check whether the named type is a direct base class.
12966 bool AnyDependentBases = false;
12967 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12968 AnyDependentBases);
12969 if (!Base && !AnyDependentBases) {
12970 Diag(UD->getUsingLoc(),
12971 diag::err_using_decl_constructor_not_in_direct_base)
12972 << UD->getNameInfo().getSourceRange()
12973 << QualType(SourceType, 0) << TargetClass;
12974 UD->setInvalidDecl();
12975 return true;
12978 if (Base)
12979 Base->setInheritConstructors();
12981 return false;
12984 /// Checks that the given using declaration is not an invalid
12985 /// redeclaration. Note that this is checking only for the using decl
12986 /// itself, not for any ill-formedness among the UsingShadowDecls.
12987 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12988 bool HasTypenameKeyword,
12989 const CXXScopeSpec &SS,
12990 SourceLocation NameLoc,
12991 const LookupResult &Prev) {
12992 NestedNameSpecifier *Qual = SS.getScopeRep();
12994 // C++03 [namespace.udecl]p8:
12995 // C++0x [namespace.udecl]p10:
12996 // A using-declaration is a declaration and can therefore be used
12997 // repeatedly where (and only where) multiple declarations are
12998 // allowed.
13000 // That's in non-member contexts.
13001 if (!CurContext->getRedeclContext()->isRecord()) {
13002 // A dependent qualifier outside a class can only ever resolve to an
13003 // enumeration type. Therefore it conflicts with any other non-type
13004 // declaration in the same scope.
13005 // FIXME: How should we check for dependent type-type conflicts at block
13006 // scope?
13007 if (Qual->isDependent() && !HasTypenameKeyword) {
13008 for (auto *D : Prev) {
13009 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13010 bool OldCouldBeEnumerator =
13011 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13012 Diag(NameLoc,
13013 OldCouldBeEnumerator ? diag::err_redefinition
13014 : diag::err_redefinition_different_kind)
13015 << Prev.getLookupName();
13016 Diag(D->getLocation(), diag::note_previous_definition);
13017 return true;
13021 return false;
13024 const NestedNameSpecifier *CNNS =
13025 Context.getCanonicalNestedNameSpecifier(Qual);
13026 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13027 NamedDecl *D = *I;
13029 bool DTypename;
13030 NestedNameSpecifier *DQual;
13031 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13032 DTypename = UD->hasTypename();
13033 DQual = UD->getQualifier();
13034 } else if (UnresolvedUsingValueDecl *UD
13035 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13036 DTypename = false;
13037 DQual = UD->getQualifier();
13038 } else if (UnresolvedUsingTypenameDecl *UD
13039 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13040 DTypename = true;
13041 DQual = UD->getQualifier();
13042 } else continue;
13044 // using decls differ if one says 'typename' and the other doesn't.
13045 // FIXME: non-dependent using decls?
13046 if (HasTypenameKeyword != DTypename) continue;
13048 // using decls differ if they name different scopes (but note that
13049 // template instantiation can cause this check to trigger when it
13050 // didn't before instantiation).
13051 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13052 continue;
13054 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13055 Diag(D->getLocation(), diag::note_using_decl) << 1;
13056 return true;
13059 return false;
13062 /// Checks that the given nested-name qualifier used in a using decl
13063 /// in the current context is appropriately related to the current
13064 /// scope. If an error is found, diagnoses it and returns true.
13065 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13066 /// result of that lookup. UD is likewise nullptr, except when we have an
13067 /// already-populated UsingDecl whose shadow decls contain the same information
13068 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13069 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13070 const CXXScopeSpec &SS,
13071 const DeclarationNameInfo &NameInfo,
13072 SourceLocation NameLoc,
13073 const LookupResult *R, const UsingDecl *UD) {
13074 DeclContext *NamedContext = computeDeclContext(SS);
13075 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13076 "resolvable context must have exactly one set of decls");
13078 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13079 // relationship.
13080 bool Cxx20Enumerator = false;
13081 if (NamedContext) {
13082 EnumConstantDecl *EC = nullptr;
13083 if (R)
13084 EC = R->getAsSingle<EnumConstantDecl>();
13085 else if (UD && UD->shadow_size() == 1)
13086 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13087 if (EC)
13088 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13090 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13091 // C++14 [namespace.udecl]p7:
13092 // A using-declaration shall not name a scoped enumerator.
13093 // C++20 p1099 permits enumerators.
13094 if (EC && R && ED->isScoped())
13095 Diag(SS.getBeginLoc(),
13096 getLangOpts().CPlusPlus20
13097 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13098 : diag::ext_using_decl_scoped_enumerator)
13099 << SS.getRange();
13101 // We want to consider the scope of the enumerator
13102 NamedContext = ED->getDeclContext();
13106 if (!CurContext->isRecord()) {
13107 // C++03 [namespace.udecl]p3:
13108 // C++0x [namespace.udecl]p8:
13109 // A using-declaration for a class member shall be a member-declaration.
13110 // C++20 [namespace.udecl]p7
13111 // ... other than an enumerator ...
13113 // If we weren't able to compute a valid scope, it might validly be a
13114 // dependent class or enumeration scope. If we have a 'typename' keyword,
13115 // the scope must resolve to a class type.
13116 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13117 : !HasTypename)
13118 return false; // OK
13120 Diag(NameLoc,
13121 Cxx20Enumerator
13122 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13123 : diag::err_using_decl_can_not_refer_to_class_member)
13124 << SS.getRange();
13126 if (Cxx20Enumerator)
13127 return false; // OK
13129 auto *RD = NamedContext
13130 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13131 : nullptr;
13132 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13133 // See if there's a helpful fixit
13135 if (!R) {
13136 // We will have already diagnosed the problem on the template
13137 // definition, Maybe we should do so again?
13138 } else if (R->getAsSingle<TypeDecl>()) {
13139 if (getLangOpts().CPlusPlus11) {
13140 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13141 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13142 << 0 // alias declaration
13143 << FixItHint::CreateInsertion(SS.getBeginLoc(),
13144 NameInfo.getName().getAsString() +
13145 " = ");
13146 } else {
13147 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13148 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13149 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13150 << 1 // typedef declaration
13151 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13152 << FixItHint::CreateInsertion(
13153 InsertLoc, " " + NameInfo.getName().getAsString());
13155 } else if (R->getAsSingle<VarDecl>()) {
13156 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13157 // repeating the type of the static data member here.
13158 FixItHint FixIt;
13159 if (getLangOpts().CPlusPlus11) {
13160 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13161 FixIt = FixItHint::CreateReplacement(
13162 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13165 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13166 << 2 // reference declaration
13167 << FixIt;
13168 } else if (R->getAsSingle<EnumConstantDecl>()) {
13169 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13170 // repeating the type of the enumeration here, and we can't do so if
13171 // the type is anonymous.
13172 FixItHint FixIt;
13173 if (getLangOpts().CPlusPlus11) {
13174 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13175 FixIt = FixItHint::CreateReplacement(
13176 UsingLoc,
13177 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13180 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13181 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13182 << FixIt;
13186 return true; // Fail
13189 // If the named context is dependent, we can't decide much.
13190 if (!NamedContext) {
13191 // FIXME: in C++0x, we can diagnose if we can prove that the
13192 // nested-name-specifier does not refer to a base class, which is
13193 // still possible in some cases.
13195 // Otherwise we have to conservatively report that things might be
13196 // okay.
13197 return false;
13200 // The current scope is a record.
13201 if (!NamedContext->isRecord()) {
13202 // Ideally this would point at the last name in the specifier,
13203 // but we don't have that level of source info.
13204 Diag(SS.getBeginLoc(),
13205 Cxx20Enumerator
13206 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13207 : diag::err_using_decl_nested_name_specifier_is_not_class)
13208 << SS.getScopeRep() << SS.getRange();
13210 if (Cxx20Enumerator)
13211 return false; // OK
13213 return true;
13216 if (!NamedContext->isDependentContext() &&
13217 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13218 return true;
13220 if (getLangOpts().CPlusPlus11) {
13221 // C++11 [namespace.udecl]p3:
13222 // In a using-declaration used as a member-declaration, the
13223 // nested-name-specifier shall name a base class of the class
13224 // being defined.
13226 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13227 cast<CXXRecordDecl>(NamedContext))) {
13229 if (Cxx20Enumerator) {
13230 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13231 << SS.getRange();
13232 return false;
13235 if (CurContext == NamedContext) {
13236 Diag(SS.getBeginLoc(),
13237 diag::err_using_decl_nested_name_specifier_is_current_class)
13238 << SS.getRange();
13239 return !getLangOpts().CPlusPlus20;
13242 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13243 Diag(SS.getBeginLoc(),
13244 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13245 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13246 << SS.getRange();
13248 return true;
13251 return false;
13254 // C++03 [namespace.udecl]p4:
13255 // A using-declaration used as a member-declaration shall refer
13256 // to a member of a base class of the class being defined [etc.].
13258 // Salient point: SS doesn't have to name a base class as long as
13259 // lookup only finds members from base classes. Therefore we can
13260 // diagnose here only if we can prove that can't happen,
13261 // i.e. if the class hierarchies provably don't intersect.
13263 // TODO: it would be nice if "definitely valid" results were cached
13264 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13265 // need to be repeated.
13267 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13268 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13269 Bases.insert(Base);
13270 return true;
13273 // Collect all bases. Return false if we find a dependent base.
13274 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13275 return false;
13277 // Returns true if the base is dependent or is one of the accumulated base
13278 // classes.
13279 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13280 return !Bases.count(Base);
13283 // Return false if the class has a dependent base or if it or one
13284 // of its bases is present in the base set of the current context.
13285 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13286 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13287 return false;
13289 Diag(SS.getRange().getBegin(),
13290 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13291 << SS.getScopeRep()
13292 << cast<CXXRecordDecl>(CurContext)
13293 << SS.getRange();
13295 return true;
13298 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13299 MultiTemplateParamsArg TemplateParamLists,
13300 SourceLocation UsingLoc, UnqualifiedId &Name,
13301 const ParsedAttributesView &AttrList,
13302 TypeResult Type, Decl *DeclFromDeclSpec) {
13303 // Skip up to the relevant declaration scope.
13304 while (S->isTemplateParamScope())
13305 S = S->getParent();
13306 assert((S->getFlags() & Scope::DeclScope) &&
13307 "got alias-declaration outside of declaration scope");
13309 if (Type.isInvalid())
13310 return nullptr;
13312 bool Invalid = false;
13313 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13314 TypeSourceInfo *TInfo = nullptr;
13315 GetTypeFromParser(Type.get(), &TInfo);
13317 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13318 return nullptr;
13320 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13321 UPPC_DeclarationType)) {
13322 Invalid = true;
13323 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13324 TInfo->getTypeLoc().getBeginLoc());
13327 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13328 TemplateParamLists.size()
13329 ? forRedeclarationInCurContext()
13330 : ForVisibleRedeclaration);
13331 LookupName(Previous, S);
13333 // Warn about shadowing the name of a template parameter.
13334 if (Previous.isSingleResult() &&
13335 Previous.getFoundDecl()->isTemplateParameter()) {
13336 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13337 Previous.clear();
13340 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13341 "name in alias declaration must be an identifier");
13342 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13343 Name.StartLocation,
13344 Name.Identifier, TInfo);
13346 NewTD->setAccess(AS);
13348 if (Invalid)
13349 NewTD->setInvalidDecl();
13351 ProcessDeclAttributeList(S, NewTD, AttrList);
13352 AddPragmaAttributes(S, NewTD);
13354 CheckTypedefForVariablyModifiedType(S, NewTD);
13355 Invalid |= NewTD->isInvalidDecl();
13357 bool Redeclaration = false;
13359 NamedDecl *NewND;
13360 if (TemplateParamLists.size()) {
13361 TypeAliasTemplateDecl *OldDecl = nullptr;
13362 TemplateParameterList *OldTemplateParams = nullptr;
13364 if (TemplateParamLists.size() != 1) {
13365 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13366 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13367 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13369 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13371 // Check that we can declare a template here.
13372 if (CheckTemplateDeclScope(S, TemplateParams))
13373 return nullptr;
13375 // Only consider previous declarations in the same scope.
13376 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13377 /*ExplicitInstantiationOrSpecialization*/false);
13378 if (!Previous.empty()) {
13379 Redeclaration = true;
13381 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13382 if (!OldDecl && !Invalid) {
13383 Diag(UsingLoc, diag::err_redefinition_different_kind)
13384 << Name.Identifier;
13386 NamedDecl *OldD = Previous.getRepresentativeDecl();
13387 if (OldD->getLocation().isValid())
13388 Diag(OldD->getLocation(), diag::note_previous_definition);
13390 Invalid = true;
13393 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13394 if (TemplateParameterListsAreEqual(TemplateParams,
13395 OldDecl->getTemplateParameters(),
13396 /*Complain=*/true,
13397 TPL_TemplateMatch))
13398 OldTemplateParams =
13399 OldDecl->getMostRecentDecl()->getTemplateParameters();
13400 else
13401 Invalid = true;
13403 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13404 if (!Invalid &&
13405 !Context.hasSameType(OldTD->getUnderlyingType(),
13406 NewTD->getUnderlyingType())) {
13407 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13408 // but we can't reasonably accept it.
13409 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13410 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13411 if (OldTD->getLocation().isValid())
13412 Diag(OldTD->getLocation(), diag::note_previous_definition);
13413 Invalid = true;
13418 // Merge any previous default template arguments into our parameters,
13419 // and check the parameter list.
13420 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13421 TPC_TypeAliasTemplate))
13422 return nullptr;
13424 TypeAliasTemplateDecl *NewDecl =
13425 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13426 Name.Identifier, TemplateParams,
13427 NewTD);
13428 NewTD->setDescribedAliasTemplate(NewDecl);
13430 NewDecl->setAccess(AS);
13432 if (Invalid)
13433 NewDecl->setInvalidDecl();
13434 else if (OldDecl) {
13435 NewDecl->setPreviousDecl(OldDecl);
13436 CheckRedeclarationInModule(NewDecl, OldDecl);
13439 NewND = NewDecl;
13440 } else {
13441 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13442 setTagNameForLinkagePurposes(TD, NewTD);
13443 handleTagNumbering(TD, S);
13445 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13446 NewND = NewTD;
13449 PushOnScopeChains(NewND, S);
13450 ActOnDocumentableDecl(NewND);
13451 return NewND;
13454 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13455 SourceLocation AliasLoc,
13456 IdentifierInfo *Alias, CXXScopeSpec &SS,
13457 SourceLocation IdentLoc,
13458 IdentifierInfo *Ident) {
13460 // Lookup the namespace name.
13461 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13462 LookupParsedName(R, S, &SS);
13464 if (R.isAmbiguous())
13465 return nullptr;
13467 if (R.empty()) {
13468 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13469 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13470 return nullptr;
13473 assert(!R.isAmbiguous() && !R.empty());
13474 NamedDecl *ND = R.getRepresentativeDecl();
13476 // Check if we have a previous declaration with the same name.
13477 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13478 ForVisibleRedeclaration);
13479 LookupName(PrevR, S);
13481 // Check we're not shadowing a template parameter.
13482 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13483 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13484 PrevR.clear();
13487 // Filter out any other lookup result from an enclosing scope.
13488 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13489 /*AllowInlineNamespace*/false);
13491 // Find the previous declaration and check that we can redeclare it.
13492 NamespaceAliasDecl *Prev = nullptr;
13493 if (PrevR.isSingleResult()) {
13494 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13495 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13496 // We already have an alias with the same name that points to the same
13497 // namespace; check that it matches.
13498 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13499 Prev = AD;
13500 } else if (isVisible(PrevDecl)) {
13501 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13502 << Alias;
13503 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13504 << AD->getNamespace();
13505 return nullptr;
13507 } else if (isVisible(PrevDecl)) {
13508 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13509 ? diag::err_redefinition
13510 : diag::err_redefinition_different_kind;
13511 Diag(AliasLoc, DiagID) << Alias;
13512 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13513 return nullptr;
13517 // The use of a nested name specifier may trigger deprecation warnings.
13518 DiagnoseUseOfDecl(ND, IdentLoc);
13520 NamespaceAliasDecl *AliasDecl =
13521 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13522 Alias, SS.getWithLocInContext(Context),
13523 IdentLoc, ND);
13524 if (Prev)
13525 AliasDecl->setPreviousDecl(Prev);
13527 PushOnScopeChains(AliasDecl, S);
13528 return AliasDecl;
13531 namespace {
13532 struct SpecialMemberExceptionSpecInfo
13533 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13534 SourceLocation Loc;
13535 Sema::ImplicitExceptionSpecification ExceptSpec;
13537 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13538 Sema::CXXSpecialMember CSM,
13539 Sema::InheritedConstructorInfo *ICI,
13540 SourceLocation Loc)
13541 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13543 bool visitBase(CXXBaseSpecifier *Base);
13544 bool visitField(FieldDecl *FD);
13546 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13547 unsigned Quals);
13549 void visitSubobjectCall(Subobject Subobj,
13550 Sema::SpecialMemberOverloadResult SMOR);
13554 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13555 auto *RT = Base->getType()->getAs<RecordType>();
13556 if (!RT)
13557 return false;
13559 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13560 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13561 if (auto *BaseCtor = SMOR.getMethod()) {
13562 visitSubobjectCall(Base, BaseCtor);
13563 return false;
13566 visitClassSubobject(BaseClass, Base, 0);
13567 return false;
13570 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13571 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13572 Expr *E = FD->getInClassInitializer();
13573 if (!E)
13574 // FIXME: It's a little wasteful to build and throw away a
13575 // CXXDefaultInitExpr here.
13576 // FIXME: We should have a single context note pointing at Loc, and
13577 // this location should be MD->getLocation() instead, since that's
13578 // the location where we actually use the default init expression.
13579 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13580 if (E)
13581 ExceptSpec.CalledExpr(E);
13582 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13583 ->getAs<RecordType>()) {
13584 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13585 FD->getType().getCVRQualifiers());
13587 return false;
13590 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13591 Subobject Subobj,
13592 unsigned Quals) {
13593 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13594 bool IsMutable = Field && Field->isMutable();
13595 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13598 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13599 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13600 // Note, if lookup fails, it doesn't matter what exception specification we
13601 // choose because the special member will be deleted.
13602 if (CXXMethodDecl *MD = SMOR.getMethod())
13603 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13606 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13607 llvm::APSInt Result;
13608 ExprResult Converted = CheckConvertedConstantExpression(
13609 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13610 ExplicitSpec.setExpr(Converted.get());
13611 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13612 ExplicitSpec.setKind(Result.getBoolValue()
13613 ? ExplicitSpecKind::ResolvedTrue
13614 : ExplicitSpecKind::ResolvedFalse);
13615 return true;
13617 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13618 return false;
13621 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13622 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13623 if (!ExplicitExpr->isTypeDependent())
13624 tryResolveExplicitSpecifier(ES);
13625 return ES;
13628 static Sema::ImplicitExceptionSpecification
13629 ComputeDefaultedSpecialMemberExceptionSpec(
13630 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13631 Sema::InheritedConstructorInfo *ICI) {
13632 ComputingExceptionSpec CES(S, MD, Loc);
13634 CXXRecordDecl *ClassDecl = MD->getParent();
13636 // C++ [except.spec]p14:
13637 // An implicitly declared special member function (Clause 12) shall have an
13638 // exception-specification. [...]
13639 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13640 if (ClassDecl->isInvalidDecl())
13641 return Info.ExceptSpec;
13643 // FIXME: If this diagnostic fires, we're probably missing a check for
13644 // attempting to resolve an exception specification before it's known
13645 // at a higher level.
13646 if (S.RequireCompleteType(MD->getLocation(),
13647 S.Context.getRecordType(ClassDecl),
13648 diag::err_exception_spec_incomplete_type))
13649 return Info.ExceptSpec;
13651 // C++1z [except.spec]p7:
13652 // [Look for exceptions thrown by] a constructor selected [...] to
13653 // initialize a potentially constructed subobject,
13654 // C++1z [except.spec]p8:
13655 // The exception specification for an implicitly-declared destructor, or a
13656 // destructor without a noexcept-specifier, is potentially-throwing if and
13657 // only if any of the destructors for any of its potentially constructed
13658 // subojects is potentially throwing.
13659 // FIXME: We respect the first rule but ignore the "potentially constructed"
13660 // in the second rule to resolve a core issue (no number yet) that would have
13661 // us reject:
13662 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13663 // struct B : A {};
13664 // struct C : B { void f(); };
13665 // ... due to giving B::~B() a non-throwing exception specification.
13666 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13667 : Info.VisitAllBases);
13669 return Info.ExceptSpec;
13672 namespace {
13673 /// RAII object to register a special member as being currently declared.
13674 struct DeclaringSpecialMember {
13675 Sema &S;
13676 Sema::SpecialMemberDecl D;
13677 Sema::ContextRAII SavedContext;
13678 bool WasAlreadyBeingDeclared;
13680 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13681 : S(S), D(RD, CSM), SavedContext(S, RD) {
13682 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13683 if (WasAlreadyBeingDeclared)
13684 // This almost never happens, but if it does, ensure that our cache
13685 // doesn't contain a stale result.
13686 S.SpecialMemberCache.clear();
13687 else {
13688 // Register a note to be produced if we encounter an error while
13689 // declaring the special member.
13690 Sema::CodeSynthesisContext Ctx;
13691 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13692 // FIXME: We don't have a location to use here. Using the class's
13693 // location maintains the fiction that we declare all special members
13694 // with the class, but (1) it's not clear that lying about that helps our
13695 // users understand what's going on, and (2) there may be outer contexts
13696 // on the stack (some of which are relevant) and printing them exposes
13697 // our lies.
13698 Ctx.PointOfInstantiation = RD->getLocation();
13699 Ctx.Entity = RD;
13700 Ctx.SpecialMember = CSM;
13701 S.pushCodeSynthesisContext(Ctx);
13704 ~DeclaringSpecialMember() {
13705 if (!WasAlreadyBeingDeclared) {
13706 S.SpecialMembersBeingDeclared.erase(D);
13707 S.popCodeSynthesisContext();
13711 /// Are we already trying to declare this special member?
13712 bool isAlreadyBeingDeclared() const {
13713 return WasAlreadyBeingDeclared;
13718 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13719 // Look up any existing declarations, but don't trigger declaration of all
13720 // implicit special members with this name.
13721 DeclarationName Name = FD->getDeclName();
13722 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13723 ForExternalRedeclaration);
13724 for (auto *D : FD->getParent()->lookup(Name))
13725 if (auto *Acceptable = R.getAcceptableDecl(D))
13726 R.addDecl(Acceptable);
13727 R.resolveKind();
13728 R.suppressDiagnostics();
13730 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13731 FD->isThisDeclarationADefinition());
13734 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13735 QualType ResultTy,
13736 ArrayRef<QualType> Args) {
13737 // Build an exception specification pointing back at this constructor.
13738 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13740 LangAS AS = getDefaultCXXMethodAddrSpace();
13741 if (AS != LangAS::Default) {
13742 EPI.TypeQuals.addAddressSpace(AS);
13745 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13746 SpecialMem->setType(QT);
13748 // During template instantiation of implicit special member functions we need
13749 // a reliable TypeSourceInfo for the function prototype in order to allow
13750 // functions to be substituted.
13751 if (inTemplateInstantiation() &&
13752 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13753 TypeSourceInfo *TSI =
13754 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13755 SpecialMem->setTypeSourceInfo(TSI);
13759 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13760 CXXRecordDecl *ClassDecl) {
13761 // C++ [class.ctor]p5:
13762 // A default constructor for a class X is a constructor of class X
13763 // that can be called without an argument. If there is no
13764 // user-declared constructor for class X, a default constructor is
13765 // implicitly declared. An implicitly-declared default constructor
13766 // is an inline public member of its class.
13767 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13768 "Should not build implicit default constructor!");
13770 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13771 if (DSM.isAlreadyBeingDeclared())
13772 return nullptr;
13774 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13775 CXXDefaultConstructor,
13776 false);
13778 // Create the actual constructor declaration.
13779 CanQualType ClassType
13780 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13781 SourceLocation ClassLoc = ClassDecl->getLocation();
13782 DeclarationName Name
13783 = Context.DeclarationNames.getCXXConstructorName(ClassType);
13784 DeclarationNameInfo NameInfo(Name, ClassLoc);
13785 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13786 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13787 /*TInfo=*/nullptr, ExplicitSpecifier(),
13788 getCurFPFeatures().isFPConstrained(),
13789 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13790 Constexpr ? ConstexprSpecKind::Constexpr
13791 : ConstexprSpecKind::Unspecified);
13792 DefaultCon->setAccess(AS_public);
13793 DefaultCon->setDefaulted();
13795 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13797 if (getLangOpts().CUDA)
13798 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13799 DefaultCon,
13800 /* ConstRHS */ false,
13801 /* Diagnose */ false);
13803 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13804 // constructors is easy to compute.
13805 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13807 // Note that we have declared this constructor.
13808 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13810 Scope *S = getScopeForContext(ClassDecl);
13811 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13813 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13814 SetDeclDeleted(DefaultCon, ClassLoc);
13816 if (S)
13817 PushOnScopeChains(DefaultCon, S, false);
13818 ClassDecl->addDecl(DefaultCon);
13820 return DefaultCon;
13823 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13824 CXXConstructorDecl *Constructor) {
13825 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13826 !Constructor->doesThisDeclarationHaveABody() &&
13827 !Constructor->isDeleted()) &&
13828 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13829 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13830 return;
13832 CXXRecordDecl *ClassDecl = Constructor->getParent();
13833 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13835 SynthesizedFunctionScope Scope(*this, Constructor);
13837 // The exception specification is needed because we are defining the
13838 // function.
13839 ResolveExceptionSpec(CurrentLocation,
13840 Constructor->getType()->castAs<FunctionProtoType>());
13841 MarkVTableUsed(CurrentLocation, ClassDecl);
13843 // Add a context note for diagnostics produced after this point.
13844 Scope.addContextNote(CurrentLocation);
13846 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13847 Constructor->setInvalidDecl();
13848 return;
13851 SourceLocation Loc = Constructor->getEndLoc().isValid()
13852 ? Constructor->getEndLoc()
13853 : Constructor->getLocation();
13854 Constructor->setBody(new (Context) CompoundStmt(Loc));
13855 Constructor->markUsed(Context);
13857 if (ASTMutationListener *L = getASTMutationListener()) {
13858 L->CompletedImplicitDefinition(Constructor);
13861 DiagnoseUninitializedFields(*this, Constructor);
13864 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13865 // Perform any delayed checks on exception specifications.
13866 CheckDelayedMemberExceptionSpecs();
13869 /// Find or create the fake constructor we synthesize to model constructing an
13870 /// object of a derived class via a constructor of a base class.
13871 CXXConstructorDecl *
13872 Sema::findInheritingConstructor(SourceLocation Loc,
13873 CXXConstructorDecl *BaseCtor,
13874 ConstructorUsingShadowDecl *Shadow) {
13875 CXXRecordDecl *Derived = Shadow->getParent();
13876 SourceLocation UsingLoc = Shadow->getLocation();
13878 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13879 // For now we use the name of the base class constructor as a member of the
13880 // derived class to indicate a (fake) inherited constructor name.
13881 DeclarationName Name = BaseCtor->getDeclName();
13883 // Check to see if we already have a fake constructor for this inherited
13884 // constructor call.
13885 for (NamedDecl *Ctor : Derived->lookup(Name))
13886 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13887 ->getInheritedConstructor()
13888 .getConstructor(),
13889 BaseCtor))
13890 return cast<CXXConstructorDecl>(Ctor);
13892 DeclarationNameInfo NameInfo(Name, UsingLoc);
13893 TypeSourceInfo *TInfo =
13894 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13895 FunctionProtoTypeLoc ProtoLoc =
13896 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13898 // Check the inherited constructor is valid and find the list of base classes
13899 // from which it was inherited.
13900 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13902 bool Constexpr =
13903 BaseCtor->isConstexpr() &&
13904 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13905 false, BaseCtor, &ICI);
13907 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13908 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13909 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13910 /*isInline=*/true,
13911 /*isImplicitlyDeclared=*/true,
13912 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13913 InheritedConstructor(Shadow, BaseCtor),
13914 BaseCtor->getTrailingRequiresClause());
13915 if (Shadow->isInvalidDecl())
13916 DerivedCtor->setInvalidDecl();
13918 // Build an unevaluated exception specification for this fake constructor.
13919 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13920 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13921 EPI.ExceptionSpec.Type = EST_Unevaluated;
13922 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13923 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13924 FPT->getParamTypes(), EPI));
13926 // Build the parameter declarations.
13927 SmallVector<ParmVarDecl *, 16> ParamDecls;
13928 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13929 TypeSourceInfo *TInfo =
13930 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13931 ParmVarDecl *PD = ParmVarDecl::Create(
13932 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13933 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13934 PD->setScopeInfo(0, I);
13935 PD->setImplicit();
13936 // Ensure attributes are propagated onto parameters (this matters for
13937 // format, pass_object_size, ...).
13938 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13939 ParamDecls.push_back(PD);
13940 ProtoLoc.setParam(I, PD);
13943 // Set up the new constructor.
13944 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13945 DerivedCtor->setAccess(BaseCtor->getAccess());
13946 DerivedCtor->setParams(ParamDecls);
13947 Derived->addDecl(DerivedCtor);
13949 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13950 SetDeclDeleted(DerivedCtor, UsingLoc);
13952 return DerivedCtor;
13955 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13956 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13957 Ctor->getInheritedConstructor().getShadowDecl());
13958 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13959 /*Diagnose*/true);
13962 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13963 CXXConstructorDecl *Constructor) {
13964 CXXRecordDecl *ClassDecl = Constructor->getParent();
13965 assert(Constructor->getInheritedConstructor() &&
13966 !Constructor->doesThisDeclarationHaveABody() &&
13967 !Constructor->isDeleted());
13968 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13969 return;
13971 // Initializations are performed "as if by a defaulted default constructor",
13972 // so enter the appropriate scope.
13973 SynthesizedFunctionScope Scope(*this, Constructor);
13975 // The exception specification is needed because we are defining the
13976 // function.
13977 ResolveExceptionSpec(CurrentLocation,
13978 Constructor->getType()->castAs<FunctionProtoType>());
13979 MarkVTableUsed(CurrentLocation, ClassDecl);
13981 // Add a context note for diagnostics produced after this point.
13982 Scope.addContextNote(CurrentLocation);
13984 ConstructorUsingShadowDecl *Shadow =
13985 Constructor->getInheritedConstructor().getShadowDecl();
13986 CXXConstructorDecl *InheritedCtor =
13987 Constructor->getInheritedConstructor().getConstructor();
13989 // [class.inhctor.init]p1:
13990 // initialization proceeds as if a defaulted default constructor is used to
13991 // initialize the D object and each base class subobject from which the
13992 // constructor was inherited
13994 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13995 CXXRecordDecl *RD = Shadow->getParent();
13996 SourceLocation InitLoc = Shadow->getLocation();
13998 // Build explicit initializers for all base classes from which the
13999 // constructor was inherited.
14000 SmallVector<CXXCtorInitializer*, 8> Inits;
14001 for (bool VBase : {false, true}) {
14002 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14003 if (B.isVirtual() != VBase)
14004 continue;
14006 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14007 if (!BaseRD)
14008 continue;
14010 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14011 if (!BaseCtor.first)
14012 continue;
14014 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14015 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14016 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14018 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14019 Inits.push_back(new (Context) CXXCtorInitializer(
14020 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14021 SourceLocation()));
14025 // We now proceed as if for a defaulted default constructor, with the relevant
14026 // initializers replaced.
14028 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14029 Constructor->setInvalidDecl();
14030 return;
14033 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14034 Constructor->markUsed(Context);
14036 if (ASTMutationListener *L = getASTMutationListener()) {
14037 L->CompletedImplicitDefinition(Constructor);
14040 DiagnoseUninitializedFields(*this, Constructor);
14043 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14044 // C++ [class.dtor]p2:
14045 // If a class has no user-declared destructor, a destructor is
14046 // declared implicitly. An implicitly-declared destructor is an
14047 // inline public member of its class.
14048 assert(ClassDecl->needsImplicitDestructor());
14050 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
14051 if (DSM.isAlreadyBeingDeclared())
14052 return nullptr;
14054 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14055 CXXDestructor,
14056 false);
14058 // Create the actual destructor declaration.
14059 CanQualType ClassType
14060 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
14061 SourceLocation ClassLoc = ClassDecl->getLocation();
14062 DeclarationName Name
14063 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14064 DeclarationNameInfo NameInfo(Name, ClassLoc);
14065 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14066 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14067 getCurFPFeatures().isFPConstrained(),
14068 /*isInline=*/true,
14069 /*isImplicitlyDeclared=*/true,
14070 Constexpr ? ConstexprSpecKind::Constexpr
14071 : ConstexprSpecKind::Unspecified);
14072 Destructor->setAccess(AS_public);
14073 Destructor->setDefaulted();
14075 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14077 if (getLangOpts().CUDA)
14078 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
14079 Destructor,
14080 /* ConstRHS */ false,
14081 /* Diagnose */ false);
14083 // We don't need to use SpecialMemberIsTrivial here; triviality for
14084 // destructors is easy to compute.
14085 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14086 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14087 ClassDecl->hasTrivialDestructorForCall());
14089 // Note that we have declared this destructor.
14090 ++getASTContext().NumImplicitDestructorsDeclared;
14092 Scope *S = getScopeForContext(ClassDecl);
14093 CheckImplicitSpecialMemberDeclaration(S, Destructor);
14095 // We can't check whether an implicit destructor is deleted before we complete
14096 // the definition of the class, because its validity depends on the alignment
14097 // of the class. We'll check this from ActOnFields once the class is complete.
14098 if (ClassDecl->isCompleteDefinition() &&
14099 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
14100 SetDeclDeleted(Destructor, ClassLoc);
14102 // Introduce this destructor into its scope.
14103 if (S)
14104 PushOnScopeChains(Destructor, S, false);
14105 ClassDecl->addDecl(Destructor);
14107 return Destructor;
14110 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14111 CXXDestructorDecl *Destructor) {
14112 assert((Destructor->isDefaulted() &&
14113 !Destructor->doesThisDeclarationHaveABody() &&
14114 !Destructor->isDeleted()) &&
14115 "DefineImplicitDestructor - call it for implicit default dtor");
14116 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14117 return;
14119 CXXRecordDecl *ClassDecl = Destructor->getParent();
14120 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14122 SynthesizedFunctionScope Scope(*this, Destructor);
14124 // The exception specification is needed because we are defining the
14125 // function.
14126 ResolveExceptionSpec(CurrentLocation,
14127 Destructor->getType()->castAs<FunctionProtoType>());
14128 MarkVTableUsed(CurrentLocation, ClassDecl);
14130 // Add a context note for diagnostics produced after this point.
14131 Scope.addContextNote(CurrentLocation);
14133 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14134 Destructor->getParent());
14136 if (CheckDestructor(Destructor)) {
14137 Destructor->setInvalidDecl();
14138 return;
14141 SourceLocation Loc = Destructor->getEndLoc().isValid()
14142 ? Destructor->getEndLoc()
14143 : Destructor->getLocation();
14144 Destructor->setBody(new (Context) CompoundStmt(Loc));
14145 Destructor->markUsed(Context);
14147 if (ASTMutationListener *L = getASTMutationListener()) {
14148 L->CompletedImplicitDefinition(Destructor);
14152 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14153 CXXDestructorDecl *Destructor) {
14154 if (Destructor->isInvalidDecl())
14155 return;
14157 CXXRecordDecl *ClassDecl = Destructor->getParent();
14158 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14159 "implicit complete dtors unneeded outside MS ABI");
14160 assert(ClassDecl->getNumVBases() > 0 &&
14161 "complete dtor only exists for classes with vbases");
14163 SynthesizedFunctionScope Scope(*this, Destructor);
14165 // Add a context note for diagnostics produced after this point.
14166 Scope.addContextNote(CurrentLocation);
14168 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14171 /// Perform any semantic analysis which needs to be delayed until all
14172 /// pending class member declarations have been parsed.
14173 void Sema::ActOnFinishCXXMemberDecls() {
14174 // If the context is an invalid C++ class, just suppress these checks.
14175 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14176 if (Record->isInvalidDecl()) {
14177 DelayedOverridingExceptionSpecChecks.clear();
14178 DelayedEquivalentExceptionSpecChecks.clear();
14179 return;
14181 checkForMultipleExportedDefaultConstructors(*this, Record);
14185 void Sema::ActOnFinishCXXNonNestedClass() {
14186 referenceDLLExportedClassMethods();
14188 if (!DelayedDllExportMemberFunctions.empty()) {
14189 SmallVector<CXXMethodDecl*, 4> WorkList;
14190 std::swap(DelayedDllExportMemberFunctions, WorkList);
14191 for (CXXMethodDecl *M : WorkList) {
14192 DefineDefaultedFunction(*this, M, M->getLocation());
14194 // Pass the method to the consumer to get emitted. This is not necessary
14195 // for explicit instantiation definitions, as they will get emitted
14196 // anyway.
14197 if (M->getParent()->getTemplateSpecializationKind() !=
14198 TSK_ExplicitInstantiationDefinition)
14199 ActOnFinishInlineFunctionDef(M);
14204 void Sema::referenceDLLExportedClassMethods() {
14205 if (!DelayedDllExportClasses.empty()) {
14206 // Calling ReferenceDllExportedMembers might cause the current function to
14207 // be called again, so use a local copy of DelayedDllExportClasses.
14208 SmallVector<CXXRecordDecl *, 4> WorkList;
14209 std::swap(DelayedDllExportClasses, WorkList);
14210 for (CXXRecordDecl *Class : WorkList)
14211 ReferenceDllExportedMembers(*this, Class);
14215 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14216 assert(getLangOpts().CPlusPlus11 &&
14217 "adjusting dtor exception specs was introduced in c++11");
14219 if (Destructor->isDependentContext())
14220 return;
14222 // C++11 [class.dtor]p3:
14223 // A declaration of a destructor that does not have an exception-
14224 // specification is implicitly considered to have the same exception-
14225 // specification as an implicit declaration.
14226 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14227 if (DtorType->hasExceptionSpec())
14228 return;
14230 // Replace the destructor's type, building off the existing one. Fortunately,
14231 // the only thing of interest in the destructor type is its extended info.
14232 // The return and arguments are fixed.
14233 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14234 EPI.ExceptionSpec.Type = EST_Unevaluated;
14235 EPI.ExceptionSpec.SourceDecl = Destructor;
14236 Destructor->setType(
14237 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14239 // FIXME: If the destructor has a body that could throw, and the newly created
14240 // spec doesn't allow exceptions, we should emit a warning, because this
14241 // change in behavior can break conforming C++03 programs at runtime.
14242 // However, we don't have a body or an exception specification yet, so it
14243 // needs to be done somewhere else.
14246 namespace {
14247 /// An abstract base class for all helper classes used in building the
14248 // copy/move operators. These classes serve as factory functions and help us
14249 // avoid using the same Expr* in the AST twice.
14250 class ExprBuilder {
14251 ExprBuilder(const ExprBuilder&) = delete;
14252 ExprBuilder &operator=(const ExprBuilder&) = delete;
14254 protected:
14255 static Expr *assertNotNull(Expr *E) {
14256 assert(E && "Expression construction must not fail.");
14257 return E;
14260 public:
14261 ExprBuilder() {}
14262 virtual ~ExprBuilder() {}
14264 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14267 class RefBuilder: public ExprBuilder {
14268 VarDecl *Var;
14269 QualType VarType;
14271 public:
14272 Expr *build(Sema &S, SourceLocation Loc) const override {
14273 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14276 RefBuilder(VarDecl *Var, QualType VarType)
14277 : Var(Var), VarType(VarType) {}
14280 class ThisBuilder: public ExprBuilder {
14281 public:
14282 Expr *build(Sema &S, SourceLocation Loc) const override {
14283 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14287 class CastBuilder: public ExprBuilder {
14288 const ExprBuilder &Builder;
14289 QualType Type;
14290 ExprValueKind Kind;
14291 const CXXCastPath &Path;
14293 public:
14294 Expr *build(Sema &S, SourceLocation Loc) const override {
14295 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14296 CK_UncheckedDerivedToBase, Kind,
14297 &Path).get());
14300 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14301 const CXXCastPath &Path)
14302 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14305 class DerefBuilder: public ExprBuilder {
14306 const ExprBuilder &Builder;
14308 public:
14309 Expr *build(Sema &S, SourceLocation Loc) const override {
14310 return assertNotNull(
14311 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14314 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14317 class MemberBuilder: public ExprBuilder {
14318 const ExprBuilder &Builder;
14319 QualType Type;
14320 CXXScopeSpec SS;
14321 bool IsArrow;
14322 LookupResult &MemberLookup;
14324 public:
14325 Expr *build(Sema &S, SourceLocation Loc) const override {
14326 return assertNotNull(S.BuildMemberReferenceExpr(
14327 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14328 nullptr, MemberLookup, nullptr, nullptr).get());
14331 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14332 LookupResult &MemberLookup)
14333 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14334 MemberLookup(MemberLookup) {}
14337 class MoveCastBuilder: public ExprBuilder {
14338 const ExprBuilder &Builder;
14340 public:
14341 Expr *build(Sema &S, SourceLocation Loc) const override {
14342 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14345 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14348 class LvalueConvBuilder: public ExprBuilder {
14349 const ExprBuilder &Builder;
14351 public:
14352 Expr *build(Sema &S, SourceLocation Loc) const override {
14353 return assertNotNull(
14354 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14357 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14360 class SubscriptBuilder: public ExprBuilder {
14361 const ExprBuilder &Base;
14362 const ExprBuilder &Index;
14364 public:
14365 Expr *build(Sema &S, SourceLocation Loc) const override {
14366 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14367 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14370 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14371 : Base(Base), Index(Index) {}
14374 } // end anonymous namespace
14376 /// When generating a defaulted copy or move assignment operator, if a field
14377 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14378 /// do so. This optimization only applies for arrays of scalars, and for arrays
14379 /// of class type where the selected copy/move-assignment operator is trivial.
14380 static StmtResult
14381 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14382 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14383 // Compute the size of the memory buffer to be copied.
14384 QualType SizeType = S.Context.getSizeType();
14385 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14386 S.Context.getTypeSizeInChars(T).getQuantity());
14388 // Take the address of the field references for "from" and "to". We
14389 // directly construct UnaryOperators here because semantic analysis
14390 // does not permit us to take the address of an xvalue.
14391 Expr *From = FromB.build(S, Loc);
14392 From = UnaryOperator::Create(
14393 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14394 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14395 Expr *To = ToB.build(S, Loc);
14396 To = UnaryOperator::Create(
14397 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14398 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14400 const Type *E = T->getBaseElementTypeUnsafe();
14401 bool NeedsCollectableMemCpy =
14402 E->isRecordType() &&
14403 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14405 // Create a reference to the __builtin_objc_memmove_collectable function
14406 StringRef MemCpyName = NeedsCollectableMemCpy ?
14407 "__builtin_objc_memmove_collectable" :
14408 "__builtin_memcpy";
14409 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14410 Sema::LookupOrdinaryName);
14411 S.LookupName(R, S.TUScope, true);
14413 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14414 if (!MemCpy)
14415 // Something went horribly wrong earlier, and we will have complained
14416 // about it.
14417 return StmtError();
14419 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14420 VK_PRValue, Loc, nullptr);
14421 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14423 Expr *CallArgs[] = {
14424 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14426 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14427 Loc, CallArgs, Loc);
14429 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14430 return Call.getAs<Stmt>();
14433 /// Builds a statement that copies/moves the given entity from \p From to
14434 /// \c To.
14436 /// This routine is used to copy/move the members of a class with an
14437 /// implicitly-declared copy/move assignment operator. When the entities being
14438 /// copied are arrays, this routine builds for loops to copy them.
14440 /// \param S The Sema object used for type-checking.
14442 /// \param Loc The location where the implicit copy/move is being generated.
14444 /// \param T The type of the expressions being copied/moved. Both expressions
14445 /// must have this type.
14447 /// \param To The expression we are copying/moving to.
14449 /// \param From The expression we are copying/moving from.
14451 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14452 /// Otherwise, it's a non-static member subobject.
14454 /// \param Copying Whether we're copying or moving.
14456 /// \param Depth Internal parameter recording the depth of the recursion.
14458 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14459 /// if a memcpy should be used instead.
14460 static StmtResult
14461 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14462 const ExprBuilder &To, const ExprBuilder &From,
14463 bool CopyingBaseSubobject, bool Copying,
14464 unsigned Depth = 0) {
14465 // C++11 [class.copy]p28:
14466 // Each subobject is assigned in the manner appropriate to its type:
14468 // - if the subobject is of class type, as if by a call to operator= with
14469 // the subobject as the object expression and the corresponding
14470 // subobject of x as a single function argument (as if by explicit
14471 // qualification; that is, ignoring any possible virtual overriding
14472 // functions in more derived classes);
14474 // C++03 [class.copy]p13:
14475 // - if the subobject is of class type, the copy assignment operator for
14476 // the class is used (as if by explicit qualification; that is,
14477 // ignoring any possible virtual overriding functions in more derived
14478 // classes);
14479 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14480 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14482 // Look for operator=.
14483 DeclarationName Name
14484 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14485 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14486 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14488 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14489 // operator.
14490 if (!S.getLangOpts().CPlusPlus11) {
14491 LookupResult::Filter F = OpLookup.makeFilter();
14492 while (F.hasNext()) {
14493 NamedDecl *D = F.next();
14494 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14495 if (Method->isCopyAssignmentOperator() ||
14496 (!Copying && Method->isMoveAssignmentOperator()))
14497 continue;
14499 F.erase();
14501 F.done();
14504 // Suppress the protected check (C++ [class.protected]) for each of the
14505 // assignment operators we found. This strange dance is required when
14506 // we're assigning via a base classes's copy-assignment operator. To
14507 // ensure that we're getting the right base class subobject (without
14508 // ambiguities), we need to cast "this" to that subobject type; to
14509 // ensure that we don't go through the virtual call mechanism, we need
14510 // to qualify the operator= name with the base class (see below). However,
14511 // this means that if the base class has a protected copy assignment
14512 // operator, the protected member access check will fail. So, we
14513 // rewrite "protected" access to "public" access in this case, since we
14514 // know by construction that we're calling from a derived class.
14515 if (CopyingBaseSubobject) {
14516 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14517 L != LEnd; ++L) {
14518 if (L.getAccess() == AS_protected)
14519 L.setAccess(AS_public);
14523 // Create the nested-name-specifier that will be used to qualify the
14524 // reference to operator=; this is required to suppress the virtual
14525 // call mechanism.
14526 CXXScopeSpec SS;
14527 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14528 SS.MakeTrivial(S.Context,
14529 NestedNameSpecifier::Create(S.Context, nullptr, false,
14530 CanonicalT),
14531 Loc);
14533 // Create the reference to operator=.
14534 ExprResult OpEqualRef
14535 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14536 SS, /*TemplateKWLoc=*/SourceLocation(),
14537 /*FirstQualifierInScope=*/nullptr,
14538 OpLookup,
14539 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14540 /*SuppressQualifierCheck=*/true);
14541 if (OpEqualRef.isInvalid())
14542 return StmtError();
14544 // Build the call to the assignment operator.
14546 Expr *FromInst = From.build(S, Loc);
14547 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14548 OpEqualRef.getAs<Expr>(),
14549 Loc, FromInst, Loc);
14550 if (Call.isInvalid())
14551 return StmtError();
14553 // If we built a call to a trivial 'operator=' while copying an array,
14554 // bail out. We'll replace the whole shebang with a memcpy.
14555 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14556 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14557 return StmtResult((Stmt*)nullptr);
14559 // Convert to an expression-statement, and clean up any produced
14560 // temporaries.
14561 return S.ActOnExprStmt(Call);
14564 // - if the subobject is of scalar type, the built-in assignment
14565 // operator is used.
14566 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14567 if (!ArrayTy) {
14568 ExprResult Assignment = S.CreateBuiltinBinOp(
14569 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14570 if (Assignment.isInvalid())
14571 return StmtError();
14572 return S.ActOnExprStmt(Assignment);
14575 // - if the subobject is an array, each element is assigned, in the
14576 // manner appropriate to the element type;
14578 // Construct a loop over the array bounds, e.g.,
14580 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14582 // that will copy each of the array elements.
14583 QualType SizeType = S.Context.getSizeType();
14585 // Create the iteration variable.
14586 IdentifierInfo *IterationVarName = nullptr;
14588 SmallString<8> Str;
14589 llvm::raw_svector_ostream OS(Str);
14590 OS << "__i" << Depth;
14591 IterationVarName = &S.Context.Idents.get(OS.str());
14593 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14594 IterationVarName, SizeType,
14595 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14596 SC_None);
14598 // Initialize the iteration variable to zero.
14599 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14600 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14602 // Creates a reference to the iteration variable.
14603 RefBuilder IterationVarRef(IterationVar, SizeType);
14604 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14606 // Create the DeclStmt that holds the iteration variable.
14607 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14609 // Subscript the "from" and "to" expressions with the iteration variable.
14610 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14611 MoveCastBuilder FromIndexMove(FromIndexCopy);
14612 const ExprBuilder *FromIndex;
14613 if (Copying)
14614 FromIndex = &FromIndexCopy;
14615 else
14616 FromIndex = &FromIndexMove;
14618 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14620 // Build the copy/move for an individual element of the array.
14621 StmtResult Copy =
14622 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14623 ToIndex, *FromIndex, CopyingBaseSubobject,
14624 Copying, Depth + 1);
14625 // Bail out if copying fails or if we determined that we should use memcpy.
14626 if (Copy.isInvalid() || !Copy.get())
14627 return Copy;
14629 // Create the comparison against the array bound.
14630 llvm::APInt Upper
14631 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14632 Expr *Comparison = BinaryOperator::Create(
14633 S.Context, IterationVarRefRVal.build(S, Loc),
14634 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14635 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14636 S.CurFPFeatureOverrides());
14638 // Create the pre-increment of the iteration variable. We can determine
14639 // whether the increment will overflow based on the value of the array
14640 // bound.
14641 Expr *Increment = UnaryOperator::Create(
14642 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14643 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14645 // Construct the loop that copies all elements of this array.
14646 return S.ActOnForStmt(
14647 Loc, Loc, InitStmt,
14648 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14649 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14652 static StmtResult
14653 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14654 const ExprBuilder &To, const ExprBuilder &From,
14655 bool CopyingBaseSubobject, bool Copying) {
14656 // Maybe we should use a memcpy?
14657 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14658 T.isTriviallyCopyableType(S.Context))
14659 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14661 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14662 CopyingBaseSubobject,
14663 Copying, 0));
14665 // If we ended up picking a trivial assignment operator for an array of a
14666 // non-trivially-copyable class type, just emit a memcpy.
14667 if (!Result.isInvalid() && !Result.get())
14668 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14670 return Result;
14673 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14674 // Note: The following rules are largely analoguous to the copy
14675 // constructor rules. Note that virtual bases are not taken into account
14676 // for determining the argument type of the operator. Note also that
14677 // operators taking an object instead of a reference are allowed.
14678 assert(ClassDecl->needsImplicitCopyAssignment());
14680 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14681 if (DSM.isAlreadyBeingDeclared())
14682 return nullptr;
14684 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14685 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
14686 LangAS AS = getDefaultCXXMethodAddrSpace();
14687 if (AS != LangAS::Default)
14688 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14689 QualType RetType = Context.getLValueReferenceType(ArgType);
14690 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14691 if (Const)
14692 ArgType = ArgType.withConst();
14694 ArgType = Context.getLValueReferenceType(ArgType);
14696 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14697 CXXCopyAssignment,
14698 Const);
14700 // An implicitly-declared copy assignment operator is an inline public
14701 // member of its class.
14702 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14703 SourceLocation ClassLoc = ClassDecl->getLocation();
14704 DeclarationNameInfo NameInfo(Name, ClassLoc);
14705 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14706 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14707 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14708 getCurFPFeatures().isFPConstrained(),
14709 /*isInline=*/true,
14710 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14711 SourceLocation());
14712 CopyAssignment->setAccess(AS_public);
14713 CopyAssignment->setDefaulted();
14714 CopyAssignment->setImplicit();
14716 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14718 if (getLangOpts().CUDA)
14719 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14720 CopyAssignment,
14721 /* ConstRHS */ Const,
14722 /* Diagnose */ false);
14724 // Add the parameter to the operator.
14725 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14726 ClassLoc, ClassLoc,
14727 /*Id=*/nullptr, ArgType,
14728 /*TInfo=*/nullptr, SC_None,
14729 nullptr);
14730 CopyAssignment->setParams(FromParam);
14732 CopyAssignment->setTrivial(
14733 ClassDecl->needsOverloadResolutionForCopyAssignment()
14734 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14735 : ClassDecl->hasTrivialCopyAssignment());
14737 // Note that we have added this copy-assignment operator.
14738 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14740 Scope *S = getScopeForContext(ClassDecl);
14741 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14743 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14744 ClassDecl->setImplicitCopyAssignmentIsDeleted();
14745 SetDeclDeleted(CopyAssignment, ClassLoc);
14748 if (S)
14749 PushOnScopeChains(CopyAssignment, S, false);
14750 ClassDecl->addDecl(CopyAssignment);
14752 return CopyAssignment;
14755 /// Diagnose an implicit copy operation for a class which is odr-used, but
14756 /// which is deprecated because the class has a user-declared copy constructor,
14757 /// copy assignment operator, or destructor.
14758 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14759 assert(CopyOp->isImplicit());
14761 CXXRecordDecl *RD = CopyOp->getParent();
14762 CXXMethodDecl *UserDeclaredOperation = nullptr;
14764 if (RD->hasUserDeclaredDestructor()) {
14765 UserDeclaredOperation = RD->getDestructor();
14766 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14767 RD->hasUserDeclaredCopyConstructor()) {
14768 // Find any user-declared copy constructor.
14769 for (auto *I : RD->ctors()) {
14770 if (I->isCopyConstructor()) {
14771 UserDeclaredOperation = I;
14772 break;
14775 assert(UserDeclaredOperation);
14776 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14777 RD->hasUserDeclaredCopyAssignment()) {
14778 // Find any user-declared move assignment operator.
14779 for (auto *I : RD->methods()) {
14780 if (I->isCopyAssignmentOperator()) {
14781 UserDeclaredOperation = I;
14782 break;
14785 assert(UserDeclaredOperation);
14788 if (UserDeclaredOperation) {
14789 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14790 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14791 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14792 unsigned DiagID =
14793 (UDOIsUserProvided && UDOIsDestructor)
14794 ? diag::warn_deprecated_copy_with_user_provided_dtor
14795 : (UDOIsUserProvided && !UDOIsDestructor)
14796 ? diag::warn_deprecated_copy_with_user_provided_copy
14797 : (!UDOIsUserProvided && UDOIsDestructor)
14798 ? diag::warn_deprecated_copy_with_dtor
14799 : diag::warn_deprecated_copy;
14800 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14801 << RD << IsCopyAssignment;
14805 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14806 CXXMethodDecl *CopyAssignOperator) {
14807 assert((CopyAssignOperator->isDefaulted() &&
14808 CopyAssignOperator->isOverloadedOperator() &&
14809 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14810 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14811 !CopyAssignOperator->isDeleted()) &&
14812 "DefineImplicitCopyAssignment called for wrong function");
14813 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14814 return;
14816 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14817 if (ClassDecl->isInvalidDecl()) {
14818 CopyAssignOperator->setInvalidDecl();
14819 return;
14822 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14824 // The exception specification is needed because we are defining the
14825 // function.
14826 ResolveExceptionSpec(CurrentLocation,
14827 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14829 // Add a context note for diagnostics produced after this point.
14830 Scope.addContextNote(CurrentLocation);
14832 // C++11 [class.copy]p18:
14833 // The [definition of an implicitly declared copy assignment operator] is
14834 // deprecated if the class has a user-declared copy constructor or a
14835 // user-declared destructor.
14836 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14837 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14839 // C++0x [class.copy]p30:
14840 // The implicitly-defined or explicitly-defaulted copy assignment operator
14841 // for a non-union class X performs memberwise copy assignment of its
14842 // subobjects. The direct base classes of X are assigned first, in the
14843 // order of their declaration in the base-specifier-list, and then the
14844 // immediate non-static data members of X are assigned, in the order in
14845 // which they were declared in the class definition.
14847 // The statements that form the synthesized function body.
14848 SmallVector<Stmt*, 8> Statements;
14850 // The parameter for the "other" object, which we are copying from.
14851 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14852 Qualifiers OtherQuals = Other->getType().getQualifiers();
14853 QualType OtherRefType = Other->getType();
14854 if (const LValueReferenceType *OtherRef
14855 = OtherRefType->getAs<LValueReferenceType>()) {
14856 OtherRefType = OtherRef->getPointeeType();
14857 OtherQuals = OtherRefType.getQualifiers();
14860 // Our location for everything implicitly-generated.
14861 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14862 ? CopyAssignOperator->getEndLoc()
14863 : CopyAssignOperator->getLocation();
14865 // Builds a DeclRefExpr for the "other" object.
14866 RefBuilder OtherRef(Other, OtherRefType);
14868 // Builds the "this" pointer.
14869 ThisBuilder This;
14871 // Assign base classes.
14872 bool Invalid = false;
14873 for (auto &Base : ClassDecl->bases()) {
14874 // Form the assignment:
14875 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14876 QualType BaseType = Base.getType().getUnqualifiedType();
14877 if (!BaseType->isRecordType()) {
14878 Invalid = true;
14879 continue;
14882 CXXCastPath BasePath;
14883 BasePath.push_back(&Base);
14885 // Construct the "from" expression, which is an implicit cast to the
14886 // appropriately-qualified base type.
14887 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14888 VK_LValue, BasePath);
14890 // Dereference "this".
14891 DerefBuilder DerefThis(This);
14892 CastBuilder To(DerefThis,
14893 Context.getQualifiedType(
14894 BaseType, CopyAssignOperator->getMethodQualifiers()),
14895 VK_LValue, BasePath);
14897 // Build the copy.
14898 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14899 To, From,
14900 /*CopyingBaseSubobject=*/true,
14901 /*Copying=*/true);
14902 if (Copy.isInvalid()) {
14903 CopyAssignOperator->setInvalidDecl();
14904 return;
14907 // Success! Record the copy.
14908 Statements.push_back(Copy.getAs<Expr>());
14911 // Assign non-static members.
14912 for (auto *Field : ClassDecl->fields()) {
14913 // FIXME: We should form some kind of AST representation for the implied
14914 // memcpy in a union copy operation.
14915 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14916 continue;
14918 if (Field->isInvalidDecl()) {
14919 Invalid = true;
14920 continue;
14923 // Check for members of reference type; we can't copy those.
14924 if (Field->getType()->isReferenceType()) {
14925 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14926 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14927 Diag(Field->getLocation(), diag::note_declared_at);
14928 Invalid = true;
14929 continue;
14932 // Check for members of const-qualified, non-class type.
14933 QualType BaseType = Context.getBaseElementType(Field->getType());
14934 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14935 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14936 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14937 Diag(Field->getLocation(), diag::note_declared_at);
14938 Invalid = true;
14939 continue;
14942 // Suppress assigning zero-width bitfields.
14943 if (Field->isZeroLengthBitField(Context))
14944 continue;
14946 QualType FieldType = Field->getType().getNonReferenceType();
14947 if (FieldType->isIncompleteArrayType()) {
14948 assert(ClassDecl->hasFlexibleArrayMember() &&
14949 "Incomplete array type is not valid");
14950 continue;
14953 // Build references to the field in the object we're copying from and to.
14954 CXXScopeSpec SS; // Intentionally empty
14955 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14956 LookupMemberName);
14957 MemberLookup.addDecl(Field);
14958 MemberLookup.resolveKind();
14960 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14962 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/!LangOpts.HLSL,
14963 MemberLookup);
14965 // Build the copy of this field.
14966 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14967 To, From,
14968 /*CopyingBaseSubobject=*/false,
14969 /*Copying=*/true);
14970 if (Copy.isInvalid()) {
14971 CopyAssignOperator->setInvalidDecl();
14972 return;
14975 // Success! Record the copy.
14976 Statements.push_back(Copy.getAs<Stmt>());
14979 if (!Invalid) {
14980 // Add a "return *this;"
14981 Expr *ThisExpr = nullptr;
14982 if (!LangOpts.HLSL) {
14983 ExprResult ThisObj =
14984 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14985 ThisExpr = ThisObj.get();
14986 } else {
14987 ThisExpr = This.build(*this, Loc);
14990 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
14991 if (Return.isInvalid())
14992 Invalid = true;
14993 else
14994 Statements.push_back(Return.getAs<Stmt>());
14997 if (Invalid) {
14998 CopyAssignOperator->setInvalidDecl();
14999 return;
15002 StmtResult Body;
15004 CompoundScopeRAII CompoundScope(*this);
15005 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15006 /*isStmtExpr=*/false);
15007 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15009 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15010 CopyAssignOperator->markUsed(Context);
15012 if (ASTMutationListener *L = getASTMutationListener()) {
15013 L->CompletedImplicitDefinition(CopyAssignOperator);
15017 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15018 assert(ClassDecl->needsImplicitMoveAssignment());
15020 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
15021 if (DSM.isAlreadyBeingDeclared())
15022 return nullptr;
15024 // Note: The following rules are largely analoguous to the move
15025 // constructor rules.
15027 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15028 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
15029 LangAS AS = getDefaultCXXMethodAddrSpace();
15030 if (AS != LangAS::Default)
15031 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15032 QualType RetType = Context.getLValueReferenceType(ArgType);
15033 ArgType = Context.getRValueReferenceType(ArgType);
15035 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15036 CXXMoveAssignment,
15037 false);
15039 // An implicitly-declared move assignment operator is an inline public
15040 // member of its class.
15041 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15042 SourceLocation ClassLoc = ClassDecl->getLocation();
15043 DeclarationNameInfo NameInfo(Name, ClassLoc);
15044 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15045 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15046 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15047 getCurFPFeatures().isFPConstrained(),
15048 /*isInline=*/true,
15049 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15050 SourceLocation());
15051 MoveAssignment->setAccess(AS_public);
15052 MoveAssignment->setDefaulted();
15053 MoveAssignment->setImplicit();
15055 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15057 if (getLangOpts().CUDA)
15058 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
15059 MoveAssignment,
15060 /* ConstRHS */ false,
15061 /* Diagnose */ false);
15063 // Add the parameter to the operator.
15064 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15065 ClassLoc, ClassLoc,
15066 /*Id=*/nullptr, ArgType,
15067 /*TInfo=*/nullptr, SC_None,
15068 nullptr);
15069 MoveAssignment->setParams(FromParam);
15071 MoveAssignment->setTrivial(
15072 ClassDecl->needsOverloadResolutionForMoveAssignment()
15073 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
15074 : ClassDecl->hasTrivialMoveAssignment());
15076 // Note that we have added this copy-assignment operator.
15077 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15079 Scope *S = getScopeForContext(ClassDecl);
15080 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15082 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
15083 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15084 SetDeclDeleted(MoveAssignment, ClassLoc);
15087 if (S)
15088 PushOnScopeChains(MoveAssignment, S, false);
15089 ClassDecl->addDecl(MoveAssignment);
15091 return MoveAssignment;
15094 /// Check if we're implicitly defining a move assignment operator for a class
15095 /// with virtual bases. Such a move assignment might move-assign the virtual
15096 /// base multiple times.
15097 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15098 SourceLocation CurrentLocation) {
15099 assert(!Class->isDependentContext() && "should not define dependent move");
15101 // Only a virtual base could get implicitly move-assigned multiple times.
15102 // Only a non-trivial move assignment can observe this. We only want to
15103 // diagnose if we implicitly define an assignment operator that assigns
15104 // two base classes, both of which move-assign the same virtual base.
15105 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15106 Class->getNumBases() < 2)
15107 return;
15109 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15110 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15111 VBaseMap VBases;
15113 for (auto &BI : Class->bases()) {
15114 Worklist.push_back(&BI);
15115 while (!Worklist.empty()) {
15116 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15117 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15119 // If the base has no non-trivial move assignment operators,
15120 // we don't care about moves from it.
15121 if (!Base->hasNonTrivialMoveAssignment())
15122 continue;
15124 // If there's nothing virtual here, skip it.
15125 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15126 continue;
15128 // If we're not actually going to call a move assignment for this base,
15129 // or the selected move assignment is trivial, skip it.
15130 Sema::SpecialMemberOverloadResult SMOR =
15131 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
15132 /*ConstArg*/false, /*VolatileArg*/false,
15133 /*RValueThis*/true, /*ConstThis*/false,
15134 /*VolatileThis*/false);
15135 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15136 !SMOR.getMethod()->isMoveAssignmentOperator())
15137 continue;
15139 if (BaseSpec->isVirtual()) {
15140 // We're going to move-assign this virtual base, and its move
15141 // assignment operator is not trivial. If this can happen for
15142 // multiple distinct direct bases of Class, diagnose it. (If it
15143 // only happens in one base, we'll diagnose it when synthesizing
15144 // that base class's move assignment operator.)
15145 CXXBaseSpecifier *&Existing =
15146 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15147 .first->second;
15148 if (Existing && Existing != &BI) {
15149 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15150 << Class << Base;
15151 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15152 << (Base->getCanonicalDecl() ==
15153 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15154 << Base << Existing->getType() << Existing->getSourceRange();
15155 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15156 << (Base->getCanonicalDecl() ==
15157 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15158 << Base << BI.getType() << BaseSpec->getSourceRange();
15160 // Only diagnose each vbase once.
15161 Existing = nullptr;
15163 } else {
15164 // Only walk over bases that have defaulted move assignment operators.
15165 // We assume that any user-provided move assignment operator handles
15166 // the multiple-moves-of-vbase case itself somehow.
15167 if (!SMOR.getMethod()->isDefaulted())
15168 continue;
15170 // We're going to move the base classes of Base. Add them to the list.
15171 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15177 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15178 CXXMethodDecl *MoveAssignOperator) {
15179 assert((MoveAssignOperator->isDefaulted() &&
15180 MoveAssignOperator->isOverloadedOperator() &&
15181 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15182 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15183 !MoveAssignOperator->isDeleted()) &&
15184 "DefineImplicitMoveAssignment called for wrong function");
15185 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15186 return;
15188 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15189 if (ClassDecl->isInvalidDecl()) {
15190 MoveAssignOperator->setInvalidDecl();
15191 return;
15194 // C++0x [class.copy]p28:
15195 // The implicitly-defined or move assignment operator for a non-union class
15196 // X performs memberwise move assignment of its subobjects. The direct base
15197 // classes of X are assigned first, in the order of their declaration in the
15198 // base-specifier-list, and then the immediate non-static data members of X
15199 // are assigned, in the order in which they were declared in the class
15200 // definition.
15202 // Issue a warning if our implicit move assignment operator will move
15203 // from a virtual base more than once.
15204 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15206 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15208 // The exception specification is needed because we are defining the
15209 // function.
15210 ResolveExceptionSpec(CurrentLocation,
15211 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15213 // Add a context note for diagnostics produced after this point.
15214 Scope.addContextNote(CurrentLocation);
15216 // The statements that form the synthesized function body.
15217 SmallVector<Stmt*, 8> Statements;
15219 // The parameter for the "other" object, which we are move from.
15220 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
15221 QualType OtherRefType =
15222 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15224 // Our location for everything implicitly-generated.
15225 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15226 ? MoveAssignOperator->getEndLoc()
15227 : MoveAssignOperator->getLocation();
15229 // Builds a reference to the "other" object.
15230 RefBuilder OtherRef(Other, OtherRefType);
15231 // Cast to rvalue.
15232 MoveCastBuilder MoveOther(OtherRef);
15234 // Builds the "this" pointer.
15235 ThisBuilder This;
15237 // Assign base classes.
15238 bool Invalid = false;
15239 for (auto &Base : ClassDecl->bases()) {
15240 // C++11 [class.copy]p28:
15241 // It is unspecified whether subobjects representing virtual base classes
15242 // are assigned more than once by the implicitly-defined copy assignment
15243 // operator.
15244 // FIXME: Do not assign to a vbase that will be assigned by some other base
15245 // class. For a move-assignment, this can result in the vbase being moved
15246 // multiple times.
15248 // Form the assignment:
15249 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15250 QualType BaseType = Base.getType().getUnqualifiedType();
15251 if (!BaseType->isRecordType()) {
15252 Invalid = true;
15253 continue;
15256 CXXCastPath BasePath;
15257 BasePath.push_back(&Base);
15259 // Construct the "from" expression, which is an implicit cast to the
15260 // appropriately-qualified base type.
15261 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15263 // Dereference "this".
15264 DerefBuilder DerefThis(This);
15266 // Implicitly cast "this" to the appropriately-qualified base type.
15267 CastBuilder To(DerefThis,
15268 Context.getQualifiedType(
15269 BaseType, MoveAssignOperator->getMethodQualifiers()),
15270 VK_LValue, BasePath);
15272 // Build the move.
15273 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15274 To, From,
15275 /*CopyingBaseSubobject=*/true,
15276 /*Copying=*/false);
15277 if (Move.isInvalid()) {
15278 MoveAssignOperator->setInvalidDecl();
15279 return;
15282 // Success! Record the move.
15283 Statements.push_back(Move.getAs<Expr>());
15286 // Assign non-static members.
15287 for (auto *Field : ClassDecl->fields()) {
15288 // FIXME: We should form some kind of AST representation for the implied
15289 // memcpy in a union copy operation.
15290 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15291 continue;
15293 if (Field->isInvalidDecl()) {
15294 Invalid = true;
15295 continue;
15298 // Check for members of reference type; we can't move those.
15299 if (Field->getType()->isReferenceType()) {
15300 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15301 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15302 Diag(Field->getLocation(), diag::note_declared_at);
15303 Invalid = true;
15304 continue;
15307 // Check for members of const-qualified, non-class type.
15308 QualType BaseType = Context.getBaseElementType(Field->getType());
15309 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15310 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15311 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15312 Diag(Field->getLocation(), diag::note_declared_at);
15313 Invalid = true;
15314 continue;
15317 // Suppress assigning zero-width bitfields.
15318 if (Field->isZeroLengthBitField(Context))
15319 continue;
15321 QualType FieldType = Field->getType().getNonReferenceType();
15322 if (FieldType->isIncompleteArrayType()) {
15323 assert(ClassDecl->hasFlexibleArrayMember() &&
15324 "Incomplete array type is not valid");
15325 continue;
15328 // Build references to the field in the object we're copying from and to.
15329 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15330 LookupMemberName);
15331 MemberLookup.addDecl(Field);
15332 MemberLookup.resolveKind();
15333 MemberBuilder From(MoveOther, OtherRefType,
15334 /*IsArrow=*/false, MemberLookup);
15335 MemberBuilder To(This, getCurrentThisType(),
15336 /*IsArrow=*/true, MemberLookup);
15338 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15339 "Member reference with rvalue base must be rvalue except for reference "
15340 "members, which aren't allowed for move assignment.");
15342 // Build the move of this field.
15343 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15344 To, From,
15345 /*CopyingBaseSubobject=*/false,
15346 /*Copying=*/false);
15347 if (Move.isInvalid()) {
15348 MoveAssignOperator->setInvalidDecl();
15349 return;
15352 // Success! Record the copy.
15353 Statements.push_back(Move.getAs<Stmt>());
15356 if (!Invalid) {
15357 // Add a "return *this;"
15358 ExprResult ThisObj =
15359 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
15361 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15362 if (Return.isInvalid())
15363 Invalid = true;
15364 else
15365 Statements.push_back(Return.getAs<Stmt>());
15368 if (Invalid) {
15369 MoveAssignOperator->setInvalidDecl();
15370 return;
15373 StmtResult Body;
15375 CompoundScopeRAII CompoundScope(*this);
15376 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15377 /*isStmtExpr=*/false);
15378 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15380 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15381 MoveAssignOperator->markUsed(Context);
15383 if (ASTMutationListener *L = getASTMutationListener()) {
15384 L->CompletedImplicitDefinition(MoveAssignOperator);
15388 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15389 CXXRecordDecl *ClassDecl) {
15390 // C++ [class.copy]p4:
15391 // If the class definition does not explicitly declare a copy
15392 // constructor, one is declared implicitly.
15393 assert(ClassDecl->needsImplicitCopyConstructor());
15395 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15396 if (DSM.isAlreadyBeingDeclared())
15397 return nullptr;
15399 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15400 QualType ArgType = ClassType;
15401 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
15402 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15403 if (Const)
15404 ArgType = ArgType.withConst();
15406 LangAS AS = getDefaultCXXMethodAddrSpace();
15407 if (AS != LangAS::Default)
15408 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15410 ArgType = Context.getLValueReferenceType(ArgType);
15412 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15413 CXXCopyConstructor,
15414 Const);
15416 DeclarationName Name
15417 = Context.DeclarationNames.getCXXConstructorName(
15418 Context.getCanonicalType(ClassType));
15419 SourceLocation ClassLoc = ClassDecl->getLocation();
15420 DeclarationNameInfo NameInfo(Name, ClassLoc);
15422 // An implicitly-declared copy constructor is an inline public
15423 // member of its class.
15424 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15425 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15426 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15427 /*isInline=*/true,
15428 /*isImplicitlyDeclared=*/true,
15429 Constexpr ? ConstexprSpecKind::Constexpr
15430 : ConstexprSpecKind::Unspecified);
15431 CopyConstructor->setAccess(AS_public);
15432 CopyConstructor->setDefaulted();
15434 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15436 if (getLangOpts().CUDA)
15437 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15438 CopyConstructor,
15439 /* ConstRHS */ Const,
15440 /* Diagnose */ false);
15442 // During template instantiation of special member functions we need a
15443 // reliable TypeSourceInfo for the parameter types in order to allow functions
15444 // to be substituted.
15445 TypeSourceInfo *TSI = nullptr;
15446 if (inTemplateInstantiation() && ClassDecl->isLambda())
15447 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15449 // Add the parameter to the constructor.
15450 ParmVarDecl *FromParam =
15451 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15452 /*IdentifierInfo=*/nullptr, ArgType,
15453 /*TInfo=*/TSI, SC_None, nullptr);
15454 CopyConstructor->setParams(FromParam);
15456 CopyConstructor->setTrivial(
15457 ClassDecl->needsOverloadResolutionForCopyConstructor()
15458 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15459 : ClassDecl->hasTrivialCopyConstructor());
15461 CopyConstructor->setTrivialForCall(
15462 ClassDecl->hasAttr<TrivialABIAttr>() ||
15463 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15464 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15465 TAH_ConsiderTrivialABI)
15466 : ClassDecl->hasTrivialCopyConstructorForCall()));
15468 // Note that we have declared this constructor.
15469 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15471 Scope *S = getScopeForContext(ClassDecl);
15472 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15474 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15475 ClassDecl->setImplicitCopyConstructorIsDeleted();
15476 SetDeclDeleted(CopyConstructor, ClassLoc);
15479 if (S)
15480 PushOnScopeChains(CopyConstructor, S, false);
15481 ClassDecl->addDecl(CopyConstructor);
15483 return CopyConstructor;
15486 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15487 CXXConstructorDecl *CopyConstructor) {
15488 assert((CopyConstructor->isDefaulted() &&
15489 CopyConstructor->isCopyConstructor() &&
15490 !CopyConstructor->doesThisDeclarationHaveABody() &&
15491 !CopyConstructor->isDeleted()) &&
15492 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15493 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15494 return;
15496 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15497 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15499 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15501 // The exception specification is needed because we are defining the
15502 // function.
15503 ResolveExceptionSpec(CurrentLocation,
15504 CopyConstructor->getType()->castAs<FunctionProtoType>());
15505 MarkVTableUsed(CurrentLocation, ClassDecl);
15507 // Add a context note for diagnostics produced after this point.
15508 Scope.addContextNote(CurrentLocation);
15510 // C++11 [class.copy]p7:
15511 // The [definition of an implicitly declared copy constructor] is
15512 // deprecated if the class has a user-declared copy assignment operator
15513 // or a user-declared destructor.
15514 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15515 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15517 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15518 CopyConstructor->setInvalidDecl();
15519 } else {
15520 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15521 ? CopyConstructor->getEndLoc()
15522 : CopyConstructor->getLocation();
15523 Sema::CompoundScopeRAII CompoundScope(*this);
15524 CopyConstructor->setBody(
15525 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15526 .getAs<Stmt>());
15527 CopyConstructor->markUsed(Context);
15530 if (ASTMutationListener *L = getASTMutationListener()) {
15531 L->CompletedImplicitDefinition(CopyConstructor);
15535 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15536 CXXRecordDecl *ClassDecl) {
15537 assert(ClassDecl->needsImplicitMoveConstructor());
15539 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15540 if (DSM.isAlreadyBeingDeclared())
15541 return nullptr;
15543 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15545 QualType ArgType = ClassType;
15546 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
15547 LangAS AS = getDefaultCXXMethodAddrSpace();
15548 if (AS != LangAS::Default)
15549 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15550 ArgType = Context.getRValueReferenceType(ArgType);
15552 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15553 CXXMoveConstructor,
15554 false);
15556 DeclarationName Name
15557 = Context.DeclarationNames.getCXXConstructorName(
15558 Context.getCanonicalType(ClassType));
15559 SourceLocation ClassLoc = ClassDecl->getLocation();
15560 DeclarationNameInfo NameInfo(Name, ClassLoc);
15562 // C++11 [class.copy]p11:
15563 // An implicitly-declared copy/move constructor is an inline public
15564 // member of its class.
15565 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15566 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15567 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15568 /*isInline=*/true,
15569 /*isImplicitlyDeclared=*/true,
15570 Constexpr ? ConstexprSpecKind::Constexpr
15571 : ConstexprSpecKind::Unspecified);
15572 MoveConstructor->setAccess(AS_public);
15573 MoveConstructor->setDefaulted();
15575 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15577 if (getLangOpts().CUDA)
15578 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15579 MoveConstructor,
15580 /* ConstRHS */ false,
15581 /* Diagnose */ false);
15583 // Add the parameter to the constructor.
15584 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15585 ClassLoc, ClassLoc,
15586 /*IdentifierInfo=*/nullptr,
15587 ArgType, /*TInfo=*/nullptr,
15588 SC_None, nullptr);
15589 MoveConstructor->setParams(FromParam);
15591 MoveConstructor->setTrivial(
15592 ClassDecl->needsOverloadResolutionForMoveConstructor()
15593 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15594 : ClassDecl->hasTrivialMoveConstructor());
15596 MoveConstructor->setTrivialForCall(
15597 ClassDecl->hasAttr<TrivialABIAttr>() ||
15598 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15599 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15600 TAH_ConsiderTrivialABI)
15601 : ClassDecl->hasTrivialMoveConstructorForCall()));
15603 // Note that we have declared this constructor.
15604 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15606 Scope *S = getScopeForContext(ClassDecl);
15607 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15609 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15610 ClassDecl->setImplicitMoveConstructorIsDeleted();
15611 SetDeclDeleted(MoveConstructor, ClassLoc);
15614 if (S)
15615 PushOnScopeChains(MoveConstructor, S, false);
15616 ClassDecl->addDecl(MoveConstructor);
15618 return MoveConstructor;
15621 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15622 CXXConstructorDecl *MoveConstructor) {
15623 assert((MoveConstructor->isDefaulted() &&
15624 MoveConstructor->isMoveConstructor() &&
15625 !MoveConstructor->doesThisDeclarationHaveABody() &&
15626 !MoveConstructor->isDeleted()) &&
15627 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15628 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15629 return;
15631 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15632 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15634 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15636 // The exception specification is needed because we are defining the
15637 // function.
15638 ResolveExceptionSpec(CurrentLocation,
15639 MoveConstructor->getType()->castAs<FunctionProtoType>());
15640 MarkVTableUsed(CurrentLocation, ClassDecl);
15642 // Add a context note for diagnostics produced after this point.
15643 Scope.addContextNote(CurrentLocation);
15645 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15646 MoveConstructor->setInvalidDecl();
15647 } else {
15648 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15649 ? MoveConstructor->getEndLoc()
15650 : MoveConstructor->getLocation();
15651 Sema::CompoundScopeRAII CompoundScope(*this);
15652 MoveConstructor->setBody(
15653 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15654 .getAs<Stmt>());
15655 MoveConstructor->markUsed(Context);
15658 if (ASTMutationListener *L = getASTMutationListener()) {
15659 L->CompletedImplicitDefinition(MoveConstructor);
15663 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15664 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15667 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15668 SourceLocation CurrentLocation,
15669 CXXConversionDecl *Conv) {
15670 SynthesizedFunctionScope Scope(*this, Conv);
15671 assert(!Conv->getReturnType()->isUndeducedType());
15673 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15674 CallingConv CC =
15675 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15677 CXXRecordDecl *Lambda = Conv->getParent();
15678 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15679 FunctionDecl *Invoker =
15680 CallOp->isStatic() ? CallOp : Lambda->getLambdaStaticInvoker(CC);
15682 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15683 CallOp = InstantiateFunctionDeclaration(
15684 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15685 if (!CallOp)
15686 return;
15688 if (CallOp != Invoker) {
15689 Invoker = InstantiateFunctionDeclaration(
15690 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15691 CurrentLocation);
15692 if (!Invoker)
15693 return;
15697 if (CallOp->isInvalidDecl())
15698 return;
15700 // Mark the call operator referenced (and add to pending instantiations
15701 // if necessary).
15702 // For both the conversion and static-invoker template specializations
15703 // we construct their body's in this function, so no need to add them
15704 // to the PendingInstantiations.
15705 MarkFunctionReferenced(CurrentLocation, CallOp);
15707 if (Invoker != CallOp) {
15708 // Fill in the __invoke function with a dummy implementation. IR generation
15709 // will fill in the actual details. Update its type in case it contained
15710 // an 'auto'.
15711 Invoker->markUsed(Context);
15712 Invoker->setReferenced();
15713 Invoker->setType(Conv->getReturnType()->getPointeeType());
15714 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15717 // Construct the body of the conversion function { return __invoke; }.
15718 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15719 Conv->getLocation());
15720 assert(FunctionRef && "Can't refer to __invoke function?");
15721 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15722 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15723 Conv->getLocation(), Conv->getLocation()));
15724 Conv->markUsed(Context);
15725 Conv->setReferenced();
15727 if (ASTMutationListener *L = getASTMutationListener()) {
15728 L->CompletedImplicitDefinition(Conv);
15729 if (Invoker != CallOp)
15730 L->CompletedImplicitDefinition(Invoker);
15734 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15735 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15736 assert(!Conv->getParent()->isGenericLambda());
15738 SynthesizedFunctionScope Scope(*this, Conv);
15740 // Copy-initialize the lambda object as needed to capture it.
15741 Expr *This = ActOnCXXThis(CurrentLocation).get();
15742 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15744 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15745 Conv->getLocation(),
15746 Conv, DerefThis);
15748 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15749 // behavior. Note that only the general conversion function does this
15750 // (since it's unusable otherwise); in the case where we inline the
15751 // block literal, it has block literal lifetime semantics.
15752 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15753 BuildBlock = ImplicitCastExpr::Create(
15754 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15755 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15757 if (BuildBlock.isInvalid()) {
15758 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15759 Conv->setInvalidDecl();
15760 return;
15763 // Create the return statement that returns the block from the conversion
15764 // function.
15765 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15766 if (Return.isInvalid()) {
15767 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15768 Conv->setInvalidDecl();
15769 return;
15772 // Set the body of the conversion function.
15773 Stmt *ReturnS = Return.get();
15774 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15775 Conv->getLocation(), Conv->getLocation()));
15776 Conv->markUsed(Context);
15778 // We're done; notify the mutation listener, if any.
15779 if (ASTMutationListener *L = getASTMutationListener()) {
15780 L->CompletedImplicitDefinition(Conv);
15784 /// Determine whether the given list arguments contains exactly one
15785 /// "real" (non-default) argument.
15786 static bool hasOneRealArgument(MultiExprArg Args) {
15787 switch (Args.size()) {
15788 case 0:
15789 return false;
15791 default:
15792 if (!Args[1]->isDefaultArgument())
15793 return false;
15795 [[fallthrough]];
15796 case 1:
15797 return !Args[0]->isDefaultArgument();
15800 return false;
15803 ExprResult
15804 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15805 NamedDecl *FoundDecl,
15806 CXXConstructorDecl *Constructor,
15807 MultiExprArg ExprArgs,
15808 bool HadMultipleCandidates,
15809 bool IsListInitialization,
15810 bool IsStdInitListInitialization,
15811 bool RequiresZeroInit,
15812 unsigned ConstructKind,
15813 SourceRange ParenRange) {
15814 bool Elidable = false;
15816 // C++0x [class.copy]p34:
15817 // When certain criteria are met, an implementation is allowed to
15818 // omit the copy/move construction of a class object, even if the
15819 // copy/move constructor and/or destructor for the object have
15820 // side effects. [...]
15821 // - when a temporary class object that has not been bound to a
15822 // reference (12.2) would be copied/moved to a class object
15823 // with the same cv-unqualified type, the copy/move operation
15824 // can be omitted by constructing the temporary object
15825 // directly into the target of the omitted copy/move
15826 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15827 // FIXME: Converting constructors should also be accepted.
15828 // But to fix this, the logic that digs down into a CXXConstructExpr
15829 // to find the source object needs to handle it.
15830 // Right now it assumes the source object is passed directly as the
15831 // first argument.
15832 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15833 Expr *SubExpr = ExprArgs[0];
15834 // FIXME: Per above, this is also incorrect if we want to accept
15835 // converting constructors, as isTemporaryObject will
15836 // reject temporaries with different type from the
15837 // CXXRecord itself.
15838 Elidable = SubExpr->isTemporaryObject(
15839 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15842 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15843 FoundDecl, Constructor,
15844 Elidable, ExprArgs, HadMultipleCandidates,
15845 IsListInitialization,
15846 IsStdInitListInitialization, RequiresZeroInit,
15847 ConstructKind, ParenRange);
15850 ExprResult
15851 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15852 NamedDecl *FoundDecl,
15853 CXXConstructorDecl *Constructor,
15854 bool Elidable,
15855 MultiExprArg ExprArgs,
15856 bool HadMultipleCandidates,
15857 bool IsListInitialization,
15858 bool IsStdInitListInitialization,
15859 bool RequiresZeroInit,
15860 unsigned ConstructKind,
15861 SourceRange ParenRange) {
15862 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15863 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15864 // The only way to get here is if we did overlaod resolution to find the
15865 // shadow decl, so we don't need to worry about re-checking the trailing
15866 // requires clause.
15867 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15868 return ExprError();
15871 return BuildCXXConstructExpr(
15872 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15873 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15874 RequiresZeroInit, ConstructKind, ParenRange);
15877 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15878 /// including handling of its default argument expressions.
15879 ExprResult
15880 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15881 CXXConstructorDecl *Constructor,
15882 bool Elidable,
15883 MultiExprArg ExprArgs,
15884 bool HadMultipleCandidates,
15885 bool IsListInitialization,
15886 bool IsStdInitListInitialization,
15887 bool RequiresZeroInit,
15888 unsigned ConstructKind,
15889 SourceRange ParenRange) {
15890 assert(declaresSameEntity(
15891 Constructor->getParent(),
15892 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15893 "given constructor for wrong type");
15894 MarkFunctionReferenced(ConstructLoc, Constructor);
15895 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15896 return ExprError();
15898 return CheckForImmediateInvocation(
15899 CXXConstructExpr::Create(
15900 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15901 HadMultipleCandidates, IsListInitialization,
15902 IsStdInitListInitialization, RequiresZeroInit,
15903 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15904 ParenRange),
15905 Constructor);
15908 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15909 if (VD->isInvalidDecl()) return;
15910 // If initializing the variable failed, don't also diagnose problems with
15911 // the destructor, they're likely related.
15912 if (VD->getInit() && VD->getInit()->containsErrors())
15913 return;
15915 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15916 if (ClassDecl->isInvalidDecl()) return;
15917 if (ClassDecl->hasIrrelevantDestructor()) return;
15918 if (ClassDecl->isDependentContext()) return;
15920 if (VD->isNoDestroy(getASTContext()))
15921 return;
15923 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15924 // The result of `LookupDestructor` might be nullptr if the destructor is
15925 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
15926 // will not be selected by `CXXRecordDecl::getDestructor()`.
15927 if (!Destructor)
15928 return;
15929 // If this is an array, we'll require the destructor during initialization, so
15930 // we can skip over this. We still want to emit exit-time destructor warnings
15931 // though.
15932 if (!VD->getType()->isArrayType()) {
15933 MarkFunctionReferenced(VD->getLocation(), Destructor);
15934 CheckDestructorAccess(VD->getLocation(), Destructor,
15935 PDiag(diag::err_access_dtor_var)
15936 << VD->getDeclName() << VD->getType());
15937 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15940 if (Destructor->isTrivial()) return;
15942 // If the destructor is constexpr, check whether the variable has constant
15943 // destruction now.
15944 if (Destructor->isConstexpr()) {
15945 bool HasConstantInit = false;
15946 if (VD->getInit() && !VD->getInit()->isValueDependent())
15947 HasConstantInit = VD->evaluateValue();
15948 SmallVector<PartialDiagnosticAt, 8> Notes;
15949 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15950 HasConstantInit) {
15951 Diag(VD->getLocation(),
15952 diag::err_constexpr_var_requires_const_destruction) << VD;
15953 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15954 Diag(Notes[I].first, Notes[I].second);
15958 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
15959 return;
15961 // Emit warning for non-trivial dtor in global scope (a real global,
15962 // class-static, function-static).
15963 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15965 // TODO: this should be re-enabled for static locals by !CXAAtExit
15966 if (!VD->isStaticLocal())
15967 Diag(VD->getLocation(), diag::warn_global_destructor);
15970 /// Given a constructor and the set of arguments provided for the
15971 /// constructor, convert the arguments and add any required default arguments
15972 /// to form a proper call to this constructor.
15974 /// \returns true if an error occurred, false otherwise.
15975 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15976 QualType DeclInitType, MultiExprArg ArgsPtr,
15977 SourceLocation Loc,
15978 SmallVectorImpl<Expr *> &ConvertedArgs,
15979 bool AllowExplicit,
15980 bool IsListInitialization) {
15981 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15982 unsigned NumArgs = ArgsPtr.size();
15983 Expr **Args = ArgsPtr.data();
15985 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15986 unsigned NumParams = Proto->getNumParams();
15988 // If too few arguments are available, we'll fill in the rest with defaults.
15989 if (NumArgs < NumParams)
15990 ConvertedArgs.reserve(NumParams);
15991 else
15992 ConvertedArgs.reserve(NumArgs);
15994 VariadicCallType CallType =
15995 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15996 SmallVector<Expr *, 8> AllArgs;
15997 bool Invalid = GatherArgumentsForCall(
15998 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
15999 CallType, AllowExplicit, IsListInitialization);
16000 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16002 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16004 CheckConstructorCall(Constructor, DeclInitType,
16005 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16006 Loc);
16008 return Invalid;
16011 static inline bool
16012 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16013 const FunctionDecl *FnDecl) {
16014 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16015 if (isa<NamespaceDecl>(DC)) {
16016 return SemaRef.Diag(FnDecl->getLocation(),
16017 diag::err_operator_new_delete_declared_in_namespace)
16018 << FnDecl->getDeclName();
16021 if (isa<TranslationUnitDecl>(DC) &&
16022 FnDecl->getStorageClass() == SC_Static) {
16023 return SemaRef.Diag(FnDecl->getLocation(),
16024 diag::err_operator_new_delete_declared_static)
16025 << FnDecl->getDeclName();
16028 return false;
16031 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16032 const PointerType *PtrTy) {
16033 auto &Ctx = SemaRef.Context;
16034 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16035 PtrQuals.removeAddressSpace();
16036 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16037 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16040 static inline bool
16041 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
16042 CanQualType ExpectedResultType,
16043 CanQualType ExpectedFirstParamType,
16044 unsigned DependentParamTypeDiag,
16045 unsigned InvalidParamTypeDiag) {
16046 QualType ResultType =
16047 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16049 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16050 // The operator is valid on any address space for OpenCL.
16051 // Drop address space from actual and expected result types.
16052 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16053 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16055 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16056 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16059 // Check that the result type is what we expect.
16060 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16061 // Reject even if the type is dependent; an operator delete function is
16062 // required to have a non-dependent result type.
16063 return SemaRef.Diag(
16064 FnDecl->getLocation(),
16065 ResultType->isDependentType()
16066 ? diag::err_operator_new_delete_dependent_result_type
16067 : diag::err_operator_new_delete_invalid_result_type)
16068 << FnDecl->getDeclName() << ExpectedResultType;
16071 // A function template must have at least 2 parameters.
16072 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16073 return SemaRef.Diag(FnDecl->getLocation(),
16074 diag::err_operator_new_delete_template_too_few_parameters)
16075 << FnDecl->getDeclName();
16077 // The function decl must have at least 1 parameter.
16078 if (FnDecl->getNumParams() == 0)
16079 return SemaRef.Diag(FnDecl->getLocation(),
16080 diag::err_operator_new_delete_too_few_parameters)
16081 << FnDecl->getDeclName();
16083 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16084 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16085 // The operator is valid on any address space for OpenCL.
16086 // Drop address space from actual and expected first parameter types.
16087 if (const auto *PtrTy =
16088 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16089 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16091 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16092 ExpectedFirstParamType =
16093 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16096 // Check that the first parameter type is what we expect.
16097 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16098 ExpectedFirstParamType) {
16099 // The first parameter type is not allowed to be dependent. As a tentative
16100 // DR resolution, we allow a dependent parameter type if it is the right
16101 // type anyway, to allow destroying operator delete in class templates.
16102 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16103 ? DependentParamTypeDiag
16104 : InvalidParamTypeDiag)
16105 << FnDecl->getDeclName() << ExpectedFirstParamType;
16108 return false;
16111 static bool
16112 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
16113 // C++ [basic.stc.dynamic.allocation]p1:
16114 // A program is ill-formed if an allocation function is declared in a
16115 // namespace scope other than global scope or declared static in global
16116 // scope.
16117 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16118 return true;
16120 CanQualType SizeTy =
16121 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16123 // C++ [basic.stc.dynamic.allocation]p1:
16124 // The return type shall be void*. The first parameter shall have type
16125 // std::size_t.
16126 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
16127 SizeTy,
16128 diag::err_operator_new_dependent_param_type,
16129 diag::err_operator_new_param_type))
16130 return true;
16132 // C++ [basic.stc.dynamic.allocation]p1:
16133 // The first parameter shall not have an associated default argument.
16134 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16135 return SemaRef.Diag(FnDecl->getLocation(),
16136 diag::err_operator_new_default_arg)
16137 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16139 return false;
16142 static bool
16143 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16144 // C++ [basic.stc.dynamic.deallocation]p1:
16145 // A program is ill-formed if deallocation functions are declared in a
16146 // namespace scope other than global scope or declared static in global
16147 // scope.
16148 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16149 return true;
16151 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16153 // C++ P0722:
16154 // Within a class C, the first parameter of a destroying operator delete
16155 // shall be of type C *. The first parameter of any other deallocation
16156 // function shall be of type void *.
16157 CanQualType ExpectedFirstParamType =
16158 MD && MD->isDestroyingOperatorDelete()
16159 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16160 SemaRef.Context.getRecordType(MD->getParent())))
16161 : SemaRef.Context.VoidPtrTy;
16163 // C++ [basic.stc.dynamic.deallocation]p2:
16164 // Each deallocation function shall return void
16165 if (CheckOperatorNewDeleteTypes(
16166 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16167 diag::err_operator_delete_dependent_param_type,
16168 diag::err_operator_delete_param_type))
16169 return true;
16171 // C++ P0722:
16172 // A destroying operator delete shall be a usual deallocation function.
16173 if (MD && !MD->getParent()->isDependentContext() &&
16174 MD->isDestroyingOperatorDelete() &&
16175 !SemaRef.isUsualDeallocationFunction(MD)) {
16176 SemaRef.Diag(MD->getLocation(),
16177 diag::err_destroying_operator_delete_not_usual);
16178 return true;
16181 return false;
16184 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
16185 /// of this overloaded operator is well-formed. If so, returns false;
16186 /// otherwise, emits appropriate diagnostics and returns true.
16187 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16188 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16189 "Expected an overloaded operator declaration");
16191 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16193 // C++ [over.oper]p5:
16194 // The allocation and deallocation functions, operator new,
16195 // operator new[], operator delete and operator delete[], are
16196 // described completely in 3.7.3. The attributes and restrictions
16197 // found in the rest of this subclause do not apply to them unless
16198 // explicitly stated in 3.7.3.
16199 if (Op == OO_Delete || Op == OO_Array_Delete)
16200 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16202 if (Op == OO_New || Op == OO_Array_New)
16203 return CheckOperatorNewDeclaration(*this, FnDecl);
16205 // C++ [over.oper]p7:
16206 // An operator function shall either be a member function or
16207 // be a non-member function and have at least one parameter
16208 // whose type is a class, a reference to a class, an enumeration,
16209 // or a reference to an enumeration.
16210 // Note: Before C++23, a member function could not be static. The only member
16211 // function allowed to be static is the call operator function.
16212 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16213 if (MethodDecl->isStatic()) {
16214 if (Op == OO_Call || Op == OO_Subscript)
16215 Diag(FnDecl->getLocation(),
16216 (LangOpts.CPlusPlus23
16217 ? diag::warn_cxx20_compat_operator_overload_static
16218 : diag::ext_operator_overload_static))
16219 << FnDecl;
16220 else
16221 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16222 << FnDecl;
16224 } else {
16225 bool ClassOrEnumParam = false;
16226 for (auto *Param : FnDecl->parameters()) {
16227 QualType ParamType = Param->getType().getNonReferenceType();
16228 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16229 ParamType->isEnumeralType()) {
16230 ClassOrEnumParam = true;
16231 break;
16235 if (!ClassOrEnumParam)
16236 return Diag(FnDecl->getLocation(),
16237 diag::err_operator_overload_needs_class_or_enum)
16238 << FnDecl->getDeclName();
16241 // C++ [over.oper]p8:
16242 // An operator function cannot have default arguments (8.3.6),
16243 // except where explicitly stated below.
16245 // Only the function-call operator (C++ [over.call]p1) and the subscript
16246 // operator (CWG2507) allow default arguments.
16247 if (Op != OO_Call) {
16248 ParmVarDecl *FirstDefaultedParam = nullptr;
16249 for (auto *Param : FnDecl->parameters()) {
16250 if (Param->hasDefaultArg()) {
16251 FirstDefaultedParam = Param;
16252 break;
16255 if (FirstDefaultedParam) {
16256 if (Op == OO_Subscript) {
16257 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16258 ? diag::ext_subscript_overload
16259 : diag::error_subscript_overload)
16260 << FnDecl->getDeclName() << 1
16261 << FirstDefaultedParam->getDefaultArgRange();
16262 } else {
16263 return Diag(FirstDefaultedParam->getLocation(),
16264 diag::err_operator_overload_default_arg)
16265 << FnDecl->getDeclName()
16266 << FirstDefaultedParam->getDefaultArgRange();
16271 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16272 { false, false, false }
16273 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16274 , { Unary, Binary, MemberOnly }
16275 #include "clang/Basic/OperatorKinds.def"
16278 bool CanBeUnaryOperator = OperatorUses[Op][0];
16279 bool CanBeBinaryOperator = OperatorUses[Op][1];
16280 bool MustBeMemberOperator = OperatorUses[Op][2];
16282 // C++ [over.oper]p8:
16283 // [...] Operator functions cannot have more or fewer parameters
16284 // than the number required for the corresponding operator, as
16285 // described in the rest of this subclause.
16286 unsigned NumParams = FnDecl->getNumParams()
16287 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
16288 if (Op != OO_Call && Op != OO_Subscript &&
16289 ((NumParams == 1 && !CanBeUnaryOperator) ||
16290 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16291 (NumParams > 2))) {
16292 // We have the wrong number of parameters.
16293 unsigned ErrorKind;
16294 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16295 ErrorKind = 2; // 2 -> unary or binary.
16296 } else if (CanBeUnaryOperator) {
16297 ErrorKind = 0; // 0 -> unary
16298 } else {
16299 assert(CanBeBinaryOperator &&
16300 "All non-call overloaded operators are unary or binary!");
16301 ErrorKind = 1; // 1 -> binary
16303 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16304 << FnDecl->getDeclName() << NumParams << ErrorKind;
16307 if (Op == OO_Subscript && NumParams != 2) {
16308 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16309 ? diag::ext_subscript_overload
16310 : diag::error_subscript_overload)
16311 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16314 // Overloaded operators other than operator() and operator[] cannot be
16315 // variadic.
16316 if (Op != OO_Call &&
16317 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16318 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16319 << FnDecl->getDeclName();
16322 // Some operators must be member functions.
16323 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16324 return Diag(FnDecl->getLocation(),
16325 diag::err_operator_overload_must_be_member)
16326 << FnDecl->getDeclName();
16329 // C++ [over.inc]p1:
16330 // The user-defined function called operator++ implements the
16331 // prefix and postfix ++ operator. If this function is a member
16332 // function with no parameters, or a non-member function with one
16333 // parameter of class or enumeration type, it defines the prefix
16334 // increment operator ++ for objects of that type. If the function
16335 // is a member function with one parameter (which shall be of type
16336 // int) or a non-member function with two parameters (the second
16337 // of which shall be of type int), it defines the postfix
16338 // increment operator ++ for objects of that type.
16339 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16340 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16341 QualType ParamType = LastParam->getType();
16343 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16344 !ParamType->isDependentType())
16345 return Diag(LastParam->getLocation(),
16346 diag::err_operator_overload_post_incdec_must_be_int)
16347 << LastParam->getType() << (Op == OO_MinusMinus);
16350 return false;
16353 static bool
16354 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16355 FunctionTemplateDecl *TpDecl) {
16356 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16358 // Must have one or two template parameters.
16359 if (TemplateParams->size() == 1) {
16360 NonTypeTemplateParmDecl *PmDecl =
16361 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16363 // The template parameter must be a char parameter pack.
16364 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16365 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16366 return false;
16368 // C++20 [over.literal]p5:
16369 // A string literal operator template is a literal operator template
16370 // whose template-parameter-list comprises a single non-type
16371 // template-parameter of class type.
16373 // As a DR resolution, we also allow placeholders for deduced class
16374 // template specializations.
16375 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16376 !PmDecl->isTemplateParameterPack() &&
16377 (PmDecl->getType()->isRecordType() ||
16378 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16379 return false;
16380 } else if (TemplateParams->size() == 2) {
16381 TemplateTypeParmDecl *PmType =
16382 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16383 NonTypeTemplateParmDecl *PmArgs =
16384 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16386 // The second template parameter must be a parameter pack with the
16387 // first template parameter as its type.
16388 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16389 PmArgs->isTemplateParameterPack()) {
16390 const TemplateTypeParmType *TArgs =
16391 PmArgs->getType()->getAs<TemplateTypeParmType>();
16392 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16393 TArgs->getIndex() == PmType->getIndex()) {
16394 if (!SemaRef.inTemplateInstantiation())
16395 SemaRef.Diag(TpDecl->getLocation(),
16396 diag::ext_string_literal_operator_template);
16397 return false;
16402 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16403 diag::err_literal_operator_template)
16404 << TpDecl->getTemplateParameters()->getSourceRange();
16405 return true;
16408 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16409 /// of this literal operator function is well-formed. If so, returns
16410 /// false; otherwise, emits appropriate diagnostics and returns true.
16411 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16412 if (isa<CXXMethodDecl>(FnDecl)) {
16413 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16414 << FnDecl->getDeclName();
16415 return true;
16418 if (FnDecl->isExternC()) {
16419 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16420 if (const LinkageSpecDecl *LSD =
16421 FnDecl->getDeclContext()->getExternCContext())
16422 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16423 return true;
16426 // This might be the definition of a literal operator template.
16427 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16429 // This might be a specialization of a literal operator template.
16430 if (!TpDecl)
16431 TpDecl = FnDecl->getPrimaryTemplate();
16433 // template <char...> type operator "" name() and
16434 // template <class T, T...> type operator "" name() are the only valid
16435 // template signatures, and the only valid signatures with no parameters.
16437 // C++20 also allows template <SomeClass T> type operator "" name().
16438 if (TpDecl) {
16439 if (FnDecl->param_size() != 0) {
16440 Diag(FnDecl->getLocation(),
16441 diag::err_literal_operator_template_with_params);
16442 return true;
16445 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16446 return true;
16448 } else if (FnDecl->param_size() == 1) {
16449 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16451 QualType ParamType = Param->getType().getUnqualifiedType();
16453 // Only unsigned long long int, long double, any character type, and const
16454 // char * are allowed as the only parameters.
16455 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16456 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16457 Context.hasSameType(ParamType, Context.CharTy) ||
16458 Context.hasSameType(ParamType, Context.WideCharTy) ||
16459 Context.hasSameType(ParamType, Context.Char8Ty) ||
16460 Context.hasSameType(ParamType, Context.Char16Ty) ||
16461 Context.hasSameType(ParamType, Context.Char32Ty)) {
16462 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16463 QualType InnerType = Ptr->getPointeeType();
16465 // Pointer parameter must be a const char *.
16466 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16467 Context.CharTy) &&
16468 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16469 Diag(Param->getSourceRange().getBegin(),
16470 diag::err_literal_operator_param)
16471 << ParamType << "'const char *'" << Param->getSourceRange();
16472 return true;
16475 } else if (ParamType->isRealFloatingType()) {
16476 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16477 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16478 return true;
16480 } else if (ParamType->isIntegerType()) {
16481 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16482 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16483 return true;
16485 } else {
16486 Diag(Param->getSourceRange().getBegin(),
16487 diag::err_literal_operator_invalid_param)
16488 << ParamType << Param->getSourceRange();
16489 return true;
16492 } else if (FnDecl->param_size() == 2) {
16493 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16495 // First, verify that the first parameter is correct.
16497 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16499 // Two parameter function must have a pointer to const as a
16500 // first parameter; let's strip those qualifiers.
16501 const PointerType *PT = FirstParamType->getAs<PointerType>();
16503 if (!PT) {
16504 Diag((*Param)->getSourceRange().getBegin(),
16505 diag::err_literal_operator_param)
16506 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16507 return true;
16510 QualType PointeeType = PT->getPointeeType();
16511 // First parameter must be const
16512 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16513 Diag((*Param)->getSourceRange().getBegin(),
16514 diag::err_literal_operator_param)
16515 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16516 return true;
16519 QualType InnerType = PointeeType.getUnqualifiedType();
16520 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16521 // const char32_t* are allowed as the first parameter to a two-parameter
16522 // function
16523 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16524 Context.hasSameType(InnerType, Context.WideCharTy) ||
16525 Context.hasSameType(InnerType, Context.Char8Ty) ||
16526 Context.hasSameType(InnerType, Context.Char16Ty) ||
16527 Context.hasSameType(InnerType, Context.Char32Ty))) {
16528 Diag((*Param)->getSourceRange().getBegin(),
16529 diag::err_literal_operator_param)
16530 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16531 return true;
16534 // Move on to the second and final parameter.
16535 ++Param;
16537 // The second parameter must be a std::size_t.
16538 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16539 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16540 Diag((*Param)->getSourceRange().getBegin(),
16541 diag::err_literal_operator_param)
16542 << SecondParamType << Context.getSizeType()
16543 << (*Param)->getSourceRange();
16544 return true;
16546 } else {
16547 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16548 return true;
16551 // Parameters are good.
16553 // A parameter-declaration-clause containing a default argument is not
16554 // equivalent to any of the permitted forms.
16555 for (auto *Param : FnDecl->parameters()) {
16556 if (Param->hasDefaultArg()) {
16557 Diag(Param->getDefaultArgRange().getBegin(),
16558 diag::err_literal_operator_default_argument)
16559 << Param->getDefaultArgRange();
16560 break;
16564 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16565 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
16566 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
16567 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16568 // C++23 [usrlit.suffix]p1:
16569 // Literal suffix identifiers that do not start with an underscore are
16570 // reserved for future standardization. Literal suffix identifiers that
16571 // contain a double underscore __ are reserved for use by C++
16572 // implementations.
16573 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16574 << static_cast<int>(Status)
16575 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
16578 return false;
16581 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16582 /// linkage specification, including the language and (if present)
16583 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16584 /// language string literal. LBraceLoc, if valid, provides the location of
16585 /// the '{' brace. Otherwise, this linkage specification does not
16586 /// have any braces.
16587 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16588 Expr *LangStr,
16589 SourceLocation LBraceLoc) {
16590 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16591 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16593 StringRef Lang = Lit->getString();
16594 LinkageSpecDecl::LanguageIDs Language;
16595 if (Lang == "C")
16596 Language = LinkageSpecDecl::lang_c;
16597 else if (Lang == "C++")
16598 Language = LinkageSpecDecl::lang_cxx;
16599 else {
16600 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16601 << LangStr->getSourceRange();
16602 return nullptr;
16605 // FIXME: Add all the various semantics of linkage specifications
16607 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16608 LangStr->getExprLoc(), Language,
16609 LBraceLoc.isValid());
16611 /// C++ [module.unit]p7.2.3
16612 /// - Otherwise, if the declaration
16613 /// - ...
16614 /// - ...
16615 /// - appears within a linkage-specification,
16616 /// it is attached to the global module.
16618 /// If the declaration is already in global module fragment, we don't
16619 /// need to attach it again.
16620 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16621 Module *GlobalModule = PushImplicitGlobalModuleFragment(
16622 ExternLoc, /*IsExported=*/D->isInExportDeclContext());
16623 D->setLocalOwningModule(GlobalModule);
16626 CurContext->addDecl(D);
16627 PushDeclContext(S, D);
16628 return D;
16631 /// ActOnFinishLinkageSpecification - Complete the definition of
16632 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16633 /// valid, it's the position of the closing '}' brace in a linkage
16634 /// specification that uses braces.
16635 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16636 Decl *LinkageSpec,
16637 SourceLocation RBraceLoc) {
16638 if (RBraceLoc.isValid()) {
16639 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16640 LSDecl->setRBraceLoc(RBraceLoc);
16643 // If the current module doesn't has Parent, it implies that the
16644 // LinkageSpec isn't in the module created by itself. So we don't
16645 // need to pop it.
16646 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16647 getCurrentModule()->isImplicitGlobalModule() &&
16648 getCurrentModule()->Parent)
16649 PopImplicitGlobalModuleFragment();
16651 PopDeclContext();
16652 return LinkageSpec;
16655 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16656 const ParsedAttributesView &AttrList,
16657 SourceLocation SemiLoc) {
16658 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16659 // Attribute declarations appertain to empty declaration so we handle
16660 // them here.
16661 ProcessDeclAttributeList(S, ED, AttrList);
16663 CurContext->addDecl(ED);
16664 return ED;
16667 /// Perform semantic analysis for the variable declaration that
16668 /// occurs within a C++ catch clause, returning the newly-created
16669 /// variable.
16670 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16671 TypeSourceInfo *TInfo,
16672 SourceLocation StartLoc,
16673 SourceLocation Loc,
16674 IdentifierInfo *Name) {
16675 bool Invalid = false;
16676 QualType ExDeclType = TInfo->getType();
16678 // Arrays and functions decay.
16679 if (ExDeclType->isArrayType())
16680 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16681 else if (ExDeclType->isFunctionType())
16682 ExDeclType = Context.getPointerType(ExDeclType);
16684 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16685 // The exception-declaration shall not denote a pointer or reference to an
16686 // incomplete type, other than [cv] void*.
16687 // N2844 forbids rvalue references.
16688 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16689 Diag(Loc, diag::err_catch_rvalue_ref);
16690 Invalid = true;
16693 if (ExDeclType->isVariablyModifiedType()) {
16694 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16695 Invalid = true;
16698 QualType BaseType = ExDeclType;
16699 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16700 unsigned DK = diag::err_catch_incomplete;
16701 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16702 BaseType = Ptr->getPointeeType();
16703 Mode = 1;
16704 DK = diag::err_catch_incomplete_ptr;
16705 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16706 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16707 BaseType = Ref->getPointeeType();
16708 Mode = 2;
16709 DK = diag::err_catch_incomplete_ref;
16711 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16712 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16713 Invalid = true;
16715 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16716 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16717 Invalid = true;
16720 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16721 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16722 Invalid = true;
16725 if (!Invalid && !ExDeclType->isDependentType() &&
16726 RequireNonAbstractType(Loc, ExDeclType,
16727 diag::err_abstract_type_in_decl,
16728 AbstractVariableType))
16729 Invalid = true;
16731 // Only the non-fragile NeXT runtime currently supports C++ catches
16732 // of ObjC types, and no runtime supports catching ObjC types by value.
16733 if (!Invalid && getLangOpts().ObjC) {
16734 QualType T = ExDeclType;
16735 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16736 T = RT->getPointeeType();
16738 if (T->isObjCObjectType()) {
16739 Diag(Loc, diag::err_objc_object_catch);
16740 Invalid = true;
16741 } else if (T->isObjCObjectPointerType()) {
16742 // FIXME: should this be a test for macosx-fragile specifically?
16743 if (getLangOpts().ObjCRuntime.isFragile())
16744 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16748 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16749 ExDeclType, TInfo, SC_None);
16750 ExDecl->setExceptionVariable(true);
16752 // In ARC, infer 'retaining' for variables of retainable type.
16753 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16754 Invalid = true;
16756 if (!Invalid && !ExDeclType->isDependentType()) {
16757 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16758 // Insulate this from anything else we might currently be parsing.
16759 EnterExpressionEvaluationContext scope(
16760 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16762 // C++ [except.handle]p16:
16763 // The object declared in an exception-declaration or, if the
16764 // exception-declaration does not specify a name, a temporary (12.2) is
16765 // copy-initialized (8.5) from the exception object. [...]
16766 // The object is destroyed when the handler exits, after the destruction
16767 // of any automatic objects initialized within the handler.
16769 // We just pretend to initialize the object with itself, then make sure
16770 // it can be destroyed later.
16771 QualType initType = Context.getExceptionObjectType(ExDeclType);
16773 InitializedEntity entity =
16774 InitializedEntity::InitializeVariable(ExDecl);
16775 InitializationKind initKind =
16776 InitializationKind::CreateCopy(Loc, SourceLocation());
16778 Expr *opaqueValue =
16779 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16780 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16781 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16782 if (result.isInvalid())
16783 Invalid = true;
16784 else {
16785 // If the constructor used was non-trivial, set this as the
16786 // "initializer".
16787 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16788 if (!construct->getConstructor()->isTrivial()) {
16789 Expr *init = MaybeCreateExprWithCleanups(construct);
16790 ExDecl->setInit(init);
16793 // And make sure it's destructable.
16794 FinalizeVarWithDestructor(ExDecl, recordType);
16799 if (Invalid)
16800 ExDecl->setInvalidDecl();
16802 return ExDecl;
16805 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16806 /// handler.
16807 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16808 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16809 bool Invalid = D.isInvalidType();
16811 // Check for unexpanded parameter packs.
16812 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16813 UPPC_ExceptionType)) {
16814 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16815 D.getIdentifierLoc());
16816 Invalid = true;
16819 IdentifierInfo *II = D.getIdentifier();
16820 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16821 LookupOrdinaryName,
16822 ForVisibleRedeclaration)) {
16823 // The scope should be freshly made just for us. There is just no way
16824 // it contains any previous declaration, except for function parameters in
16825 // a function-try-block's catch statement.
16826 assert(!S->isDeclScope(PrevDecl));
16827 if (isDeclInScope(PrevDecl, CurContext, S)) {
16828 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16829 << D.getIdentifier();
16830 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16831 Invalid = true;
16832 } else if (PrevDecl->isTemplateParameter())
16833 // Maybe we will complain about the shadowed template parameter.
16834 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16837 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16838 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16839 << D.getCXXScopeSpec().getRange();
16840 Invalid = true;
16843 VarDecl *ExDecl = BuildExceptionDeclaration(
16844 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16845 if (Invalid)
16846 ExDecl->setInvalidDecl();
16848 // Add the exception declaration into this scope.
16849 if (II)
16850 PushOnScopeChains(ExDecl, S);
16851 else
16852 CurContext->addDecl(ExDecl);
16854 ProcessDeclAttributes(S, ExDecl, D);
16855 return ExDecl;
16858 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16859 Expr *AssertExpr,
16860 Expr *AssertMessageExpr,
16861 SourceLocation RParenLoc) {
16862 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16863 return nullptr;
16865 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16866 AssertMessageExpr, RParenLoc, false);
16869 /// Convert \V to a string we can present to the user in a diagnostic
16870 /// \T is the type of the expression that has been evaluated into \V
16871 static bool ConvertAPValueToString(const APValue &V, QualType T,
16872 SmallVectorImpl<char> &Str) {
16873 if (!V.hasValue())
16874 return false;
16876 switch (V.getKind()) {
16877 case APValue::ValueKind::Int:
16878 if (T->isBooleanType()) {
16879 // Bools are reduced to ints during evaluation, but for
16880 // diagnostic purposes we want to print them as
16881 // true or false.
16882 int64_t BoolValue = V.getInt().getExtValue();
16883 assert((BoolValue == 0 || BoolValue == 1) &&
16884 "Bool type, but value is not 0 or 1");
16885 llvm::raw_svector_ostream OS(Str);
16886 OS << (BoolValue ? "true" : "false");
16887 } else if (T->isCharType()) {
16888 // Same is true for chars.
16889 Str.push_back('\'');
16890 Str.push_back(V.getInt().getExtValue());
16891 Str.push_back('\'');
16892 } else
16893 V.getInt().toString(Str);
16895 break;
16897 case APValue::ValueKind::Float:
16898 V.getFloat().toString(Str);
16899 break;
16901 case APValue::ValueKind::LValue:
16902 if (V.isNullPointer()) {
16903 llvm::raw_svector_ostream OS(Str);
16904 OS << "nullptr";
16905 } else
16906 return false;
16907 break;
16909 case APValue::ValueKind::ComplexFloat: {
16910 llvm::raw_svector_ostream OS(Str);
16911 OS << '(';
16912 V.getComplexFloatReal().toString(Str);
16913 OS << " + ";
16914 V.getComplexFloatImag().toString(Str);
16915 OS << "i)";
16916 } break;
16918 case APValue::ValueKind::ComplexInt: {
16919 llvm::raw_svector_ostream OS(Str);
16920 OS << '(';
16921 V.getComplexIntReal().toString(Str);
16922 OS << " + ";
16923 V.getComplexIntImag().toString(Str);
16924 OS << "i)";
16925 } break;
16927 default:
16928 return false;
16931 return true;
16934 /// Some Expression types are not useful to print notes about,
16935 /// e.g. literals and values that have already been expanded
16936 /// before such as int-valued template parameters.
16937 static bool UsefulToPrintExpr(const Expr *E) {
16938 E = E->IgnoreParenImpCasts();
16939 // Literals are pretty easy for humans to understand.
16940 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
16941 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
16942 return false;
16944 // These have been substituted from template parameters
16945 // and appear as literals in the static assert error.
16946 if (isa<SubstNonTypeTemplateParmExpr>(E))
16947 return false;
16949 // -5 is also simple to understand.
16950 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
16951 return UsefulToPrintExpr(UnaryOp->getSubExpr());
16953 // Ignore nested binary operators. This could be a FIXME for improvements
16954 // to the diagnostics in the future.
16955 if (isa<BinaryOperator>(E))
16956 return false;
16958 return true;
16961 /// Try to print more useful information about a failed static_assert
16962 /// with expression \E
16963 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
16964 if (const auto *Op = dyn_cast<BinaryOperator>(E);
16965 Op && Op->getOpcode() != BO_LOr) {
16966 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
16967 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
16969 // Ignore comparisons of boolean expressions with a boolean literal.
16970 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
16971 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
16972 return;
16974 // Don't print obvious expressions.
16975 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
16976 return;
16978 struct {
16979 const clang::Expr *Cond;
16980 Expr::EvalResult Result;
16981 SmallString<12> ValueString;
16982 bool Print;
16983 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
16984 {RHS, Expr::EvalResult(), {}, false}};
16985 for (unsigned I = 0; I < 2; I++) {
16986 const Expr *Side = DiagSide[I].Cond;
16988 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
16990 DiagSide[I].Print = ConvertAPValueToString(
16991 DiagSide[I].Result.Val, Side->getType(), DiagSide[I].ValueString);
16993 if (DiagSide[0].Print && DiagSide[1].Print) {
16994 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
16995 << DiagSide[0].ValueString << Op->getOpcodeStr()
16996 << DiagSide[1].ValueString << Op->getSourceRange();
17001 bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message,
17002 std::string &Result,
17003 ASTContext &Ctx,
17004 bool ErrorOnInvalidMessage) {
17005 assert(Message);
17006 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17007 "can't evaluate a dependant static assert message");
17009 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17010 assert(SL->isUnevaluated() && "expected an unevaluated string");
17011 Result.assign(SL->getString().begin(), SL->getString().end());
17012 return true;
17015 SourceLocation Loc = Message->getBeginLoc();
17016 QualType T = Message->getType().getNonReferenceType();
17017 auto *RD = T->getAsCXXRecordDecl();
17018 if (!RD) {
17019 Diag(Loc, diag::err_static_assert_invalid_message);
17020 return false;
17023 auto FindMember = [&](StringRef Member, bool &Empty,
17024 bool Diag = false) -> std::optional<LookupResult> {
17025 QualType ObjectType = Message->getType();
17026 Expr::Classification ObjectClassification =
17027 Message->Classify(getASTContext());
17029 DeclarationName DN = PP.getIdentifierInfo(Member);
17030 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17031 LookupQualifiedName(MemberLookup, RD);
17032 Empty = MemberLookup.empty();
17033 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17034 OverloadCandidateSet::CSK_Normal);
17035 for (NamedDecl *D : MemberLookup) {
17036 AddMethodCandidate(DeclAccessPair::make(D, D->getAccess()), ObjectType,
17037 ObjectClassification, /*Args=*/{}, Candidates);
17039 OverloadCandidateSet::iterator Best;
17040 switch (Candidates.BestViableFunction(*this, Loc, Best)) {
17041 case OR_Success:
17042 return std::move(MemberLookup);
17043 default:
17044 if (Diag)
17045 Candidates.NoteCandidates(
17046 PartialDiagnosticAt(
17047 Loc, PDiag(diag::err_static_assert_invalid_mem_fn_ret_ty)
17048 << (Member == "data")),
17049 *this, OCD_AllCandidates, /*Args=*/{});
17051 return std::nullopt;
17054 bool SizeNotFound, DataNotFound;
17055 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17056 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17057 if (SizeNotFound || DataNotFound) {
17058 Diag(Loc, diag::err_static_assert_missing_member_function)
17059 << ((SizeNotFound && DataNotFound) ? 2
17060 : SizeNotFound ? 0
17061 : 1);
17062 return false;
17065 if (!SizeMember || !DataMember) {
17066 if (!SizeMember)
17067 FindMember("size", SizeNotFound, /*Diag=*/true);
17068 if (!DataMember)
17069 FindMember("data", DataNotFound, /*Diag=*/true);
17070 return false;
17073 auto BuildExpr = [&](LookupResult &LR) {
17074 ExprResult Res = BuildMemberReferenceExpr(
17075 Message, Message->getType(), Message->getBeginLoc(), false,
17076 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17077 if (Res.isInvalid())
17078 return ExprError();
17079 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17080 false, true);
17081 if (Res.isInvalid())
17082 return ExprError();
17083 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17084 return ExprError();
17085 return TemporaryMaterializationConversion(Res.get());
17088 ExprResult SizeE = BuildExpr(*SizeMember);
17089 ExprResult DataE = BuildExpr(*DataMember);
17091 QualType SizeT = Context.getSizeType();
17092 QualType ConstCharPtr =
17093 Context.getPointerType(Context.getConstType(Context.CharTy));
17095 ExprResult EvaluatedSize =
17096 SizeE.isInvalid() ? ExprError()
17097 : BuildConvertedConstantExpression(
17098 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17099 if (EvaluatedSize.isInvalid()) {
17100 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17101 return false;
17104 ExprResult EvaluatedData =
17105 DataE.isInvalid()
17106 ? ExprError()
17107 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17108 CCEK_StaticAssertMessageData);
17109 if (EvaluatedData.isInvalid()) {
17110 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17111 return false;
17114 if (!ErrorOnInvalidMessage &&
17115 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17116 return true;
17118 Expr::EvalResult Status;
17119 SmallVector<PartialDiagnosticAt, 8> Notes;
17120 Status.Diag = &Notes;
17121 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17122 EvaluatedData.get(), Ctx, Status) ||
17123 !Notes.empty()) {
17124 Diag(Message->getBeginLoc(),
17125 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17126 : diag::warn_static_assert_message_constexpr);
17127 for (const auto &Note : Notes)
17128 Diag(Note.first, Note.second);
17129 return !ErrorOnInvalidMessage;
17131 return true;
17134 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17135 Expr *AssertExpr, Expr *AssertMessage,
17136 SourceLocation RParenLoc,
17137 bool Failed) {
17138 assert(AssertExpr != nullptr && "Expected non-null condition");
17139 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17140 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17141 !AssertMessage->isValueDependent())) &&
17142 !Failed) {
17143 // In a static_assert-declaration, the constant-expression shall be a
17144 // constant expression that can be contextually converted to bool.
17145 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17146 if (Converted.isInvalid())
17147 Failed = true;
17149 ExprResult FullAssertExpr =
17150 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17151 /*DiscardedValue*/ false,
17152 /*IsConstexpr*/ true);
17153 if (FullAssertExpr.isInvalid())
17154 Failed = true;
17155 else
17156 AssertExpr = FullAssertExpr.get();
17158 llvm::APSInt Cond;
17159 Expr *BaseExpr = AssertExpr;
17160 AllowFoldKind FoldKind = NoFold;
17162 if (!getLangOpts().CPlusPlus) {
17163 // In C mode, allow folding as an extension for better compatibility with
17164 // C++ in terms of expressions like static_assert("test") or
17165 // static_assert(nullptr).
17166 FoldKind = AllowFold;
17169 if (!Failed && VerifyIntegerConstantExpression(
17170 BaseExpr, &Cond,
17171 diag::err_static_assert_expression_is_not_constant,
17172 FoldKind).isInvalid())
17173 Failed = true;
17175 // If the static_assert passes, only verify that
17176 // the message is grammatically valid without evaluating it.
17177 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17178 std::string Str;
17179 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17180 /*ErrorOnInvalidMessage=*/false);
17183 // CWG2518
17184 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17185 // template definition, the declaration has no effect.
17186 bool InTemplateDefinition =
17187 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17189 if (!Failed && !Cond && !InTemplateDefinition) {
17190 SmallString<256> MsgBuffer;
17191 llvm::raw_svector_ostream Msg(MsgBuffer);
17192 bool HasMessage = AssertMessage;
17193 if (AssertMessage) {
17194 std::string Str;
17195 HasMessage =
17196 EvaluateStaticAssertMessageAsString(
17197 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17198 !Str.empty();
17199 Msg << Str;
17201 Expr *InnerCond = nullptr;
17202 std::string InnerCondDescription;
17203 std::tie(InnerCond, InnerCondDescription) =
17204 findFailedBooleanCondition(Converted.get());
17205 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17206 // Drill down into concept specialization expressions to see why they
17207 // weren't satisfied.
17208 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17209 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17210 ConstraintSatisfaction Satisfaction;
17211 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17212 DiagnoseUnsatisfiedConstraint(Satisfaction);
17213 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17214 && !isa<IntegerLiteral>(InnerCond)) {
17215 Diag(InnerCond->getBeginLoc(),
17216 diag::err_static_assert_requirement_failed)
17217 << InnerCondDescription << !HasMessage << Msg.str()
17218 << InnerCond->getSourceRange();
17219 DiagnoseStaticAssertDetails(InnerCond);
17220 } else {
17221 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17222 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17223 PrintContextStack();
17225 Failed = true;
17227 } else {
17228 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17229 /*DiscardedValue*/false,
17230 /*IsConstexpr*/true);
17231 if (FullAssertExpr.isInvalid())
17232 Failed = true;
17233 else
17234 AssertExpr = FullAssertExpr.get();
17237 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17238 AssertExpr, AssertMessage, RParenLoc,
17239 Failed);
17241 CurContext->addDecl(Decl);
17242 return Decl;
17245 /// Perform semantic analysis of the given friend type declaration.
17247 /// \returns A friend declaration that.
17248 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
17249 SourceLocation FriendLoc,
17250 TypeSourceInfo *TSInfo) {
17251 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
17253 QualType T = TSInfo->getType();
17254 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
17256 // C++03 [class.friend]p2:
17257 // An elaborated-type-specifier shall be used in a friend declaration
17258 // for a class.*
17260 // * The class-key of the elaborated-type-specifier is required.
17261 if (!CodeSynthesisContexts.empty()) {
17262 // Do not complain about the form of friend template types during any kind
17263 // of code synthesis. For template instantiation, we will have complained
17264 // when the template was defined.
17265 } else {
17266 if (!T->isElaboratedTypeSpecifier()) {
17267 // If we evaluated the type to a record type, suggest putting
17268 // a tag in front.
17269 if (const RecordType *RT = T->getAs<RecordType>()) {
17270 RecordDecl *RD = RT->getDecl();
17272 SmallString<16> InsertionText(" ");
17273 InsertionText += RD->getKindName();
17275 Diag(TypeRange.getBegin(),
17276 getLangOpts().CPlusPlus11 ?
17277 diag::warn_cxx98_compat_unelaborated_friend_type :
17278 diag::ext_unelaborated_friend_type)
17279 << (unsigned) RD->getTagKind()
17280 << T
17281 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
17282 InsertionText);
17283 } else {
17284 Diag(FriendLoc,
17285 getLangOpts().CPlusPlus11 ?
17286 diag::warn_cxx98_compat_nonclass_type_friend :
17287 diag::ext_nonclass_type_friend)
17288 << T
17289 << TypeRange;
17291 } else if (T->getAs<EnumType>()) {
17292 Diag(FriendLoc,
17293 getLangOpts().CPlusPlus11 ?
17294 diag::warn_cxx98_compat_enum_friend :
17295 diag::ext_enum_friend)
17296 << T
17297 << TypeRange;
17300 // C++11 [class.friend]p3:
17301 // A friend declaration that does not declare a function shall have one
17302 // of the following forms:
17303 // friend elaborated-type-specifier ;
17304 // friend simple-type-specifier ;
17305 // friend typename-specifier ;
17306 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
17307 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
17310 // If the type specifier in a friend declaration designates a (possibly
17311 // cv-qualified) class type, that class is declared as a friend; otherwise,
17312 // the friend declaration is ignored.
17313 return FriendDecl::Create(Context, CurContext,
17314 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
17315 FriendLoc);
17318 /// Handle a friend tag declaration where the scope specifier was
17319 /// templated.
17320 DeclResult Sema::ActOnTemplatedFriendTag(
17321 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17322 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17323 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17324 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17326 bool IsMemberSpecialization = false;
17327 bool Invalid = false;
17329 if (TemplateParameterList *TemplateParams =
17330 MatchTemplateParametersToScopeSpecifier(
17331 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17332 IsMemberSpecialization, Invalid)) {
17333 if (TemplateParams->size() > 0) {
17334 // This is a declaration of a class template.
17335 if (Invalid)
17336 return true;
17338 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17339 NameLoc, Attr, TemplateParams, AS_public,
17340 /*ModulePrivateLoc=*/SourceLocation(),
17341 FriendLoc, TempParamLists.size() - 1,
17342 TempParamLists.data()).get();
17343 } else {
17344 // The "template<>" header is extraneous.
17345 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17346 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17347 IsMemberSpecialization = true;
17351 if (Invalid) return true;
17353 bool isAllExplicitSpecializations = true;
17354 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17355 if (TempParamLists[I]->size()) {
17356 isAllExplicitSpecializations = false;
17357 break;
17361 // FIXME: don't ignore attributes.
17363 // If it's explicit specializations all the way down, just forget
17364 // about the template header and build an appropriate non-templated
17365 // friend. TODO: for source fidelity, remember the headers.
17366 if (isAllExplicitSpecializations) {
17367 if (SS.isEmpty()) {
17368 bool Owned = false;
17369 bool IsDependent = false;
17370 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17371 AS_public,
17372 /*ModulePrivateLoc=*/SourceLocation(),
17373 MultiTemplateParamsArg(), Owned, IsDependent,
17374 /*ScopedEnumKWLoc=*/SourceLocation(),
17375 /*ScopedEnumUsesClassTag=*/false,
17376 /*UnderlyingType=*/TypeResult(),
17377 /*IsTypeSpecifier=*/false,
17378 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17381 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17382 ElaboratedTypeKeyword Keyword
17383 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17384 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17385 *Name, NameLoc);
17386 if (T.isNull())
17387 return true;
17389 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17390 if (isa<DependentNameType>(T)) {
17391 DependentNameTypeLoc TL =
17392 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17393 TL.setElaboratedKeywordLoc(TagLoc);
17394 TL.setQualifierLoc(QualifierLoc);
17395 TL.setNameLoc(NameLoc);
17396 } else {
17397 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17398 TL.setElaboratedKeywordLoc(TagLoc);
17399 TL.setQualifierLoc(QualifierLoc);
17400 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17403 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17404 TSI, FriendLoc, TempParamLists);
17405 Friend->setAccess(AS_public);
17406 CurContext->addDecl(Friend);
17407 return Friend;
17410 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17414 // Handle the case of a templated-scope friend class. e.g.
17415 // template <class T> class A<T>::B;
17416 // FIXME: we don't support these right now.
17417 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17418 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17419 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17420 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17421 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17422 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17423 TL.setElaboratedKeywordLoc(TagLoc);
17424 TL.setQualifierLoc(SS.getWithLocInContext(Context));
17425 TL.setNameLoc(NameLoc);
17427 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17428 TSI, FriendLoc, TempParamLists);
17429 Friend->setAccess(AS_public);
17430 Friend->setUnsupportedFriend(true);
17431 CurContext->addDecl(Friend);
17432 return Friend;
17435 /// Handle a friend type declaration. This works in tandem with
17436 /// ActOnTag.
17438 /// Notes on friend class templates:
17440 /// We generally treat friend class declarations as if they were
17441 /// declaring a class. So, for example, the elaborated type specifier
17442 /// in a friend declaration is required to obey the restrictions of a
17443 /// class-head (i.e. no typedefs in the scope chain), template
17444 /// parameters are required to match up with simple template-ids, &c.
17445 /// However, unlike when declaring a template specialization, it's
17446 /// okay to refer to a template specialization without an empty
17447 /// template parameter declaration, e.g.
17448 /// friend class A<T>::B<unsigned>;
17449 /// We permit this as a special case; if there are any template
17450 /// parameters present at all, require proper matching, i.e.
17451 /// template <> template \<class T> friend class A<int>::B;
17452 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17453 MultiTemplateParamsArg TempParams) {
17454 SourceLocation Loc = DS.getBeginLoc();
17456 assert(DS.isFriendSpecified());
17457 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17459 // C++ [class.friend]p3:
17460 // A friend declaration that does not declare a function shall have one of
17461 // the following forms:
17462 // friend elaborated-type-specifier ;
17463 // friend simple-type-specifier ;
17464 // friend typename-specifier ;
17466 // Any declaration with a type qualifier does not have that form. (It's
17467 // legal to specify a qualified type as a friend, you just can't write the
17468 // keywords.)
17469 if (DS.getTypeQualifiers()) {
17470 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17471 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17472 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17473 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17474 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17475 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17476 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17477 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17478 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17479 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17482 // Try to convert the decl specifier to a type. This works for
17483 // friend templates because ActOnTag never produces a ClassTemplateDecl
17484 // for a TUK_Friend.
17485 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17486 DeclaratorContext::Member);
17487 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
17488 QualType T = TSI->getType();
17489 if (TheDeclarator.isInvalidType())
17490 return nullptr;
17492 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17493 return nullptr;
17495 // This is definitely an error in C++98. It's probably meant to
17496 // be forbidden in C++0x, too, but the specification is just
17497 // poorly written.
17499 // The problem is with declarations like the following:
17500 // template <T> friend A<T>::foo;
17501 // where deciding whether a class C is a friend or not now hinges
17502 // on whether there exists an instantiation of A that causes
17503 // 'foo' to equal C. There are restrictions on class-heads
17504 // (which we declare (by fiat) elaborated friend declarations to
17505 // be) that makes this tractable.
17507 // FIXME: handle "template <> friend class A<T>;", which
17508 // is possibly well-formed? Who even knows?
17509 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
17510 Diag(Loc, diag::err_tagless_friend_type_template)
17511 << DS.getSourceRange();
17512 return nullptr;
17515 // C++98 [class.friend]p1: A friend of a class is a function
17516 // or class that is not a member of the class . . .
17517 // This is fixed in DR77, which just barely didn't make the C++03
17518 // deadline. It's also a very silly restriction that seriously
17519 // affects inner classes and which nobody else seems to implement;
17520 // thus we never diagnose it, not even in -pedantic.
17522 // But note that we could warn about it: it's always useless to
17523 // friend one of your own members (it's not, however, worthless to
17524 // friend a member of an arbitrary specialization of your template).
17526 Decl *D;
17527 if (!TempParams.empty())
17528 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
17529 TempParams,
17530 TSI,
17531 DS.getFriendSpecLoc());
17532 else
17533 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
17535 if (!D)
17536 return nullptr;
17538 D->setAccess(AS_public);
17539 CurContext->addDecl(D);
17541 return D;
17544 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17545 MultiTemplateParamsArg TemplateParams) {
17546 const DeclSpec &DS = D.getDeclSpec();
17548 assert(DS.isFriendSpecified());
17549 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17551 SourceLocation Loc = D.getIdentifierLoc();
17552 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17554 // C++ [class.friend]p1
17555 // A friend of a class is a function or class....
17556 // Note that this sees through typedefs, which is intended.
17557 // It *doesn't* see through dependent types, which is correct
17558 // according to [temp.arg.type]p3:
17559 // If a declaration acquires a function type through a
17560 // type dependent on a template-parameter and this causes
17561 // a declaration that does not use the syntactic form of a
17562 // function declarator to have a function type, the program
17563 // is ill-formed.
17564 if (!TInfo->getType()->isFunctionType()) {
17565 Diag(Loc, diag::err_unexpected_friend);
17567 // It might be worthwhile to try to recover by creating an
17568 // appropriate declaration.
17569 return nullptr;
17572 // C++ [namespace.memdef]p3
17573 // - If a friend declaration in a non-local class first declares a
17574 // class or function, the friend class or function is a member
17575 // of the innermost enclosing namespace.
17576 // - The name of the friend is not found by simple name lookup
17577 // until a matching declaration is provided in that namespace
17578 // scope (either before or after the class declaration granting
17579 // friendship).
17580 // - If a friend function is called, its name may be found by the
17581 // name lookup that considers functions from namespaces and
17582 // classes associated with the types of the function arguments.
17583 // - When looking for a prior declaration of a class or a function
17584 // declared as a friend, scopes outside the innermost enclosing
17585 // namespace scope are not considered.
17587 CXXScopeSpec &SS = D.getCXXScopeSpec();
17588 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17589 assert(NameInfo.getName());
17591 // Check for unexpanded parameter packs.
17592 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17593 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17594 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17595 return nullptr;
17597 // The context we found the declaration in, or in which we should
17598 // create the declaration.
17599 DeclContext *DC;
17600 Scope *DCScope = S;
17601 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17602 ForExternalRedeclaration);
17604 // There are five cases here.
17605 // - There's no scope specifier and we're in a local class. Only look
17606 // for functions declared in the immediately-enclosing block scope.
17607 // We recover from invalid scope qualifiers as if they just weren't there.
17608 FunctionDecl *FunctionContainingLocalClass = nullptr;
17609 if ((SS.isInvalid() || !SS.isSet()) &&
17610 (FunctionContainingLocalClass =
17611 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17612 // C++11 [class.friend]p11:
17613 // If a friend declaration appears in a local class and the name
17614 // specified is an unqualified name, a prior declaration is
17615 // looked up without considering scopes that are outside the
17616 // innermost enclosing non-class scope. For a friend function
17617 // declaration, if there is no prior declaration, the program is
17618 // ill-formed.
17620 // Find the innermost enclosing non-class scope. This is the block
17621 // scope containing the local class definition (or for a nested class,
17622 // the outer local class).
17623 DCScope = S->getFnParent();
17625 // Look up the function name in the scope.
17626 Previous.clear(LookupLocalFriendName);
17627 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17629 if (!Previous.empty()) {
17630 // All possible previous declarations must have the same context:
17631 // either they were declared at block scope or they are members of
17632 // one of the enclosing local classes.
17633 DC = Previous.getRepresentativeDecl()->getDeclContext();
17634 } else {
17635 // This is ill-formed, but provide the context that we would have
17636 // declared the function in, if we were permitted to, for error recovery.
17637 DC = FunctionContainingLocalClass;
17639 adjustContextForLocalExternDecl(DC);
17641 // C++ [class.friend]p6:
17642 // A function can be defined in a friend declaration of a class if and
17643 // only if the class is a non-local class (9.8), the function name is
17644 // unqualified, and the function has namespace scope.
17645 if (D.isFunctionDefinition()) {
17646 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17649 // - There's no scope specifier, in which case we just go to the
17650 // appropriate scope and look for a function or function template
17651 // there as appropriate.
17652 } else if (SS.isInvalid() || !SS.isSet()) {
17653 // C++11 [namespace.memdef]p3:
17654 // If the name in a friend declaration is neither qualified nor
17655 // a template-id and the declaration is a function or an
17656 // elaborated-type-specifier, the lookup to determine whether
17657 // the entity has been previously declared shall not consider
17658 // any scopes outside the innermost enclosing namespace.
17659 bool isTemplateId =
17660 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17662 // Find the appropriate context according to the above.
17663 DC = CurContext;
17665 // Skip class contexts. If someone can cite chapter and verse
17666 // for this behavior, that would be nice --- it's what GCC and
17667 // EDG do, and it seems like a reasonable intent, but the spec
17668 // really only says that checks for unqualified existing
17669 // declarations should stop at the nearest enclosing namespace,
17670 // not that they should only consider the nearest enclosing
17671 // namespace.
17672 while (DC->isRecord())
17673 DC = DC->getParent();
17675 DeclContext *LookupDC = DC->getNonTransparentContext();
17676 while (true) {
17677 LookupQualifiedName(Previous, LookupDC);
17679 if (!Previous.empty()) {
17680 DC = LookupDC;
17681 break;
17684 if (isTemplateId) {
17685 if (isa<TranslationUnitDecl>(LookupDC)) break;
17686 } else {
17687 if (LookupDC->isFileContext()) break;
17689 LookupDC = LookupDC->getParent();
17692 DCScope = getScopeForDeclContext(S, DC);
17694 // - There's a non-dependent scope specifier, in which case we
17695 // compute it and do a previous lookup there for a function
17696 // or function template.
17697 } else if (!SS.getScopeRep()->isDependent()) {
17698 DC = computeDeclContext(SS);
17699 if (!DC) return nullptr;
17701 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17703 LookupQualifiedName(Previous, DC);
17705 // C++ [class.friend]p1: A friend of a class is a function or
17706 // class that is not a member of the class . . .
17707 if (DC->Equals(CurContext))
17708 Diag(DS.getFriendSpecLoc(),
17709 getLangOpts().CPlusPlus11 ?
17710 diag::warn_cxx98_compat_friend_is_member :
17711 diag::err_friend_is_member);
17713 if (D.isFunctionDefinition()) {
17714 // C++ [class.friend]p6:
17715 // A function can be defined in a friend declaration of a class if and
17716 // only if the class is a non-local class (9.8), the function name is
17717 // unqualified, and the function has namespace scope.
17719 // FIXME: We should only do this if the scope specifier names the
17720 // innermost enclosing namespace; otherwise the fixit changes the
17721 // meaning of the code.
17722 SemaDiagnosticBuilder DB
17723 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17725 DB << SS.getScopeRep();
17726 if (DC->isFileContext())
17727 DB << FixItHint::CreateRemoval(SS.getRange());
17728 SS.clear();
17731 // - There's a scope specifier that does not match any template
17732 // parameter lists, in which case we use some arbitrary context,
17733 // create a method or method template, and wait for instantiation.
17734 // - There's a scope specifier that does match some template
17735 // parameter lists, which we don't handle right now.
17736 } else {
17737 if (D.isFunctionDefinition()) {
17738 // C++ [class.friend]p6:
17739 // A function can be defined in a friend declaration of a class if and
17740 // only if the class is a non-local class (9.8), the function name is
17741 // unqualified, and the function has namespace scope.
17742 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17743 << SS.getScopeRep();
17746 DC = CurContext;
17747 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17750 if (!DC->isRecord()) {
17751 int DiagArg = -1;
17752 switch (D.getName().getKind()) {
17753 case UnqualifiedIdKind::IK_ConstructorTemplateId:
17754 case UnqualifiedIdKind::IK_ConstructorName:
17755 DiagArg = 0;
17756 break;
17757 case UnqualifiedIdKind::IK_DestructorName:
17758 DiagArg = 1;
17759 break;
17760 case UnqualifiedIdKind::IK_ConversionFunctionId:
17761 DiagArg = 2;
17762 break;
17763 case UnqualifiedIdKind::IK_DeductionGuideName:
17764 DiagArg = 3;
17765 break;
17766 case UnqualifiedIdKind::IK_Identifier:
17767 case UnqualifiedIdKind::IK_ImplicitSelfParam:
17768 case UnqualifiedIdKind::IK_LiteralOperatorId:
17769 case UnqualifiedIdKind::IK_OperatorFunctionId:
17770 case UnqualifiedIdKind::IK_TemplateId:
17771 break;
17773 // This implies that it has to be an operator or function.
17774 if (DiagArg >= 0) {
17775 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17776 return nullptr;
17780 // FIXME: This is an egregious hack to cope with cases where the scope stack
17781 // does not contain the declaration context, i.e., in an out-of-line
17782 // definition of a class.
17783 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17784 if (!DCScope) {
17785 FakeDCScope.setEntity(DC);
17786 DCScope = &FakeDCScope;
17789 bool AddToScope = true;
17790 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17791 TemplateParams, AddToScope);
17792 if (!ND) return nullptr;
17794 assert(ND->getLexicalDeclContext() == CurContext);
17796 // If we performed typo correction, we might have added a scope specifier
17797 // and changed the decl context.
17798 DC = ND->getDeclContext();
17800 // Add the function declaration to the appropriate lookup tables,
17801 // adjusting the redeclarations list as necessary. We don't
17802 // want to do this yet if the friending class is dependent.
17804 // Also update the scope-based lookup if the target context's
17805 // lookup context is in lexical scope.
17806 if (!CurContext->isDependentContext()) {
17807 DC = DC->getRedeclContext();
17808 DC->makeDeclVisibleInContext(ND);
17809 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17810 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17813 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17814 D.getIdentifierLoc(), ND,
17815 DS.getFriendSpecLoc());
17816 FrD->setAccess(AS_public);
17817 CurContext->addDecl(FrD);
17819 if (ND->isInvalidDecl()) {
17820 FrD->setInvalidDecl();
17821 } else {
17822 if (DC->isRecord()) CheckFriendAccess(ND);
17824 FunctionDecl *FD;
17825 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17826 FD = FTD->getTemplatedDecl();
17827 else
17828 FD = cast<FunctionDecl>(ND);
17830 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17831 // default argument expression, that declaration shall be a definition
17832 // and shall be the only declaration of the function or function
17833 // template in the translation unit.
17834 if (functionDeclHasDefaultArgument(FD)) {
17835 // We can't look at FD->getPreviousDecl() because it may not have been set
17836 // if we're in a dependent context. If the function is known to be a
17837 // redeclaration, we will have narrowed Previous down to the right decl.
17838 if (D.isRedeclaration()) {
17839 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17840 Diag(Previous.getRepresentativeDecl()->getLocation(),
17841 diag::note_previous_declaration);
17842 } else if (!D.isFunctionDefinition())
17843 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17846 // Mark templated-scope function declarations as unsupported.
17847 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17848 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17849 << SS.getScopeRep() << SS.getRange()
17850 << cast<CXXRecordDecl>(CurContext);
17851 FrD->setUnsupportedFriend(true);
17855 warnOnReservedIdentifier(ND);
17857 return ND;
17860 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17861 AdjustDeclIfTemplate(Dcl);
17863 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17864 if (!Fn) {
17865 Diag(DelLoc, diag::err_deleted_non_function);
17866 return;
17869 // Deleted function does not have a body.
17870 Fn->setWillHaveBody(false);
17872 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17873 // Don't consider the implicit declaration we generate for explicit
17874 // specializations. FIXME: Do not generate these implicit declarations.
17875 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17876 Prev->getPreviousDecl()) &&
17877 !Prev->isDefined()) {
17878 Diag(DelLoc, diag::err_deleted_decl_not_first);
17879 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17880 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17881 : diag::note_previous_declaration);
17882 // We can't recover from this; the declaration might have already
17883 // been used.
17884 Fn->setInvalidDecl();
17885 return;
17888 // To maintain the invariant that functions are only deleted on their first
17889 // declaration, mark the implicitly-instantiated declaration of the
17890 // explicitly-specialized function as deleted instead of marking the
17891 // instantiated redeclaration.
17892 Fn = Fn->getCanonicalDecl();
17895 // dllimport/dllexport cannot be deleted.
17896 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17897 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17898 Fn->setInvalidDecl();
17901 // C++11 [basic.start.main]p3:
17902 // A program that defines main as deleted [...] is ill-formed.
17903 if (Fn->isMain())
17904 Diag(DelLoc, diag::err_deleted_main);
17906 // C++11 [dcl.fct.def.delete]p4:
17907 // A deleted function is implicitly inline.
17908 Fn->setImplicitlyInline();
17909 Fn->setDeletedAsWritten();
17912 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17913 if (!Dcl || Dcl->isInvalidDecl())
17914 return;
17916 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17917 if (!FD) {
17918 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17919 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17920 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17921 return;
17925 Diag(DefaultLoc, diag::err_default_special_members)
17926 << getLangOpts().CPlusPlus20;
17927 return;
17930 // Reject if this can't possibly be a defaultable function.
17931 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17932 if (!DefKind &&
17933 // A dependent function that doesn't locally look defaultable can
17934 // still instantiate to a defaultable function if it's a constructor
17935 // or assignment operator.
17936 (!FD->isDependentContext() ||
17937 (!isa<CXXConstructorDecl>(FD) &&
17938 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17939 Diag(DefaultLoc, diag::err_default_special_members)
17940 << getLangOpts().CPlusPlus20;
17941 return;
17944 // Issue compatibility warning. We already warned if the operator is
17945 // 'operator<=>' when parsing the '<=>' token.
17946 if (DefKind.isComparison() &&
17947 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17948 Diag(DefaultLoc, getLangOpts().CPlusPlus20
17949 ? diag::warn_cxx17_compat_defaulted_comparison
17950 : diag::ext_defaulted_comparison);
17953 FD->setDefaulted();
17954 FD->setExplicitlyDefaulted();
17955 FD->setDefaultLoc(DefaultLoc);
17957 // Defer checking functions that are defaulted in a dependent context.
17958 if (FD->isDependentContext())
17959 return;
17961 // Unset that we will have a body for this function. We might not,
17962 // if it turns out to be trivial, and we don't need this marking now
17963 // that we've marked it as defaulted.
17964 FD->setWillHaveBody(false);
17966 if (DefKind.isComparison()) {
17967 // If this comparison's defaulting occurs within the definition of its
17968 // lexical class context, we have to do the checking when complete.
17969 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17970 if (!RD->isCompleteDefinition())
17971 return;
17974 // If this member fn was defaulted on its first declaration, we will have
17975 // already performed the checking in CheckCompletedCXXClass. Such a
17976 // declaration doesn't trigger an implicit definition.
17977 if (isa<CXXMethodDecl>(FD)) {
17978 const FunctionDecl *Primary = FD;
17979 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17980 // Ask the template instantiation pattern that actually had the
17981 // '= default' on it.
17982 Primary = Pattern;
17983 if (Primary->getCanonicalDecl()->isDefaulted())
17984 return;
17987 if (DefKind.isComparison()) {
17988 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17989 FD->setInvalidDecl();
17990 else
17991 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17992 } else {
17993 auto *MD = cast<CXXMethodDecl>(FD);
17995 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
17996 DefaultLoc))
17997 MD->setInvalidDecl();
17998 else
17999 DefineDefaultedFunction(*this, MD, DefaultLoc);
18003 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18004 for (Stmt *SubStmt : S->children()) {
18005 if (!SubStmt)
18006 continue;
18007 if (isa<ReturnStmt>(SubStmt))
18008 Self.Diag(SubStmt->getBeginLoc(),
18009 diag::err_return_in_constructor_handler);
18010 if (!isa<Expr>(SubStmt))
18011 SearchForReturnInStmt(Self, SubStmt);
18015 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18016 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18017 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18018 SearchForReturnInStmt(*this, Handler);
18022 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
18023 FnBodyKind BodyKind) {
18024 switch (BodyKind) {
18025 case FnBodyKind::Delete:
18026 SetDeclDeleted(D, Loc);
18027 break;
18028 case FnBodyKind::Default:
18029 SetDeclDefaulted(D, Loc);
18030 break;
18031 case FnBodyKind::Other:
18032 llvm_unreachable(
18033 "Parsed function body should be '= delete;' or '= default;'");
18037 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
18038 const CXXMethodDecl *Old) {
18039 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18040 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18042 if (OldFT->hasExtParameterInfos()) {
18043 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18044 // A parameter of the overriding method should be annotated with noescape
18045 // if the corresponding parameter of the overridden method is annotated.
18046 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18047 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18048 Diag(New->getParamDecl(I)->getLocation(),
18049 diag::warn_overriding_method_missing_noescape);
18050 Diag(Old->getParamDecl(I)->getLocation(),
18051 diag::note_overridden_marked_noescape);
18055 // SME attributes must match when overriding a function declaration.
18056 if (IsInvalidSMECallConversion(
18057 Old->getType(), New->getType(),
18058 AArch64SMECallConversionKind::MayAddPreservesZA)) {
18059 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18060 << New << New->getType() << Old->getType();
18061 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18062 return true;
18065 // Virtual overrides must have the same code_seg.
18066 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18067 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18068 if ((NewCSA || OldCSA) &&
18069 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18070 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18071 Diag(Old->getLocation(), diag::note_previous_declaration);
18072 return true;
18075 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18077 // If the calling conventions match, everything is fine
18078 if (NewCC == OldCC)
18079 return false;
18081 // If the calling conventions mismatch because the new function is static,
18082 // suppress the calling convention mismatch error; the error about static
18083 // function override (err_static_overrides_virtual from
18084 // Sema::CheckFunctionDeclaration) is more clear.
18085 if (New->getStorageClass() == SC_Static)
18086 return false;
18088 Diag(New->getLocation(),
18089 diag::err_conflicting_overriding_cc_attributes)
18090 << New->getDeclName() << New->getType() << Old->getType();
18091 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18092 return true;
18095 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18096 const CXXMethodDecl *Old) {
18097 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18098 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18100 if (Context.hasSameType(NewTy, OldTy) ||
18101 NewTy->isDependentType() || OldTy->isDependentType())
18102 return false;
18104 // Check if the return types are covariant
18105 QualType NewClassTy, OldClassTy;
18107 /// Both types must be pointers or references to classes.
18108 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18109 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18110 NewClassTy = NewPT->getPointeeType();
18111 OldClassTy = OldPT->getPointeeType();
18113 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18114 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18115 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18116 NewClassTy = NewRT->getPointeeType();
18117 OldClassTy = OldRT->getPointeeType();
18122 // The return types aren't either both pointers or references to a class type.
18123 if (NewClassTy.isNull()) {
18124 Diag(New->getLocation(),
18125 diag::err_different_return_type_for_overriding_virtual_function)
18126 << New->getDeclName() << NewTy << OldTy
18127 << New->getReturnTypeSourceRange();
18128 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18129 << Old->getReturnTypeSourceRange();
18131 return true;
18134 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18135 // C++14 [class.virtual]p8:
18136 // If the class type in the covariant return type of D::f differs from
18137 // that of B::f, the class type in the return type of D::f shall be
18138 // complete at the point of declaration of D::f or shall be the class
18139 // type D.
18140 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18141 if (!RT->isBeingDefined() &&
18142 RequireCompleteType(New->getLocation(), NewClassTy,
18143 diag::err_covariant_return_incomplete,
18144 New->getDeclName()))
18145 return true;
18148 // Check if the new class derives from the old class.
18149 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18150 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18151 << New->getDeclName() << NewTy << OldTy
18152 << New->getReturnTypeSourceRange();
18153 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18154 << Old->getReturnTypeSourceRange();
18155 return true;
18158 // Check if we the conversion from derived to base is valid.
18159 if (CheckDerivedToBaseConversion(
18160 NewClassTy, OldClassTy,
18161 diag::err_covariant_return_inaccessible_base,
18162 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18163 New->getLocation(), New->getReturnTypeSourceRange(),
18164 New->getDeclName(), nullptr)) {
18165 // FIXME: this note won't trigger for delayed access control
18166 // diagnostics, and it's impossible to get an undelayed error
18167 // here from access control during the original parse because
18168 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18169 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18170 << Old->getReturnTypeSourceRange();
18171 return true;
18175 // The qualifiers of the return types must be the same.
18176 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18177 Diag(New->getLocation(),
18178 diag::err_covariant_return_type_different_qualifications)
18179 << New->getDeclName() << NewTy << OldTy
18180 << New->getReturnTypeSourceRange();
18181 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18182 << Old->getReturnTypeSourceRange();
18183 return true;
18187 // The new class type must have the same or less qualifiers as the old type.
18188 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18189 Diag(New->getLocation(),
18190 diag::err_covariant_return_type_class_type_more_qualified)
18191 << New->getDeclName() << NewTy << OldTy
18192 << New->getReturnTypeSourceRange();
18193 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18194 << Old->getReturnTypeSourceRange();
18195 return true;
18198 return false;
18201 /// Mark the given method pure.
18203 /// \param Method the method to be marked pure.
18205 /// \param InitRange the source range that covers the "0" initializer.
18206 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18207 SourceLocation EndLoc = InitRange.getEnd();
18208 if (EndLoc.isValid())
18209 Method->setRangeEnd(EndLoc);
18211 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18212 Method->setPure();
18213 return false;
18216 if (!Method->isInvalidDecl())
18217 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18218 << Method->getDeclName() << InitRange;
18219 return true;
18222 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18223 if (D->getFriendObjectKind())
18224 Diag(D->getLocation(), diag::err_pure_friend);
18225 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18226 CheckPureMethod(M, ZeroLoc);
18227 else
18228 Diag(D->getLocation(), diag::err_illegal_initializer);
18231 /// Determine whether the given declaration is a global variable or
18232 /// static data member.
18233 static bool isNonlocalVariable(const Decl *D) {
18234 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
18235 return Var->hasGlobalStorage();
18237 return false;
18240 /// Invoked when we are about to parse an initializer for the declaration
18241 /// 'Dcl'.
18243 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18244 /// static data member of class X, names should be looked up in the scope of
18245 /// class X. If the declaration had a scope specifier, a scope will have
18246 /// been created and passed in for this purpose. Otherwise, S will be null.
18247 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18248 // If there is no declaration, there was an error parsing it.
18249 if (!D || D->isInvalidDecl())
18250 return;
18252 // We will always have a nested name specifier here, but this declaration
18253 // might not be out of line if the specifier names the current namespace:
18254 // extern int n;
18255 // int ::n = 0;
18256 if (S && D->isOutOfLine())
18257 EnterDeclaratorContext(S, D->getDeclContext());
18259 // If we are parsing the initializer for a static data member, push a
18260 // new expression evaluation context that is associated with this static
18261 // data member.
18262 if (isNonlocalVariable(D))
18263 PushExpressionEvaluationContext(
18264 ExpressionEvaluationContext::PotentiallyEvaluated, D);
18267 /// Invoked after we are finished parsing an initializer for the declaration D.
18268 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18269 // If there is no declaration, there was an error parsing it.
18270 if (!D || D->isInvalidDecl())
18271 return;
18273 if (isNonlocalVariable(D))
18274 PopExpressionEvaluationContext();
18276 if (S && D->isOutOfLine())
18277 ExitDeclaratorContext(S);
18280 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18281 /// C++ if/switch/while/for statement.
18282 /// e.g: "if (int x = f()) {...}"
18283 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18284 // C++ 6.4p2:
18285 // The declarator shall not specify a function or an array.
18286 // The type-specifier-seq shall not contain typedef and shall not declare a
18287 // new class or enumeration.
18288 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18289 "Parser allowed 'typedef' as storage class of condition decl.");
18291 Decl *Dcl = ActOnDeclarator(S, D);
18292 if (!Dcl)
18293 return true;
18295 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18296 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18297 << D.getSourceRange();
18298 return true;
18301 return Dcl;
18304 void Sema::LoadExternalVTableUses() {
18305 if (!ExternalSource)
18306 return;
18308 SmallVector<ExternalVTableUse, 4> VTables;
18309 ExternalSource->ReadUsedVTables(VTables);
18310 SmallVector<VTableUse, 4> NewUses;
18311 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18312 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18313 = VTablesUsed.find(VTables[I].Record);
18314 // Even if a definition wasn't required before, it may be required now.
18315 if (Pos != VTablesUsed.end()) {
18316 if (!Pos->second && VTables[I].DefinitionRequired)
18317 Pos->second = true;
18318 continue;
18321 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18322 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18325 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18328 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18329 bool DefinitionRequired) {
18330 // Ignore any vtable uses in unevaluated operands or for classes that do
18331 // not have a vtable.
18332 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18333 CurContext->isDependentContext() || isUnevaluatedContext())
18334 return;
18335 // Do not mark as used if compiling for the device outside of the target
18336 // region.
18337 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18338 !isInOpenMPDeclareTargetContext() &&
18339 !isInOpenMPTargetExecutionDirective()) {
18340 if (!DefinitionRequired)
18341 MarkVirtualMembersReferenced(Loc, Class);
18342 return;
18345 // Try to insert this class into the map.
18346 LoadExternalVTableUses();
18347 Class = Class->getCanonicalDecl();
18348 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18349 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18350 if (!Pos.second) {
18351 // If we already had an entry, check to see if we are promoting this vtable
18352 // to require a definition. If so, we need to reappend to the VTableUses
18353 // list, since we may have already processed the first entry.
18354 if (DefinitionRequired && !Pos.first->second) {
18355 Pos.first->second = true;
18356 } else {
18357 // Otherwise, we can early exit.
18358 return;
18360 } else {
18361 // The Microsoft ABI requires that we perform the destructor body
18362 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18363 // the deleting destructor is emitted with the vtable, not with the
18364 // destructor definition as in the Itanium ABI.
18365 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18366 CXXDestructorDecl *DD = Class->getDestructor();
18367 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18368 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18369 // If this is an out-of-line declaration, marking it referenced will
18370 // not do anything. Manually call CheckDestructor to look up operator
18371 // delete().
18372 ContextRAII SavedContext(*this, DD);
18373 CheckDestructor(DD);
18374 } else {
18375 MarkFunctionReferenced(Loc, Class->getDestructor());
18381 // Local classes need to have their virtual members marked
18382 // immediately. For all other classes, we mark their virtual members
18383 // at the end of the translation unit.
18384 if (Class->isLocalClass())
18385 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18386 else
18387 VTableUses.push_back(std::make_pair(Class, Loc));
18390 bool Sema::DefineUsedVTables() {
18391 LoadExternalVTableUses();
18392 if (VTableUses.empty())
18393 return false;
18395 // Note: The VTableUses vector could grow as a result of marking
18396 // the members of a class as "used", so we check the size each
18397 // time through the loop and prefer indices (which are stable) to
18398 // iterators (which are not).
18399 bool DefinedAnything = false;
18400 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18401 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18402 if (!Class)
18403 continue;
18404 TemplateSpecializationKind ClassTSK =
18405 Class->getTemplateSpecializationKind();
18407 SourceLocation Loc = VTableUses[I].second;
18409 bool DefineVTable = true;
18411 // If this class has a key function, but that key function is
18412 // defined in another translation unit, we don't need to emit the
18413 // vtable even though we're using it.
18414 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18415 if (KeyFunction && !KeyFunction->hasBody()) {
18416 // The key function is in another translation unit.
18417 DefineVTable = false;
18418 TemplateSpecializationKind TSK =
18419 KeyFunction->getTemplateSpecializationKind();
18420 assert(TSK != TSK_ExplicitInstantiationDefinition &&
18421 TSK != TSK_ImplicitInstantiation &&
18422 "Instantiations don't have key functions");
18423 (void)TSK;
18424 } else if (!KeyFunction) {
18425 // If we have a class with no key function that is the subject
18426 // of an explicit instantiation declaration, suppress the
18427 // vtable; it will live with the explicit instantiation
18428 // definition.
18429 bool IsExplicitInstantiationDeclaration =
18430 ClassTSK == TSK_ExplicitInstantiationDeclaration;
18431 for (auto *R : Class->redecls()) {
18432 TemplateSpecializationKind TSK
18433 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18434 if (TSK == TSK_ExplicitInstantiationDeclaration)
18435 IsExplicitInstantiationDeclaration = true;
18436 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18437 IsExplicitInstantiationDeclaration = false;
18438 break;
18442 if (IsExplicitInstantiationDeclaration)
18443 DefineVTable = false;
18446 // The exception specifications for all virtual members may be needed even
18447 // if we are not providing an authoritative form of the vtable in this TU.
18448 // We may choose to emit it available_externally anyway.
18449 if (!DefineVTable) {
18450 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18451 continue;
18454 // Mark all of the virtual members of this class as referenced, so
18455 // that we can build a vtable. Then, tell the AST consumer that a
18456 // vtable for this class is required.
18457 DefinedAnything = true;
18458 MarkVirtualMembersReferenced(Loc, Class);
18459 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18460 if (VTablesUsed[Canonical])
18461 Consumer.HandleVTable(Class);
18463 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18464 // no key function or the key function is inlined. Don't warn in C++ ABIs
18465 // that lack key functions, since the user won't be able to make one.
18466 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18467 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18468 ClassTSK != TSK_ExplicitInstantiationDefinition) {
18469 const FunctionDecl *KeyFunctionDef = nullptr;
18470 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18471 KeyFunctionDef->isInlined()))
18472 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18475 VTableUses.clear();
18477 return DefinedAnything;
18480 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18481 const CXXRecordDecl *RD) {
18482 for (const auto *I : RD->methods())
18483 if (I->isVirtual() && !I->isPure())
18484 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18487 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18488 const CXXRecordDecl *RD,
18489 bool ConstexprOnly) {
18490 // Mark all functions which will appear in RD's vtable as used.
18491 CXXFinalOverriderMap FinalOverriders;
18492 RD->getFinalOverriders(FinalOverriders);
18493 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18494 E = FinalOverriders.end();
18495 I != E; ++I) {
18496 for (OverridingMethods::const_iterator OI = I->second.begin(),
18497 OE = I->second.end();
18498 OI != OE; ++OI) {
18499 assert(OI->second.size() > 0 && "no final overrider");
18500 CXXMethodDecl *Overrider = OI->second.front().Method;
18502 // C++ [basic.def.odr]p2:
18503 // [...] A virtual member function is used if it is not pure. [...]
18504 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
18505 MarkFunctionReferenced(Loc, Overrider);
18509 // Only classes that have virtual bases need a VTT.
18510 if (RD->getNumVBases() == 0)
18511 return;
18513 for (const auto &I : RD->bases()) {
18514 const auto *Base =
18515 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18516 if (Base->getNumVBases() == 0)
18517 continue;
18518 MarkVirtualMembersReferenced(Loc, Base);
18522 /// SetIvarInitializers - This routine builds initialization ASTs for the
18523 /// Objective-C implementation whose ivars need be initialized.
18524 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18525 if (!getLangOpts().CPlusPlus)
18526 return;
18527 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18528 SmallVector<ObjCIvarDecl*, 8> ivars;
18529 CollectIvarsToConstructOrDestruct(OID, ivars);
18530 if (ivars.empty())
18531 return;
18532 SmallVector<CXXCtorInitializer*, 32> AllToInit;
18533 for (unsigned i = 0; i < ivars.size(); i++) {
18534 FieldDecl *Field = ivars[i];
18535 if (Field->isInvalidDecl())
18536 continue;
18538 CXXCtorInitializer *Member;
18539 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
18540 InitializationKind InitKind =
18541 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18543 InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18544 ExprResult MemberInit =
18545 InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18546 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18547 // Note, MemberInit could actually come back empty if no initialization
18548 // is required (e.g., because it would call a trivial default constructor)
18549 if (!MemberInit.get() || MemberInit.isInvalid())
18550 continue;
18552 Member =
18553 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18554 SourceLocation(),
18555 MemberInit.getAs<Expr>(),
18556 SourceLocation());
18557 AllToInit.push_back(Member);
18559 // Be sure that the destructor is accessible and is marked as referenced.
18560 if (const RecordType *RecordTy =
18561 Context.getBaseElementType(Field->getType())
18562 ->getAs<RecordType>()) {
18563 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18564 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18565 MarkFunctionReferenced(Field->getLocation(), Destructor);
18566 CheckDestructorAccess(Field->getLocation(), Destructor,
18567 PDiag(diag::err_access_dtor_ivar)
18568 << Context.getBaseElementType(Field->getType()));
18572 ObjCImplementation->setIvarInitializers(Context,
18573 AllToInit.data(), AllToInit.size());
18577 static
18578 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18579 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18580 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18581 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18582 Sema &S) {
18583 if (Ctor->isInvalidDecl())
18584 return;
18586 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18588 // Target may not be determinable yet, for instance if this is a dependent
18589 // call in an uninstantiated template.
18590 if (Target) {
18591 const FunctionDecl *FNTarget = nullptr;
18592 (void)Target->hasBody(FNTarget);
18593 Target = const_cast<CXXConstructorDecl*>(
18594 cast_or_null<CXXConstructorDecl>(FNTarget));
18597 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18598 // Avoid dereferencing a null pointer here.
18599 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18601 if (!Current.insert(Canonical).second)
18602 return;
18604 // We know that beyond here, we aren't chaining into a cycle.
18605 if (!Target || !Target->isDelegatingConstructor() ||
18606 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18607 Valid.insert(Current.begin(), Current.end());
18608 Current.clear();
18609 // We've hit a cycle.
18610 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18611 Current.count(TCanonical)) {
18612 // If we haven't diagnosed this cycle yet, do so now.
18613 if (!Invalid.count(TCanonical)) {
18614 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18615 diag::warn_delegating_ctor_cycle)
18616 << Ctor;
18618 // Don't add a note for a function delegating directly to itself.
18619 if (TCanonical != Canonical)
18620 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18622 CXXConstructorDecl *C = Target;
18623 while (C->getCanonicalDecl() != Canonical) {
18624 const FunctionDecl *FNTarget = nullptr;
18625 (void)C->getTargetConstructor()->hasBody(FNTarget);
18626 assert(FNTarget && "Ctor cycle through bodiless function");
18628 C = const_cast<CXXConstructorDecl*>(
18629 cast<CXXConstructorDecl>(FNTarget));
18630 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18634 Invalid.insert(Current.begin(), Current.end());
18635 Current.clear();
18636 } else {
18637 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18642 void Sema::CheckDelegatingCtorCycles() {
18643 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18645 for (DelegatingCtorDeclsType::iterator
18646 I = DelegatingCtorDecls.begin(ExternalSource.get()),
18647 E = DelegatingCtorDecls.end();
18648 I != E; ++I)
18649 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18651 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18652 (*CI)->setInvalidDecl();
18655 namespace {
18656 /// AST visitor that finds references to the 'this' expression.
18657 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18658 Sema &S;
18660 public:
18661 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18663 bool VisitCXXThisExpr(CXXThisExpr *E) {
18664 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18665 << E->isImplicit();
18666 return false;
18671 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18672 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18673 if (!TSInfo)
18674 return false;
18676 TypeLoc TL = TSInfo->getTypeLoc();
18677 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18678 if (!ProtoTL)
18679 return false;
18681 // C++11 [expr.prim.general]p3:
18682 // [The expression this] shall not appear before the optional
18683 // cv-qualifier-seq and it shall not appear within the declaration of a
18684 // static member function (although its type and value category are defined
18685 // within a static member function as they are within a non-static member
18686 // function). [ Note: this is because declaration matching does not occur
18687 // until the complete declarator is known. - end note ]
18688 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18689 FindCXXThisExpr Finder(*this);
18691 // If the return type came after the cv-qualifier-seq, check it now.
18692 if (Proto->hasTrailingReturn() &&
18693 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18694 return true;
18696 // Check the exception specification.
18697 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18698 return true;
18700 // Check the trailing requires clause
18701 if (Expr *E = Method->getTrailingRequiresClause())
18702 if (!Finder.TraverseStmt(E))
18703 return true;
18705 return checkThisInStaticMemberFunctionAttributes(Method);
18708 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18709 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18710 if (!TSInfo)
18711 return false;
18713 TypeLoc TL = TSInfo->getTypeLoc();
18714 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18715 if (!ProtoTL)
18716 return false;
18718 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18719 FindCXXThisExpr Finder(*this);
18721 switch (Proto->getExceptionSpecType()) {
18722 case EST_Unparsed:
18723 case EST_Uninstantiated:
18724 case EST_Unevaluated:
18725 case EST_BasicNoexcept:
18726 case EST_NoThrow:
18727 case EST_DynamicNone:
18728 case EST_MSAny:
18729 case EST_None:
18730 break;
18732 case EST_DependentNoexcept:
18733 case EST_NoexceptFalse:
18734 case EST_NoexceptTrue:
18735 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18736 return true;
18737 [[fallthrough]];
18739 case EST_Dynamic:
18740 for (const auto &E : Proto->exceptions()) {
18741 if (!Finder.TraverseType(E))
18742 return true;
18744 break;
18747 return false;
18750 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18751 FindCXXThisExpr Finder(*this);
18753 // Check attributes.
18754 for (const auto *A : Method->attrs()) {
18755 // FIXME: This should be emitted by tblgen.
18756 Expr *Arg = nullptr;
18757 ArrayRef<Expr *> Args;
18758 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18759 Arg = G->getArg();
18760 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18761 Arg = G->getArg();
18762 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18763 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18764 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18765 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18766 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18767 Arg = ETLF->getSuccessValue();
18768 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18769 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18770 Arg = STLF->getSuccessValue();
18771 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18772 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18773 Arg = LR->getArg();
18774 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18775 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18776 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18777 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18778 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18779 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18780 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18781 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18782 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18783 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18785 if (Arg && !Finder.TraverseStmt(Arg))
18786 return true;
18788 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18789 if (!Finder.TraverseStmt(Args[I]))
18790 return true;
18794 return false;
18797 void Sema::checkExceptionSpecification(
18798 bool IsTopLevel, ExceptionSpecificationType EST,
18799 ArrayRef<ParsedType> DynamicExceptions,
18800 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18801 SmallVectorImpl<QualType> &Exceptions,
18802 FunctionProtoType::ExceptionSpecInfo &ESI) {
18803 Exceptions.clear();
18804 ESI.Type = EST;
18805 if (EST == EST_Dynamic) {
18806 Exceptions.reserve(DynamicExceptions.size());
18807 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18808 // FIXME: Preserve type source info.
18809 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18811 if (IsTopLevel) {
18812 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18813 collectUnexpandedParameterPacks(ET, Unexpanded);
18814 if (!Unexpanded.empty()) {
18815 DiagnoseUnexpandedParameterPacks(
18816 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18817 Unexpanded);
18818 continue;
18822 // Check that the type is valid for an exception spec, and
18823 // drop it if not.
18824 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18825 Exceptions.push_back(ET);
18827 ESI.Exceptions = Exceptions;
18828 return;
18831 if (isComputedNoexcept(EST)) {
18832 assert((NoexceptExpr->isTypeDependent() ||
18833 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18834 Context.BoolTy) &&
18835 "Parser should have made sure that the expression is boolean");
18836 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18837 ESI.Type = EST_BasicNoexcept;
18838 return;
18841 ESI.NoexceptExpr = NoexceptExpr;
18842 return;
18846 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18847 ExceptionSpecificationType EST,
18848 SourceRange SpecificationRange,
18849 ArrayRef<ParsedType> DynamicExceptions,
18850 ArrayRef<SourceRange> DynamicExceptionRanges,
18851 Expr *NoexceptExpr) {
18852 if (!MethodD)
18853 return;
18855 // Dig out the method we're referring to.
18856 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18857 MethodD = FunTmpl->getTemplatedDecl();
18859 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18860 if (!Method)
18861 return;
18863 // Check the exception specification.
18864 llvm::SmallVector<QualType, 4> Exceptions;
18865 FunctionProtoType::ExceptionSpecInfo ESI;
18866 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18867 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18868 ESI);
18870 // Update the exception specification on the function type.
18871 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18873 if (Method->isStatic())
18874 checkThisInStaticMemberFunctionExceptionSpec(Method);
18876 if (Method->isVirtual()) {
18877 // Check overrides, which we previously had to delay.
18878 for (const CXXMethodDecl *O : Method->overridden_methods())
18879 CheckOverridingFunctionExceptionSpec(Method, O);
18883 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18885 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18886 SourceLocation DeclStart, Declarator &D,
18887 Expr *BitWidth,
18888 InClassInitStyle InitStyle,
18889 AccessSpecifier AS,
18890 const ParsedAttr &MSPropertyAttr) {
18891 IdentifierInfo *II = D.getIdentifier();
18892 if (!II) {
18893 Diag(DeclStart, diag::err_anonymous_property);
18894 return nullptr;
18896 SourceLocation Loc = D.getIdentifierLoc();
18898 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18899 QualType T = TInfo->getType();
18900 if (getLangOpts().CPlusPlus) {
18901 CheckExtraCXXDefaultArguments(D);
18903 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18904 UPPC_DataMemberType)) {
18905 D.setInvalidType();
18906 T = Context.IntTy;
18907 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18911 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18913 if (D.getDeclSpec().isInlineSpecified())
18914 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18915 << getLangOpts().CPlusPlus17;
18916 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18917 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18918 diag::err_invalid_thread)
18919 << DeclSpec::getSpecifierName(TSCS);
18921 // Check to see if this name was declared as a member previously
18922 NamedDecl *PrevDecl = nullptr;
18923 LookupResult Previous(*this, II, Loc, LookupMemberName,
18924 ForVisibleRedeclaration);
18925 LookupName(Previous, S);
18926 switch (Previous.getResultKind()) {
18927 case LookupResult::Found:
18928 case LookupResult::FoundUnresolvedValue:
18929 PrevDecl = Previous.getAsSingle<NamedDecl>();
18930 break;
18932 case LookupResult::FoundOverloaded:
18933 PrevDecl = Previous.getRepresentativeDecl();
18934 break;
18936 case LookupResult::NotFound:
18937 case LookupResult::NotFoundInCurrentInstantiation:
18938 case LookupResult::Ambiguous:
18939 break;
18942 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18943 // Maybe we will complain about the shadowed template parameter.
18944 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18945 // Just pretend that we didn't see the previous declaration.
18946 PrevDecl = nullptr;
18949 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18950 PrevDecl = nullptr;
18952 SourceLocation TSSL = D.getBeginLoc();
18953 MSPropertyDecl *NewPD =
18954 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18955 MSPropertyAttr.getPropertyDataGetter(),
18956 MSPropertyAttr.getPropertyDataSetter());
18957 ProcessDeclAttributes(TUScope, NewPD, D);
18958 NewPD->setAccess(AS);
18960 if (NewPD->isInvalidDecl())
18961 Record->setInvalidDecl();
18963 if (D.getDeclSpec().isModulePrivateSpecified())
18964 NewPD->setModulePrivate();
18966 if (NewPD->isInvalidDecl() && PrevDecl) {
18967 // Don't introduce NewFD into scope; there's already something
18968 // with the same name in the same scope.
18969 } else if (II) {
18970 PushOnScopeChains(NewPD, S);
18971 } else
18972 Record->addDecl(NewPD);
18974 return NewPD;
18977 void Sema::ActOnStartFunctionDeclarationDeclarator(
18978 Declarator &Declarator, unsigned TemplateParameterDepth) {
18979 auto &Info = InventedParameterInfos.emplace_back();
18980 TemplateParameterList *ExplicitParams = nullptr;
18981 ArrayRef<TemplateParameterList *> ExplicitLists =
18982 Declarator.getTemplateParameterLists();
18983 if (!ExplicitLists.empty()) {
18984 bool IsMemberSpecialization, IsInvalid;
18985 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18986 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18987 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18988 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18989 /*SuppressDiagnostic=*/true);
18991 if (ExplicitParams) {
18992 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18993 llvm::append_range(Info.TemplateParams, *ExplicitParams);
18994 Info.NumExplicitTemplateParams = ExplicitParams->size();
18995 } else {
18996 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18997 Info.NumExplicitTemplateParams = 0;
19001 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19002 auto &FSI = InventedParameterInfos.back();
19003 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19004 if (FSI.NumExplicitTemplateParams != 0) {
19005 TemplateParameterList *ExplicitParams =
19006 Declarator.getTemplateParameterLists().back();
19007 Declarator.setInventedTemplateParameterList(
19008 TemplateParameterList::Create(
19009 Context, ExplicitParams->getTemplateLoc(),
19010 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19011 ExplicitParams->getRAngleLoc(),
19012 ExplicitParams->getRequiresClause()));
19013 } else {
19014 Declarator.setInventedTemplateParameterList(
19015 TemplateParameterList::Create(
19016 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19017 SourceLocation(), /*RequiresClause=*/nullptr));
19020 InventedParameterInfos.pop_back();