1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
45 using namespace clang;
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
57 class CheckDefaultArgumentVisitor
58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64 : DefaultArg(defarg), S(s) {}
66 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
68 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69 bool VisitLambdaExpr(LambdaExpr *Lambda);
70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
76 for (Stmt *SubStmt : Node->children())
77 IsInvalid |= Visit(SubStmt);
81 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85 NamedDecl *Decl = DRE->getDecl();
86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
95 return S->Diag(DRE->getLocStart(),
96 diag::err_param_default_argument_references_param)
97 << Param->getDeclName() << DefaultArg->getSourceRange();
98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
102 if (VDecl->isLocalVarDecl())
103 return S->Diag(DRE->getLocStart(),
104 diag::err_param_default_argument_references_local)
105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
116 return S->Diag(ThisE->getLocStart(),
117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 // If this function can throw any exceptions, make a note of that.
166 if (EST == EST_MSAny || EST == EST_None) {
172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
204 ComputedEST = EST_None;
206 // noexcept(true) won't change anything either.
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217 Exceptions.push_back(E);
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221 if (!E || ComputedEST == EST_MSAny)
226 // C++0x [except.spec]p14:
227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
245 if (Self->canThrow(E))
246 ComputedEST = EST_None;
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251 SourceLocation EqualLoc) {
252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270 if (Result.isInvalid())
272 Arg = Result.getAs<Expr>();
274 CheckCompletedExpr(Arg, EqualLoc);
275 Arg = MaybeCreateExprWithCleanups(Arg);
277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
301 if (!param || !DefaultArg)
304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
305 UnparsedDefaultArgLocs.erase(Param);
307 // Default arguments are only permitted in C++
308 if (!getLangOpts().CPlusPlus) {
309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
311 Param->setInvalidDecl();
315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
321 // C++11 [dcl.fct.default]p3
322 // A default argument expression [...] shall not be specified for a
324 if (Param->isParameterPack()) {
325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326 << DefaultArg->getSourceRange();
330 // Check that the default argument is well-formed
331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332 if (DefaultArgChecker.Visit(DefaultArg)) {
333 Param->setInvalidDecl();
337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
341 /// argument for a function parameter, but we can't parse it yet
342 /// because we're inside a class definition. Note that this default
343 /// argument will be parsed later.
344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345 SourceLocation EqualLoc,
346 SourceLocation ArgLoc) {
350 ParmVarDecl *Param = cast<ParmVarDecl>(param);
351 Param->setUnparsedDefaultArg();
352 UnparsedDefaultArgLocs[Param] = ArgLoc;
355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356 /// the default argument for the parameter param failed.
357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
358 SourceLocation EqualLoc) {
362 ParmVarDecl *Param = cast<ParmVarDecl>(param);
363 Param->setInvalidDecl();
364 UnparsedDefaultArgLocs.erase(Param);
365 Param->setDefaultArg(new(Context)
366 OpaqueValueExpr(EqualLoc,
367 Param->getType().getNonReferenceType(),
371 /// CheckExtraCXXDefaultArguments - Check for any extra default
372 /// arguments in the declarator, which is not a function declaration
373 /// or definition and therefore is not permitted to have default
374 /// arguments. This routine should be invoked for every declarator
375 /// that is not a function declaration or definition.
376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377 // C++ [dcl.fct.default]p3
378 // A default argument expression shall be specified only in the
379 // parameter-declaration-clause of a function declaration or in a
380 // template-parameter (14.1). It shall not be specified for a
381 // parameter pack. If it is specified in a
382 // parameter-declaration-clause, it shall not occur within a
383 // declarator or abstract-declarator of a parameter-declaration.
384 bool MightBeFunction = D.isFunctionDeclarationContext();
385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386 DeclaratorChunk &chunk = D.getTypeObject(i);
387 if (chunk.Kind == DeclaratorChunk::Function) {
388 if (MightBeFunction) {
389 // This is a function declaration. It can have default arguments, but
390 // keep looking in case its return type is a function type with default
392 MightBeFunction = false;
395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398 if (Param->hasUnparsedDefaultArg()) {
399 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
405 SR = UnparsedDefaultArgLocs[Param];
406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
409 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
410 } else if (Param->getDefaultArg()) {
411 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
412 << Param->getDefaultArg()->getSourceRange();
413 Param->setDefaultArg(nullptr);
416 } else if (chunk.Kind != DeclaratorChunk::Paren) {
417 MightBeFunction = false;
422 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
423 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
424 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
425 if (!PVD->hasDefaultArg())
427 if (!PVD->hasInheritedDefaultArg())
433 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
434 /// function, once we already know that they have the same
435 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
436 /// error, false otherwise.
437 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
439 bool Invalid = false;
441 // The declaration context corresponding to the scope is the semantic
442 // parent, unless this is a local function declaration, in which case
443 // it is that surrounding function.
444 DeclContext *ScopeDC = New->isLocalExternDecl()
445 ? New->getLexicalDeclContext()
446 : New->getDeclContext();
448 // Find the previous declaration for the purpose of default arguments.
449 FunctionDecl *PrevForDefaultArgs = Old;
450 for (/**/; PrevForDefaultArgs;
451 // Don't bother looking back past the latest decl if this is a local
452 // extern declaration; nothing else could work.
453 PrevForDefaultArgs = New->isLocalExternDecl()
455 : PrevForDefaultArgs->getPreviousDecl()) {
456 // Ignore hidden declarations.
457 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
460 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
461 !New->isCXXClassMember()) {
462 // Ignore default arguments of old decl if they are not in
463 // the same scope and this is not an out-of-line definition of
464 // a member function.
468 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
469 // If only one of these is a local function declaration, then they are
470 // declared in different scopes, even though isDeclInScope may think
471 // they're in the same scope. (If both are local, the scope check is
472 // sufficent, and if neither is local, then they are in the same scope.)
480 // C++ [dcl.fct.default]p4:
481 // For non-template functions, default arguments can be added in
482 // later declarations of a function in the same
483 // scope. Declarations in different scopes have completely
484 // distinct sets of default arguments. That is, declarations in
485 // inner scopes do not acquire default arguments from
486 // declarations in outer scopes, and vice versa. In a given
487 // function declaration, all parameters subsequent to a
488 // parameter with a default argument shall have default
489 // arguments supplied in this or previous declarations. A
490 // default argument shall not be redefined by a later
491 // declaration (not even to the same value).
493 // C++ [dcl.fct.default]p6:
494 // Except for member functions of class templates, the default arguments
495 // in a member function definition that appears outside of the class
496 // definition are added to the set of default arguments provided by the
497 // member function declaration in the class definition.
498 for (unsigned p = 0, NumParams = PrevForDefaultArgs
499 ? PrevForDefaultArgs->getNumParams()
501 p < NumParams; ++p) {
502 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
503 ParmVarDecl *NewParam = New->getParamDecl(p);
505 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
506 bool NewParamHasDfl = NewParam->hasDefaultArg();
508 if (OldParamHasDfl && NewParamHasDfl) {
509 unsigned DiagDefaultParamID =
510 diag::err_param_default_argument_redefinition;
512 // MSVC accepts that default parameters be redefined for member functions
513 // of template class. The new default parameter's value is ignored.
515 if (getLangOpts().MicrosoftExt) {
516 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
517 if (MD && MD->getParent()->getDescribedClassTemplate()) {
518 // Merge the old default argument into the new parameter.
519 NewParam->setHasInheritedDefaultArg();
520 if (OldParam->hasUninstantiatedDefaultArg())
521 NewParam->setUninstantiatedDefaultArg(
522 OldParam->getUninstantiatedDefaultArg());
524 NewParam->setDefaultArg(OldParam->getInit());
525 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
530 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
531 // hint here. Alternatively, we could walk the type-source information
532 // for NewParam to find the last source location in the type... but it
533 // isn't worth the effort right now. This is the kind of test case that
534 // is hard to get right:
536 // void g(int (*fp)(int) = f);
537 // void g(int (*fp)(int) = &f);
538 Diag(NewParam->getLocation(), DiagDefaultParamID)
539 << NewParam->getDefaultArgRange();
541 // Look for the function declaration where the default argument was
542 // actually written, which may be a declaration prior to Old.
543 for (auto Older = PrevForDefaultArgs;
544 OldParam->hasInheritedDefaultArg(); /**/) {
545 Older = Older->getPreviousDecl();
546 OldParam = Older->getParamDecl(p);
549 Diag(OldParam->getLocation(), diag::note_previous_definition)
550 << OldParam->getDefaultArgRange();
551 } else if (OldParamHasDfl) {
552 // Merge the old default argument into the new parameter.
553 // It's important to use getInit() here; getDefaultArg()
554 // strips off any top-level ExprWithCleanups.
555 NewParam->setHasInheritedDefaultArg();
556 if (OldParam->hasUnparsedDefaultArg())
557 NewParam->setUnparsedDefaultArg();
558 else if (OldParam->hasUninstantiatedDefaultArg())
559 NewParam->setUninstantiatedDefaultArg(
560 OldParam->getUninstantiatedDefaultArg());
562 NewParam->setDefaultArg(OldParam->getInit());
563 } else if (NewParamHasDfl) {
564 if (New->getDescribedFunctionTemplate()) {
565 // Paragraph 4, quoted above, only applies to non-template functions.
566 Diag(NewParam->getLocation(),
567 diag::err_param_default_argument_template_redecl)
568 << NewParam->getDefaultArgRange();
569 Diag(PrevForDefaultArgs->getLocation(),
570 diag::note_template_prev_declaration)
572 } else if (New->getTemplateSpecializationKind()
573 != TSK_ImplicitInstantiation &&
574 New->getTemplateSpecializationKind() != TSK_Undeclared) {
575 // C++ [temp.expr.spec]p21:
576 // Default function arguments shall not be specified in a declaration
577 // or a definition for one of the following explicit specializations:
578 // - the explicit specialization of a function template;
579 // - the explicit specialization of a member function template;
580 // - the explicit specialization of a member function of a class
581 // template where the class template specialization to which the
582 // member function specialization belongs is implicitly
584 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
585 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
586 << New->getDeclName()
587 << NewParam->getDefaultArgRange();
588 } else if (New->getDeclContext()->isDependentContext()) {
589 // C++ [dcl.fct.default]p6 (DR217):
590 // Default arguments for a member function of a class template shall
591 // be specified on the initial declaration of the member function
592 // within the class template.
594 // Reading the tea leaves a bit in DR217 and its reference to DR205
595 // leads me to the conclusion that one cannot add default function
596 // arguments for an out-of-line definition of a member function of a
599 if (CXXRecordDecl *Record
600 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
601 if (Record->getDescribedClassTemplate())
603 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
609 Diag(NewParam->getLocation(),
610 diag::err_param_default_argument_member_template_redecl)
612 << NewParam->getDefaultArgRange();
617 // DR1344: If a default argument is added outside a class definition and that
618 // default argument makes the function a special member function, the program
619 // is ill-formed. This can only happen for constructors.
620 if (isa<CXXConstructorDecl>(New) &&
621 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
622 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
623 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
624 if (NewSM != OldSM) {
625 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
626 assert(NewParam->hasDefaultArg());
627 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
628 << NewParam->getDefaultArgRange() << NewSM;
629 Diag(Old->getLocation(), diag::note_previous_declaration);
633 const FunctionDecl *Def;
634 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
635 // template has a constexpr specifier then all its declarations shall
636 // contain the constexpr specifier.
637 if (New->isConstexpr() != Old->isConstexpr()) {
638 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
639 << New << New->isConstexpr();
640 Diag(Old->getLocation(), diag::note_previous_declaration);
642 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
643 Old->isDefined(Def)) {
644 // C++11 [dcl.fcn.spec]p4:
645 // If the definition of a function appears in a translation unit before its
646 // first declaration as inline, the program is ill-formed.
647 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
648 Diag(Def->getLocation(), diag::note_previous_definition);
652 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
653 // argument expression, that declaration shall be a definition and shall be
654 // the only declaration of the function or function template in the
656 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
657 functionDeclHasDefaultArgument(Old)) {
658 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
659 Diag(Old->getLocation(), diag::note_previous_declaration);
663 if (CheckEquivalentExceptionSpec(Old, New))
669 /// \brief Merge the exception specifications of two variable declarations.
671 /// This is called when there's a redeclaration of a VarDecl. The function
672 /// checks if the redeclaration might have an exception specification and
673 /// validates compatibility and merges the specs if necessary.
674 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
675 // Shortcut if exceptions are disabled.
676 if (!getLangOpts().CXXExceptions)
679 assert(Context.hasSameType(New->getType(), Old->getType()) &&
680 "Should only be called if types are otherwise the same.");
682 QualType NewType = New->getType();
683 QualType OldType = Old->getType();
685 // We're only interested in pointers and references to functions, as well
686 // as pointers to member functions.
687 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
688 NewType = R->getPointeeType();
689 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
690 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
691 NewType = P->getPointeeType();
692 OldType = OldType->getAs<PointerType>()->getPointeeType();
693 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
694 NewType = M->getPointeeType();
695 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
698 if (!NewType->isFunctionProtoType())
701 // There's lots of special cases for functions. For function pointers, system
702 // libraries are hopefully not as broken so that we don't need these
704 if (CheckEquivalentExceptionSpec(
705 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
706 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
707 New->setInvalidDecl();
711 /// CheckCXXDefaultArguments - Verify that the default arguments for a
712 /// function declaration are well-formed according to C++
713 /// [dcl.fct.default].
714 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
715 unsigned NumParams = FD->getNumParams();
718 // Find first parameter with a default argument
719 for (p = 0; p < NumParams; ++p) {
720 ParmVarDecl *Param = FD->getParamDecl(p);
721 if (Param->hasDefaultArg())
725 // C++11 [dcl.fct.default]p4:
726 // In a given function declaration, each parameter subsequent to a parameter
727 // with a default argument shall have a default argument supplied in this or
728 // a previous declaration or shall be a function parameter pack. A default
729 // argument shall not be redefined by a later declaration (not even to the
731 unsigned LastMissingDefaultArg = 0;
732 for (; p < NumParams; ++p) {
733 ParmVarDecl *Param = FD->getParamDecl(p);
734 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
735 if (Param->isInvalidDecl())
736 /* We already complained about this parameter. */;
737 else if (Param->getIdentifier())
738 Diag(Param->getLocation(),
739 diag::err_param_default_argument_missing_name)
740 << Param->getIdentifier();
742 Diag(Param->getLocation(),
743 diag::err_param_default_argument_missing);
745 LastMissingDefaultArg = p;
749 if (LastMissingDefaultArg > 0) {
750 // Some default arguments were missing. Clear out all of the
751 // default arguments up to (and including) the last missing
752 // default argument, so that we leave the function parameters
753 // in a semantically valid state.
754 for (p = 0; p <= LastMissingDefaultArg; ++p) {
755 ParmVarDecl *Param = FD->getParamDecl(p);
756 if (Param->hasDefaultArg()) {
757 Param->setDefaultArg(nullptr);
763 // CheckConstexprParameterTypes - Check whether a function's parameter types
764 // are all literal types. If so, return true. If not, produce a suitable
765 // diagnostic and return false.
766 static bool CheckConstexprParameterTypes(Sema &SemaRef,
767 const FunctionDecl *FD) {
768 unsigned ArgIndex = 0;
769 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
770 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
771 e = FT->param_type_end();
772 i != e; ++i, ++ArgIndex) {
773 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
774 SourceLocation ParamLoc = PD->getLocation();
775 if (!(*i)->isDependentType() &&
776 SemaRef.RequireLiteralType(ParamLoc, *i,
777 diag::err_constexpr_non_literal_param,
778 ArgIndex+1, PD->getSourceRange(),
779 isa<CXXConstructorDecl>(FD)))
785 /// \brief Get diagnostic %select index for tag kind for
786 /// record diagnostic message.
787 /// WARNING: Indexes apply to particular diagnostics only!
789 /// \returns diagnostic %select index.
790 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
792 case TTK_Struct: return 0;
793 case TTK_Interface: return 1;
794 case TTK_Class: return 2;
795 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
799 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
800 // the requirements of a constexpr function definition or a constexpr
801 // constructor definition. If so, return true. If not, produce appropriate
802 // diagnostics and return false.
804 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
805 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
806 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
807 if (MD && MD->isInstance()) {
808 // C++11 [dcl.constexpr]p4:
809 // The definition of a constexpr constructor shall satisfy the following
811 // - the class shall not have any virtual base classes;
812 const CXXRecordDecl *RD = MD->getParent();
813 if (RD->getNumVBases()) {
814 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
815 << isa<CXXConstructorDecl>(NewFD)
816 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
817 for (const auto &I : RD->vbases())
818 Diag(I.getLocStart(),
819 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
824 if (!isa<CXXConstructorDecl>(NewFD)) {
825 // C++11 [dcl.constexpr]p3:
826 // The definition of a constexpr function shall satisfy the following
828 // - it shall not be virtual;
829 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
830 if (Method && Method->isVirtual()) {
831 Method = Method->getCanonicalDecl();
832 Diag(Method->getLocation(), diag::err_constexpr_virtual);
834 // If it's not obvious why this function is virtual, find an overridden
835 // function which uses the 'virtual' keyword.
836 const CXXMethodDecl *WrittenVirtual = Method;
837 while (!WrittenVirtual->isVirtualAsWritten())
838 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
839 if (WrittenVirtual != Method)
840 Diag(WrittenVirtual->getLocation(),
841 diag::note_overridden_virtual_function);
845 // - its return type shall be a literal type;
846 QualType RT = NewFD->getReturnType();
847 if (!RT->isDependentType() &&
848 RequireLiteralType(NewFD->getLocation(), RT,
849 diag::err_constexpr_non_literal_return))
853 // - each of its parameter types shall be a literal type;
854 if (!CheckConstexprParameterTypes(*this, NewFD))
860 /// Check the given declaration statement is legal within a constexpr function
861 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
863 /// \return true if the body is OK (maybe only as an extension), false if we
864 /// have diagnosed a problem.
865 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
866 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
867 // C++11 [dcl.constexpr]p3 and p4:
868 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
870 for (const auto *DclIt : DS->decls()) {
871 switch (DclIt->getKind()) {
872 case Decl::StaticAssert:
874 case Decl::UsingShadow:
875 case Decl::UsingDirective:
876 case Decl::UnresolvedUsingTypename:
877 case Decl::UnresolvedUsingValue:
878 // - static_assert-declarations
879 // - using-declarations,
880 // - using-directives,
884 case Decl::TypeAlias: {
885 // - typedef declarations and alias-declarations that do not define
886 // classes or enumerations,
887 const auto *TN = cast<TypedefNameDecl>(DclIt);
888 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
889 // Don't allow variably-modified types in constexpr functions.
890 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
891 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
892 << TL.getSourceRange() << TL.getType()
893 << isa<CXXConstructorDecl>(Dcl);
900 case Decl::CXXRecord:
901 // C++1y allows types to be defined, not just declared.
902 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
903 SemaRef.Diag(DS->getLocStart(),
904 SemaRef.getLangOpts().CPlusPlus14
905 ? diag::warn_cxx11_compat_constexpr_type_definition
906 : diag::ext_constexpr_type_definition)
907 << isa<CXXConstructorDecl>(Dcl);
910 case Decl::EnumConstant:
911 case Decl::IndirectField:
913 // These can only appear with other declarations which are banned in
914 // C++11 and permitted in C++1y, so ignore them.
918 // C++1y [dcl.constexpr]p3 allows anything except:
919 // a definition of a variable of non-literal type or of static or
920 // thread storage duration or for which no initialization is performed.
921 const auto *VD = cast<VarDecl>(DclIt);
922 if (VD->isThisDeclarationADefinition()) {
923 if (VD->isStaticLocal()) {
924 SemaRef.Diag(VD->getLocation(),
925 diag::err_constexpr_local_var_static)
926 << isa<CXXConstructorDecl>(Dcl)
927 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
930 if (!VD->getType()->isDependentType() &&
931 SemaRef.RequireLiteralType(
932 VD->getLocation(), VD->getType(),
933 diag::err_constexpr_local_var_non_literal_type,
934 isa<CXXConstructorDecl>(Dcl)))
936 if (!VD->getType()->isDependentType() &&
937 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
938 SemaRef.Diag(VD->getLocation(),
939 diag::err_constexpr_local_var_no_init)
940 << isa<CXXConstructorDecl>(Dcl);
944 SemaRef.Diag(VD->getLocation(),
945 SemaRef.getLangOpts().CPlusPlus14
946 ? diag::warn_cxx11_compat_constexpr_local_var
947 : diag::ext_constexpr_local_var)
948 << isa<CXXConstructorDecl>(Dcl);
952 case Decl::NamespaceAlias:
954 // These are disallowed in C++11 and permitted in C++1y. Allow them
955 // everywhere as an extension.
956 if (!Cxx1yLoc.isValid())
957 Cxx1yLoc = DS->getLocStart();
961 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
962 << isa<CXXConstructorDecl>(Dcl);
970 /// Check that the given field is initialized within a constexpr constructor.
972 /// \param Dcl The constexpr constructor being checked.
973 /// \param Field The field being checked. This may be a member of an anonymous
974 /// struct or union nested within the class being checked.
975 /// \param Inits All declarations, including anonymous struct/union members and
976 /// indirect members, for which any initialization was provided.
977 /// \param Diagnosed Set to true if an error is produced.
978 static void CheckConstexprCtorInitializer(Sema &SemaRef,
979 const FunctionDecl *Dcl,
981 llvm::SmallSet<Decl*, 16> &Inits,
983 if (Field->isInvalidDecl())
986 if (Field->isUnnamedBitfield())
989 // Anonymous unions with no variant members and empty anonymous structs do not
990 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
991 // indirect fields don't need initializing.
992 if (Field->isAnonymousStructOrUnion() &&
993 (Field->getType()->isUnionType()
994 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
995 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
998 if (!Inits.count(Field)) {
1000 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1003 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1004 } else if (Field->isAnonymousStructOrUnion()) {
1005 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1006 for (auto *I : RD->fields())
1007 // If an anonymous union contains an anonymous struct of which any member
1008 // is initialized, all members must be initialized.
1009 if (!RD->isUnion() || Inits.count(I))
1010 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1014 /// Check the provided statement is allowed in a constexpr function
1017 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1018 SmallVectorImpl<SourceLocation> &ReturnStmts,
1019 SourceLocation &Cxx1yLoc) {
1020 // - its function-body shall be [...] a compound-statement that contains only
1021 switch (S->getStmtClass()) {
1022 case Stmt::NullStmtClass:
1023 // - null statements,
1026 case Stmt::DeclStmtClass:
1027 // - static_assert-declarations
1028 // - using-declarations,
1029 // - using-directives,
1030 // - typedef declarations and alias-declarations that do not define
1031 // classes or enumerations,
1032 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1036 case Stmt::ReturnStmtClass:
1037 // - and exactly one return statement;
1038 if (isa<CXXConstructorDecl>(Dcl)) {
1039 // C++1y allows return statements in constexpr constructors.
1040 if (!Cxx1yLoc.isValid())
1041 Cxx1yLoc = S->getLocStart();
1045 ReturnStmts.push_back(S->getLocStart());
1048 case Stmt::CompoundStmtClass: {
1049 // C++1y allows compound-statements.
1050 if (!Cxx1yLoc.isValid())
1051 Cxx1yLoc = S->getLocStart();
1053 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1054 for (auto *BodyIt : CompStmt->body()) {
1055 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1062 case Stmt::AttributedStmtClass:
1063 if (!Cxx1yLoc.isValid())
1064 Cxx1yLoc = S->getLocStart();
1067 case Stmt::IfStmtClass: {
1068 // C++1y allows if-statements.
1069 if (!Cxx1yLoc.isValid())
1070 Cxx1yLoc = S->getLocStart();
1072 IfStmt *If = cast<IfStmt>(S);
1073 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1076 if (If->getElse() &&
1077 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1083 case Stmt::WhileStmtClass:
1084 case Stmt::DoStmtClass:
1085 case Stmt::ForStmtClass:
1086 case Stmt::CXXForRangeStmtClass:
1087 case Stmt::ContinueStmtClass:
1088 // C++1y allows all of these. We don't allow them as extensions in C++11,
1089 // because they don't make sense without variable mutation.
1090 if (!SemaRef.getLangOpts().CPlusPlus14)
1092 if (!Cxx1yLoc.isValid())
1093 Cxx1yLoc = S->getLocStart();
1094 for (Stmt *SubStmt : S->children())
1096 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1101 case Stmt::SwitchStmtClass:
1102 case Stmt::CaseStmtClass:
1103 case Stmt::DefaultStmtClass:
1104 case Stmt::BreakStmtClass:
1105 // C++1y allows switch-statements, and since they don't need variable
1106 // mutation, we can reasonably allow them in C++11 as an extension.
1107 if (!Cxx1yLoc.isValid())
1108 Cxx1yLoc = S->getLocStart();
1109 for (Stmt *SubStmt : S->children())
1111 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1120 // C++1y allows expression-statements.
1121 if (!Cxx1yLoc.isValid())
1122 Cxx1yLoc = S->getLocStart();
1126 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1127 << isa<CXXConstructorDecl>(Dcl);
1131 /// Check the body for the given constexpr function declaration only contains
1132 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1134 /// \return true if the body is OK, false if we have diagnosed a problem.
1135 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1136 if (isa<CXXTryStmt>(Body)) {
1137 // C++11 [dcl.constexpr]p3:
1138 // The definition of a constexpr function shall satisfy the following
1139 // constraints: [...]
1140 // - its function-body shall be = delete, = default, or a
1141 // compound-statement
1143 // C++11 [dcl.constexpr]p4:
1144 // In the definition of a constexpr constructor, [...]
1145 // - its function-body shall not be a function-try-block;
1146 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1147 << isa<CXXConstructorDecl>(Dcl);
1151 SmallVector<SourceLocation, 4> ReturnStmts;
1153 // - its function-body shall be [...] a compound-statement that contains only
1154 // [... list of cases ...]
1155 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1156 SourceLocation Cxx1yLoc;
1157 for (auto *BodyIt : CompBody->body()) {
1158 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1162 if (Cxx1yLoc.isValid())
1164 getLangOpts().CPlusPlus14
1165 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1166 : diag::ext_constexpr_body_invalid_stmt)
1167 << isa<CXXConstructorDecl>(Dcl);
1169 if (const CXXConstructorDecl *Constructor
1170 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1171 const CXXRecordDecl *RD = Constructor->getParent();
1173 // - every non-variant non-static data member and base class sub-object
1174 // shall be initialized;
1176 // - if the class is a union having variant members, exactly one of them
1177 // shall be initialized;
1178 if (RD->isUnion()) {
1179 if (Constructor->getNumCtorInitializers() == 0 &&
1180 RD->hasVariantMembers()) {
1181 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1184 } else if (!Constructor->isDependentContext() &&
1185 !Constructor->isDelegatingConstructor()) {
1186 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1188 // Skip detailed checking if we have enough initializers, and we would
1189 // allow at most one initializer per member.
1190 bool AnyAnonStructUnionMembers = false;
1191 unsigned Fields = 0;
1192 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1193 E = RD->field_end(); I != E; ++I, ++Fields) {
1194 if (I->isAnonymousStructOrUnion()) {
1195 AnyAnonStructUnionMembers = true;
1200 // - if the class is a union-like class, but is not a union, for each of
1201 // its anonymous union members having variant members, exactly one of
1202 // them shall be initialized;
1203 if (AnyAnonStructUnionMembers ||
1204 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1205 // Check initialization of non-static data members. Base classes are
1206 // always initialized so do not need to be checked. Dependent bases
1207 // might not have initializers in the member initializer list.
1208 llvm::SmallSet<Decl*, 16> Inits;
1209 for (const auto *I: Constructor->inits()) {
1210 if (FieldDecl *FD = I->getMember())
1212 else if (IndirectFieldDecl *ID = I->getIndirectMember())
1213 Inits.insert(ID->chain_begin(), ID->chain_end());
1216 bool Diagnosed = false;
1217 for (auto *I : RD->fields())
1218 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1224 if (ReturnStmts.empty()) {
1225 // C++1y doesn't require constexpr functions to contain a 'return'
1226 // statement. We still do, unless the return type might be void, because
1227 // otherwise if there's no return statement, the function cannot
1228 // be used in a core constant expression.
1229 bool OK = getLangOpts().CPlusPlus14 &&
1230 (Dcl->getReturnType()->isVoidType() ||
1231 Dcl->getReturnType()->isDependentType());
1232 Diag(Dcl->getLocation(),
1233 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1234 : diag::err_constexpr_body_no_return);
1237 if (ReturnStmts.size() > 1) {
1238 Diag(ReturnStmts.back(),
1239 getLangOpts().CPlusPlus14
1240 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1241 : diag::ext_constexpr_body_multiple_return);
1242 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1243 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1247 // C++11 [dcl.constexpr]p5:
1248 // if no function argument values exist such that the function invocation
1249 // substitution would produce a constant expression, the program is
1250 // ill-formed; no diagnostic required.
1251 // C++11 [dcl.constexpr]p3:
1252 // - every constructor call and implicit conversion used in initializing the
1253 // return value shall be one of those allowed in a constant expression.
1254 // C++11 [dcl.constexpr]p4:
1255 // - every constructor involved in initializing non-static data members and
1256 // base class sub-objects shall be a constexpr constructor.
1257 SmallVector<PartialDiagnosticAt, 8> Diags;
1258 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1259 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1260 << isa<CXXConstructorDecl>(Dcl);
1261 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1262 Diag(Diags[I].first, Diags[I].second);
1263 // Don't return false here: we allow this for compatibility in
1270 /// isCurrentClassName - Determine whether the identifier II is the
1271 /// name of the class type currently being defined. In the case of
1272 /// nested classes, this will only return true if II is the name of
1273 /// the innermost class.
1274 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1275 const CXXScopeSpec *SS) {
1276 assert(getLangOpts().CPlusPlus && "No class names in C!");
1278 CXXRecordDecl *CurDecl;
1279 if (SS && SS->isSet() && !SS->isInvalid()) {
1280 DeclContext *DC = computeDeclContext(*SS, true);
1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1283 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1285 if (CurDecl && CurDecl->getIdentifier())
1286 return &II == CurDecl->getIdentifier();
1290 /// \brief Determine whether the identifier II is a typo for the name of
1291 /// the class type currently being defined. If so, update it to the identifier
1292 /// that should have been used.
1293 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1294 assert(getLangOpts().CPlusPlus && "No class names in C!");
1296 if (!getLangOpts().SpellChecking)
1299 CXXRecordDecl *CurDecl;
1300 if (SS && SS->isSet() && !SS->isInvalid()) {
1301 DeclContext *DC = computeDeclContext(*SS, true);
1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1306 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1307 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1308 < II->getLength()) {
1309 II = CurDecl->getIdentifier();
1316 /// \brief Determine whether the given class is a base class of the given
1317 /// class, including looking at dependent bases.
1318 static bool findCircularInheritance(const CXXRecordDecl *Class,
1319 const CXXRecordDecl *Current) {
1320 SmallVector<const CXXRecordDecl*, 8> Queue;
1322 Class = Class->getCanonicalDecl();
1324 for (const auto &I : Current->bases()) {
1325 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1329 Base = Base->getDefinition();
1333 if (Base->getCanonicalDecl() == Class)
1336 Queue.push_back(Base);
1342 Current = Queue.pop_back_val();
1348 /// \brief Check the validity of a C++ base class specifier.
1350 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1351 /// and returns NULL otherwise.
1353 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1354 SourceRange SpecifierRange,
1355 bool Virtual, AccessSpecifier Access,
1356 TypeSourceInfo *TInfo,
1357 SourceLocation EllipsisLoc) {
1358 QualType BaseType = TInfo->getType();
1360 // C++ [class.union]p1:
1361 // A union shall not have base classes.
1362 if (Class->isUnion()) {
1363 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1368 if (EllipsisLoc.isValid() &&
1369 !TInfo->getType()->containsUnexpandedParameterPack()) {
1370 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1371 << TInfo->getTypeLoc().getSourceRange();
1372 EllipsisLoc = SourceLocation();
1375 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1377 if (BaseType->isDependentType()) {
1378 // Make sure that we don't have circular inheritance among our dependent
1379 // bases. For non-dependent bases, the check for completeness below handles
1381 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1382 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1383 ((BaseDecl = BaseDecl->getDefinition()) &&
1384 findCircularInheritance(Class, BaseDecl))) {
1385 Diag(BaseLoc, diag::err_circular_inheritance)
1386 << BaseType << Context.getTypeDeclType(Class);
1388 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1389 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1396 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1397 Class->getTagKind() == TTK_Class,
1398 Access, TInfo, EllipsisLoc);
1401 // Base specifiers must be record types.
1402 if (!BaseType->isRecordType()) {
1403 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1407 // C++ [class.union]p1:
1408 // A union shall not be used as a base class.
1409 if (BaseType->isUnionType()) {
1410 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1414 // For the MS ABI, propagate DLL attributes to base class templates.
1415 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1416 if (Attr *ClassAttr = getDLLAttr(Class)) {
1417 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1418 BaseType->getAsCXXRecordDecl())) {
1419 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1425 // C++ [class.derived]p2:
1426 // The class-name in a base-specifier shall not be an incompletely
1428 if (RequireCompleteType(BaseLoc, BaseType,
1429 diag::err_incomplete_base_class, SpecifierRange)) {
1430 Class->setInvalidDecl();
1434 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1435 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1436 assert(BaseDecl && "Record type has no declaration");
1437 BaseDecl = BaseDecl->getDefinition();
1438 assert(BaseDecl && "Base type is not incomplete, but has no definition");
1439 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1440 assert(CXXBaseDecl && "Base type is not a C++ type");
1442 // A class which contains a flexible array member is not suitable for use as a
1444 // - If the layout determines that a base comes before another base,
1445 // the flexible array member would index into the subsequent base.
1446 // - If the layout determines that base comes before the derived class,
1447 // the flexible array member would index into the derived class.
1448 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1449 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1450 << CXXBaseDecl->getDeclName();
1455 // If a class is marked final and it appears as a base-type-specifier in
1456 // base-clause, the program is ill-formed.
1457 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1458 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1459 << CXXBaseDecl->getDeclName()
1460 << FA->isSpelledAsSealed();
1461 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1462 << CXXBaseDecl->getDeclName() << FA->getRange();
1466 if (BaseDecl->isInvalidDecl())
1467 Class->setInvalidDecl();
1469 // Create the base specifier.
1470 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1471 Class->getTagKind() == TTK_Class,
1472 Access, TInfo, EllipsisLoc);
1475 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1476 /// one entry in the base class list of a class specifier, for
1478 /// class foo : public bar, virtual private baz {
1479 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1481 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1482 ParsedAttributes &Attributes,
1483 bool Virtual, AccessSpecifier Access,
1484 ParsedType basetype, SourceLocation BaseLoc,
1485 SourceLocation EllipsisLoc) {
1489 AdjustDeclIfTemplate(classdecl);
1490 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1494 // We haven't yet attached the base specifiers.
1495 Class->setIsParsingBaseSpecifiers();
1497 // We do not support any C++11 attributes on base-specifiers yet.
1498 // Diagnose any attributes we see.
1499 if (!Attributes.empty()) {
1500 for (AttributeList *Attr = Attributes.getList(); Attr;
1501 Attr = Attr->getNext()) {
1502 if (Attr->isInvalid() ||
1503 Attr->getKind() == AttributeList::IgnoredAttribute)
1505 Diag(Attr->getLoc(),
1506 Attr->getKind() == AttributeList::UnknownAttribute
1507 ? diag::warn_unknown_attribute_ignored
1508 : diag::err_base_specifier_attribute)
1513 TypeSourceInfo *TInfo = nullptr;
1514 GetTypeFromParser(basetype, &TInfo);
1516 if (EllipsisLoc.isInvalid() &&
1517 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1521 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1522 Virtual, Access, TInfo,
1526 Class->setInvalidDecl();
1531 /// Use small set to collect indirect bases. As this is only used
1532 /// locally, there's no need to abstract the small size parameter.
1533 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1535 /// \brief Recursively add the bases of Type. Don't add Type itself.
1537 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1538 const QualType &Type)
1540 // Even though the incoming type is a base, it might not be
1541 // a class -- it could be a template parm, for instance.
1542 if (auto Rec = Type->getAs<RecordType>()) {
1543 auto Decl = Rec->getAsCXXRecordDecl();
1545 // Iterate over its bases.
1546 for (const auto &BaseSpec : Decl->bases()) {
1547 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1548 .getUnqualifiedType();
1549 if (Set.insert(Base).second)
1550 // If we've not already seen it, recurse.
1551 NoteIndirectBases(Context, Set, Base);
1556 /// \brief Performs the actual work of attaching the given base class
1557 /// specifiers to a C++ class.
1558 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1559 unsigned NumBases) {
1563 // Used to keep track of which base types we have already seen, so
1564 // that we can properly diagnose redundant direct base types. Note
1565 // that the key is always the unqualified canonical type of the base
1567 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1569 // Used to track indirect bases so we can see if a direct base is
1571 IndirectBaseSet IndirectBaseTypes;
1573 // Copy non-redundant base specifiers into permanent storage.
1574 unsigned NumGoodBases = 0;
1575 bool Invalid = false;
1576 for (unsigned idx = 0; idx < NumBases; ++idx) {
1577 QualType NewBaseType
1578 = Context.getCanonicalType(Bases[idx]->getType());
1579 NewBaseType = NewBaseType.getLocalUnqualifiedType();
1581 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1583 // C++ [class.mi]p3:
1584 // A class shall not be specified as a direct base class of a
1585 // derived class more than once.
1586 Diag(Bases[idx]->getLocStart(),
1587 diag::err_duplicate_base_class)
1588 << KnownBase->getType()
1589 << Bases[idx]->getSourceRange();
1591 // Delete the duplicate base class specifier; we're going to
1592 // overwrite its pointer later.
1593 Context.Deallocate(Bases[idx]);
1597 // Okay, add this new base class.
1598 KnownBase = Bases[idx];
1599 Bases[NumGoodBases++] = Bases[idx];
1601 // Note this base's direct & indirect bases, if there could be ambiguity.
1603 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1605 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1606 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1607 if (Class->isInterface() &&
1608 (!RD->isInterface() ||
1609 KnownBase->getAccessSpecifier() != AS_public)) {
1610 // The Microsoft extension __interface does not permit bases that
1611 // are not themselves public interfaces.
1612 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1613 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1614 << RD->getSourceRange();
1617 if (RD->hasAttr<WeakAttr>())
1618 Class->addAttr(WeakAttr::CreateImplicit(Context));
1623 // Attach the remaining base class specifiers to the derived class.
1624 Class->setBases(Bases, NumGoodBases);
1626 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1627 // Check whether this direct base is inaccessible due to ambiguity.
1628 QualType BaseType = Bases[idx]->getType();
1629 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1630 .getUnqualifiedType();
1632 if (IndirectBaseTypes.count(CanonicalBase)) {
1633 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1634 /*DetectVirtual=*/true);
1636 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1640 if (Paths.isAmbiguous(CanonicalBase))
1641 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1642 << BaseType << getAmbiguousPathsDisplayString(Paths)
1643 << Bases[idx]->getSourceRange();
1645 assert(Bases[idx]->isVirtual());
1648 // Delete the base class specifier, since its data has been copied
1649 // into the CXXRecordDecl.
1650 Context.Deallocate(Bases[idx]);
1656 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1657 /// class, after checking whether there are any duplicate base
1659 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1660 unsigned NumBases) {
1661 if (!ClassDecl || !Bases || !NumBases)
1664 AdjustDeclIfTemplate(ClassDecl);
1665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1668 /// \brief Determine whether the type \p Derived is a C++ class that is
1669 /// derived from the type \p Base.
1670 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1671 if (!getLangOpts().CPlusPlus)
1674 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1678 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1682 // If either the base or the derived type is invalid, don't try to
1683 // check whether one is derived from the other.
1684 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1687 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1688 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1691 /// \brief Determine whether the type \p Derived is a C++ class that is
1692 /// derived from the type \p Base.
1693 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1694 if (!getLangOpts().CPlusPlus)
1697 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1701 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1705 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1708 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1709 CXXCastPath &BasePathArray) {
1710 assert(BasePathArray.empty() && "Base path array must be empty!");
1711 assert(Paths.isRecordingPaths() && "Must record paths!");
1713 const CXXBasePath &Path = Paths.front();
1715 // We first go backward and check if we have a virtual base.
1716 // FIXME: It would be better if CXXBasePath had the base specifier for
1717 // the nearest virtual base.
1719 for (unsigned I = Path.size(); I != 0; --I) {
1720 if (Path[I - 1].Base->isVirtual()) {
1726 // Now add all bases.
1727 for (unsigned I = Start, E = Path.size(); I != E; ++I)
1728 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1731 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1732 /// conversion (where Derived and Base are class types) is
1733 /// well-formed, meaning that the conversion is unambiguous (and
1734 /// that all of the base classes are accessible). Returns true
1735 /// and emits a diagnostic if the code is ill-formed, returns false
1736 /// otherwise. Loc is the location where this routine should point to
1737 /// if there is an error, and Range is the source range to highlight
1738 /// if there is an error.
1740 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1741 unsigned InaccessibleBaseID,
1742 unsigned AmbigiousBaseConvID,
1743 SourceLocation Loc, SourceRange Range,
1744 DeclarationName Name,
1745 CXXCastPath *BasePath) {
1746 // First, determine whether the path from Derived to Base is
1747 // ambiguous. This is slightly more expensive than checking whether
1748 // the Derived to Base conversion exists, because here we need to
1749 // explore multiple paths to determine if there is an ambiguity.
1750 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1751 /*DetectVirtual=*/false);
1752 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1753 assert(DerivationOkay &&
1754 "Can only be used with a derived-to-base conversion");
1755 (void)DerivationOkay;
1757 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1758 if (InaccessibleBaseID) {
1759 // Check that the base class can be accessed.
1760 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1761 InaccessibleBaseID)) {
1762 case AR_inaccessible:
1771 // Build a base path if necessary.
1773 BuildBasePathArray(Paths, *BasePath);
1777 if (AmbigiousBaseConvID) {
1778 // We know that the derived-to-base conversion is ambiguous, and
1779 // we're going to produce a diagnostic. Perform the derived-to-base
1780 // search just one more time to compute all of the possible paths so
1781 // that we can print them out. This is more expensive than any of
1782 // the previous derived-to-base checks we've done, but at this point
1783 // performance isn't as much of an issue.
1785 Paths.setRecordingPaths(true);
1786 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1787 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1790 // Build up a textual representation of the ambiguous paths, e.g.,
1791 // D -> B -> A, that will be used to illustrate the ambiguous
1792 // conversions in the diagnostic. We only print one of the paths
1793 // to each base class subobject.
1794 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1796 Diag(Loc, AmbigiousBaseConvID)
1797 << Derived << Base << PathDisplayStr << Range << Name;
1803 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1804 SourceLocation Loc, SourceRange Range,
1805 CXXCastPath *BasePath,
1806 bool IgnoreAccess) {
1807 return CheckDerivedToBaseConversion(Derived, Base,
1809 : diag::err_upcast_to_inaccessible_base,
1810 diag::err_ambiguous_derived_to_base_conv,
1811 Loc, Range, DeclarationName(),
1816 /// @brief Builds a string representing ambiguous paths from a
1817 /// specific derived class to different subobjects of the same base
1820 /// This function builds a string that can be used in error messages
1821 /// to show the different paths that one can take through the
1822 /// inheritance hierarchy to go from the derived class to different
1823 /// subobjects of a base class. The result looks something like this:
1825 /// struct D -> struct B -> struct A
1826 /// struct D -> struct C -> struct A
1828 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1829 std::string PathDisplayStr;
1830 std::set<unsigned> DisplayedPaths;
1831 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1832 Path != Paths.end(); ++Path) {
1833 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1834 // We haven't displayed a path to this particular base
1835 // class subobject yet.
1836 PathDisplayStr += "\n ";
1837 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1838 for (CXXBasePath::const_iterator Element = Path->begin();
1839 Element != Path->end(); ++Element)
1840 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1844 return PathDisplayStr;
1847 //===----------------------------------------------------------------------===//
1848 // C++ class member Handling
1849 //===----------------------------------------------------------------------===//
1851 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1852 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1853 SourceLocation ASLoc,
1854 SourceLocation ColonLoc,
1855 AttributeList *Attrs) {
1856 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1857 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1859 CurContext->addHiddenDecl(ASDecl);
1860 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1863 /// CheckOverrideControl - Check C++11 override control semantics.
1864 void Sema::CheckOverrideControl(NamedDecl *D) {
1865 if (D->isInvalidDecl())
1868 // We only care about "override" and "final" declarations.
1869 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1872 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1874 // We can't check dependent instance methods.
1875 if (MD && MD->isInstance() &&
1876 (MD->getParent()->hasAnyDependentBases() ||
1877 MD->getType()->isDependentType()))
1880 if (MD && !MD->isVirtual()) {
1881 // If we have a non-virtual method, check if if hides a virtual method.
1882 // (In that case, it's most likely the method has the wrong type.)
1883 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1884 FindHiddenVirtualMethods(MD, OverloadedMethods);
1886 if (!OverloadedMethods.empty()) {
1887 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1888 Diag(OA->getLocation(),
1889 diag::override_keyword_hides_virtual_member_function)
1890 << "override" << (OverloadedMethods.size() > 1);
1891 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1892 Diag(FA->getLocation(),
1893 diag::override_keyword_hides_virtual_member_function)
1894 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1895 << (OverloadedMethods.size() > 1);
1897 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1898 MD->setInvalidDecl();
1901 // Fall through into the general case diagnostic.
1902 // FIXME: We might want to attempt typo correction here.
1905 if (!MD || !MD->isVirtual()) {
1906 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1907 Diag(OA->getLocation(),
1908 diag::override_keyword_only_allowed_on_virtual_member_functions)
1909 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1910 D->dropAttr<OverrideAttr>();
1912 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1913 Diag(FA->getLocation(),
1914 diag::override_keyword_only_allowed_on_virtual_member_functions)
1915 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1916 << FixItHint::CreateRemoval(FA->getLocation());
1917 D->dropAttr<FinalAttr>();
1922 // C++11 [class.virtual]p5:
1923 // If a function is marked with the virt-specifier override and
1924 // does not override a member function of a base class, the program is
1926 bool HasOverriddenMethods =
1927 MD->begin_overridden_methods() != MD->end_overridden_methods();
1928 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1929 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1930 << MD->getDeclName();
1933 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1934 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1936 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1937 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1938 isa<CXXDestructorDecl>(MD))
1941 SourceLocation Loc = MD->getLocation();
1942 SourceLocation SpellingLoc = Loc;
1943 if (getSourceManager().isMacroArgExpansion(Loc))
1944 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1945 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1946 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1949 if (MD->size_overridden_methods() > 0) {
1950 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1951 << MD->getDeclName();
1952 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1953 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1957 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1958 /// function overrides a virtual member function marked 'final', according to
1959 /// C++11 [class.virtual]p4.
1960 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1961 const CXXMethodDecl *Old) {
1962 FinalAttr *FA = Old->getAttr<FinalAttr>();
1966 Diag(New->getLocation(), diag::err_final_function_overridden)
1967 << New->getDeclName()
1968 << FA->isSpelledAsSealed();
1969 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1973 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1974 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1975 // FIXME: Destruction of ObjC lifetime types has side-effects.
1976 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1977 return !RD->isCompleteDefinition() ||
1978 !RD->hasTrivialDefaultConstructor() ||
1979 !RD->hasTrivialDestructor();
1983 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1984 for (AttributeList *it = list; it != nullptr; it = it->getNext())
1985 if (it->isDeclspecPropertyAttribute())
1990 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1991 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1992 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1993 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1994 /// present (but parsing it has been deferred).
1996 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1997 MultiTemplateParamsArg TemplateParameterLists,
1998 Expr *BW, const VirtSpecifiers &VS,
1999 InClassInitStyle InitStyle) {
2000 const DeclSpec &DS = D.getDeclSpec();
2001 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2002 DeclarationName Name = NameInfo.getName();
2003 SourceLocation Loc = NameInfo.getLoc();
2005 // For anonymous bitfields, the location should point to the type.
2006 if (Loc.isInvalid())
2007 Loc = D.getLocStart();
2009 Expr *BitWidth = static_cast<Expr*>(BW);
2011 assert(isa<CXXRecordDecl>(CurContext));
2012 assert(!DS.isFriendSpecified());
2014 bool isFunc = D.isDeclarationOfFunction();
2016 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2017 // The Microsoft extension __interface only permits public member functions
2018 // and prohibits constructors, destructors, operators, non-public member
2019 // functions, static methods and data members.
2020 unsigned InvalidDecl;
2021 bool ShowDeclName = true;
2023 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2024 else if (AS != AS_public)
2026 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2028 else switch (Name.getNameKind()) {
2029 case DeclarationName::CXXConstructorName:
2031 ShowDeclName = false;
2034 case DeclarationName::CXXDestructorName:
2036 ShowDeclName = false;
2039 case DeclarationName::CXXOperatorName:
2040 case DeclarationName::CXXConversionFunctionName:
2051 Diag(Loc, diag::err_invalid_member_in_interface)
2052 << (InvalidDecl-1) << Name;
2054 Diag(Loc, diag::err_invalid_member_in_interface)
2055 << (InvalidDecl-1) << "";
2060 // C++ 9.2p6: A member shall not be declared to have automatic storage
2061 // duration (auto, register) or with the extern storage-class-specifier.
2062 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2063 // data members and cannot be applied to names declared const or static,
2064 // and cannot be applied to reference members.
2065 switch (DS.getStorageClassSpec()) {
2066 case DeclSpec::SCS_unspecified:
2067 case DeclSpec::SCS_typedef:
2068 case DeclSpec::SCS_static:
2070 case DeclSpec::SCS_mutable:
2072 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2074 // FIXME: It would be nicer if the keyword was ignored only for this
2075 // declarator. Otherwise we could get follow-up errors.
2076 D.getMutableDeclSpec().ClearStorageClassSpecs();
2080 Diag(DS.getStorageClassSpecLoc(),
2081 diag::err_storageclass_invalid_for_member);
2082 D.getMutableDeclSpec().ClearStorageClassSpecs();
2086 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2087 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2090 if (DS.isConstexprSpecified() && isInstField) {
2091 SemaDiagnosticBuilder B =
2092 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2093 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2094 if (InitStyle == ICIS_NoInit) {
2096 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2097 B << FixItHint::CreateRemoval(ConstexprLoc);
2099 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2100 D.getMutableDeclSpec().ClearConstexprSpec();
2101 const char *PrevSpec;
2103 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2104 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2106 assert(!Failed && "Making a constexpr member const shouldn't fail");
2110 const char *PrevSpec;
2112 if (D.getMutableDeclSpec().SetStorageClassSpec(
2113 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2114 Context.getPrintingPolicy())) {
2115 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2116 "This is the only DeclSpec that should fail to be applied");
2119 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2120 isInstField = false;
2127 CXXScopeSpec &SS = D.getCXXScopeSpec();
2129 // Data members must have identifiers for names.
2130 if (!Name.isIdentifier()) {
2131 Diag(Loc, diag::err_bad_variable_name)
2136 IdentifierInfo *II = Name.getAsIdentifierInfo();
2138 // Member field could not be with "template" keyword.
2139 // So TemplateParameterLists should be empty in this case.
2140 if (TemplateParameterLists.size()) {
2141 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2142 if (TemplateParams->size()) {
2143 // There is no such thing as a member field template.
2144 Diag(D.getIdentifierLoc(), diag::err_template_member)
2146 << SourceRange(TemplateParams->getTemplateLoc(),
2147 TemplateParams->getRAngleLoc());
2149 // There is an extraneous 'template<>' for this member.
2150 Diag(TemplateParams->getTemplateLoc(),
2151 diag::err_template_member_noparams)
2153 << SourceRange(TemplateParams->getTemplateLoc(),
2154 TemplateParams->getRAngleLoc());
2159 if (SS.isSet() && !SS.isInvalid()) {
2160 // The user provided a superfluous scope specifier inside a class
2166 if (DeclContext *DC = computeDeclContext(SS, false))
2167 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2169 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2170 << Name << SS.getRange();
2175 AttributeList *MSPropertyAttr =
2176 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2177 if (MSPropertyAttr) {
2178 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2179 BitWidth, InitStyle, AS, MSPropertyAttr);
2182 isInstField = false;
2184 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2185 BitWidth, InitStyle, AS);
2186 assert(Member && "HandleField never returns null");
2189 Member = HandleDeclarator(S, D, TemplateParameterLists);
2193 // Non-instance-fields can't have a bitfield.
2195 if (Member->isInvalidDecl()) {
2196 // don't emit another diagnostic.
2197 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2198 // C++ 9.6p3: A bit-field shall not be a static member.
2199 // "static member 'A' cannot be a bit-field"
2200 Diag(Loc, diag::err_static_not_bitfield)
2201 << Name << BitWidth->getSourceRange();
2202 } else if (isa<TypedefDecl>(Member)) {
2203 // "typedef member 'x' cannot be a bit-field"
2204 Diag(Loc, diag::err_typedef_not_bitfield)
2205 << Name << BitWidth->getSourceRange();
2207 // A function typedef ("typedef int f(); f a;").
2208 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2209 Diag(Loc, diag::err_not_integral_type_bitfield)
2210 << Name << cast<ValueDecl>(Member)->getType()
2211 << BitWidth->getSourceRange();
2215 Member->setInvalidDecl();
2218 Member->setAccess(AS);
2220 // If we have declared a member function template or static data member
2221 // template, set the access of the templated declaration as well.
2222 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2223 FunTmpl->getTemplatedDecl()->setAccess(AS);
2224 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2225 VarTmpl->getTemplatedDecl()->setAccess(AS);
2228 if (VS.isOverrideSpecified())
2229 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2230 if (VS.isFinalSpecified())
2231 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2232 VS.isFinalSpelledSealed()));
2234 if (VS.getLastLocation().isValid()) {
2235 // Update the end location of a method that has a virt-specifiers.
2236 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2237 MD->setRangeEnd(VS.getLastLocation());
2240 CheckOverrideControl(Member);
2242 assert((Name || isInstField) && "No identifier for non-field ?");
2245 FieldDecl *FD = cast<FieldDecl>(Member);
2246 FieldCollector->Add(FD);
2248 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2249 // Remember all explicit private FieldDecls that have a name, no side
2250 // effects and are not part of a dependent type declaration.
2251 if (!FD->isImplicit() && FD->getDeclName() &&
2252 FD->getAccess() == AS_private &&
2253 !FD->hasAttr<UnusedAttr>() &&
2254 !FD->getParent()->isDependentContext() &&
2255 !InitializationHasSideEffects(*FD))
2256 UnusedPrivateFields.insert(FD);
2264 class UninitializedFieldVisitor
2265 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2267 // List of Decls to generate a warning on. Also remove Decls that become
2269 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2270 // List of base classes of the record. Classes are removed after their
2272 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2273 // Vector of decls to be removed from the Decl set prior to visiting the
2274 // nodes. These Decls may have been initialized in the prior initializer.
2275 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2276 // If non-null, add a note to the warning pointing back to the constructor.
2277 const CXXConstructorDecl *Constructor;
2278 // Variables to hold state when processing an initializer list. When
2279 // InitList is true, special case initialization of FieldDecls matching
2280 // InitListFieldDecl.
2282 FieldDecl *InitListFieldDecl;
2283 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2286 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2287 UninitializedFieldVisitor(Sema &S,
2288 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2289 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2290 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2291 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2293 // Returns true if the use of ME is not an uninitialized use.
2294 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2295 bool CheckReferenceOnly) {
2296 llvm::SmallVector<FieldDecl*, 4> Fields;
2297 bool ReferenceField = false;
2299 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2302 Fields.push_back(FD);
2303 if (FD->getType()->isReferenceType())
2304 ReferenceField = true;
2305 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2308 // Binding a reference to an unintialized field is not an
2309 // uninitialized use.
2310 if (CheckReferenceOnly && !ReferenceField)
2313 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2314 // Discard the first field since it is the field decl that is being
2316 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2317 UsedFieldIndex.push_back((*I)->getFieldIndex());
2320 for (auto UsedIter = UsedFieldIndex.begin(),
2321 UsedEnd = UsedFieldIndex.end(),
2322 OrigIter = InitFieldIndex.begin(),
2323 OrigEnd = InitFieldIndex.end();
2324 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2325 if (*UsedIter < *OrigIter)
2327 if (*UsedIter > *OrigIter)
2334 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2336 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2339 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2341 MemberExpr *FieldME = ME;
2343 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2346 while (MemberExpr *SubME =
2347 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2349 if (isa<VarDecl>(SubME->getMemberDecl()))
2352 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2353 if (!FD->isAnonymousStructOrUnion())
2356 if (!FieldME->getType().isPODType(S.Context))
2357 AllPODFields = false;
2359 Base = SubME->getBase();
2362 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2365 if (AddressOf && AllPODFields)
2368 ValueDecl* FoundVD = FieldME->getMemberDecl();
2370 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2371 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2372 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2375 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2376 QualType T = BaseCast->getType();
2377 if (T->isPointerType() &&
2378 BaseClasses.count(T->getPointeeType())) {
2379 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2380 << T->getPointeeType() << FoundVD;
2385 if (!Decls.count(FoundVD))
2388 const bool IsReference = FoundVD->getType()->isReferenceType();
2390 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2391 // Special checking for initializer lists.
2392 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2396 // Prevent double warnings on use of unbounded references.
2397 if (CheckReferenceOnly && !IsReference)
2401 unsigned diag = IsReference
2402 ? diag::warn_reference_field_is_uninit
2403 : diag::warn_field_is_uninit;
2404 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2406 S.Diag(Constructor->getLocation(),
2407 diag::note_uninit_in_this_constructor)
2408 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2412 void HandleValue(Expr *E, bool AddressOf) {
2413 E = E->IgnoreParens();
2415 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2416 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2417 AddressOf /*AddressOf*/);
2421 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2422 Visit(CO->getCond());
2423 HandleValue(CO->getTrueExpr(), AddressOf);
2424 HandleValue(CO->getFalseExpr(), AddressOf);
2428 if (BinaryConditionalOperator *BCO =
2429 dyn_cast<BinaryConditionalOperator>(E)) {
2430 Visit(BCO->getCond());
2431 HandleValue(BCO->getFalseExpr(), AddressOf);
2435 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2436 HandleValue(OVE->getSourceExpr(), AddressOf);
2440 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2441 switch (BO->getOpcode()) {
2446 HandleValue(BO->getLHS(), AddressOf);
2447 Visit(BO->getRHS());
2450 Visit(BO->getLHS());
2451 HandleValue(BO->getRHS(), AddressOf);
2459 void CheckInitListExpr(InitListExpr *ILE) {
2460 InitFieldIndex.push_back(0);
2461 for (auto Child : ILE->children()) {
2462 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2463 CheckInitListExpr(SubList);
2467 ++InitFieldIndex.back();
2469 InitFieldIndex.pop_back();
2472 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2473 FieldDecl *Field, const Type *BaseClass) {
2474 // Remove Decls that may have been initialized in the previous
2476 for (ValueDecl* VD : DeclsToRemove)
2478 DeclsToRemove.clear();
2480 Constructor = FieldConstructor;
2481 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2485 InitListFieldDecl = Field;
2486 InitFieldIndex.clear();
2487 CheckInitListExpr(ILE);
2496 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2499 void VisitMemberExpr(MemberExpr *ME) {
2500 // All uses of unbounded reference fields will warn.
2501 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2504 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2505 if (E->getCastKind() == CK_LValueToRValue) {
2506 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2510 Inherited::VisitImplicitCastExpr(E);
2513 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2514 if (E->getConstructor()->isCopyConstructor()) {
2515 Expr *ArgExpr = E->getArg(0);
2516 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2517 if (ILE->getNumInits() == 1)
2518 ArgExpr = ILE->getInit(0);
2519 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2520 if (ICE->getCastKind() == CK_NoOp)
2521 ArgExpr = ICE->getSubExpr();
2522 HandleValue(ArgExpr, false /*AddressOf*/);
2525 Inherited::VisitCXXConstructExpr(E);
2528 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2529 Expr *Callee = E->getCallee();
2530 if (isa<MemberExpr>(Callee)) {
2531 HandleValue(Callee, false /*AddressOf*/);
2532 for (auto Arg : E->arguments())
2537 Inherited::VisitCXXMemberCallExpr(E);
2540 void VisitCallExpr(CallExpr *E) {
2541 // Treat std::move as a use.
2542 if (E->getNumArgs() == 1) {
2543 if (FunctionDecl *FD = E->getDirectCallee()) {
2544 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2545 FD->getIdentifier()->isStr("move")) {
2546 HandleValue(E->getArg(0), false /*AddressOf*/);
2552 Inherited::VisitCallExpr(E);
2555 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2556 Expr *Callee = E->getCallee();
2558 if (isa<UnresolvedLookupExpr>(Callee))
2559 return Inherited::VisitCXXOperatorCallExpr(E);
2562 for (auto Arg : E->arguments())
2563 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2566 void VisitBinaryOperator(BinaryOperator *E) {
2567 // If a field assignment is detected, remove the field from the
2568 // uninitiailized field set.
2569 if (E->getOpcode() == BO_Assign)
2570 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2571 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2572 if (!FD->getType()->isReferenceType())
2573 DeclsToRemove.push_back(FD);
2575 if (E->isCompoundAssignmentOp()) {
2576 HandleValue(E->getLHS(), false /*AddressOf*/);
2581 Inherited::VisitBinaryOperator(E);
2584 void VisitUnaryOperator(UnaryOperator *E) {
2585 if (E->isIncrementDecrementOp()) {
2586 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2589 if (E->getOpcode() == UO_AddrOf) {
2590 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2591 HandleValue(ME->getBase(), true /*AddressOf*/);
2596 Inherited::VisitUnaryOperator(E);
2600 // Diagnose value-uses of fields to initialize themselves, e.g.
2602 // where foo is not also a parameter to the constructor.
2603 // Also diagnose across field uninitialized use such as
2605 // TODO: implement -Wuninitialized and fold this into that framework.
2606 static void DiagnoseUninitializedFields(
2607 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2609 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2610 Constructor->getLocation())) {
2614 if (Constructor->isInvalidDecl())
2617 const CXXRecordDecl *RD = Constructor->getParent();
2619 if (RD->getDescribedClassTemplate())
2622 // Holds fields that are uninitialized.
2623 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2625 // At the beginning, all fields are uninitialized.
2626 for (auto *I : RD->decls()) {
2627 if (auto *FD = dyn_cast<FieldDecl>(I)) {
2628 UninitializedFields.insert(FD);
2629 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2630 UninitializedFields.insert(IFD->getAnonField());
2634 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2635 for (auto I : RD->bases())
2636 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2638 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2641 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2642 UninitializedFields,
2643 UninitializedBaseClasses);
2645 for (const auto *FieldInit : Constructor->inits()) {
2646 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2649 Expr *InitExpr = FieldInit->getInit();
2653 if (CXXDefaultInitExpr *Default =
2654 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2655 InitExpr = Default->getExpr();
2658 // In class initializers will point to the constructor.
2659 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2660 FieldInit->getAnyMember(),
2661 FieldInit->getBaseClass());
2663 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2664 FieldInit->getAnyMember(),
2665 FieldInit->getBaseClass());
2671 /// \brief Enter a new C++ default initializer scope. After calling this, the
2672 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2673 /// parsing or instantiating the initializer failed.
2674 void Sema::ActOnStartCXXInClassMemberInitializer() {
2675 // Create a synthetic function scope to represent the call to the constructor
2676 // that notionally surrounds a use of this initializer.
2677 PushFunctionScope();
2680 /// \brief This is invoked after parsing an in-class initializer for a
2681 /// non-static C++ class member, and after instantiating an in-class initializer
2682 /// in a class template. Such actions are deferred until the class is complete.
2683 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2684 SourceLocation InitLoc,
2686 // Pop the notional constructor scope we created earlier.
2687 PopFunctionScopeInfo(nullptr, D);
2689 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2690 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2691 "must set init style when field is created");
2694 D->setInvalidDecl();
2696 FD->removeInClassInitializer();
2700 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2701 FD->setInvalidDecl();
2702 FD->removeInClassInitializer();
2706 ExprResult Init = InitExpr;
2707 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2708 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2709 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2710 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2711 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2712 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2713 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2714 if (Init.isInvalid()) {
2715 FD->setInvalidDecl();
2720 // C++11 [class.base.init]p7:
2721 // The initialization of each base and member constitutes a
2723 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2724 if (Init.isInvalid()) {
2725 FD->setInvalidDecl();
2729 InitExpr = Init.get();
2731 FD->setInClassInitializer(InitExpr);
2734 /// \brief Find the direct and/or virtual base specifiers that
2735 /// correspond to the given base type, for use in base initialization
2736 /// within a constructor.
2737 static bool FindBaseInitializer(Sema &SemaRef,
2738 CXXRecordDecl *ClassDecl,
2740 const CXXBaseSpecifier *&DirectBaseSpec,
2741 const CXXBaseSpecifier *&VirtualBaseSpec) {
2742 // First, check for a direct base class.
2743 DirectBaseSpec = nullptr;
2744 for (const auto &Base : ClassDecl->bases()) {
2745 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2746 // We found a direct base of this type. That's what we're
2748 DirectBaseSpec = &Base;
2753 // Check for a virtual base class.
2754 // FIXME: We might be able to short-circuit this if we know in advance that
2755 // there are no virtual bases.
2756 VirtualBaseSpec = nullptr;
2757 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2758 // We haven't found a base yet; search the class hierarchy for a
2759 // virtual base class.
2760 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2761 /*DetectVirtual=*/false);
2762 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2764 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2765 Path != Paths.end(); ++Path) {
2766 if (Path->back().Base->isVirtual()) {
2767 VirtualBaseSpec = Path->back().Base;
2774 return DirectBaseSpec || VirtualBaseSpec;
2777 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2779 Sema::ActOnMemInitializer(Decl *ConstructorD,
2782 IdentifierInfo *MemberOrBase,
2783 ParsedType TemplateTypeTy,
2785 SourceLocation IdLoc,
2787 SourceLocation EllipsisLoc) {
2788 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2789 DS, IdLoc, InitList,
2793 /// \brief Handle a C++ member initializer using parentheses syntax.
2795 Sema::ActOnMemInitializer(Decl *ConstructorD,
2798 IdentifierInfo *MemberOrBase,
2799 ParsedType TemplateTypeTy,
2801 SourceLocation IdLoc,
2802 SourceLocation LParenLoc,
2803 ArrayRef<Expr *> Args,
2804 SourceLocation RParenLoc,
2805 SourceLocation EllipsisLoc) {
2806 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2808 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2809 DS, IdLoc, List, EllipsisLoc);
2814 // Callback to only accept typo corrections that can be a valid C++ member
2815 // intializer: either a non-static field member or a base class.
2816 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2818 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2819 : ClassDecl(ClassDecl) {}
2821 bool ValidateCandidate(const TypoCorrection &candidate) override {
2822 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2823 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2824 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2825 return isa<TypeDecl>(ND);
2831 CXXRecordDecl *ClassDecl;
2836 /// \brief Handle a C++ member initializer.
2838 Sema::BuildMemInitializer(Decl *ConstructorD,
2841 IdentifierInfo *MemberOrBase,
2842 ParsedType TemplateTypeTy,
2844 SourceLocation IdLoc,
2846 SourceLocation EllipsisLoc) {
2847 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2848 if (!Res.isUsable())
2855 AdjustDeclIfTemplate(ConstructorD);
2857 CXXConstructorDecl *Constructor
2858 = dyn_cast<CXXConstructorDecl>(ConstructorD);
2860 // The user wrote a constructor initializer on a function that is
2861 // not a C++ constructor. Ignore the error for now, because we may
2862 // have more member initializers coming; we'll diagnose it just
2863 // once in ActOnMemInitializers.
2867 CXXRecordDecl *ClassDecl = Constructor->getParent();
2869 // C++ [class.base.init]p2:
2870 // Names in a mem-initializer-id are looked up in the scope of the
2871 // constructor's class and, if not found in that scope, are looked
2872 // up in the scope containing the constructor's definition.
2873 // [Note: if the constructor's class contains a member with the
2874 // same name as a direct or virtual base class of the class, a
2875 // mem-initializer-id naming the member or base class and composed
2876 // of a single identifier refers to the class member. A
2877 // mem-initializer-id for the hidden base class may be specified
2878 // using a qualified name. ]
2879 if (!SS.getScopeRep() && !TemplateTypeTy) {
2880 // Look for a member, first.
2881 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2882 if (!Result.empty()) {
2884 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2885 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2886 if (EllipsisLoc.isValid())
2887 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2889 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2891 return BuildMemberInitializer(Member, Init, IdLoc);
2895 // It didn't name a member, so see if it names a class.
2897 TypeSourceInfo *TInfo = nullptr;
2899 if (TemplateTypeTy) {
2900 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2901 } else if (DS.getTypeSpecType() == TST_decltype) {
2902 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2904 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2905 LookupParsedName(R, S, &SS);
2907 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2909 if (R.isAmbiguous()) return true;
2911 // We don't want access-control diagnostics here.
2912 R.suppressDiagnostics();
2914 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2915 bool NotUnknownSpecialization = false;
2916 DeclContext *DC = computeDeclContext(SS, false);
2917 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2918 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2920 if (!NotUnknownSpecialization) {
2921 // When the scope specifier can refer to a member of an unknown
2922 // specialization, we take it as a type name.
2923 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2924 SS.getWithLocInContext(Context),
2925 *MemberOrBase, IdLoc);
2926 if (BaseType.isNull())
2930 R.setLookupName(MemberOrBase);
2934 // If no results were found, try to correct typos.
2935 TypoCorrection Corr;
2936 if (R.empty() && BaseType.isNull() &&
2937 (Corr = CorrectTypo(
2938 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2939 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2940 CTK_ErrorRecovery, ClassDecl))) {
2941 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2942 // We have found a non-static data member with a similar
2943 // name to what was typed; complain and initialize that
2946 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2947 << MemberOrBase << true);
2948 return BuildMemberInitializer(Member, Init, IdLoc);
2949 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2950 const CXXBaseSpecifier *DirectBaseSpec;
2951 const CXXBaseSpecifier *VirtualBaseSpec;
2952 if (FindBaseInitializer(*this, ClassDecl,
2953 Context.getTypeDeclType(Type),
2954 DirectBaseSpec, VirtualBaseSpec)) {
2955 // We have found a direct or virtual base class with a
2956 // similar name to what was typed; complain and initialize
2959 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2960 << MemberOrBase << false,
2961 PDiag() /*Suppress note, we provide our own.*/);
2963 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2965 Diag(BaseSpec->getLocStart(),
2966 diag::note_base_class_specified_here)
2967 << BaseSpec->getType()
2968 << BaseSpec->getSourceRange();
2975 if (!TyD && BaseType.isNull()) {
2976 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2977 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2982 if (BaseType.isNull()) {
2983 BaseType = Context.getTypeDeclType(TyD);
2984 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2986 // FIXME: preserve source range information
2987 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2993 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2995 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2998 /// Checks a member initializer expression for cases where reference (or
2999 /// pointer) members are bound to by-value parameters (or their addresses).
3000 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3002 SourceLocation IdLoc) {
3003 QualType MemberTy = Member->getType();
3005 // We only handle pointers and references currently.
3006 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3007 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3010 const bool IsPointer = MemberTy->isPointerType();
3012 if (const UnaryOperator *Op
3013 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3014 // The only case we're worried about with pointers requires taking the
3016 if (Op->getOpcode() != UO_AddrOf)
3019 Init = Op->getSubExpr();
3021 // We only handle address-of expression initializers for pointers.
3026 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3027 // We only warn when referring to a non-reference parameter declaration.
3028 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3029 if (!Parameter || Parameter->getType()->isReferenceType())
3032 S.Diag(Init->getExprLoc(),
3033 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3034 : diag::warn_bind_ref_member_to_parameter)
3035 << Member << Parameter << Init->getSourceRange();
3037 // Other initializers are fine.
3041 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3042 << (unsigned)IsPointer;
3046 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3047 SourceLocation IdLoc) {
3048 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3049 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3050 assert((DirectMember || IndirectMember) &&
3051 "Member must be a FieldDecl or IndirectFieldDecl");
3053 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3056 if (Member->isInvalidDecl())
3060 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3061 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3062 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3063 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3065 // Template instantiation doesn't reconstruct ParenListExprs for us.
3069 SourceRange InitRange = Init->getSourceRange();
3071 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3072 // Can't check initialization for a member of dependent type or when
3073 // any of the arguments are type-dependent expressions.
3074 DiscardCleanupsInEvaluationContext();
3076 bool InitList = false;
3077 if (isa<InitListExpr>(Init)) {
3082 // Initialize the member.
3083 InitializedEntity MemberEntity =
3084 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3085 : InitializedEntity::InitializeMember(IndirectMember,
3087 InitializationKind Kind =
3088 InitList ? InitializationKind::CreateDirectList(IdLoc)
3089 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3090 InitRange.getEnd());
3092 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3093 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3095 if (MemberInit.isInvalid())
3098 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3100 // C++11 [class.base.init]p7:
3101 // The initialization of each base and member constitutes a
3103 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3104 if (MemberInit.isInvalid())
3107 Init = MemberInit.get();
3111 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3112 InitRange.getBegin(), Init,
3113 InitRange.getEnd());
3115 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3116 InitRange.getBegin(), Init,
3117 InitRange.getEnd());
3122 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3123 CXXRecordDecl *ClassDecl) {
3124 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3125 if (!LangOpts.CPlusPlus11)
3126 return Diag(NameLoc, diag::err_delegating_ctor)
3127 << TInfo->getTypeLoc().getLocalSourceRange();
3128 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3130 bool InitList = true;
3131 MultiExprArg Args = Init;
3132 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3134 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3137 SourceRange InitRange = Init->getSourceRange();
3138 // Initialize the object.
3139 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3140 QualType(ClassDecl->getTypeForDecl(), 0));
3141 InitializationKind Kind =
3142 InitList ? InitializationKind::CreateDirectList(NameLoc)
3143 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3144 InitRange.getEnd());
3145 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3146 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3148 if (DelegationInit.isInvalid())
3151 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3152 "Delegating constructor with no target?");
3154 // C++11 [class.base.init]p7:
3155 // The initialization of each base and member constitutes a
3157 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3158 InitRange.getBegin());
3159 if (DelegationInit.isInvalid())
3162 // If we are in a dependent context, template instantiation will
3163 // perform this type-checking again. Just save the arguments that we
3164 // received in a ParenListExpr.
3165 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3166 // of the information that we have about the base
3167 // initializer. However, deconstructing the ASTs is a dicey process,
3168 // and this approach is far more likely to get the corner cases right.
3169 if (CurContext->isDependentContext())
3170 DelegationInit = Init;
3172 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3173 DelegationInit.getAs<Expr>(),
3174 InitRange.getEnd());
3178 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3179 Expr *Init, CXXRecordDecl *ClassDecl,
3180 SourceLocation EllipsisLoc) {
3181 SourceLocation BaseLoc
3182 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3184 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3185 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3186 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3188 // C++ [class.base.init]p2:
3189 // [...] Unless the mem-initializer-id names a nonstatic data
3190 // member of the constructor's class or a direct or virtual base
3191 // of that class, the mem-initializer is ill-formed. A
3192 // mem-initializer-list can initialize a base class using any
3193 // name that denotes that base class type.
3194 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3196 SourceRange InitRange = Init->getSourceRange();
3197 if (EllipsisLoc.isValid()) {
3198 // This is a pack expansion.
3199 if (!BaseType->containsUnexpandedParameterPack()) {
3200 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3201 << SourceRange(BaseLoc, InitRange.getEnd());
3203 EllipsisLoc = SourceLocation();
3206 // Check for any unexpanded parameter packs.
3207 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3210 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3214 // Check for direct and virtual base classes.
3215 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3216 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3218 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3220 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3222 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3225 // C++ [base.class.init]p2:
3226 // Unless the mem-initializer-id names a nonstatic data member of the
3227 // constructor's class or a direct or virtual base of that class, the
3228 // mem-initializer is ill-formed.
3229 if (!DirectBaseSpec && !VirtualBaseSpec) {
3230 // If the class has any dependent bases, then it's possible that
3231 // one of those types will resolve to the same type as
3232 // BaseType. Therefore, just treat this as a dependent base
3233 // class initialization. FIXME: Should we try to check the
3234 // initialization anyway? It seems odd.
3235 if (ClassDecl->hasAnyDependentBases())
3238 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3239 << BaseType << Context.getTypeDeclType(ClassDecl)
3240 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3245 DiscardCleanupsInEvaluationContext();
3247 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3248 /*IsVirtual=*/false,
3249 InitRange.getBegin(), Init,
3250 InitRange.getEnd(), EllipsisLoc);
3253 // C++ [base.class.init]p2:
3254 // If a mem-initializer-id is ambiguous because it designates both
3255 // a direct non-virtual base class and an inherited virtual base
3256 // class, the mem-initializer is ill-formed.
3257 if (DirectBaseSpec && VirtualBaseSpec)
3258 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3259 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3261 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3263 BaseSpec = VirtualBaseSpec;
3265 // Initialize the base.
3266 bool InitList = true;
3267 MultiExprArg Args = Init;
3268 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3270 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3273 InitializedEntity BaseEntity =
3274 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3275 InitializationKind Kind =
3276 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3277 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3278 InitRange.getEnd());
3279 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3280 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3281 if (BaseInit.isInvalid())
3284 // C++11 [class.base.init]p7:
3285 // The initialization of each base and member constitutes a
3287 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3288 if (BaseInit.isInvalid())
3291 // If we are in a dependent context, template instantiation will
3292 // perform this type-checking again. Just save the arguments that we
3293 // received in a ParenListExpr.
3294 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3295 // of the information that we have about the base
3296 // initializer. However, deconstructing the ASTs is a dicey process,
3297 // and this approach is far more likely to get the corner cases right.
3298 if (CurContext->isDependentContext())
3301 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3302 BaseSpec->isVirtual(),
3303 InitRange.getBegin(),
3304 BaseInit.getAs<Expr>(),
3305 InitRange.getEnd(), EllipsisLoc);
3308 // Create a static_cast\<T&&>(expr).
3309 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3310 if (T.isNull()) T = E->getType();
3311 QualType TargetType = SemaRef.BuildReferenceType(
3312 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3313 SourceLocation ExprLoc = E->getLocStart();
3314 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3315 TargetType, ExprLoc);
3317 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3318 SourceRange(ExprLoc, ExprLoc),
3319 E->getSourceRange()).get();
3322 /// ImplicitInitializerKind - How an implicit base or member initializer should
3323 /// initialize its base or member.
3324 enum ImplicitInitializerKind {
3332 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3333 ImplicitInitializerKind ImplicitInitKind,
3334 CXXBaseSpecifier *BaseSpec,
3335 bool IsInheritedVirtualBase,
3336 CXXCtorInitializer *&CXXBaseInit) {
3337 InitializedEntity InitEntity
3338 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3339 IsInheritedVirtualBase);
3341 ExprResult BaseInit;
3343 switch (ImplicitInitKind) {
3345 const CXXRecordDecl *Inherited =
3346 Constructor->getInheritedConstructor()->getParent();
3347 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3348 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3349 // C++11 [class.inhctor]p8:
3350 // Each expression in the expression-list is of the form
3351 // static_cast<T&&>(p), where p is the name of the corresponding
3352 // constructor parameter and T is the declared type of p.
3353 SmallVector<Expr*, 16> Args;
3354 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3355 ParmVarDecl *PD = Constructor->getParamDecl(I);
3356 ExprResult ArgExpr =
3357 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3358 VK_LValue, SourceLocation());
3359 if (ArgExpr.isInvalid())
3361 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3364 InitializationKind InitKind = InitializationKind::CreateDirect(
3365 Constructor->getLocation(), SourceLocation(), SourceLocation());
3366 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3367 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3373 InitializationKind InitKind
3374 = InitializationKind::CreateDefault(Constructor->getLocation());
3375 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3376 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3382 bool Moving = ImplicitInitKind == IIK_Move;
3383 ParmVarDecl *Param = Constructor->getParamDecl(0);
3384 QualType ParamType = Param->getType().getNonReferenceType();
3387 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3388 SourceLocation(), Param, false,
3389 Constructor->getLocation(), ParamType,
3390 VK_LValue, nullptr);
3392 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3394 // Cast to the base class to avoid ambiguities.
3396 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3397 ParamType.getQualifiers());
3400 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3403 CXXCastPath BasePath;
3404 BasePath.push_back(BaseSpec);
3405 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3406 CK_UncheckedDerivedToBase,
3407 Moving ? VK_XValue : VK_LValue,
3410 InitializationKind InitKind
3411 = InitializationKind::CreateDirect(Constructor->getLocation(),
3412 SourceLocation(), SourceLocation());
3413 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3414 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3419 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3420 if (BaseInit.isInvalid())
3424 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3425 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3427 BaseSpec->isVirtual(),
3429 BaseInit.getAs<Expr>(),
3436 static bool RefersToRValueRef(Expr *MemRef) {
3437 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3438 return Referenced->getType()->isRValueReferenceType();
3442 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3443 ImplicitInitializerKind ImplicitInitKind,
3444 FieldDecl *Field, IndirectFieldDecl *Indirect,
3445 CXXCtorInitializer *&CXXMemberInit) {
3446 if (Field->isInvalidDecl())
3449 SourceLocation Loc = Constructor->getLocation();
3451 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3452 bool Moving = ImplicitInitKind == IIK_Move;
3453 ParmVarDecl *Param = Constructor->getParamDecl(0);
3454 QualType ParamType = Param->getType().getNonReferenceType();
3456 // Suppress copying zero-width bitfields.
3457 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3460 Expr *MemberExprBase =
3461 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3462 SourceLocation(), Param, false,
3463 Loc, ParamType, VK_LValue, nullptr);
3465 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3468 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3471 // Build a reference to this field within the parameter.
3473 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3474 Sema::LookupMemberName);
3475 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3476 : cast<ValueDecl>(Field), AS_public);
3477 MemberLookup.resolveKind();
3479 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3483 /*TemplateKWLoc=*/SourceLocation(),
3484 /*FirstQualifierInScope=*/nullptr,
3486 /*TemplateArgs=*/nullptr);
3487 if (CtorArg.isInvalid())
3490 // C++11 [class.copy]p15:
3491 // - if a member m has rvalue reference type T&&, it is direct-initialized
3492 // with static_cast<T&&>(x.m);
3493 if (RefersToRValueRef(CtorArg.get())) {
3494 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3497 // When the field we are copying is an array, create index variables for
3498 // each dimension of the array. We use these index variables to subscript
3499 // the source array, and other clients (e.g., CodeGen) will perform the
3500 // necessary iteration with these index variables.
3501 SmallVector<VarDecl *, 4> IndexVariables;
3502 QualType BaseType = Field->getType();
3503 QualType SizeType = SemaRef.Context.getSizeType();
3504 bool InitializingArray = false;
3505 while (const ConstantArrayType *Array
3506 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3507 InitializingArray = true;
3508 // Create the iteration variable for this array index.
3509 IdentifierInfo *IterationVarName = nullptr;
3512 llvm::raw_svector_ostream OS(Str);
3513 OS << "__i" << IndexVariables.size();
3514 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3516 VarDecl *IterationVar
3517 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3518 IterationVarName, SizeType,
3519 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3521 IndexVariables.push_back(IterationVar);
3523 // Create a reference to the iteration variable.
3524 ExprResult IterationVarRef
3525 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3526 assert(!IterationVarRef.isInvalid() &&
3527 "Reference to invented variable cannot fail!");
3528 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3529 assert(!IterationVarRef.isInvalid() &&
3530 "Conversion of invented variable cannot fail!");
3532 // Subscript the array with this iteration variable.
3533 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3534 IterationVarRef.get(),
3536 if (CtorArg.isInvalid())
3539 BaseType = Array->getElementType();
3542 // The array subscript expression is an lvalue, which is wrong for moving.
3543 if (Moving && InitializingArray)
3544 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3546 // Construct the entity that we will be initializing. For an array, this
3547 // will be first element in the array, which may require several levels
3548 // of array-subscript entities.
3549 SmallVector<InitializedEntity, 4> Entities;
3550 Entities.reserve(1 + IndexVariables.size());
3552 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3554 Entities.push_back(InitializedEntity::InitializeMember(Field));
3555 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3556 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3560 // Direct-initialize to use the copy constructor.
3561 InitializationKind InitKind =
3562 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3564 Expr *CtorArgE = CtorArg.getAs<Expr>();
3565 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3568 ExprResult MemberInit
3569 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3570 MultiExprArg(&CtorArgE, 1));
3571 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3572 if (MemberInit.isInvalid())
3576 assert(IndexVariables.size() == 0 &&
3577 "Indirect field improperly initialized");
3579 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3581 MemberInit.getAs<Expr>(),
3584 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3585 Loc, MemberInit.getAs<Expr>(),
3587 IndexVariables.data(),
3588 IndexVariables.size());
3592 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3593 "Unhandled implicit init kind!");
3595 QualType FieldBaseElementType =
3596 SemaRef.Context.getBaseElementType(Field->getType());
3598 if (FieldBaseElementType->isRecordType()) {
3599 InitializedEntity InitEntity
3600 = Indirect? InitializedEntity::InitializeMember(Indirect)
3601 : InitializedEntity::InitializeMember(Field);
3602 InitializationKind InitKind =
3603 InitializationKind::CreateDefault(Loc);
3605 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3606 ExprResult MemberInit =
3607 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3609 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3610 if (MemberInit.isInvalid())
3614 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3620 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3627 if (!Field->getParent()->isUnion()) {
3628 if (FieldBaseElementType->isReferenceType()) {
3629 SemaRef.Diag(Constructor->getLocation(),
3630 diag::err_uninitialized_member_in_ctor)
3631 << (int)Constructor->isImplicit()
3632 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3633 << 0 << Field->getDeclName();
3634 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3638 if (FieldBaseElementType.isConstQualified()) {
3639 SemaRef.Diag(Constructor->getLocation(),
3640 diag::err_uninitialized_member_in_ctor)
3641 << (int)Constructor->isImplicit()
3642 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3643 << 1 << Field->getDeclName();
3644 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3649 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3650 FieldBaseElementType->isObjCRetainableType() &&
3651 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3652 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3654 // Default-initialize Objective-C pointers to NULL.
3656 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3658 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3663 // Nothing to initialize.
3664 CXXMemberInit = nullptr;
3669 struct BaseAndFieldInfo {
3671 CXXConstructorDecl *Ctor;
3672 bool AnyErrorsInInits;
3673 ImplicitInitializerKind IIK;
3674 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3675 SmallVector<CXXCtorInitializer*, 8> AllToInit;
3676 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3678 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3679 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3680 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3681 if (Generated && Ctor->isCopyConstructor())
3683 else if (Generated && Ctor->isMoveConstructor())
3685 else if (Ctor->getInheritedConstructor())
3691 bool isImplicitCopyOrMove() const {
3702 llvm_unreachable("Invalid ImplicitInitializerKind!");
3705 bool addFieldInitializer(CXXCtorInitializer *Init) {
3706 AllToInit.push_back(Init);
3708 // Check whether this initializer makes the field "used".
3709 if (Init->getInit()->HasSideEffects(S.Context))
3710 S.UnusedPrivateFields.remove(Init->getAnyMember());
3715 bool isInactiveUnionMember(FieldDecl *Field) {
3716 RecordDecl *Record = Field->getParent();
3717 if (!Record->isUnion())
3720 if (FieldDecl *Active =
3721 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3722 return Active != Field->getCanonicalDecl();
3724 // In an implicit copy or move constructor, ignore any in-class initializer.
3725 if (isImplicitCopyOrMove())
3728 // If there's no explicit initialization, the field is active only if it
3729 // has an in-class initializer...
3730 if (Field->hasInClassInitializer())
3732 // ... or it's an anonymous struct or union whose class has an in-class
3734 if (!Field->isAnonymousStructOrUnion())
3736 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3737 return !FieldRD->hasInClassInitializer();
3740 /// \brief Determine whether the given field is, or is within, a union member
3741 /// that is inactive (because there was an initializer given for a different
3742 /// member of the union, or because the union was not initialized at all).
3743 bool isWithinInactiveUnionMember(FieldDecl *Field,
3744 IndirectFieldDecl *Indirect) {
3746 return isInactiveUnionMember(Field);
3748 for (auto *C : Indirect->chain()) {
3749 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3750 if (Field && isInactiveUnionMember(Field))
3758 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3760 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3761 if (T->isIncompleteArrayType())
3764 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3765 if (!ArrayT->getSize())
3768 T = ArrayT->getElementType();
3774 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3776 IndirectFieldDecl *Indirect = nullptr) {
3777 if (Field->isInvalidDecl())
3780 // Overwhelmingly common case: we have a direct initializer for this field.
3781 if (CXXCtorInitializer *Init =
3782 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3783 return Info.addFieldInitializer(Init);
3785 // C++11 [class.base.init]p8:
3786 // if the entity is a non-static data member that has a
3787 // brace-or-equal-initializer and either
3788 // -- the constructor's class is a union and no other variant member of that
3789 // union is designated by a mem-initializer-id or
3790 // -- the constructor's class is not a union, and, if the entity is a member
3791 // of an anonymous union, no other member of that union is designated by
3792 // a mem-initializer-id,
3793 // the entity is initialized as specified in [dcl.init].
3795 // We also apply the same rules to handle anonymous structs within anonymous
3797 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3800 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3802 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3803 if (DIE.isInvalid())
3805 CXXCtorInitializer *Init;
3807 Init = new (SemaRef.Context)
3808 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3809 SourceLocation(), DIE.get(), SourceLocation());
3811 Init = new (SemaRef.Context)
3812 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3813 SourceLocation(), DIE.get(), SourceLocation());
3814 return Info.addFieldInitializer(Init);
3817 // Don't initialize incomplete or zero-length arrays.
3818 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3821 // Don't try to build an implicit initializer if there were semantic
3822 // errors in any of the initializers (and therefore we might be
3823 // missing some that the user actually wrote).
3824 if (Info.AnyErrorsInInits)
3827 CXXCtorInitializer *Init = nullptr;
3828 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3835 return Info.addFieldInitializer(Init);
3839 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3840 CXXCtorInitializer *Initializer) {
3841 assert(Initializer->isDelegatingInitializer());
3842 Constructor->setNumCtorInitializers(1);
3843 CXXCtorInitializer **initializer =
3844 new (Context) CXXCtorInitializer*[1];
3845 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3846 Constructor->setCtorInitializers(initializer);
3848 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3849 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3850 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3853 DelegatingCtorDecls.push_back(Constructor);
3855 DiagnoseUninitializedFields(*this, Constructor);
3860 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3861 ArrayRef<CXXCtorInitializer *> Initializers) {
3862 if (Constructor->isDependentContext()) {
3863 // Just store the initializers as written, they will be checked during
3865 if (!Initializers.empty()) {
3866 Constructor->setNumCtorInitializers(Initializers.size());
3867 CXXCtorInitializer **baseOrMemberInitializers =
3868 new (Context) CXXCtorInitializer*[Initializers.size()];
3869 memcpy(baseOrMemberInitializers, Initializers.data(),
3870 Initializers.size() * sizeof(CXXCtorInitializer*));
3871 Constructor->setCtorInitializers(baseOrMemberInitializers);
3874 // Let template instantiation know whether we had errors.
3876 Constructor->setInvalidDecl();
3881 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3883 // We need to build the initializer AST according to order of construction
3884 // and not what user specified in the Initializers list.
3885 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3889 bool HadError = false;
3891 for (unsigned i = 0; i < Initializers.size(); i++) {
3892 CXXCtorInitializer *Member = Initializers[i];
3894 if (Member->isBaseInitializer())
3895 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3897 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3899 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3900 for (auto *C : F->chain()) {
3901 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3902 if (FD && FD->getParent()->isUnion())
3903 Info.ActiveUnionMember.insert(std::make_pair(
3904 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3906 } else if (FieldDecl *FD = Member->getMember()) {
3907 if (FD->getParent()->isUnion())
3908 Info.ActiveUnionMember.insert(std::make_pair(
3909 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3914 // Keep track of the direct virtual bases.
3915 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3916 for (auto &I : ClassDecl->bases()) {
3918 DirectVBases.insert(&I);
3921 // Push virtual bases before others.
3922 for (auto &VBase : ClassDecl->vbases()) {
3923 if (CXXCtorInitializer *Value
3924 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3925 // [class.base.init]p7, per DR257:
3926 // A mem-initializer where the mem-initializer-id names a virtual base
3927 // class is ignored during execution of a constructor of any class that
3928 // is not the most derived class.
3929 if (ClassDecl->isAbstract()) {
3930 // FIXME: Provide a fixit to remove the base specifier. This requires
3931 // tracking the location of the associated comma for a base specifier.
3932 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3933 << VBase.getType() << ClassDecl;
3934 DiagnoseAbstractType(ClassDecl);
3937 Info.AllToInit.push_back(Value);
3938 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3939 // [class.base.init]p8, per DR257:
3940 // If a given [...] base class is not named by a mem-initializer-id
3941 // [...] and the entity is not a virtual base class of an abstract
3942 // class, then [...] the entity is default-initialized.
3943 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3944 CXXCtorInitializer *CXXBaseInit;
3945 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3946 &VBase, IsInheritedVirtualBase,
3952 Info.AllToInit.push_back(CXXBaseInit);
3956 // Non-virtual bases.
3957 for (auto &Base : ClassDecl->bases()) {
3958 // Virtuals are in the virtual base list and already constructed.
3959 if (Base.isVirtual())
3962 if (CXXCtorInitializer *Value
3963 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3964 Info.AllToInit.push_back(Value);
3965 } else if (!AnyErrors) {
3966 CXXCtorInitializer *CXXBaseInit;
3967 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3968 &Base, /*IsInheritedVirtualBase=*/false,
3974 Info.AllToInit.push_back(CXXBaseInit);
3979 for (auto *Mem : ClassDecl->decls()) {
3980 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3981 // C++ [class.bit]p2:
3982 // A declaration for a bit-field that omits the identifier declares an
3983 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3985 if (F->isUnnamedBitfield())
3988 // If we're not generating the implicit copy/move constructor, then we'll
3989 // handle anonymous struct/union fields based on their individual
3991 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3994 if (CollectFieldInitializer(*this, Info, F))
3999 // Beyond this point, we only consider default initialization.
4000 if (Info.isImplicitCopyOrMove())
4003 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4004 if (F->getType()->isIncompleteArrayType()) {
4005 assert(ClassDecl->hasFlexibleArrayMember() &&
4006 "Incomplete array type is not valid");
4010 // Initialize each field of an anonymous struct individually.
4011 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4018 unsigned NumInitializers = Info.AllToInit.size();
4019 if (NumInitializers > 0) {
4020 Constructor->setNumCtorInitializers(NumInitializers);
4021 CXXCtorInitializer **baseOrMemberInitializers =
4022 new (Context) CXXCtorInitializer*[NumInitializers];
4023 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4024 NumInitializers * sizeof(CXXCtorInitializer*));
4025 Constructor->setCtorInitializers(baseOrMemberInitializers);
4027 // Constructors implicitly reference the base and member
4029 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4030 Constructor->getParent());
4036 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4037 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4038 const RecordDecl *RD = RT->getDecl();
4039 if (RD->isAnonymousStructOrUnion()) {
4040 for (auto *Field : RD->fields())
4041 PopulateKeysForFields(Field, IdealInits);
4045 IdealInits.push_back(Field->getCanonicalDecl());
4048 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4049 return Context.getCanonicalType(BaseType).getTypePtr();
4052 static const void *GetKeyForMember(ASTContext &Context,
4053 CXXCtorInitializer *Member) {
4054 if (!Member->isAnyMemberInitializer())
4055 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4057 return Member->getAnyMember()->getCanonicalDecl();
4060 static void DiagnoseBaseOrMemInitializerOrder(
4061 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4062 ArrayRef<CXXCtorInitializer *> Inits) {
4063 if (Constructor->getDeclContext()->isDependentContext())
4066 // Don't check initializers order unless the warning is enabled at the
4067 // location of at least one initializer.
4068 bool ShouldCheckOrder = false;
4069 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4070 CXXCtorInitializer *Init = Inits[InitIndex];
4071 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4072 Init->getSourceLocation())) {
4073 ShouldCheckOrder = true;
4077 if (!ShouldCheckOrder)
4080 // Build the list of bases and members in the order that they'll
4081 // actually be initialized. The explicit initializers should be in
4082 // this same order but may be missing things.
4083 SmallVector<const void*, 32> IdealInitKeys;
4085 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4087 // 1. Virtual bases.
4088 for (const auto &VBase : ClassDecl->vbases())
4089 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4091 // 2. Non-virtual bases.
4092 for (const auto &Base : ClassDecl->bases()) {
4093 if (Base.isVirtual())
4095 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4098 // 3. Direct fields.
4099 for (auto *Field : ClassDecl->fields()) {
4100 if (Field->isUnnamedBitfield())
4103 PopulateKeysForFields(Field, IdealInitKeys);
4106 unsigned NumIdealInits = IdealInitKeys.size();
4107 unsigned IdealIndex = 0;
4109 CXXCtorInitializer *PrevInit = nullptr;
4110 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4111 CXXCtorInitializer *Init = Inits[InitIndex];
4112 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4114 // Scan forward to try to find this initializer in the idealized
4115 // initializers list.
4116 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4117 if (InitKey == IdealInitKeys[IdealIndex])
4120 // If we didn't find this initializer, it must be because we
4121 // scanned past it on a previous iteration. That can only
4122 // happen if we're out of order; emit a warning.
4123 if (IdealIndex == NumIdealInits && PrevInit) {
4124 Sema::SemaDiagnosticBuilder D =
4125 SemaRef.Diag(PrevInit->getSourceLocation(),
4126 diag::warn_initializer_out_of_order);
4128 if (PrevInit->isAnyMemberInitializer())
4129 D << 0 << PrevInit->getAnyMember()->getDeclName();
4131 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4133 if (Init->isAnyMemberInitializer())
4134 D << 0 << Init->getAnyMember()->getDeclName();
4136 D << 1 << Init->getTypeSourceInfo()->getType();
4138 // Move back to the initializer's location in the ideal list.
4139 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4140 if (InitKey == IdealInitKeys[IdealIndex])
4143 assert(IdealIndex != NumIdealInits &&
4144 "initializer not found in initializer list");
4152 bool CheckRedundantInit(Sema &S,
4153 CXXCtorInitializer *Init,
4154 CXXCtorInitializer *&PrevInit) {
4160 if (FieldDecl *Field = Init->getAnyMember())
4161 S.Diag(Init->getSourceLocation(),
4162 diag::err_multiple_mem_initialization)
4163 << Field->getDeclName()
4164 << Init->getSourceRange();
4166 const Type *BaseClass = Init->getBaseClass();
4167 assert(BaseClass && "neither field nor base");
4168 S.Diag(Init->getSourceLocation(),
4169 diag::err_multiple_base_initialization)
4170 << QualType(BaseClass, 0)
4171 << Init->getSourceRange();
4173 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4174 << 0 << PrevInit->getSourceRange();
4179 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4180 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4182 bool CheckRedundantUnionInit(Sema &S,
4183 CXXCtorInitializer *Init,
4184 RedundantUnionMap &Unions) {
4185 FieldDecl *Field = Init->getAnyMember();
4186 RecordDecl *Parent = Field->getParent();
4187 NamedDecl *Child = Field;
4189 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4190 if (Parent->isUnion()) {
4191 UnionEntry &En = Unions[Parent];
4192 if (En.first && En.first != Child) {
4193 S.Diag(Init->getSourceLocation(),
4194 diag::err_multiple_mem_union_initialization)
4195 << Field->getDeclName()
4196 << Init->getSourceRange();
4197 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4198 << 0 << En.second->getSourceRange();
4205 if (!Parent->isAnonymousStructOrUnion())
4210 Parent = cast<RecordDecl>(Parent->getDeclContext());
4217 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4218 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4219 SourceLocation ColonLoc,
4220 ArrayRef<CXXCtorInitializer*> MemInits,
4222 if (!ConstructorDecl)
4225 AdjustDeclIfTemplate(ConstructorDecl);
4227 CXXConstructorDecl *Constructor
4228 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4231 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4235 // Mapping for the duplicate initializers check.
4236 // For member initializers, this is keyed with a FieldDecl*.
4237 // For base initializers, this is keyed with a Type*.
4238 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4240 // Mapping for the inconsistent anonymous-union initializers check.
4241 RedundantUnionMap MemberUnions;
4243 bool HadError = false;
4244 for (unsigned i = 0; i < MemInits.size(); i++) {
4245 CXXCtorInitializer *Init = MemInits[i];
4247 // Set the source order index.
4248 Init->setSourceOrder(i);
4250 if (Init->isAnyMemberInitializer()) {
4251 const void *Key = GetKeyForMember(Context, Init);
4252 if (CheckRedundantInit(*this, Init, Members[Key]) ||
4253 CheckRedundantUnionInit(*this, Init, MemberUnions))
4255 } else if (Init->isBaseInitializer()) {
4256 const void *Key = GetKeyForMember(Context, Init);
4257 if (CheckRedundantInit(*this, Init, Members[Key]))
4260 assert(Init->isDelegatingInitializer());
4261 // This must be the only initializer
4262 if (MemInits.size() != 1) {
4263 Diag(Init->getSourceLocation(),
4264 diag::err_delegating_initializer_alone)
4265 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4266 // We will treat this as being the only initializer.
4268 SetDelegatingInitializer(Constructor, MemInits[i]);
4269 // Return immediately as the initializer is set.
4277 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4279 SetCtorInitializers(Constructor, AnyErrors, MemInits);
4281 DiagnoseUninitializedFields(*this, Constructor);
4285 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4286 CXXRecordDecl *ClassDecl) {
4287 // Ignore dependent contexts. Also ignore unions, since their members never
4288 // have destructors implicitly called.
4289 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4292 // FIXME: all the access-control diagnostics are positioned on the
4293 // field/base declaration. That's probably good; that said, the
4294 // user might reasonably want to know why the destructor is being
4295 // emitted, and we currently don't say.
4297 // Non-static data members.
4298 for (auto *Field : ClassDecl->fields()) {
4299 if (Field->isInvalidDecl())
4302 // Don't destroy incomplete or zero-length arrays.
4303 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4306 QualType FieldType = Context.getBaseElementType(Field->getType());
4308 const RecordType* RT = FieldType->getAs<RecordType>();
4312 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4313 if (FieldClassDecl->isInvalidDecl())
4315 if (FieldClassDecl->hasIrrelevantDestructor())
4317 // The destructor for an implicit anonymous union member is never invoked.
4318 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4321 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4322 assert(Dtor && "No dtor found for FieldClassDecl!");
4323 CheckDestructorAccess(Field->getLocation(), Dtor,
4324 PDiag(diag::err_access_dtor_field)
4325 << Field->getDeclName()
4328 MarkFunctionReferenced(Location, Dtor);
4329 DiagnoseUseOfDecl(Dtor, Location);
4332 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4335 for (const auto &Base : ClassDecl->bases()) {
4336 // Bases are always records in a well-formed non-dependent class.
4337 const RecordType *RT = Base.getType()->getAs<RecordType>();
4339 // Remember direct virtual bases.
4340 if (Base.isVirtual())
4341 DirectVirtualBases.insert(RT);
4343 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4344 // If our base class is invalid, we probably can't get its dtor anyway.
4345 if (BaseClassDecl->isInvalidDecl())
4347 if (BaseClassDecl->hasIrrelevantDestructor())
4350 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4351 assert(Dtor && "No dtor found for BaseClassDecl!");
4353 // FIXME: caret should be on the start of the class name
4354 CheckDestructorAccess(Base.getLocStart(), Dtor,
4355 PDiag(diag::err_access_dtor_base)
4357 << Base.getSourceRange(),
4358 Context.getTypeDeclType(ClassDecl));
4360 MarkFunctionReferenced(Location, Dtor);
4361 DiagnoseUseOfDecl(Dtor, Location);
4365 for (const auto &VBase : ClassDecl->vbases()) {
4366 // Bases are always records in a well-formed non-dependent class.
4367 const RecordType *RT = VBase.getType()->castAs<RecordType>();
4369 // Ignore direct virtual bases.
4370 if (DirectVirtualBases.count(RT))
4373 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4374 // If our base class is invalid, we probably can't get its dtor anyway.
4375 if (BaseClassDecl->isInvalidDecl())
4377 if (BaseClassDecl->hasIrrelevantDestructor())
4380 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4381 assert(Dtor && "No dtor found for BaseClassDecl!");
4382 if (CheckDestructorAccess(
4383 ClassDecl->getLocation(), Dtor,
4384 PDiag(diag::err_access_dtor_vbase)
4385 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4386 Context.getTypeDeclType(ClassDecl)) ==
4388 CheckDerivedToBaseConversion(
4389 Context.getTypeDeclType(ClassDecl), VBase.getType(),
4390 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4391 SourceRange(), DeclarationName(), nullptr);
4394 MarkFunctionReferenced(Location, Dtor);
4395 DiagnoseUseOfDecl(Dtor, Location);
4399 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4403 if (CXXConstructorDecl *Constructor
4404 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4405 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4406 DiagnoseUninitializedFields(*this, Constructor);
4410 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4411 unsigned DiagID, AbstractDiagSelID SelID) {
4412 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4414 AbstractDiagSelID SelID;
4417 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4418 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4420 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4421 if (Suppressed) return;
4423 S.Diag(Loc, DiagID) << T;
4425 S.Diag(Loc, DiagID) << SelID << T;
4427 } Diagnoser(DiagID, SelID);
4429 return RequireNonAbstractType(Loc, T, Diagnoser);
4432 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4433 TypeDiagnoser &Diagnoser) {
4434 if (!getLangOpts().CPlusPlus)
4437 if (const ArrayType *AT = Context.getAsArrayType(T))
4438 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4440 if (const PointerType *PT = T->getAs<PointerType>()) {
4441 // Find the innermost pointer type.
4442 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4445 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4446 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4449 const RecordType *RT = T->getAs<RecordType>();
4453 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4455 // We can't answer whether something is abstract until it has a
4456 // definition. If it's currently being defined, we'll walk back
4457 // over all the declarations when we have a full definition.
4458 const CXXRecordDecl *Def = RD->getDefinition();
4459 if (!Def || Def->isBeingDefined())
4462 if (!RD->isAbstract())
4465 Diagnoser.diagnose(*this, Loc, T);
4466 DiagnoseAbstractType(RD);
4471 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4472 // Check if we've already emitted the list of pure virtual functions
4474 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4477 // If the diagnostic is suppressed, don't emit the notes. We're only
4478 // going to emit them once, so try to attach them to a diagnostic we're
4479 // actually going to show.
4480 if (Diags.isLastDiagnosticIgnored())
4483 CXXFinalOverriderMap FinalOverriders;
4484 RD->getFinalOverriders(FinalOverriders);
4486 // Keep a set of seen pure methods so we won't diagnose the same method
4488 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4490 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4491 MEnd = FinalOverriders.end();
4494 for (OverridingMethods::iterator SO = M->second.begin(),
4495 SOEnd = M->second.end();
4496 SO != SOEnd; ++SO) {
4497 // C++ [class.abstract]p4:
4498 // A class is abstract if it contains or inherits at least one
4499 // pure virtual function for which the final overrider is pure
4503 if (SO->second.size() != 1)
4506 if (!SO->second.front().Method->isPure())
4509 if (!SeenPureMethods.insert(SO->second.front().Method).second)
4512 Diag(SO->second.front().Method->getLocation(),
4513 diag::note_pure_virtual_function)
4514 << SO->second.front().Method->getDeclName() << RD->getDeclName();
4518 if (!PureVirtualClassDiagSet)
4519 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4520 PureVirtualClassDiagSet->insert(RD);
4524 struct AbstractUsageInfo {
4526 CXXRecordDecl *Record;
4527 CanQualType AbstractType;
4530 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4531 : S(S), Record(Record),
4532 AbstractType(S.Context.getCanonicalType(
4533 S.Context.getTypeDeclType(Record))),
4536 void DiagnoseAbstractType() {
4537 if (Invalid) return;
4538 S.DiagnoseAbstractType(Record);
4542 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4545 struct CheckAbstractUsage {
4546 AbstractUsageInfo &Info;
4547 const NamedDecl *Ctx;
4549 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4550 : Info(Info), Ctx(Ctx) {}
4552 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4553 switch (TL.getTypeLocClass()) {
4554 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4555 #define TYPELOC(CLASS, PARENT) \
4556 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4557 #include "clang/AST/TypeLocNodes.def"
4561 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4562 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4563 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4564 if (!TL.getParam(I))
4567 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4568 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4572 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4573 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4576 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4577 // Visit the type parameters from a permissive context.
4578 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4579 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4580 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4581 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4582 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4583 // TODO: other template argument types?
4587 // Visit pointee types from a permissive context.
4588 #define CheckPolymorphic(Type) \
4589 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4590 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4592 CheckPolymorphic(PointerTypeLoc)
4593 CheckPolymorphic(ReferenceTypeLoc)
4594 CheckPolymorphic(MemberPointerTypeLoc)
4595 CheckPolymorphic(BlockPointerTypeLoc)
4596 CheckPolymorphic(AtomicTypeLoc)
4598 /// Handle all the types we haven't given a more specific
4599 /// implementation for above.
4600 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4601 // Every other kind of type that we haven't called out already
4602 // that has an inner type is either (1) sugar or (2) contains that
4603 // inner type in some way as a subobject.
4604 if (TypeLoc Next = TL.getNextTypeLoc())
4605 return Visit(Next, Sel);
4607 // If there's no inner type and we're in a permissive context,
4609 if (Sel == Sema::AbstractNone) return;
4611 // Check whether the type matches the abstract type.
4612 QualType T = TL.getType();
4613 if (T->isArrayType()) {
4614 Sel = Sema::AbstractArrayType;
4615 T = Info.S.Context.getBaseElementType(T);
4617 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4618 if (CT != Info.AbstractType) return;
4620 // It matched; do some magic.
4621 if (Sel == Sema::AbstractArrayType) {
4622 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4623 << T << TL.getSourceRange();
4625 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4626 << Sel << T << TL.getSourceRange();
4628 Info.DiagnoseAbstractType();
4632 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4633 Sema::AbstractDiagSelID Sel) {
4634 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4639 /// Check for invalid uses of an abstract type in a method declaration.
4640 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4641 CXXMethodDecl *MD) {
4642 // No need to do the check on definitions, which require that
4643 // the return/param types be complete.
4644 if (MD->doesThisDeclarationHaveABody())
4647 // For safety's sake, just ignore it if we don't have type source
4648 // information. This should never happen for non-implicit methods,
4650 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4651 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4654 /// Check for invalid uses of an abstract type within a class definition.
4655 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4656 CXXRecordDecl *RD) {
4657 for (auto *D : RD->decls()) {
4658 if (D->isImplicit()) continue;
4660 // Methods and method templates.
4661 if (isa<CXXMethodDecl>(D)) {
4662 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4663 } else if (isa<FunctionTemplateDecl>(D)) {
4664 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4665 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4667 // Fields and static variables.
4668 } else if (isa<FieldDecl>(D)) {
4669 FieldDecl *FD = cast<FieldDecl>(D);
4670 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4671 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4672 } else if (isa<VarDecl>(D)) {
4673 VarDecl *VD = cast<VarDecl>(D);
4674 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4675 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4677 // Nested classes and class templates.
4678 } else if (isa<CXXRecordDecl>(D)) {
4679 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4680 } else if (isa<ClassTemplateDecl>(D)) {
4681 CheckAbstractClassUsage(Info,
4682 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4687 /// \brief Check class-level dllimport/dllexport attribute.
4688 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4689 Attr *ClassAttr = getDLLAttr(Class);
4691 // MSVC inherits DLL attributes to partial class template specializations.
4692 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4693 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4694 if (Attr *TemplateAttr =
4695 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4696 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4697 A->setInherited(true);
4706 if (!Class->isExternallyVisible()) {
4707 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4708 << Class << ClassAttr;
4712 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4713 !ClassAttr->isInherited()) {
4714 // Diagnose dll attributes on members of class with dll attribute.
4715 for (Decl *Member : Class->decls()) {
4716 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4718 InheritableAttr *MemberAttr = getDLLAttr(Member);
4719 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4722 Diag(MemberAttr->getLocation(),
4723 diag::err_attribute_dll_member_of_dll_class)
4724 << MemberAttr << ClassAttr;
4725 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4726 Member->setInvalidDecl();
4730 if (Class->getDescribedClassTemplate())
4731 // Don't inherit dll attribute until the template is instantiated.
4734 // The class is either imported or exported.
4735 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4736 const bool ClassImported = !ClassExported;
4738 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4740 // Ignore explicit dllexport on explicit class template instantiation declarations.
4741 if (ClassExported && !ClassAttr->isInherited() &&
4742 TSK == TSK_ExplicitInstantiationDeclaration) {
4743 Class->dropAttr<DLLExportAttr>();
4747 // Force declaration of implicit members so they can inherit the attribute.
4748 ForceDeclarationOfImplicitMembers(Class);
4750 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4751 // seem to be true in practice?
4753 for (Decl *Member : Class->decls()) {
4754 VarDecl *VD = dyn_cast<VarDecl>(Member);
4755 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4757 // Only methods and static fields inherit the attributes.
4762 // Don't process deleted methods.
4763 if (MD->isDeleted())
4766 if (MD->isInlined()) {
4767 // MinGW does not import or export inline methods.
4768 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4771 // MSVC versions before 2015 don't export the move assignment operators,
4772 // so don't attempt to import them if we have a definition.
4773 if (ClassImported && MD->isMoveAssignmentOperator() &&
4774 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4779 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4782 if (!getDLLAttr(Member)) {
4784 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4785 NewAttr->setInherited(true);
4786 Member->addAttr(NewAttr);
4789 if (MD && ClassExported) {
4790 if (TSK == TSK_ExplicitInstantiationDeclaration)
4791 // Don't go any further if this is just an explicit instantiation
4795 if (MD->isUserProvided()) {
4796 // Instantiate non-default class member functions ...
4798 // .. except for certain kinds of template specializations.
4799 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4802 MarkFunctionReferenced(Class->getLocation(), MD);
4804 // The function will be passed to the consumer when its definition is
4806 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4807 MD->isCopyAssignmentOperator() ||
4808 MD->isMoveAssignmentOperator()) {
4809 // Synthesize and instantiate non-trivial implicit methods, explicitly
4810 // defaulted methods, and the copy and move assignment operators. The
4811 // latter are exported even if they are trivial, because the address of
4812 // an operator can be taken and should compare equal accross libraries.
4813 DiagnosticErrorTrap Trap(Diags);
4814 MarkFunctionReferenced(Class->getLocation(), MD);
4815 if (Trap.hasErrorOccurred()) {
4816 Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4817 << Class->getName() << !getLangOpts().CPlusPlus11;
4821 // There is no later point when we will see the definition of this
4822 // function, so pass it to the consumer now.
4823 Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4829 /// \brief Perform propagation of DLL attributes from a derived class to a
4830 /// templated base class for MS compatibility.
4831 void Sema::propagateDLLAttrToBaseClassTemplate(
4832 CXXRecordDecl *Class, Attr *ClassAttr,
4833 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4835 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4836 // If the base class template has a DLL attribute, don't try to change it.
4840 auto TSK = BaseTemplateSpec->getSpecializationKind();
4841 if (!getDLLAttr(BaseTemplateSpec) &&
4842 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4843 TSK == TSK_ImplicitInstantiation)) {
4844 // The template hasn't been instantiated yet (or it has, but only as an
4845 // explicit instantiation declaration or implicit instantiation, which means
4846 // we haven't codegenned any members yet), so propagate the attribute.
4847 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4848 NewAttr->setInherited(true);
4849 BaseTemplateSpec->addAttr(NewAttr);
4851 // If the template is already instantiated, checkDLLAttributeRedeclaration()
4852 // needs to be run again to work see the new attribute. Otherwise this will
4853 // get run whenever the template is instantiated.
4854 if (TSK != TSK_Undeclared)
4855 checkClassLevelDLLAttribute(BaseTemplateSpec);
4860 if (getDLLAttr(BaseTemplateSpec)) {
4861 // The template has already been specialized or instantiated with an
4862 // attribute, explicitly or through propagation. We should not try to change
4867 // The template was previously instantiated or explicitly specialized without
4868 // a dll attribute, It's too late for us to add an attribute, so warn that
4869 // this is unsupported.
4870 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4871 << BaseTemplateSpec->isExplicitSpecialization();
4872 Diag(ClassAttr->getLocation(), diag::note_attribute);
4873 if (BaseTemplateSpec->isExplicitSpecialization()) {
4874 Diag(BaseTemplateSpec->getLocation(),
4875 diag::note_template_class_explicit_specialization_was_here)
4876 << BaseTemplateSpec;
4878 Diag(BaseTemplateSpec->getPointOfInstantiation(),
4879 diag::note_template_class_instantiation_was_here)
4880 << BaseTemplateSpec;
4884 /// \brief Perform semantic checks on a class definition that has been
4885 /// completing, introducing implicitly-declared members, checking for
4886 /// abstract types, etc.
4887 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4891 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4892 AbstractUsageInfo Info(*this, Record);
4893 CheckAbstractClassUsage(Info, Record);
4896 // If this is not an aggregate type and has no user-declared constructor,
4897 // complain about any non-static data members of reference or const scalar
4898 // type, since they will never get initializers.
4899 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4900 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4901 !Record->isLambda()) {
4902 bool Complained = false;
4903 for (const auto *F : Record->fields()) {
4904 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4907 if (F->getType()->isReferenceType() ||
4908 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4910 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4911 << Record->getTagKind() << Record;
4915 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4916 << F->getType()->isReferenceType()
4917 << F->getDeclName();
4922 if (Record->getIdentifier()) {
4923 // C++ [class.mem]p13:
4924 // If T is the name of a class, then each of the following shall have a
4925 // name different from T:
4926 // - every member of every anonymous union that is a member of class T.
4928 // C++ [class.mem]p14:
4929 // In addition, if class T has a user-declared constructor (12.1), every
4930 // non-static data member of class T shall have a name different from T.
4931 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4932 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4935 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4936 isa<IndirectFieldDecl>(D)) {
4937 Diag(D->getLocation(), diag::err_member_name_of_class)
4938 << D->getDeclName();
4944 // Warn if the class has virtual methods but non-virtual public destructor.
4945 if (Record->isPolymorphic() && !Record->isDependentType()) {
4946 CXXDestructorDecl *dtor = Record->getDestructor();
4947 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4948 !Record->hasAttr<FinalAttr>())
4949 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4950 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4953 if (Record->isAbstract()) {
4954 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4955 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4956 << FA->isSpelledAsSealed();
4957 DiagnoseAbstractType(Record);
4961 bool HasMethodWithOverrideControl = false,
4962 HasOverridingMethodWithoutOverrideControl = false;
4963 if (!Record->isDependentType()) {
4964 for (auto *M : Record->methods()) {
4965 // See if a method overloads virtual methods in a base
4966 // class without overriding any.
4968 DiagnoseHiddenVirtualMethods(M);
4969 if (M->hasAttr<OverrideAttr>())
4970 HasMethodWithOverrideControl = true;
4971 else if (M->size_overridden_methods() > 0)
4972 HasOverridingMethodWithoutOverrideControl = true;
4973 // Check whether the explicitly-defaulted special members are valid.
4974 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4975 CheckExplicitlyDefaultedSpecialMember(M);
4977 // For an explicitly defaulted or deleted special member, we defer
4978 // determining triviality until the class is complete. That time is now!
4979 if (!M->isImplicit() && !M->isUserProvided()) {
4980 CXXSpecialMember CSM = getSpecialMember(M);
4981 if (CSM != CXXInvalid) {
4982 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4984 // Inform the class that we've finished declaring this member.
4985 Record->finishedDefaultedOrDeletedMember(M);
4991 if (HasMethodWithOverrideControl &&
4992 HasOverridingMethodWithoutOverrideControl) {
4993 // At least one method has the 'override' control declared.
4994 // Diagnose all other overridden methods which do not have 'override' specified on them.
4995 for (auto *M : Record->methods())
4996 DiagnoseAbsenceOfOverrideControl(M);
4999 // ms_struct is a request to use the same ABI rules as MSVC. Check
5000 // whether this class uses any C++ features that are implemented
5001 // completely differently in MSVC, and if so, emit a diagnostic.
5002 // That diagnostic defaults to an error, but we allow projects to
5003 // map it down to a warning (or ignore it). It's a fairly common
5004 // practice among users of the ms_struct pragma to mass-annotate
5005 // headers, sweeping up a bunch of types that the project doesn't
5006 // really rely on MSVC-compatible layout for. We must therefore
5007 // support "ms_struct except for C++ stuff" as a secondary ABI.
5008 if (Record->isMsStruct(Context) &&
5009 (Record->isPolymorphic() || Record->getNumBases())) {
5010 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5013 // Declare inheriting constructors. We do this eagerly here because:
5014 // - The standard requires an eager diagnostic for conflicting inheriting
5015 // constructors from different classes.
5016 // - The lazy declaration of the other implicit constructors is so as to not
5017 // waste space and performance on classes that are not meant to be
5018 // instantiated (e.g. meta-functions). This doesn't apply to classes that
5019 // have inheriting constructors.
5020 DeclareInheritingConstructors(Record);
5022 checkClassLevelDLLAttribute(Record);
5025 /// Look up the special member function that would be called by a special
5026 /// member function for a subobject of class type.
5028 /// \param Class The class type of the subobject.
5029 /// \param CSM The kind of special member function.
5030 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5031 /// \param ConstRHS True if this is a copy operation with a const object
5032 /// on its RHS, that is, if the argument to the outer special member
5033 /// function is 'const' and this is not a field marked 'mutable'.
5034 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5035 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5036 unsigned FieldQuals, bool ConstRHS) {
5037 unsigned LHSQuals = 0;
5038 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5039 LHSQuals = FieldQuals;
5041 unsigned RHSQuals = FieldQuals;
5042 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5045 RHSQuals |= Qualifiers::Const;
5047 return S.LookupSpecialMember(Class, CSM,
5048 RHSQuals & Qualifiers::Const,
5049 RHSQuals & Qualifiers::Volatile,
5051 LHSQuals & Qualifiers::Const,
5052 LHSQuals & Qualifiers::Volatile);
5055 /// Is the special member function which would be selected to perform the
5056 /// specified operation on the specified class type a constexpr constructor?
5057 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5058 Sema::CXXSpecialMember CSM,
5059 unsigned Quals, bool ConstRHS) {
5060 Sema::SpecialMemberOverloadResult *SMOR =
5061 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5062 if (!SMOR || !SMOR->getMethod())
5063 // A constructor we wouldn't select can't be "involved in initializing"
5066 return SMOR->getMethod()->isConstexpr();
5069 /// Determine whether the specified special member function would be constexpr
5070 /// if it were implicitly defined.
5071 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5072 Sema::CXXSpecialMember CSM,
5074 if (!S.getLangOpts().CPlusPlus11)
5077 // C++11 [dcl.constexpr]p4:
5078 // In the definition of a constexpr constructor [...]
5081 case Sema::CXXDefaultConstructor:
5082 // Since default constructor lookup is essentially trivial (and cannot
5083 // involve, for instance, template instantiation), we compute whether a
5084 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5086 // This is important for performance; we need to know whether the default
5087 // constructor is constexpr to determine whether the type is a literal type.
5088 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5090 case Sema::CXXCopyConstructor:
5091 case Sema::CXXMoveConstructor:
5092 // For copy or move constructors, we need to perform overload resolution.
5095 case Sema::CXXCopyAssignment:
5096 case Sema::CXXMoveAssignment:
5097 if (!S.getLangOpts().CPlusPlus14)
5099 // In C++1y, we need to perform overload resolution.
5103 case Sema::CXXDestructor:
5104 case Sema::CXXInvalid:
5108 // -- if the class is a non-empty union, or for each non-empty anonymous
5109 // union member of a non-union class, exactly one non-static data member
5110 // shall be initialized; [DR1359]
5112 // If we squint, this is guaranteed, since exactly one non-static data member
5113 // will be initialized (if the constructor isn't deleted), we just don't know
5115 if (Ctor && ClassDecl->isUnion())
5118 // -- the class shall not have any virtual base classes;
5119 if (Ctor && ClassDecl->getNumVBases())
5122 // C++1y [class.copy]p26:
5123 // -- [the class] is a literal type, and
5124 if (!Ctor && !ClassDecl->isLiteral())
5127 // -- every constructor involved in initializing [...] base class
5128 // sub-objects shall be a constexpr constructor;
5129 // -- the assignment operator selected to copy/move each direct base
5130 // class is a constexpr function, and
5131 for (const auto &B : ClassDecl->bases()) {
5132 const RecordType *BaseType = B.getType()->getAs<RecordType>();
5133 if (!BaseType) continue;
5135 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5136 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5140 // -- every constructor involved in initializing non-static data members
5141 // [...] shall be a constexpr constructor;
5142 // -- every non-static data member and base class sub-object shall be
5144 // -- for each non-static data member of X that is of class type (or array
5145 // thereof), the assignment operator selected to copy/move that member is
5146 // a constexpr function
5147 for (const auto *F : ClassDecl->fields()) {
5148 if (F->isInvalidDecl())
5150 QualType BaseType = S.Context.getBaseElementType(F->getType());
5151 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5152 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5153 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5154 BaseType.getCVRQualifiers(),
5155 ConstArg && !F->isMutable()))
5160 // All OK, it's constexpr!
5164 static Sema::ImplicitExceptionSpecification
5165 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5166 switch (S.getSpecialMember(MD)) {
5167 case Sema::CXXDefaultConstructor:
5168 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5169 case Sema::CXXCopyConstructor:
5170 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5171 case Sema::CXXCopyAssignment:
5172 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5173 case Sema::CXXMoveConstructor:
5174 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5175 case Sema::CXXMoveAssignment:
5176 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5177 case Sema::CXXDestructor:
5178 return S.ComputeDefaultedDtorExceptionSpec(MD);
5179 case Sema::CXXInvalid:
5182 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5183 "only special members have implicit exception specs");
5184 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5187 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5188 CXXMethodDecl *MD) {
5189 FunctionProtoType::ExtProtoInfo EPI;
5191 // Build an exception specification pointing back at this member.
5192 EPI.ExceptionSpec.Type = EST_Unevaluated;
5193 EPI.ExceptionSpec.SourceDecl = MD;
5195 // Set the calling convention to the default for C++ instance methods.
5196 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5197 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5198 /*IsCXXMethod=*/true));
5202 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5203 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5204 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5207 // Evaluate the exception specification.
5208 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5210 // Update the type of the special member to use it.
5211 UpdateExceptionSpec(MD, ESI);
5213 // A user-provided destructor can be defined outside the class. When that
5214 // happens, be sure to update the exception specification on both
5216 const FunctionProtoType *CanonicalFPT =
5217 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5218 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5219 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5222 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5223 CXXRecordDecl *RD = MD->getParent();
5224 CXXSpecialMember CSM = getSpecialMember(MD);
5226 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5227 "not an explicitly-defaulted special member");
5229 // Whether this was the first-declared instance of the constructor.
5230 // This affects whether we implicitly add an exception spec and constexpr.
5231 bool First = MD == MD->getCanonicalDecl();
5233 bool HadError = false;
5235 // C++11 [dcl.fct.def.default]p1:
5236 // A function that is explicitly defaulted shall
5237 // -- be a special member function (checked elsewhere),
5238 // -- have the same type (except for ref-qualifiers, and except that a
5239 // copy operation can take a non-const reference) as an implicit
5241 // -- not have default arguments.
5242 unsigned ExpectedParams = 1;
5243 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5245 if (MD->getNumParams() != ExpectedParams) {
5246 // This also checks for default arguments: a copy or move constructor with a
5247 // default argument is classified as a default constructor, and assignment
5248 // operations and destructors can't have default arguments.
5249 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5250 << CSM << MD->getSourceRange();
5252 } else if (MD->isVariadic()) {
5253 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5254 << CSM << MD->getSourceRange();
5258 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5260 bool CanHaveConstParam = false;
5261 if (CSM == CXXCopyConstructor)
5262 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5263 else if (CSM == CXXCopyAssignment)
5264 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5266 QualType ReturnType = Context.VoidTy;
5267 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5268 // Check for return type matching.
5269 ReturnType = Type->getReturnType();
5270 QualType ExpectedReturnType =
5271 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5272 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5273 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5274 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5278 // A defaulted special member cannot have cv-qualifiers.
5279 if (Type->getTypeQuals()) {
5280 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5281 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5286 // Check for parameter type matching.
5287 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5288 bool HasConstParam = false;
5289 if (ExpectedParams && ArgType->isReferenceType()) {
5290 // Argument must be reference to possibly-const T.
5291 QualType ReferentType = ArgType->getPointeeType();
5292 HasConstParam = ReferentType.isConstQualified();
5294 if (ReferentType.isVolatileQualified()) {
5295 Diag(MD->getLocation(),
5296 diag::err_defaulted_special_member_volatile_param) << CSM;
5300 if (HasConstParam && !CanHaveConstParam) {
5301 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5302 Diag(MD->getLocation(),
5303 diag::err_defaulted_special_member_copy_const_param)
5304 << (CSM == CXXCopyAssignment);
5305 // FIXME: Explain why this special member can't be const.
5307 Diag(MD->getLocation(),
5308 diag::err_defaulted_special_member_move_const_param)
5309 << (CSM == CXXMoveAssignment);
5313 } else if (ExpectedParams) {
5314 // A copy assignment operator can take its argument by value, but a
5315 // defaulted one cannot.
5316 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5317 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5321 // C++11 [dcl.fct.def.default]p2:
5322 // An explicitly-defaulted function may be declared constexpr only if it
5323 // would have been implicitly declared as constexpr,
5324 // Do not apply this rule to members of class templates, since core issue 1358
5325 // makes such functions always instantiate to constexpr functions. For
5326 // functions which cannot be constexpr (for non-constructors in C++11 and for
5327 // destructors in C++1y), this is checked elsewhere.
5328 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5330 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5331 : isa<CXXConstructorDecl>(MD)) &&
5332 MD->isConstexpr() && !Constexpr &&
5333 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5334 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5335 // FIXME: Explain why the special member can't be constexpr.
5339 // and may have an explicit exception-specification only if it is compatible
5340 // with the exception-specification on the implicit declaration.
5341 if (Type->hasExceptionSpec()) {
5342 // Delay the check if this is the first declaration of the special member,
5343 // since we may not have parsed some necessary in-class initializers yet.
5345 // If the exception specification needs to be instantiated, do so now,
5346 // before we clobber it with an EST_Unevaluated specification below.
5347 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5348 InstantiateExceptionSpec(MD->getLocStart(), MD);
5349 Type = MD->getType()->getAs<FunctionProtoType>();
5351 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5353 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5356 // If a function is explicitly defaulted on its first declaration,
5358 // -- it is implicitly considered to be constexpr if the implicit
5359 // definition would be,
5360 MD->setConstexpr(Constexpr);
5362 // -- it is implicitly considered to have the same exception-specification
5363 // as if it had been implicitly declared,
5364 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5365 EPI.ExceptionSpec.Type = EST_Unevaluated;
5366 EPI.ExceptionSpec.SourceDecl = MD;
5367 MD->setType(Context.getFunctionType(ReturnType,
5368 llvm::makeArrayRef(&ArgType,
5373 if (ShouldDeleteSpecialMember(MD, CSM)) {
5375 SetDeclDeleted(MD, MD->getLocation());
5377 // C++11 [dcl.fct.def.default]p4:
5378 // [For a] user-provided explicitly-defaulted function [...] if such a
5379 // function is implicitly defined as deleted, the program is ill-formed.
5380 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5381 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5387 MD->setInvalidDecl();
5390 /// Check whether the exception specification provided for an
5391 /// explicitly-defaulted special member matches the exception specification
5392 /// that would have been generated for an implicit special member, per
5393 /// C++11 [dcl.fct.def.default]p2.
5394 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5395 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5396 // If the exception specification was explicitly specified but hadn't been
5397 // parsed when the method was defaulted, grab it now.
5398 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5400 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5402 // Compute the implicit exception specification.
5403 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5404 /*IsCXXMethod=*/true);
5405 FunctionProtoType::ExtProtoInfo EPI(CC);
5406 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5407 .getExceptionSpec();
5408 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5409 Context.getFunctionType(Context.VoidTy, None, EPI));
5411 // Ensure that it matches.
5412 CheckEquivalentExceptionSpec(
5413 PDiag(diag::err_incorrect_defaulted_exception_spec)
5414 << getSpecialMember(MD), PDiag(),
5415 ImplicitType, SourceLocation(),
5416 SpecifiedType, MD->getLocation());
5419 void Sema::CheckDelayedMemberExceptionSpecs() {
5420 decltype(DelayedExceptionSpecChecks) Checks;
5421 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5423 std::swap(Checks, DelayedExceptionSpecChecks);
5424 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5426 // Perform any deferred checking of exception specifications for virtual
5428 for (auto &Check : Checks)
5429 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5431 // Check that any explicitly-defaulted methods have exception specifications
5432 // compatible with their implicit exception specifications.
5433 for (auto &Spec : Specs)
5434 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5438 struct SpecialMemberDeletionInfo {
5441 Sema::CXXSpecialMember CSM;
5444 // Properties of the special member, computed for convenience.
5445 bool IsConstructor, IsAssignment, IsMove, ConstArg;
5448 bool AllFieldsAreConst;
5450 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5451 Sema::CXXSpecialMember CSM, bool Diagnose)
5452 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5453 IsConstructor(false), IsAssignment(false), IsMove(false),
5454 ConstArg(false), Loc(MD->getLocation()),
5455 AllFieldsAreConst(true) {
5457 case Sema::CXXDefaultConstructor:
5458 case Sema::CXXCopyConstructor:
5459 IsConstructor = true;
5461 case Sema::CXXMoveConstructor:
5462 IsConstructor = true;
5465 case Sema::CXXCopyAssignment:
5466 IsAssignment = true;
5468 case Sema::CXXMoveAssignment:
5469 IsAssignment = true;
5472 case Sema::CXXDestructor:
5474 case Sema::CXXInvalid:
5475 llvm_unreachable("invalid special member kind");
5478 if (MD->getNumParams()) {
5479 if (const ReferenceType *RT =
5480 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5481 ConstArg = RT->getPointeeType().isConstQualified();
5485 bool inUnion() const { return MD->getParent()->isUnion(); }
5487 /// Look up the corresponding special member in the given class.
5488 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5489 unsigned Quals, bool IsMutable) {
5490 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5491 ConstArg && !IsMutable);
5494 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5496 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5497 bool shouldDeleteForField(FieldDecl *FD);
5498 bool shouldDeleteForAllConstMembers();
5500 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5502 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5503 Sema::SpecialMemberOverloadResult *SMOR,
5504 bool IsDtorCallInCtor);
5506 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5510 /// Is the given special member inaccessible when used on the given
5512 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5513 CXXMethodDecl *target) {
5514 /// If we're operating on a base class, the object type is the
5515 /// type of this special member.
5517 AccessSpecifier access = target->getAccess();
5518 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5519 objectTy = S.Context.getTypeDeclType(MD->getParent());
5520 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5522 // If we're operating on a field, the object type is the type of the field.
5524 objectTy = S.Context.getTypeDeclType(target->getParent());
5527 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5530 /// Check whether we should delete a special member due to the implicit
5531 /// definition containing a call to a special member of a subobject.
5532 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5533 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5534 bool IsDtorCallInCtor) {
5535 CXXMethodDecl *Decl = SMOR->getMethod();
5536 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5540 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5541 DiagKind = !Decl ? 0 : 1;
5542 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5544 else if (!isAccessible(Subobj, Decl))
5546 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5547 !Decl->isTrivial()) {
5548 // A member of a union must have a trivial corresponding special member.
5549 // As a weird special case, a destructor call from a union's constructor
5550 // must be accessible and non-deleted, but need not be trivial. Such a
5551 // destructor is never actually called, but is semantically checked as
5561 S.Diag(Field->getLocation(),
5562 diag::note_deleted_special_member_class_subobject)
5563 << CSM << MD->getParent() << /*IsField*/true
5564 << Field << DiagKind << IsDtorCallInCtor;
5566 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5567 S.Diag(Base->getLocStart(),
5568 diag::note_deleted_special_member_class_subobject)
5569 << CSM << MD->getParent() << /*IsField*/false
5570 << Base->getType() << DiagKind << IsDtorCallInCtor;
5574 S.NoteDeletedFunction(Decl);
5575 // FIXME: Explain inaccessibility if DiagKind == 3.
5581 /// Check whether we should delete a special member function due to having a
5582 /// direct or virtual base class or non-static data member of class type M.
5583 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5584 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5585 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5586 bool IsMutable = Field && Field->isMutable();
5588 // C++11 [class.ctor]p5:
5589 // -- any direct or virtual base class, or non-static data member with no
5590 // brace-or-equal-initializer, has class type M (or array thereof) and
5591 // either M has no default constructor or overload resolution as applied
5592 // to M's default constructor results in an ambiguity or in a function
5593 // that is deleted or inaccessible
5594 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5595 // -- a direct or virtual base class B that cannot be copied/moved because
5596 // overload resolution, as applied to B's corresponding special member,
5597 // results in an ambiguity or a function that is deleted or inaccessible
5598 // from the defaulted special member
5599 // C++11 [class.dtor]p5:
5600 // -- any direct or virtual base class [...] has a type with a destructor
5601 // that is deleted or inaccessible
5602 if (!(CSM == Sema::CXXDefaultConstructor &&
5603 Field && Field->hasInClassInitializer()) &&
5604 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5608 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5609 // -- any direct or virtual base class or non-static data member has a
5610 // type with a destructor that is deleted or inaccessible
5611 if (IsConstructor) {
5612 Sema::SpecialMemberOverloadResult *SMOR =
5613 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5614 false, false, false, false, false);
5615 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5622 /// Check whether we should delete a special member function due to the class
5623 /// having a particular direct or virtual base class.
5624 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5625 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5626 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5629 /// Check whether we should delete a special member function due to the class
5630 /// having a particular non-static data member.
5631 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5632 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5633 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5635 if (CSM == Sema::CXXDefaultConstructor) {
5636 // For a default constructor, all references must be initialized in-class
5637 // and, if a union, it must have a non-const member.
5638 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5640 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5641 << MD->getParent() << FD << FieldType << /*Reference*/0;
5644 // C++11 [class.ctor]p5: any non-variant non-static data member of
5645 // const-qualified type (or array thereof) with no
5646 // brace-or-equal-initializer does not have a user-provided default
5648 if (!inUnion() && FieldType.isConstQualified() &&
5649 !FD->hasInClassInitializer() &&
5650 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5652 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5653 << MD->getParent() << FD << FD->getType() << /*Const*/1;
5657 if (inUnion() && !FieldType.isConstQualified())
5658 AllFieldsAreConst = false;
5659 } else if (CSM == Sema::CXXCopyConstructor) {
5660 // For a copy constructor, data members must not be of rvalue reference
5662 if (FieldType->isRValueReferenceType()) {
5664 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5665 << MD->getParent() << FD << FieldType;
5668 } else if (IsAssignment) {
5669 // For an assignment operator, data members must not be of reference type.
5670 if (FieldType->isReferenceType()) {
5672 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5673 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5676 if (!FieldRecord && FieldType.isConstQualified()) {
5677 // C++11 [class.copy]p23:
5678 // -- a non-static data member of const non-class type (or array thereof)
5680 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5681 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5687 // Some additional restrictions exist on the variant members.
5688 if (!inUnion() && FieldRecord->isUnion() &&
5689 FieldRecord->isAnonymousStructOrUnion()) {
5690 bool AllVariantFieldsAreConst = true;
5692 // FIXME: Handle anonymous unions declared within anonymous unions.
5693 for (auto *UI : FieldRecord->fields()) {
5694 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5696 if (!UnionFieldType.isConstQualified())
5697 AllVariantFieldsAreConst = false;
5699 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5700 if (UnionFieldRecord &&
5701 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5702 UnionFieldType.getCVRQualifiers()))
5706 // At least one member in each anonymous union must be non-const
5707 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5708 !FieldRecord->field_empty()) {
5710 S.Diag(FieldRecord->getLocation(),
5711 diag::note_deleted_default_ctor_all_const)
5712 << MD->getParent() << /*anonymous union*/1;
5716 // Don't check the implicit member of the anonymous union type.
5717 // This is technically non-conformant, but sanity demands it.
5721 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5722 FieldType.getCVRQualifiers()))
5729 /// C++11 [class.ctor] p5:
5730 /// A defaulted default constructor for a class X is defined as deleted if
5731 /// X is a union and all of its variant members are of const-qualified type.
5732 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5733 // This is a silly definition, because it gives an empty union a deleted
5734 // default constructor. Don't do that.
5735 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5736 !MD->getParent()->field_empty()) {
5738 S.Diag(MD->getParent()->getLocation(),
5739 diag::note_deleted_default_ctor_all_const)
5740 << MD->getParent() << /*not anonymous union*/0;
5746 /// Determine whether a defaulted special member function should be defined as
5747 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5748 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5749 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5751 if (MD->isInvalidDecl())
5753 CXXRecordDecl *RD = MD->getParent();
5754 assert(!RD->isDependentType() && "do deletion after instantiation");
5755 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5758 // C++11 [expr.lambda.prim]p19:
5759 // The closure type associated with a lambda-expression has a
5760 // deleted (8.4.3) default constructor and a deleted copy
5761 // assignment operator.
5762 if (RD->isLambda() &&
5763 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5765 Diag(RD->getLocation(), diag::note_lambda_decl);
5769 // For an anonymous struct or union, the copy and assignment special members
5770 // will never be used, so skip the check. For an anonymous union declared at
5771 // namespace scope, the constructor and destructor are used.
5772 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5773 RD->isAnonymousStructOrUnion())
5776 // C++11 [class.copy]p7, p18:
5777 // If the class definition declares a move constructor or move assignment
5778 // operator, an implicitly declared copy constructor or copy assignment
5779 // operator is defined as deleted.
5780 if (MD->isImplicit() &&
5781 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5782 CXXMethodDecl *UserDeclaredMove = nullptr;
5784 // In Microsoft mode, a user-declared move only causes the deletion of the
5785 // corresponding copy operation, not both copy operations.
5786 if (RD->hasUserDeclaredMoveConstructor() &&
5787 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5788 if (!Diagnose) return true;
5790 // Find any user-declared move constructor.
5791 for (auto *I : RD->ctors()) {
5792 if (I->isMoveConstructor()) {
5793 UserDeclaredMove = I;
5797 assert(UserDeclaredMove);
5798 } else if (RD->hasUserDeclaredMoveAssignment() &&
5799 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5800 if (!Diagnose) return true;
5802 // Find any user-declared move assignment operator.
5803 for (auto *I : RD->methods()) {
5804 if (I->isMoveAssignmentOperator()) {
5805 UserDeclaredMove = I;
5809 assert(UserDeclaredMove);
5812 if (UserDeclaredMove) {
5813 Diag(UserDeclaredMove->getLocation(),
5814 diag::note_deleted_copy_user_declared_move)
5815 << (CSM == CXXCopyAssignment) << RD
5816 << UserDeclaredMove->isMoveAssignmentOperator();
5821 // Do access control from the special member function
5822 ContextRAII MethodContext(*this, MD);
5824 // C++11 [class.dtor]p5:
5825 // -- for a virtual destructor, lookup of the non-array deallocation function
5826 // results in an ambiguity or in a function that is deleted or inaccessible
5827 if (CSM == CXXDestructor && MD->isVirtual()) {
5828 FunctionDecl *OperatorDelete = nullptr;
5829 DeclarationName Name =
5830 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5831 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5832 OperatorDelete, false)) {
5834 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5839 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5841 for (auto &BI : RD->bases())
5842 if (!BI.isVirtual() &&
5843 SMI.shouldDeleteForBase(&BI))
5846 // Per DR1611, do not consider virtual bases of constructors of abstract
5847 // classes, since we are not going to construct them.
5848 if (!RD->isAbstract() || !SMI.IsConstructor) {
5849 for (auto &BI : RD->vbases())
5850 if (SMI.shouldDeleteForBase(&BI))
5854 for (auto *FI : RD->fields())
5855 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5856 SMI.shouldDeleteForField(FI))
5859 if (SMI.shouldDeleteForAllConstMembers())
5862 if (getLangOpts().CUDA) {
5863 // We should delete the special member in CUDA mode if target inference
5865 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5872 /// Perform lookup for a special member of the specified kind, and determine
5873 /// whether it is trivial. If the triviality can be determined without the
5874 /// lookup, skip it. This is intended for use when determining whether a
5875 /// special member of a containing object is trivial, and thus does not ever
5876 /// perform overload resolution for default constructors.
5878 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5879 /// member that was most likely to be intended to be trivial, if any.
5880 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5881 Sema::CXXSpecialMember CSM, unsigned Quals,
5882 bool ConstRHS, CXXMethodDecl **Selected) {
5884 *Selected = nullptr;
5887 case Sema::CXXInvalid:
5888 llvm_unreachable("not a special member");
5890 case Sema::CXXDefaultConstructor:
5891 // C++11 [class.ctor]p5:
5892 // A default constructor is trivial if:
5893 // - all the [direct subobjects] have trivial default constructors
5895 // Note, no overload resolution is performed in this case.
5896 if (RD->hasTrivialDefaultConstructor())
5900 // If there's a default constructor which could have been trivial, dig it
5901 // out. Otherwise, if there's any user-provided default constructor, point
5902 // to that as an example of why there's not a trivial one.
5903 CXXConstructorDecl *DefCtor = nullptr;
5904 if (RD->needsImplicitDefaultConstructor())
5905 S.DeclareImplicitDefaultConstructor(RD);
5906 for (auto *CI : RD->ctors()) {
5907 if (!CI->isDefaultConstructor())
5910 if (!DefCtor->isUserProvided())
5914 *Selected = DefCtor;
5919 case Sema::CXXDestructor:
5920 // C++11 [class.dtor]p5:
5921 // A destructor is trivial if:
5922 // - all the direct [subobjects] have trivial destructors
5923 if (RD->hasTrivialDestructor())
5927 if (RD->needsImplicitDestructor())
5928 S.DeclareImplicitDestructor(RD);
5929 *Selected = RD->getDestructor();
5934 case Sema::CXXCopyConstructor:
5935 // C++11 [class.copy]p12:
5936 // A copy constructor is trivial if:
5937 // - the constructor selected to copy each direct [subobject] is trivial
5938 if (RD->hasTrivialCopyConstructor()) {
5939 if (Quals == Qualifiers::Const)
5940 // We must either select the trivial copy constructor or reach an
5941 // ambiguity; no need to actually perform overload resolution.
5943 } else if (!Selected) {
5946 // In C++98, we are not supposed to perform overload resolution here, but we
5947 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5948 // cases like B as having a non-trivial copy constructor:
5949 // struct A { template<typename T> A(T&); };
5950 // struct B { mutable A a; };
5951 goto NeedOverloadResolution;
5953 case Sema::CXXCopyAssignment:
5954 // C++11 [class.copy]p25:
5955 // A copy assignment operator is trivial if:
5956 // - the assignment operator selected to copy each direct [subobject] is
5958 if (RD->hasTrivialCopyAssignment()) {
5959 if (Quals == Qualifiers::Const)
5961 } else if (!Selected) {
5964 // In C++98, we are not supposed to perform overload resolution here, but we
5965 // treat that as a language defect.
5966 goto NeedOverloadResolution;
5968 case Sema::CXXMoveConstructor:
5969 case Sema::CXXMoveAssignment:
5970 NeedOverloadResolution:
5971 Sema::SpecialMemberOverloadResult *SMOR =
5972 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5974 // The standard doesn't describe how to behave if the lookup is ambiguous.
5975 // We treat it as not making the member non-trivial, just like the standard
5976 // mandates for the default constructor. This should rarely matter, because
5977 // the member will also be deleted.
5978 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5981 if (!SMOR->getMethod()) {
5982 assert(SMOR->getKind() ==
5983 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5987 // We deliberately don't check if we found a deleted special member. We're
5990 *Selected = SMOR->getMethod();
5991 return SMOR->getMethod()->isTrivial();
5994 llvm_unreachable("unknown special method kind");
5997 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5998 for (auto *CI : RD->ctors())
5999 if (!CI->isImplicit())
6002 // Look for constructor templates.
6003 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6004 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6005 if (CXXConstructorDecl *CD =
6006 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6013 /// The kind of subobject we are checking for triviality. The values of this
6014 /// enumeration are used in diagnostics.
6015 enum TrivialSubobjectKind {
6016 /// The subobject is a base class.
6018 /// The subobject is a non-static data member.
6020 /// The object is actually the complete object.
6024 /// Check whether the special member selected for a given type would be trivial.
6025 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6026 QualType SubType, bool ConstRHS,
6027 Sema::CXXSpecialMember CSM,
6028 TrivialSubobjectKind Kind,
6030 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6034 CXXMethodDecl *Selected;
6035 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6036 ConstRHS, Diagnose ? &Selected : nullptr))
6043 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6044 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6045 << Kind << SubType.getUnqualifiedType();
6046 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6047 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6048 } else if (!Selected)
6049 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6050 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6051 else if (Selected->isUserProvided()) {
6052 if (Kind == TSK_CompleteObject)
6053 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6054 << Kind << SubType.getUnqualifiedType() << CSM;
6056 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6057 << Kind << SubType.getUnqualifiedType() << CSM;
6058 S.Diag(Selected->getLocation(), diag::note_declared_at);
6061 if (Kind != TSK_CompleteObject)
6062 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6063 << Kind << SubType.getUnqualifiedType() << CSM;
6065 // Explain why the defaulted or deleted special member isn't trivial.
6066 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6073 /// Check whether the members of a class type allow a special member to be
6075 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6076 Sema::CXXSpecialMember CSM,
6077 bool ConstArg, bool Diagnose) {
6078 for (const auto *FI : RD->fields()) {
6079 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6082 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6084 // Pretend anonymous struct or union members are members of this class.
6085 if (FI->isAnonymousStructOrUnion()) {
6086 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6087 CSM, ConstArg, Diagnose))
6092 // C++11 [class.ctor]p5:
6093 // A default constructor is trivial if [...]
6094 // -- no non-static data member of its class has a
6095 // brace-or-equal-initializer
6096 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6098 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6102 // Objective C ARC 4.3.5:
6103 // [...] nontrivally ownership-qualified types are [...] not trivially
6104 // default constructible, copy constructible, move constructible, copy
6105 // assignable, move assignable, or destructible [...]
6106 if (S.getLangOpts().ObjCAutoRefCount &&
6107 FieldType.hasNonTrivialObjCLifetime()) {
6109 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6110 << RD << FieldType.getObjCLifetime();
6114 bool ConstRHS = ConstArg && !FI->isMutable();
6115 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6116 CSM, TSK_Field, Diagnose))
6123 /// Diagnose why the specified class does not have a trivial special member of
6125 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6126 QualType Ty = Context.getRecordType(RD);
6128 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6129 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6130 TSK_CompleteObject, /*Diagnose*/true);
6133 /// Determine whether a defaulted or deleted special member function is trivial,
6134 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6135 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6136 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6138 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6140 CXXRecordDecl *RD = MD->getParent();
6142 bool ConstArg = false;
6144 // C++11 [class.copy]p12, p25: [DR1593]
6145 // A [special member] is trivial if [...] its parameter-type-list is
6146 // equivalent to the parameter-type-list of an implicit declaration [...]
6148 case CXXDefaultConstructor:
6150 // Trivial default constructors and destructors cannot have parameters.
6153 case CXXCopyConstructor:
6154 case CXXCopyAssignment: {
6155 // Trivial copy operations always have const, non-volatile parameter types.
6157 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6158 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6159 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6161 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6162 << Param0->getSourceRange() << Param0->getType()
6163 << Context.getLValueReferenceType(
6164 Context.getRecordType(RD).withConst());
6170 case CXXMoveConstructor:
6171 case CXXMoveAssignment: {
6172 // Trivial move operations always have non-cv-qualified parameters.
6173 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6174 const RValueReferenceType *RT =
6175 Param0->getType()->getAs<RValueReferenceType>();
6176 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6178 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6179 << Param0->getSourceRange() << Param0->getType()
6180 << Context.getRValueReferenceType(Context.getRecordType(RD));
6187 llvm_unreachable("not a special member");
6190 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6192 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6193 diag::note_nontrivial_default_arg)
6194 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6197 if (MD->isVariadic()) {
6199 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6203 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6204 // A copy/move [constructor or assignment operator] is trivial if
6205 // -- the [member] selected to copy/move each direct base class subobject
6208 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6209 // A [default constructor or destructor] is trivial if
6210 // -- all the direct base classes have trivial [default constructors or
6212 for (const auto &BI : RD->bases())
6213 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6214 ConstArg, CSM, TSK_BaseClass, Diagnose))
6217 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6218 // A copy/move [constructor or assignment operator] for a class X is
6220 // -- for each non-static data member of X that is of class type (or array
6221 // thereof), the constructor selected to copy/move that member is
6224 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6225 // A [default constructor or destructor] is trivial if
6226 // -- for all of the non-static data members of its class that are of class
6227 // type (or array thereof), each such class has a trivial [default
6228 // constructor or destructor]
6229 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6232 // C++11 [class.dtor]p5:
6233 // A destructor is trivial if [...]
6234 // -- the destructor is not virtual
6235 if (CSM == CXXDestructor && MD->isVirtual()) {
6237 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6241 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6242 // A [special member] for class X is trivial if [...]
6243 // -- class X has no virtual functions and no virtual base classes
6244 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6248 if (RD->getNumVBases()) {
6249 // Check for virtual bases. We already know that the corresponding
6250 // member in all bases is trivial, so vbases must all be direct.
6251 CXXBaseSpecifier &BS = *RD->vbases_begin();
6252 assert(BS.isVirtual());
6253 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6257 // Must have a virtual method.
6258 for (const auto *MI : RD->methods()) {
6259 if (MI->isVirtual()) {
6260 SourceLocation MLoc = MI->getLocStart();
6261 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6266 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6269 // Looks like it's trivial!
6273 /// \brief Data used with FindHiddenVirtualMethod
6275 struct FindHiddenVirtualMethodData {
6277 CXXMethodDecl *Method;
6278 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6279 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6283 /// \brief Check whether any most overriden method from MD in Methods
6284 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6285 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6286 if (MD->size_overridden_methods() == 0)
6287 return Methods.count(MD->getCanonicalDecl());
6288 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6289 E = MD->end_overridden_methods();
6291 if (CheckMostOverridenMethods(*I, Methods))
6296 /// \brief Member lookup function that determines whether a given C++
6297 /// method overloads virtual methods in a base class without overriding any,
6298 /// to be used with CXXRecordDecl::lookupInBases().
6299 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6302 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6304 FindHiddenVirtualMethodData &Data
6305 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6307 DeclarationName Name = Data.Method->getDeclName();
6308 assert(Name.getNameKind() == DeclarationName::Identifier);
6310 bool foundSameNameMethod = false;
6311 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6312 for (Path.Decls = BaseRecord->lookup(Name);
6313 !Path.Decls.empty();
6314 Path.Decls = Path.Decls.slice(1)) {
6315 NamedDecl *D = Path.Decls.front();
6316 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6317 MD = MD->getCanonicalDecl();
6318 foundSameNameMethod = true;
6319 // Interested only in hidden virtual methods.
6320 if (!MD->isVirtual())
6322 // If the method we are checking overrides a method from its base
6323 // don't warn about the other overloaded methods. Clang deviates from GCC
6324 // by only diagnosing overloads of inherited virtual functions that do not
6325 // override any other virtual functions in the base. GCC's
6326 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6327 // function from a base class. These cases may be better served by a
6328 // warning (not specific to virtual functions) on call sites when the call
6329 // would select a different function from the base class, were it visible.
6330 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6331 if (!Data.S->IsOverload(Data.Method, MD, false))
6333 // Collect the overload only if its hidden.
6334 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6335 overloadedMethods.push_back(MD);
6339 if (foundSameNameMethod)
6340 Data.OverloadedMethods.append(overloadedMethods.begin(),
6341 overloadedMethods.end());
6342 return foundSameNameMethod;
6345 /// \brief Add the most overriden methods from MD to Methods
6346 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6347 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6348 if (MD->size_overridden_methods() == 0)
6349 Methods.insert(MD->getCanonicalDecl());
6350 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6351 E = MD->end_overridden_methods();
6353 AddMostOverridenMethods(*I, Methods);
6356 /// \brief Check if a method overloads virtual methods in a base class without
6358 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6359 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6360 if (!MD->getDeclName().isIdentifier())
6363 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6364 /*bool RecordPaths=*/false,
6365 /*bool DetectVirtual=*/false);
6366 FindHiddenVirtualMethodData Data;
6370 // Keep the base methods that were overriden or introduced in the subclass
6371 // by 'using' in a set. A base method not in this set is hidden.
6372 CXXRecordDecl *DC = MD->getParent();
6373 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6374 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6376 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6377 ND = shad->getTargetDecl();
6378 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6379 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6382 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6383 OverloadedMethods = Data.OverloadedMethods;
6386 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6387 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6388 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6389 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6390 PartialDiagnostic PD = PDiag(
6391 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6392 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6393 Diag(overloadedMD->getLocation(), PD);
6397 /// \brief Diagnose methods which overload virtual methods in a base class
6398 /// without overriding any.
6399 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6400 if (MD->isInvalidDecl())
6403 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6406 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6407 FindHiddenVirtualMethods(MD, OverloadedMethods);
6408 if (!OverloadedMethods.empty()) {
6409 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6410 << MD << (OverloadedMethods.size() > 1);
6412 NoteHiddenVirtualMethods(MD, OverloadedMethods);
6416 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6418 SourceLocation LBrac,
6419 SourceLocation RBrac,
6420 AttributeList *AttrList) {
6424 AdjustDeclIfTemplate(TagDecl);
6426 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6427 if (l->getKind() != AttributeList::AT_Visibility)
6430 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6434 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6435 // strict aliasing violation!
6436 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6437 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6439 CheckCompletedCXXClass(
6440 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6443 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6444 /// special functions, such as the default constructor, copy
6445 /// constructor, or destructor, to the given C++ class (C++
6446 /// [special]p1). This routine can only be executed just before the
6447 /// definition of the class is complete.
6448 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6449 if (!ClassDecl->hasUserDeclaredConstructor())
6450 ++ASTContext::NumImplicitDefaultConstructors;
6452 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6453 ++ASTContext::NumImplicitCopyConstructors;
6455 // If the properties or semantics of the copy constructor couldn't be
6456 // determined while the class was being declared, force a declaration
6458 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6459 DeclareImplicitCopyConstructor(ClassDecl);
6462 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6463 ++ASTContext::NumImplicitMoveConstructors;
6465 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6466 DeclareImplicitMoveConstructor(ClassDecl);
6469 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6470 ++ASTContext::NumImplicitCopyAssignmentOperators;
6472 // If we have a dynamic class, then the copy assignment operator may be
6473 // virtual, so we have to declare it immediately. This ensures that, e.g.,
6474 // it shows up in the right place in the vtable and that we diagnose
6475 // problems with the implicit exception specification.
6476 if (ClassDecl->isDynamicClass() ||
6477 ClassDecl->needsOverloadResolutionForCopyAssignment())
6478 DeclareImplicitCopyAssignment(ClassDecl);
6481 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6482 ++ASTContext::NumImplicitMoveAssignmentOperators;
6484 // Likewise for the move assignment operator.
6485 if (ClassDecl->isDynamicClass() ||
6486 ClassDecl->needsOverloadResolutionForMoveAssignment())
6487 DeclareImplicitMoveAssignment(ClassDecl);
6490 if (!ClassDecl->hasUserDeclaredDestructor()) {
6491 ++ASTContext::NumImplicitDestructors;
6493 // If we have a dynamic class, then the destructor may be virtual, so we
6494 // have to declare the destructor immediately. This ensures that, e.g., it
6495 // shows up in the right place in the vtable and that we diagnose problems
6496 // with the implicit exception specification.
6497 if (ClassDecl->isDynamicClass() ||
6498 ClassDecl->needsOverloadResolutionForDestructor())
6499 DeclareImplicitDestructor(ClassDecl);
6503 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6507 // The order of template parameters is not important here. All names
6508 // get added to the same scope.
6509 SmallVector<TemplateParameterList *, 4> ParameterLists;
6511 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6512 D = TD->getTemplatedDecl();
6514 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6515 ParameterLists.push_back(PSD->getTemplateParameters());
6517 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6518 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6519 ParameterLists.push_back(DD->getTemplateParameterList(i));
6521 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6522 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6523 ParameterLists.push_back(FTD->getTemplateParameters());
6527 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6528 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6529 ParameterLists.push_back(TD->getTemplateParameterList(i));
6531 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6532 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6533 ParameterLists.push_back(CTD->getTemplateParameters());
6538 for (TemplateParameterList *Params : ParameterLists) {
6539 if (Params->size() > 0)
6540 // Ignore explicit specializations; they don't contribute to the template
6543 for (NamedDecl *Param : *Params) {
6544 if (Param->getDeclName()) {
6546 IdResolver.AddDecl(Param);
6554 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6555 if (!RecordD) return;
6556 AdjustDeclIfTemplate(RecordD);
6557 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6558 PushDeclContext(S, Record);
6561 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6562 if (!RecordD) return;
6566 /// This is used to implement the constant expression evaluation part of the
6567 /// attribute enable_if extension. There is nothing in standard C++ which would
6568 /// require reentering parameters.
6569 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6574 if (Param->getDeclName())
6575 IdResolver.AddDecl(Param);
6578 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6579 /// parsing a top-level (non-nested) C++ class, and we are now
6580 /// parsing those parts of the given Method declaration that could
6581 /// not be parsed earlier (C++ [class.mem]p2), such as default
6582 /// arguments. This action should enter the scope of the given
6583 /// Method declaration as if we had just parsed the qualified method
6584 /// name. However, it should not bring the parameters into scope;
6585 /// that will be performed by ActOnDelayedCXXMethodParameter.
6586 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6589 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6590 /// C++ method declaration. We're (re-)introducing the given
6591 /// function parameter into scope for use in parsing later parts of
6592 /// the method declaration. For example, we could see an
6593 /// ActOnParamDefaultArgument event for this parameter.
6594 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6598 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6600 // If this parameter has an unparsed default argument, clear it out
6601 // to make way for the parsed default argument.
6602 if (Param->hasUnparsedDefaultArg())
6603 Param->setDefaultArg(nullptr);
6606 if (Param->getDeclName())
6607 IdResolver.AddDecl(Param);
6610 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6611 /// processing the delayed method declaration for Method. The method
6612 /// declaration is now considered finished. There may be a separate
6613 /// ActOnStartOfFunctionDef action later (not necessarily
6614 /// immediately!) for this method, if it was also defined inside the
6616 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6620 AdjustDeclIfTemplate(MethodD);
6622 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6624 // Now that we have our default arguments, check the constructor
6625 // again. It could produce additional diagnostics or affect whether
6626 // the class has implicitly-declared destructors, among other
6628 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6629 CheckConstructor(Constructor);
6631 // Check the default arguments, which we may have added.
6632 if (!Method->isInvalidDecl())
6633 CheckCXXDefaultArguments(Method);
6636 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6637 /// the well-formedness of the constructor declarator @p D with type @p
6638 /// R. If there are any errors in the declarator, this routine will
6639 /// emit diagnostics and set the invalid bit to true. In any case, the type
6640 /// will be updated to reflect a well-formed type for the constructor and
6642 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6644 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6646 // C++ [class.ctor]p3:
6647 // A constructor shall not be virtual (10.3) or static (9.4). A
6648 // constructor can be invoked for a const, volatile or const
6649 // volatile object. A constructor shall not be declared const,
6650 // volatile, or const volatile (9.3.2).
6652 if (!D.isInvalidType())
6653 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6654 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6655 << SourceRange(D.getIdentifierLoc());
6658 if (SC == SC_Static) {
6659 if (!D.isInvalidType())
6660 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6661 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6662 << SourceRange(D.getIdentifierLoc());
6667 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6668 diagnoseIgnoredQualifiers(
6669 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6670 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6671 D.getDeclSpec().getRestrictSpecLoc(),
6672 D.getDeclSpec().getAtomicSpecLoc());
6676 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6677 if (FTI.TypeQuals != 0) {
6678 if (FTI.TypeQuals & Qualifiers::Const)
6679 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6680 << "const" << SourceRange(D.getIdentifierLoc());
6681 if (FTI.TypeQuals & Qualifiers::Volatile)
6682 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6683 << "volatile" << SourceRange(D.getIdentifierLoc());
6684 if (FTI.TypeQuals & Qualifiers::Restrict)
6685 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6686 << "restrict" << SourceRange(D.getIdentifierLoc());
6690 // C++0x [class.ctor]p4:
6691 // A constructor shall not be declared with a ref-qualifier.
6692 if (FTI.hasRefQualifier()) {
6693 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6694 << FTI.RefQualifierIsLValueRef
6695 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6699 // Rebuild the function type "R" without any type qualifiers (in
6700 // case any of the errors above fired) and with "void" as the
6701 // return type, since constructors don't have return types.
6702 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6703 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6706 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6708 EPI.RefQualifier = RQ_None;
6710 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6713 /// CheckConstructor - Checks a fully-formed constructor for
6714 /// well-formedness, issuing any diagnostics required. Returns true if
6715 /// the constructor declarator is invalid.
6716 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6717 CXXRecordDecl *ClassDecl
6718 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6720 return Constructor->setInvalidDecl();
6722 // C++ [class.copy]p3:
6723 // A declaration of a constructor for a class X is ill-formed if
6724 // its first parameter is of type (optionally cv-qualified) X and
6725 // either there are no other parameters or else all other
6726 // parameters have default arguments.
6727 if (!Constructor->isInvalidDecl() &&
6728 ((Constructor->getNumParams() == 1) ||
6729 (Constructor->getNumParams() > 1 &&
6730 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6731 Constructor->getTemplateSpecializationKind()
6732 != TSK_ImplicitInstantiation) {
6733 QualType ParamType = Constructor->getParamDecl(0)->getType();
6734 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6735 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6736 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6737 const char *ConstRef
6738 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6740 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6741 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6743 // FIXME: Rather that making the constructor invalid, we should endeavor
6745 Constructor->setInvalidDecl();
6750 /// CheckDestructor - Checks a fully-formed destructor definition for
6751 /// well-formedness, issuing any diagnostics required. Returns true
6753 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6754 CXXRecordDecl *RD = Destructor->getParent();
6756 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6759 if (!Destructor->isImplicit())
6760 Loc = Destructor->getLocation();
6762 Loc = RD->getLocation();
6764 // If we have a virtual destructor, look up the deallocation function
6765 FunctionDecl *OperatorDelete = nullptr;
6766 DeclarationName Name =
6767 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6768 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6770 // If there's no class-specific operator delete, look up the global
6771 // non-array delete.
6772 if (!OperatorDelete)
6773 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6775 MarkFunctionReferenced(Loc, OperatorDelete);
6777 Destructor->setOperatorDelete(OperatorDelete);
6783 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6784 /// the well-formednes of the destructor declarator @p D with type @p
6785 /// R. If there are any errors in the declarator, this routine will
6786 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6787 /// will be updated to reflect a well-formed type for the destructor and
6789 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6791 // C++ [class.dtor]p1:
6792 // [...] A typedef-name that names a class is a class-name
6793 // (7.1.3); however, a typedef-name that names a class shall not
6794 // be used as the identifier in the declarator for a destructor
6796 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6797 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6798 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6799 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6800 else if (const TemplateSpecializationType *TST =
6801 DeclaratorType->getAs<TemplateSpecializationType>())
6802 if (TST->isTypeAlias())
6803 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6804 << DeclaratorType << 1;
6806 // C++ [class.dtor]p2:
6807 // A destructor is used to destroy objects of its class type. A
6808 // destructor takes no parameters, and no return type can be
6809 // specified for it (not even void). The address of a destructor
6810 // shall not be taken. A destructor shall not be static. A
6811 // destructor can be invoked for a const, volatile or const
6812 // volatile object. A destructor shall not be declared const,
6813 // volatile or const volatile (9.3.2).
6814 if (SC == SC_Static) {
6815 if (!D.isInvalidType())
6816 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6817 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6818 << SourceRange(D.getIdentifierLoc())
6819 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6823 if (!D.isInvalidType()) {
6824 // Destructors don't have return types, but the parser will
6825 // happily parse something like:
6831 // The return type will be eliminated later.
6832 if (D.getDeclSpec().hasTypeSpecifier())
6833 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6834 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6835 << SourceRange(D.getIdentifierLoc());
6836 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6837 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6839 D.getDeclSpec().getConstSpecLoc(),
6840 D.getDeclSpec().getVolatileSpecLoc(),
6841 D.getDeclSpec().getRestrictSpecLoc(),
6842 D.getDeclSpec().getAtomicSpecLoc());
6847 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6848 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6849 if (FTI.TypeQuals & Qualifiers::Const)
6850 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6851 << "const" << SourceRange(D.getIdentifierLoc());
6852 if (FTI.TypeQuals & Qualifiers::Volatile)
6853 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6854 << "volatile" << SourceRange(D.getIdentifierLoc());
6855 if (FTI.TypeQuals & Qualifiers::Restrict)
6856 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6857 << "restrict" << SourceRange(D.getIdentifierLoc());
6861 // C++0x [class.dtor]p2:
6862 // A destructor shall not be declared with a ref-qualifier.
6863 if (FTI.hasRefQualifier()) {
6864 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6865 << FTI.RefQualifierIsLValueRef
6866 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6870 // Make sure we don't have any parameters.
6871 if (FTIHasNonVoidParameters(FTI)) {
6872 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6874 // Delete the parameters.
6879 // Make sure the destructor isn't variadic.
6880 if (FTI.isVariadic) {
6881 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6885 // Rebuild the function type "R" without any type qualifiers or
6886 // parameters (in case any of the errors above fired) and with
6887 // "void" as the return type, since destructors don't have return
6889 if (!D.isInvalidType())
6892 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6893 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6894 EPI.Variadic = false;
6896 EPI.RefQualifier = RQ_None;
6897 return Context.getFunctionType(Context.VoidTy, None, EPI);
6900 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6901 if (Before.isInvalid())
6903 R.setBegin(Before.getBegin());
6904 if (R.getEnd().isInvalid())
6905 R.setEnd(Before.getEnd());
6908 static void extendRight(SourceRange &R, const SourceRange &After) {
6909 if (After.isInvalid())
6911 if (R.getBegin().isInvalid())
6912 R.setBegin(After.getBegin());
6913 R.setEnd(After.getEnd());
6916 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6917 /// well-formednes of the conversion function declarator @p D with
6918 /// type @p R. If there are any errors in the declarator, this routine
6919 /// will emit diagnostics and return true. Otherwise, it will return
6920 /// false. Either way, the type @p R will be updated to reflect a
6921 /// well-formed type for the conversion operator.
6922 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6924 // C++ [class.conv.fct]p1:
6925 // Neither parameter types nor return type can be specified. The
6926 // type of a conversion function (8.3.5) is "function taking no
6927 // parameter returning conversion-type-id."
6928 if (SC == SC_Static) {
6929 if (!D.isInvalidType())
6930 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6931 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6932 << D.getName().getSourceRange();
6937 TypeSourceInfo *ConvTSI = nullptr;
6939 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6941 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6942 // Conversion functions don't have return types, but the parser will
6943 // happily parse something like:
6946 // float operator bool();
6949 // The return type will be changed later anyway.
6950 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6951 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6952 << SourceRange(D.getIdentifierLoc());
6956 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6958 // Make sure we don't have any parameters.
6959 if (Proto->getNumParams() > 0) {
6960 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6962 // Delete the parameters.
6963 D.getFunctionTypeInfo().freeParams();
6965 } else if (Proto->isVariadic()) {
6966 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6970 // Diagnose "&operator bool()" and other such nonsense. This
6971 // is actually a gcc extension which we don't support.
6972 if (Proto->getReturnType() != ConvType) {
6973 bool NeedsTypedef = false;
6974 SourceRange Before, After;
6976 // Walk the chunks and extract information on them for our diagnostic.
6977 bool PastFunctionChunk = false;
6978 for (auto &Chunk : D.type_objects()) {
6979 switch (Chunk.Kind) {
6980 case DeclaratorChunk::Function:
6981 if (!PastFunctionChunk) {
6982 if (Chunk.Fun.HasTrailingReturnType) {
6983 TypeSourceInfo *TRT = nullptr;
6984 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6985 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6987 PastFunctionChunk = true;
6991 case DeclaratorChunk::Array:
6992 NeedsTypedef = true;
6993 extendRight(After, Chunk.getSourceRange());
6996 case DeclaratorChunk::Pointer:
6997 case DeclaratorChunk::BlockPointer:
6998 case DeclaratorChunk::Reference:
6999 case DeclaratorChunk::MemberPointer:
7000 extendLeft(Before, Chunk.getSourceRange());
7003 case DeclaratorChunk::Paren:
7004 extendLeft(Before, Chunk.Loc);
7005 extendRight(After, Chunk.EndLoc);
7010 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7011 After.isValid() ? After.getBegin() :
7012 D.getIdentifierLoc();
7013 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7014 DB << Before << After;
7016 if (!NeedsTypedef) {
7017 DB << /*don't need a typedef*/0;
7019 // If we can provide a correct fix-it hint, do so.
7020 if (After.isInvalid() && ConvTSI) {
7021 SourceLocation InsertLoc =
7022 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7023 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7024 << FixItHint::CreateInsertionFromRange(
7025 InsertLoc, CharSourceRange::getTokenRange(Before))
7026 << FixItHint::CreateRemoval(Before);
7028 } else if (!Proto->getReturnType()->isDependentType()) {
7029 DB << /*typedef*/1 << Proto->getReturnType();
7030 } else if (getLangOpts().CPlusPlus11) {
7031 DB << /*alias template*/2 << Proto->getReturnType();
7033 DB << /*might not be fixable*/3;
7036 // Recover by incorporating the other type chunks into the result type.
7037 // Note, this does *not* change the name of the function. This is compatible
7038 // with the GCC extension:
7039 // struct S { &operator int(); } s;
7040 // int &r = s.operator int(); // ok in GCC
7041 // S::operator int&() {} // error in GCC, function name is 'operator int'.
7042 ConvType = Proto->getReturnType();
7045 // C++ [class.conv.fct]p4:
7046 // The conversion-type-id shall not represent a function type nor
7048 if (ConvType->isArrayType()) {
7049 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7050 ConvType = Context.getPointerType(ConvType);
7052 } else if (ConvType->isFunctionType()) {
7053 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7054 ConvType = Context.getPointerType(ConvType);
7058 // Rebuild the function type "R" without any parameters (in case any
7059 // of the errors above fired) and with the conversion type as the
7061 if (D.isInvalidType())
7062 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7064 // C++0x explicit conversion operators.
7065 if (D.getDeclSpec().isExplicitSpecified())
7066 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7067 getLangOpts().CPlusPlus11 ?
7068 diag::warn_cxx98_compat_explicit_conversion_functions :
7069 diag::ext_explicit_conversion_functions)
7070 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7073 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7074 /// the declaration of the given C++ conversion function. This routine
7075 /// is responsible for recording the conversion function in the C++
7076 /// class, if possible.
7077 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7078 assert(Conversion && "Expected to receive a conversion function declaration");
7080 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7082 // Make sure we aren't redeclaring the conversion function.
7083 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7085 // C++ [class.conv.fct]p1:
7086 // [...] A conversion function is never used to convert a
7087 // (possibly cv-qualified) object to the (possibly cv-qualified)
7088 // same object type (or a reference to it), to a (possibly
7089 // cv-qualified) base class of that type (or a reference to it),
7090 // or to (possibly cv-qualified) void.
7091 // FIXME: Suppress this warning if the conversion function ends up being a
7092 // virtual function that overrides a virtual function in a base class.
7094 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7095 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7096 ConvType = ConvTypeRef->getPointeeType();
7097 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7098 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7099 /* Suppress diagnostics for instantiations. */;
7100 else if (ConvType->isRecordType()) {
7101 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7102 if (ConvType == ClassType)
7103 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7105 else if (IsDerivedFrom(ClassType, ConvType))
7106 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7107 << ClassType << ConvType;
7108 } else if (ConvType->isVoidType()) {
7109 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7110 << ClassType << ConvType;
7113 if (FunctionTemplateDecl *ConversionTemplate
7114 = Conversion->getDescribedFunctionTemplate())
7115 return ConversionTemplate;
7120 //===----------------------------------------------------------------------===//
7121 // Namespace Handling
7122 //===----------------------------------------------------------------------===//
7124 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7126 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7128 IdentifierInfo *II, bool *IsInline,
7129 NamespaceDecl *PrevNS) {
7130 assert(*IsInline != PrevNS->isInline());
7132 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7133 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7134 // inline namespaces, with the intention of bringing names into namespace std.
7136 // We support this just well enough to get that case working; this is not
7137 // sufficient to support reopening namespaces as inline in general.
7138 if (*IsInline && II && II->getName().startswith("__atomic") &&
7139 S.getSourceManager().isInSystemHeader(Loc)) {
7140 // Mark all prior declarations of the namespace as inline.
7141 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7142 NS = NS->getPreviousDecl())
7143 NS->setInline(*IsInline);
7144 // Patch up the lookup table for the containing namespace. This isn't really
7145 // correct, but it's good enough for this particular case.
7146 for (auto *I : PrevNS->decls())
7147 if (auto *ND = dyn_cast<NamedDecl>(I))
7148 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7152 if (PrevNS->isInline())
7153 // The user probably just forgot the 'inline', so suggest that it
7155 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7156 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7158 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7160 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7161 *IsInline = PrevNS->isInline();
7164 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7166 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7167 SourceLocation InlineLoc,
7168 SourceLocation NamespaceLoc,
7169 SourceLocation IdentLoc,
7171 SourceLocation LBrace,
7172 AttributeList *AttrList) {
7173 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7174 // For anonymous namespace, take the location of the left brace.
7175 SourceLocation Loc = II ? IdentLoc : LBrace;
7176 bool IsInline = InlineLoc.isValid();
7177 bool IsInvalid = false;
7179 bool AddToKnown = false;
7180 Scope *DeclRegionScope = NamespcScope->getParent();
7182 NamespaceDecl *PrevNS = nullptr;
7184 // C++ [namespace.def]p2:
7185 // The identifier in an original-namespace-definition shall not
7186 // have been previously defined in the declarative region in
7187 // which the original-namespace-definition appears. The
7188 // identifier in an original-namespace-definition is the name of
7189 // the namespace. Subsequently in that declarative region, it is
7190 // treated as an original-namespace-name.
7192 // Since namespace names are unique in their scope, and we don't
7193 // look through using directives, just look for any ordinary names.
7195 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
7196 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7197 Decl::IDNS_Namespace;
7198 NamedDecl *PrevDecl = nullptr;
7199 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7200 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7202 if ((*I)->getIdentifierNamespace() & IDNS) {
7208 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7211 // This is an extended namespace definition.
7212 if (IsInline != PrevNS->isInline())
7213 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7215 } else if (PrevDecl) {
7216 // This is an invalid name redefinition.
7217 Diag(Loc, diag::err_redefinition_different_kind)
7219 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7221 // Continue on to push Namespc as current DeclContext and return it.
7222 } else if (II->isStr("std") &&
7223 CurContext->getRedeclContext()->isTranslationUnit()) {
7224 // This is the first "real" definition of the namespace "std", so update
7225 // our cache of the "std" namespace to point at this definition.
7226 PrevNS = getStdNamespace();
7228 AddToKnown = !IsInline;
7230 // We've seen this namespace for the first time.
7231 AddToKnown = !IsInline;
7234 // Anonymous namespaces.
7236 // Determine whether the parent already has an anonymous namespace.
7237 DeclContext *Parent = CurContext->getRedeclContext();
7238 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7239 PrevNS = TU->getAnonymousNamespace();
7241 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7242 PrevNS = ND->getAnonymousNamespace();
7245 if (PrevNS && IsInline != PrevNS->isInline())
7246 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7250 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7251 StartLoc, Loc, II, PrevNS);
7253 Namespc->setInvalidDecl();
7255 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7257 // FIXME: Should we be merging attributes?
7258 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7259 PushNamespaceVisibilityAttr(Attr, Loc);
7262 StdNamespace = Namespc;
7264 KnownNamespaces[Namespc] = false;
7267 PushOnScopeChains(Namespc, DeclRegionScope);
7269 // Link the anonymous namespace into its parent.
7270 DeclContext *Parent = CurContext->getRedeclContext();
7271 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7272 TU->setAnonymousNamespace(Namespc);
7274 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7277 CurContext->addDecl(Namespc);
7279 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7280 // behaves as if it were replaced by
7281 // namespace unique { /* empty body */ }
7282 // using namespace unique;
7283 // namespace unique { namespace-body }
7284 // where all occurrences of 'unique' in a translation unit are
7285 // replaced by the same identifier and this identifier differs
7286 // from all other identifiers in the entire program.
7288 // We just create the namespace with an empty name and then add an
7289 // implicit using declaration, just like the standard suggests.
7291 // CodeGen enforces the "universally unique" aspect by giving all
7292 // declarations semantically contained within an anonymous
7293 // namespace internal linkage.
7296 UsingDirectiveDecl* UD
7297 = UsingDirectiveDecl::Create(Context, Parent,
7298 /* 'using' */ LBrace,
7299 /* 'namespace' */ SourceLocation(),
7300 /* qualifier */ NestedNameSpecifierLoc(),
7301 /* identifier */ SourceLocation(),
7303 /* Ancestor */ Parent);
7305 Parent->addDecl(UD);
7309 ActOnDocumentableDecl(Namespc);
7311 // Although we could have an invalid decl (i.e. the namespace name is a
7312 // redefinition), push it as current DeclContext and try to continue parsing.
7313 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7314 // for the namespace has the declarations that showed up in that particular
7315 // namespace definition.
7316 PushDeclContext(NamespcScope, Namespc);
7320 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7321 /// is a namespace alias, returns the namespace it points to.
7322 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7323 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7324 return AD->getNamespace();
7325 return dyn_cast_or_null<NamespaceDecl>(D);
7328 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7329 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7330 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7331 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7332 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7333 Namespc->setRBraceLoc(RBrace);
7335 if (Namespc->hasAttr<VisibilityAttr>())
7336 PopPragmaVisibility(true, RBrace);
7339 CXXRecordDecl *Sema::getStdBadAlloc() const {
7340 return cast_or_null<CXXRecordDecl>(
7341 StdBadAlloc.get(Context.getExternalSource()));
7344 NamespaceDecl *Sema::getStdNamespace() const {
7345 return cast_or_null<NamespaceDecl>(
7346 StdNamespace.get(Context.getExternalSource()));
7349 /// \brief Retrieve the special "std" namespace, which may require us to
7350 /// implicitly define the namespace.
7351 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7352 if (!StdNamespace) {
7353 // The "std" namespace has not yet been defined, so build one implicitly.
7354 StdNamespace = NamespaceDecl::Create(Context,
7355 Context.getTranslationUnitDecl(),
7357 SourceLocation(), SourceLocation(),
7358 &PP.getIdentifierTable().get("std"),
7359 /*PrevDecl=*/nullptr);
7360 getStdNamespace()->setImplicit(true);
7363 return getStdNamespace();
7366 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7367 assert(getLangOpts().CPlusPlus &&
7368 "Looking for std::initializer_list outside of C++.");
7370 // We're looking for implicit instantiations of
7371 // template <typename E> class std::initializer_list.
7373 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7376 ClassTemplateDecl *Template = nullptr;
7377 const TemplateArgument *Arguments = nullptr;
7379 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7381 ClassTemplateSpecializationDecl *Specialization =
7382 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7383 if (!Specialization)
7386 Template = Specialization->getSpecializedTemplate();
7387 Arguments = Specialization->getTemplateArgs().data();
7388 } else if (const TemplateSpecializationType *TST =
7389 Ty->getAs<TemplateSpecializationType>()) {
7390 Template = dyn_cast_or_null<ClassTemplateDecl>(
7391 TST->getTemplateName().getAsTemplateDecl());
7392 Arguments = TST->getArgs();
7397 if (!StdInitializerList) {
7398 // Haven't recognized std::initializer_list yet, maybe this is it.
7399 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7400 if (TemplateClass->getIdentifier() !=
7401 &PP.getIdentifierTable().get("initializer_list") ||
7402 !getStdNamespace()->InEnclosingNamespaceSetOf(
7403 TemplateClass->getDeclContext()))
7405 // This is a template called std::initializer_list, but is it the right
7407 TemplateParameterList *Params = Template->getTemplateParameters();
7408 if (Params->getMinRequiredArguments() != 1)
7410 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7413 // It's the right template.
7414 StdInitializerList = Template;
7417 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7420 // This is an instance of std::initializer_list. Find the argument type.
7422 *Element = Arguments[0].getAsType();
7426 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7427 NamespaceDecl *Std = S.getStdNamespace();
7429 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7433 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7434 Loc, Sema::LookupOrdinaryName);
7435 if (!S.LookupQualifiedName(Result, Std)) {
7436 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7439 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7441 Result.suppressDiagnostics();
7442 // We found something weird. Complain about the first thing we found.
7443 NamedDecl *Found = *Result.begin();
7444 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7448 // We found some template called std::initializer_list. Now verify that it's
7450 TemplateParameterList *Params = Template->getTemplateParameters();
7451 if (Params->getMinRequiredArguments() != 1 ||
7452 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7453 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7460 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7461 if (!StdInitializerList) {
7462 StdInitializerList = LookupStdInitializerList(*this, Loc);
7463 if (!StdInitializerList)
7467 TemplateArgumentListInfo Args(Loc, Loc);
7468 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7469 Context.getTrivialTypeSourceInfo(Element,
7471 return Context.getCanonicalType(
7472 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7475 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7476 // C++ [dcl.init.list]p2:
7477 // A constructor is an initializer-list constructor if its first parameter
7478 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7479 // std::initializer_list<E> for some type E, and either there are no other
7480 // parameters or else all other parameters have default arguments.
7481 if (Ctor->getNumParams() < 1 ||
7482 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7485 QualType ArgType = Ctor->getParamDecl(0)->getType();
7486 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7487 ArgType = RT->getPointeeType().getUnqualifiedType();
7489 return isStdInitializerList(ArgType, nullptr);
7492 /// \brief Determine whether a using statement is in a context where it will be
7493 /// apply in all contexts.
7494 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7495 switch (CurContext->getDeclKind()) {
7496 case Decl::TranslationUnit:
7498 case Decl::LinkageSpec:
7499 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7507 // Callback to only accept typo corrections that are namespaces.
7508 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7510 bool ValidateCandidate(const TypoCorrection &candidate) override {
7511 if (NamedDecl *ND = candidate.getCorrectionDecl())
7512 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7519 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7521 SourceLocation IdentLoc,
7522 IdentifierInfo *Ident) {
7524 if (TypoCorrection Corrected =
7525 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7526 llvm::make_unique<NamespaceValidatorCCC>(),
7527 Sema::CTK_ErrorRecovery)) {
7528 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7529 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7530 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7531 Ident->getName().equals(CorrectedStr);
7532 S.diagnoseTypo(Corrected,
7533 S.PDiag(diag::err_using_directive_member_suggest)
7534 << Ident << DC << DroppedSpecifier << SS.getRange(),
7535 S.PDiag(diag::note_namespace_defined_here));
7537 S.diagnoseTypo(Corrected,
7538 S.PDiag(diag::err_using_directive_suggest) << Ident,
7539 S.PDiag(diag::note_namespace_defined_here));
7541 R.addDecl(Corrected.getCorrectionDecl());
7547 Decl *Sema::ActOnUsingDirective(Scope *S,
7548 SourceLocation UsingLoc,
7549 SourceLocation NamespcLoc,
7551 SourceLocation IdentLoc,
7552 IdentifierInfo *NamespcName,
7553 AttributeList *AttrList) {
7554 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7555 assert(NamespcName && "Invalid NamespcName.");
7556 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7558 // This can only happen along a recovery path.
7559 while (S->getFlags() & Scope::TemplateParamScope)
7561 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7563 UsingDirectiveDecl *UDir = nullptr;
7564 NestedNameSpecifier *Qualifier = nullptr;
7566 Qualifier = SS.getScopeRep();
7568 // Lookup namespace name.
7569 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7570 LookupParsedName(R, S, &SS);
7571 if (R.isAmbiguous())
7576 // Allow "using namespace std;" or "using namespace ::std;" even if
7577 // "std" hasn't been defined yet, for GCC compatibility.
7578 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7579 NamespcName->isStr("std")) {
7580 Diag(IdentLoc, diag::ext_using_undefined_std);
7581 R.addDecl(getOrCreateStdNamespace());
7584 // Otherwise, attempt typo correction.
7585 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7589 NamedDecl *Named = R.getFoundDecl();
7590 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7591 && "expected namespace decl");
7593 // The use of a nested name specifier may trigger deprecation warnings.
7594 DiagnoseUseOfDecl(Named, IdentLoc);
7596 // C++ [namespace.udir]p1:
7597 // A using-directive specifies that the names in the nominated
7598 // namespace can be used in the scope in which the
7599 // using-directive appears after the using-directive. During
7600 // unqualified name lookup (3.4.1), the names appear as if they
7601 // were declared in the nearest enclosing namespace which
7602 // contains both the using-directive and the nominated
7603 // namespace. [Note: in this context, "contains" means "contains
7604 // directly or indirectly". ]
7606 // Find enclosing context containing both using-directive and
7607 // nominated namespace.
7608 NamespaceDecl *NS = getNamespaceDecl(Named);
7609 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7610 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7611 CommonAncestor = CommonAncestor->getParent();
7613 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7614 SS.getWithLocInContext(Context),
7615 IdentLoc, Named, CommonAncestor);
7617 if (IsUsingDirectiveInToplevelContext(CurContext) &&
7618 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7619 Diag(IdentLoc, diag::warn_using_directive_in_header);
7622 PushUsingDirective(S, UDir);
7624 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7628 ProcessDeclAttributeList(S, UDir, AttrList);
7633 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7634 // If the scope has an associated entity and the using directive is at
7635 // namespace or translation unit scope, add the UsingDirectiveDecl into
7636 // its lookup structure so qualified name lookup can find it.
7637 DeclContext *Ctx = S->getEntity();
7638 if (Ctx && !Ctx->isFunctionOrMethod())
7641 // Otherwise, it is at block scope. The using-directives will affect lookup
7642 // only to the end of the scope.
7643 S->PushUsingDirective(UDir);
7647 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7649 bool HasUsingKeyword,
7650 SourceLocation UsingLoc,
7652 UnqualifiedId &Name,
7653 AttributeList *AttrList,
7654 bool HasTypenameKeyword,
7655 SourceLocation TypenameLoc) {
7656 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7658 switch (Name.getKind()) {
7659 case UnqualifiedId::IK_ImplicitSelfParam:
7660 case UnqualifiedId::IK_Identifier:
7661 case UnqualifiedId::IK_OperatorFunctionId:
7662 case UnqualifiedId::IK_LiteralOperatorId:
7663 case UnqualifiedId::IK_ConversionFunctionId:
7666 case UnqualifiedId::IK_ConstructorName:
7667 case UnqualifiedId::IK_ConstructorTemplateId:
7668 // C++11 inheriting constructors.
7669 Diag(Name.getLocStart(),
7670 getLangOpts().CPlusPlus11 ?
7671 diag::warn_cxx98_compat_using_decl_constructor :
7672 diag::err_using_decl_constructor)
7675 if (getLangOpts().CPlusPlus11) break;
7679 case UnqualifiedId::IK_DestructorName:
7680 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7684 case UnqualifiedId::IK_TemplateId:
7685 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7686 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7690 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7691 DeclarationName TargetName = TargetNameInfo.getName();
7695 // Warn about access declarations.
7696 if (!HasUsingKeyword) {
7697 Diag(Name.getLocStart(),
7698 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7699 : diag::warn_access_decl_deprecated)
7700 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7703 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7704 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7707 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7708 TargetNameInfo, AttrList,
7709 /* IsInstantiation */ false,
7710 HasTypenameKeyword, TypenameLoc);
7712 PushOnScopeChains(UD, S, /*AddToContext*/ false);
7717 /// \brief Determine whether a using declaration considers the given
7718 /// declarations as "equivalent", e.g., if they are redeclarations of
7719 /// the same entity or are both typedefs of the same type.
7721 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7722 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7725 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7726 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7727 return Context.hasSameType(TD1->getUnderlyingType(),
7728 TD2->getUnderlyingType());
7734 /// Determines whether to create a using shadow decl for a particular
7735 /// decl, given the set of decls existing prior to this using lookup.
7736 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7737 const LookupResult &Previous,
7738 UsingShadowDecl *&PrevShadow) {
7739 // Diagnose finding a decl which is not from a base class of the
7740 // current class. We do this now because there are cases where this
7741 // function will silently decide not to build a shadow decl, which
7742 // will pre-empt further diagnostics.
7744 // We don't need to do this in C++0x because we do the check once on
7747 // FIXME: diagnose the following if we care enough:
7748 // struct A { int foo; };
7749 // struct B : A { using A::foo; };
7750 // template <class T> struct C : A {};
7751 // template <class T> struct D : C<T> { using B::foo; } // <---
7752 // This is invalid (during instantiation) in C++03 because B::foo
7753 // resolves to the using decl in B, which is not a base class of D<T>.
7754 // We can't diagnose it immediately because C<T> is an unknown
7755 // specialization. The UsingShadowDecl in D<T> then points directly
7756 // to A::foo, which will look well-formed when we instantiate.
7757 // The right solution is to not collapse the shadow-decl chain.
7758 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7759 DeclContext *OrigDC = Orig->getDeclContext();
7761 // Handle enums and anonymous structs.
7762 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7763 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7764 while (OrigRec->isAnonymousStructOrUnion())
7765 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7767 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7768 if (OrigDC == CurContext) {
7769 Diag(Using->getLocation(),
7770 diag::err_using_decl_nested_name_specifier_is_current_class)
7771 << Using->getQualifierLoc().getSourceRange();
7772 Diag(Orig->getLocation(), diag::note_using_decl_target);
7776 Diag(Using->getQualifierLoc().getBeginLoc(),
7777 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7778 << Using->getQualifier()
7779 << cast<CXXRecordDecl>(CurContext)
7780 << Using->getQualifierLoc().getSourceRange();
7781 Diag(Orig->getLocation(), diag::note_using_decl_target);
7786 if (Previous.empty()) return false;
7788 NamedDecl *Target = Orig;
7789 if (isa<UsingShadowDecl>(Target))
7790 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7792 // If the target happens to be one of the previous declarations, we
7793 // don't have a conflict.
7795 // FIXME: but we might be increasing its access, in which case we
7796 // should redeclare it.
7797 NamedDecl *NonTag = nullptr, *Tag = nullptr;
7798 bool FoundEquivalentDecl = false;
7799 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7801 NamedDecl *D = (*I)->getUnderlyingDecl();
7802 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7803 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7804 PrevShadow = Shadow;
7805 FoundEquivalentDecl = true;
7808 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7811 if (FoundEquivalentDecl)
7814 if (FunctionDecl *FD = Target->getAsFunction()) {
7815 NamedDecl *OldDecl = nullptr;
7816 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7817 /*IsForUsingDecl*/ true)) {
7821 case Ovl_NonFunction:
7822 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7825 // We found a decl with the exact signature.
7827 // If we're in a record, we want to hide the target, so we
7828 // return true (without a diagnostic) to tell the caller not to
7829 // build a shadow decl.
7830 if (CurContext->isRecord())
7833 // If we're not in a record, this is an error.
7834 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7838 Diag(Target->getLocation(), diag::note_using_decl_target);
7839 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7843 // Target is not a function.
7845 if (isa<TagDecl>(Target)) {
7846 // No conflict between a tag and a non-tag.
7847 if (!Tag) return false;
7849 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7850 Diag(Target->getLocation(), diag::note_using_decl_target);
7851 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7855 // No conflict between a tag and a non-tag.
7856 if (!NonTag) return false;
7858 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7859 Diag(Target->getLocation(), diag::note_using_decl_target);
7860 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7864 /// Builds a shadow declaration corresponding to a 'using' declaration.
7865 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7868 UsingShadowDecl *PrevDecl) {
7870 // If we resolved to another shadow declaration, just coalesce them.
7871 NamedDecl *Target = Orig;
7872 if (isa<UsingShadowDecl>(Target)) {
7873 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7874 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7877 UsingShadowDecl *Shadow
7878 = UsingShadowDecl::Create(Context, CurContext,
7879 UD->getLocation(), UD, Target);
7880 UD->addShadowDecl(Shadow);
7882 Shadow->setAccess(UD->getAccess());
7883 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7884 Shadow->setInvalidDecl();
7886 Shadow->setPreviousDecl(PrevDecl);
7889 PushOnScopeChains(Shadow, S);
7891 CurContext->addDecl(Shadow);
7897 /// Hides a using shadow declaration. This is required by the current
7898 /// using-decl implementation when a resolvable using declaration in a
7899 /// class is followed by a declaration which would hide or override
7900 /// one or more of the using decl's targets; for example:
7902 /// struct Base { void foo(int); };
7903 /// struct Derived : Base {
7904 /// using Base::foo;
7908 /// The governing language is C++03 [namespace.udecl]p12:
7910 /// When a using-declaration brings names from a base class into a
7911 /// derived class scope, member functions in the derived class
7912 /// override and/or hide member functions with the same name and
7913 /// parameter types in a base class (rather than conflicting).
7915 /// There are two ways to implement this:
7916 /// (1) optimistically create shadow decls when they're not hidden
7917 /// by existing declarations, or
7918 /// (2) don't create any shadow decls (or at least don't make them
7919 /// visible) until we've fully parsed/instantiated the class.
7920 /// The problem with (1) is that we might have to retroactively remove
7921 /// a shadow decl, which requires several O(n) operations because the
7922 /// decl structures are (very reasonably) not designed for removal.
7923 /// (2) avoids this but is very fiddly and phase-dependent.
7924 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7925 if (Shadow->getDeclName().getNameKind() ==
7926 DeclarationName::CXXConversionFunctionName)
7927 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7929 // Remove it from the DeclContext...
7930 Shadow->getDeclContext()->removeDecl(Shadow);
7932 // ...and the scope, if applicable...
7934 S->RemoveDecl(Shadow);
7935 IdResolver.RemoveDecl(Shadow);
7938 // ...and the using decl.
7939 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7941 // TODO: complain somehow if Shadow was used. It shouldn't
7942 // be possible for this to happen, because...?
7945 /// Find the base specifier for a base class with the given type.
7946 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7947 QualType DesiredBase,
7948 bool &AnyDependentBases) {
7949 // Check whether the named type is a direct base class.
7950 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7951 for (auto &Base : Derived->bases()) {
7952 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7953 if (CanonicalDesiredBase == BaseType)
7955 if (BaseType->isDependentType())
7956 AnyDependentBases = true;
7962 class UsingValidatorCCC : public CorrectionCandidateCallback {
7964 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7965 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7966 : HasTypenameKeyword(HasTypenameKeyword),
7967 IsInstantiation(IsInstantiation), OldNNS(NNS),
7968 RequireMemberOf(RequireMemberOf) {}
7970 bool ValidateCandidate(const TypoCorrection &Candidate) override {
7971 NamedDecl *ND = Candidate.getCorrectionDecl();
7973 // Keywords are not valid here.
7974 if (!ND || isa<NamespaceDecl>(ND))
7977 // Completely unqualified names are invalid for a 'using' declaration.
7978 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7981 if (RequireMemberOf) {
7982 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7983 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7984 // No-one ever wants a using-declaration to name an injected-class-name
7985 // of a base class, unless they're declaring an inheriting constructor.
7986 ASTContext &Ctx = ND->getASTContext();
7987 if (!Ctx.getLangOpts().CPlusPlus11)
7989 QualType FoundType = Ctx.getRecordType(FoundRecord);
7991 // Check that the injected-class-name is named as a member of its own
7992 // type; we don't want to suggest 'using Derived::Base;', since that
7993 // means something else.
7994 NestedNameSpecifier *Specifier =
7995 Candidate.WillReplaceSpecifier()
7996 ? Candidate.getCorrectionSpecifier()
7998 if (!Specifier->getAsType() ||
7999 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8002 // Check that this inheriting constructor declaration actually names a
8003 // direct base class of the current class.
8004 bool AnyDependentBases = false;
8005 if (!findDirectBaseWithType(RequireMemberOf,
8006 Ctx.getRecordType(FoundRecord),
8007 AnyDependentBases) &&
8011 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8012 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8015 // FIXME: Check that the base class member is accessible?
8019 if (isa<TypeDecl>(ND))
8020 return HasTypenameKeyword || !IsInstantiation;
8022 return !HasTypenameKeyword;
8026 bool HasTypenameKeyword;
8027 bool IsInstantiation;
8028 NestedNameSpecifier *OldNNS;
8029 CXXRecordDecl *RequireMemberOf;
8031 } // end anonymous namespace
8033 /// Builds a using declaration.
8035 /// \param IsInstantiation - Whether this call arises from an
8036 /// instantiation of an unresolved using declaration. We treat
8037 /// the lookup differently for these declarations.
8038 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8039 SourceLocation UsingLoc,
8041 DeclarationNameInfo NameInfo,
8042 AttributeList *AttrList,
8043 bool IsInstantiation,
8044 bool HasTypenameKeyword,
8045 SourceLocation TypenameLoc) {
8046 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8047 SourceLocation IdentLoc = NameInfo.getLoc();
8048 assert(IdentLoc.isValid() && "Invalid TargetName location.");
8050 // FIXME: We ignore attributes for now.
8053 Diag(IdentLoc, diag::err_using_requires_qualname);
8057 // Do the redeclaration lookup in the current scope.
8058 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8060 Previous.setHideTags(false);
8062 LookupName(Previous, S);
8064 // It is really dumb that we have to do this.
8065 LookupResult::Filter F = Previous.makeFilter();
8066 while (F.hasNext()) {
8067 NamedDecl *D = F.next();
8068 if (!isDeclInScope(D, CurContext, S))
8070 // If we found a local extern declaration that's not ordinarily visible,
8071 // and this declaration is being added to a non-block scope, ignore it.
8072 // We're only checking for scope conflicts here, not also for violations
8073 // of the linkage rules.
8074 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8075 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8080 assert(IsInstantiation && "no scope in non-instantiation");
8081 assert(CurContext->isRecord() && "scope not record in instantiation");
8082 LookupQualifiedName(Previous, CurContext);
8085 // Check for invalid redeclarations.
8086 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8087 SS, IdentLoc, Previous))
8090 // Check for bad qualifiers.
8091 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8094 DeclContext *LookupContext = computeDeclContext(SS);
8096 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8097 if (!LookupContext) {
8098 if (HasTypenameKeyword) {
8099 // FIXME: not all declaration name kinds are legal here
8100 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8101 UsingLoc, TypenameLoc,
8103 IdentLoc, NameInfo.getName());
8105 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8106 QualifierLoc, NameInfo);
8109 CurContext->addDecl(D);
8113 auto Build = [&](bool Invalid) {
8115 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8116 HasTypenameKeyword);
8118 CurContext->addDecl(UD);
8119 UD->setInvalidDecl(Invalid);
8122 auto BuildInvalid = [&]{ return Build(true); };
8123 auto BuildValid = [&]{ return Build(false); };
8125 if (RequireCompleteDeclContext(SS, LookupContext))
8126 return BuildInvalid();
8128 // Look up the target name.
8129 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8131 // Unlike most lookups, we don't always want to hide tag
8132 // declarations: tag names are visible through the using declaration
8133 // even if hidden by ordinary names, *except* in a dependent context
8134 // where it's important for the sanity of two-phase lookup.
8135 if (!IsInstantiation)
8136 R.setHideTags(false);
8138 // For the purposes of this lookup, we have a base object type
8139 // equal to that of the current context.
8140 if (CurContext->isRecord()) {
8141 R.setBaseObjectType(
8142 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8145 LookupQualifiedName(R, LookupContext);
8147 // Try to correct typos if possible. If constructor name lookup finds no
8148 // results, that means the named class has no explicit constructors, and we
8149 // suppressed declaring implicit ones (probably because it's dependent or
8152 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8153 if (TypoCorrection Corrected = CorrectTypo(
8154 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8155 llvm::make_unique<UsingValidatorCCC>(
8156 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8157 dyn_cast<CXXRecordDecl>(CurContext)),
8158 CTK_ErrorRecovery)) {
8159 // We reject any correction for which ND would be NULL.
8160 NamedDecl *ND = Corrected.getCorrectionDecl();
8162 // We reject candidates where DroppedSpecifier == true, hence the
8163 // literal '0' below.
8164 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8165 << NameInfo.getName() << LookupContext << 0
8168 // If we corrected to an inheriting constructor, handle it as one.
8169 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8170 if (RD && RD->isInjectedClassName()) {
8171 // Fix up the information we'll use to build the using declaration.
8172 if (Corrected.WillReplaceSpecifier()) {
8173 NestedNameSpecifierLocBuilder Builder;
8174 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8175 QualifierLoc.getSourceRange());
8176 QualifierLoc = Builder.getWithLocInContext(Context);
8179 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8180 Context.getCanonicalType(Context.getRecordType(RD))));
8181 NameInfo.setNamedTypeInfo(nullptr);
8182 for (auto *Ctor : LookupConstructors(RD))
8185 // FIXME: Pick up all the declarations if we found an overloaded function.
8189 Diag(IdentLoc, diag::err_no_member)
8190 << NameInfo.getName() << LookupContext << SS.getRange();
8191 return BuildInvalid();
8195 if (R.isAmbiguous())
8196 return BuildInvalid();
8198 if (HasTypenameKeyword) {
8199 // If we asked for a typename and got a non-type decl, error out.
8200 if (!R.getAsSingle<TypeDecl>()) {
8201 Diag(IdentLoc, diag::err_using_typename_non_type);
8202 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8203 Diag((*I)->getUnderlyingDecl()->getLocation(),
8204 diag::note_using_decl_target);
8205 return BuildInvalid();
8208 // If we asked for a non-typename and we got a type, error out,
8209 // but only if this is an instantiation of an unresolved using
8210 // decl. Otherwise just silently find the type name.
8211 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8212 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8213 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8214 return BuildInvalid();
8218 // C++0x N2914 [namespace.udecl]p6:
8219 // A using-declaration shall not name a namespace.
8220 if (R.getAsSingle<NamespaceDecl>()) {
8221 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8223 return BuildInvalid();
8226 UsingDecl *UD = BuildValid();
8228 // The normal rules do not apply to inheriting constructor declarations.
8229 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8230 // Suppress access diagnostics; the access check is instead performed at the
8231 // point of use for an inheriting constructor.
8232 R.suppressDiagnostics();
8233 CheckInheritingConstructorUsingDecl(UD);
8237 // Otherwise, look up the target name.
8239 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8240 UsingShadowDecl *PrevDecl = nullptr;
8241 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8242 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8248 /// Additional checks for a using declaration referring to a constructor name.
8249 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8250 assert(!UD->hasTypename() && "expecting a constructor name");
8252 const Type *SourceType = UD->getQualifier()->getAsType();
8253 assert(SourceType &&
8254 "Using decl naming constructor doesn't have type in scope spec.");
8255 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8257 // Check whether the named type is a direct base class.
8258 bool AnyDependentBases = false;
8259 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8261 if (!Base && !AnyDependentBases) {
8262 Diag(UD->getUsingLoc(),
8263 diag::err_using_decl_constructor_not_in_direct_base)
8264 << UD->getNameInfo().getSourceRange()
8265 << QualType(SourceType, 0) << TargetClass;
8266 UD->setInvalidDecl();
8271 Base->setInheritConstructors();
8276 /// Checks that the given using declaration is not an invalid
8277 /// redeclaration. Note that this is checking only for the using decl
8278 /// itself, not for any ill-formedness among the UsingShadowDecls.
8279 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8280 bool HasTypenameKeyword,
8281 const CXXScopeSpec &SS,
8282 SourceLocation NameLoc,
8283 const LookupResult &Prev) {
8284 // C++03 [namespace.udecl]p8:
8285 // C++0x [namespace.udecl]p10:
8286 // A using-declaration is a declaration and can therefore be used
8287 // repeatedly where (and only where) multiple declarations are
8290 // That's in non-member contexts.
8291 if (!CurContext->getRedeclContext()->isRecord())
8294 NestedNameSpecifier *Qual = SS.getScopeRep();
8296 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8300 NestedNameSpecifier *DQual;
8301 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8302 DTypename = UD->hasTypename();
8303 DQual = UD->getQualifier();
8304 } else if (UnresolvedUsingValueDecl *UD
8305 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8307 DQual = UD->getQualifier();
8308 } else if (UnresolvedUsingTypenameDecl *UD
8309 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8311 DQual = UD->getQualifier();
8314 // using decls differ if one says 'typename' and the other doesn't.
8315 // FIXME: non-dependent using decls?
8316 if (HasTypenameKeyword != DTypename) continue;
8318 // using decls differ if they name different scopes (but note that
8319 // template instantiation can cause this check to trigger when it
8320 // didn't before instantiation).
8321 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8322 Context.getCanonicalNestedNameSpecifier(DQual))
8325 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8326 Diag(D->getLocation(), diag::note_using_decl) << 1;
8334 /// Checks that the given nested-name qualifier used in a using decl
8335 /// in the current context is appropriately related to the current
8336 /// scope. If an error is found, diagnoses it and returns true.
8337 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8338 const CXXScopeSpec &SS,
8339 const DeclarationNameInfo &NameInfo,
8340 SourceLocation NameLoc) {
8341 DeclContext *NamedContext = computeDeclContext(SS);
8343 if (!CurContext->isRecord()) {
8344 // C++03 [namespace.udecl]p3:
8345 // C++0x [namespace.udecl]p8:
8346 // A using-declaration for a class member shall be a member-declaration.
8348 // If we weren't able to compute a valid scope, it must be a
8349 // dependent class scope.
8350 if (!NamedContext || NamedContext->isRecord()) {
8351 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8352 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8355 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8358 // If we have a complete, non-dependent source type, try to suggest a
8359 // way to get the same effect.
8363 // Find what this using-declaration was referring to.
8364 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8365 R.setHideTags(false);
8366 R.suppressDiagnostics();
8367 LookupQualifiedName(R, RD);
8369 if (R.getAsSingle<TypeDecl>()) {
8370 if (getLangOpts().CPlusPlus11) {
8371 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8372 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8373 << 0 // alias declaration
8374 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8375 NameInfo.getName().getAsString() +
8378 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8379 SourceLocation InsertLoc =
8380 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8381 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8382 << 1 // typedef declaration
8383 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8384 << FixItHint::CreateInsertion(
8385 InsertLoc, " " + NameInfo.getName().getAsString());
8387 } else if (R.getAsSingle<VarDecl>()) {
8388 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8389 // repeating the type of the static data member here.
8391 if (getLangOpts().CPlusPlus11) {
8392 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8393 FixIt = FixItHint::CreateReplacement(
8394 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8397 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8398 << 2 // reference declaration
8404 // Otherwise, everything is known to be fine.
8408 // The current scope is a record.
8410 // If the named context is dependent, we can't decide much.
8411 if (!NamedContext) {
8412 // FIXME: in C++0x, we can diagnose if we can prove that the
8413 // nested-name-specifier does not refer to a base class, which is
8414 // still possible in some cases.
8416 // Otherwise we have to conservatively report that things might be
8421 if (!NamedContext->isRecord()) {
8422 // Ideally this would point at the last name in the specifier,
8423 // but we don't have that level of source info.
8424 Diag(SS.getRange().getBegin(),
8425 diag::err_using_decl_nested_name_specifier_is_not_class)
8426 << SS.getScopeRep() << SS.getRange();
8430 if (!NamedContext->isDependentContext() &&
8431 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8434 if (getLangOpts().CPlusPlus11) {
8435 // C++0x [namespace.udecl]p3:
8436 // In a using-declaration used as a member-declaration, the
8437 // nested-name-specifier shall name a base class of the class
8440 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8441 cast<CXXRecordDecl>(NamedContext))) {
8442 if (CurContext == NamedContext) {
8444 diag::err_using_decl_nested_name_specifier_is_current_class)
8449 Diag(SS.getRange().getBegin(),
8450 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8452 << cast<CXXRecordDecl>(CurContext)
8460 // C++03 [namespace.udecl]p4:
8461 // A using-declaration used as a member-declaration shall refer
8462 // to a member of a base class of the class being defined [etc.].
8464 // Salient point: SS doesn't have to name a base class as long as
8465 // lookup only finds members from base classes. Therefore we can
8466 // diagnose here only if we can prove that that can't happen,
8467 // i.e. if the class hierarchies provably don't intersect.
8469 // TODO: it would be nice if "definitely valid" results were cached
8470 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8471 // need to be repeated.
8474 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8476 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8477 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8478 Data->Bases.insert(Base);
8482 bool hasDependentBases(const CXXRecordDecl *Class) {
8483 return !Class->forallBases(collect, this);
8486 /// Returns true if the base is dependent or is one of the
8487 /// accumulated base classes.
8488 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8489 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8490 return !Data->Bases.count(Base);
8493 bool mightShareBases(const CXXRecordDecl *Class) {
8494 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8500 // Returns false if we find a dependent base.
8501 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8504 // Returns false if the class has a dependent base or if it or one
8505 // of its bases is present in the base set of the current context.
8506 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8509 Diag(SS.getRange().getBegin(),
8510 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8512 << cast<CXXRecordDecl>(CurContext)
8518 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8520 MultiTemplateParamsArg TemplateParamLists,
8521 SourceLocation UsingLoc,
8522 UnqualifiedId &Name,
8523 AttributeList *AttrList,
8525 Decl *DeclFromDeclSpec) {
8526 // Skip up to the relevant declaration scope.
8527 while (S->getFlags() & Scope::TemplateParamScope)
8529 assert((S->getFlags() & Scope::DeclScope) &&
8530 "got alias-declaration outside of declaration scope");
8532 if (Type.isInvalid())
8535 bool Invalid = false;
8536 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8537 TypeSourceInfo *TInfo = nullptr;
8538 GetTypeFromParser(Type.get(), &TInfo);
8540 if (DiagnoseClassNameShadow(CurContext, NameInfo))
8543 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8544 UPPC_DeclarationType)) {
8546 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8547 TInfo->getTypeLoc().getBeginLoc());
8550 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8551 LookupName(Previous, S);
8553 // Warn about shadowing the name of a template parameter.
8554 if (Previous.isSingleResult() &&
8555 Previous.getFoundDecl()->isTemplateParameter()) {
8556 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8560 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8561 "name in alias declaration must be an identifier");
8562 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8564 Name.Identifier, TInfo);
8566 NewTD->setAccess(AS);
8569 NewTD->setInvalidDecl();
8571 ProcessDeclAttributeList(S, NewTD, AttrList);
8573 CheckTypedefForVariablyModifiedType(S, NewTD);
8574 Invalid |= NewTD->isInvalidDecl();
8576 bool Redeclaration = false;
8579 if (TemplateParamLists.size()) {
8580 TypeAliasTemplateDecl *OldDecl = nullptr;
8581 TemplateParameterList *OldTemplateParams = nullptr;
8583 if (TemplateParamLists.size() != 1) {
8584 Diag(UsingLoc, diag::err_alias_template_extra_headers)
8585 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8586 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8588 TemplateParameterList *TemplateParams = TemplateParamLists[0];
8590 // Only consider previous declarations in the same scope.
8591 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8592 /*ExplicitInstantiationOrSpecialization*/false);
8593 if (!Previous.empty()) {
8594 Redeclaration = true;
8596 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8597 if (!OldDecl && !Invalid) {
8598 Diag(UsingLoc, diag::err_redefinition_different_kind)
8601 NamedDecl *OldD = Previous.getRepresentativeDecl();
8602 if (OldD->getLocation().isValid())
8603 Diag(OldD->getLocation(), diag::note_previous_definition);
8608 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8609 if (TemplateParameterListsAreEqual(TemplateParams,
8610 OldDecl->getTemplateParameters(),
8613 OldTemplateParams = OldDecl->getTemplateParameters();
8617 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8619 !Context.hasSameType(OldTD->getUnderlyingType(),
8620 NewTD->getUnderlyingType())) {
8621 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8622 // but we can't reasonably accept it.
8623 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8624 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8625 if (OldTD->getLocation().isValid())
8626 Diag(OldTD->getLocation(), diag::note_previous_definition);
8632 // Merge any previous default template arguments into our parameters,
8633 // and check the parameter list.
8634 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8635 TPC_TypeAliasTemplate))
8638 TypeAliasTemplateDecl *NewDecl =
8639 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8640 Name.Identifier, TemplateParams,
8642 NewTD->setDescribedAliasTemplate(NewDecl);
8644 NewDecl->setAccess(AS);
8647 NewDecl->setInvalidDecl();
8649 NewDecl->setPreviousDecl(OldDecl);
8653 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8654 setTagNameForLinkagePurposes(TD, NewTD);
8655 handleTagNumbering(TD, S);
8657 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8662 PushOnScopeChains(NewND, S);
8664 ActOnDocumentableDecl(NewND);
8668 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8669 SourceLocation AliasLoc,
8670 IdentifierInfo *Alias, CXXScopeSpec &SS,
8671 SourceLocation IdentLoc,
8672 IdentifierInfo *Ident) {
8674 // Lookup the namespace name.
8675 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8676 LookupParsedName(R, S, &SS);
8678 if (R.isAmbiguous())
8682 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8683 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8687 assert(!R.isAmbiguous() && !R.empty());
8689 // Check if we have a previous declaration with the same name.
8690 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8692 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8695 NamedDecl *ND = R.getFoundDecl();
8698 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8699 // We already have an alias with the same name that points to the same
8700 // namespace; check that it matches.
8701 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8702 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8704 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8705 << AD->getNamespace();
8709 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8710 ? diag::err_redefinition
8711 : diag::err_redefinition_different_kind;
8712 Diag(AliasLoc, DiagID) << Alias;
8713 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8718 // The use of a nested name specifier may trigger deprecation warnings.
8719 DiagnoseUseOfDecl(ND, IdentLoc);
8721 NamespaceAliasDecl *AliasDecl =
8722 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8723 Alias, SS.getWithLocInContext(Context),
8726 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8728 PushOnScopeChains(AliasDecl, S);
8732 Sema::ImplicitExceptionSpecification
8733 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8734 CXXMethodDecl *MD) {
8735 CXXRecordDecl *ClassDecl = MD->getParent();
8737 // C++ [except.spec]p14:
8738 // An implicitly declared special member function (Clause 12) shall have an
8739 // exception-specification. [...]
8740 ImplicitExceptionSpecification ExceptSpec(*this);
8741 if (ClassDecl->isInvalidDecl())
8744 // Direct base-class constructors.
8745 for (const auto &B : ClassDecl->bases()) {
8746 if (B.isVirtual()) // Handled below.
8749 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8750 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8751 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8752 // If this is a deleted function, add it anyway. This might be conformant
8753 // with the standard. This might not. I'm not sure. It might not matter.
8755 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8759 // Virtual base-class constructors.
8760 for (const auto &B : ClassDecl->vbases()) {
8761 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8762 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8763 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8764 // If this is a deleted function, add it anyway. This might be conformant
8765 // with the standard. This might not. I'm not sure. It might not matter.
8767 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8771 // Field constructors.
8772 for (const auto *F : ClassDecl->fields()) {
8773 if (F->hasInClassInitializer()) {
8774 if (Expr *E = F->getInClassInitializer())
8775 ExceptSpec.CalledExpr(E);
8776 } else if (const RecordType *RecordTy
8777 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8778 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8779 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8780 // If this is a deleted function, add it anyway. This might be conformant
8781 // with the standard. This might not. I'm not sure. It might not matter.
8782 // In particular, the problem is that this function never gets called. It
8783 // might just be ill-formed because this function attempts to refer to
8784 // a deleted function here.
8786 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8793 Sema::ImplicitExceptionSpecification
8794 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8795 CXXRecordDecl *ClassDecl = CD->getParent();
8797 // C++ [except.spec]p14:
8798 // An inheriting constructor [...] shall have an exception-specification. [...]
8799 ImplicitExceptionSpecification ExceptSpec(*this);
8800 if (ClassDecl->isInvalidDecl())
8803 // Inherited constructor.
8804 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8805 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8806 // FIXME: Copying or moving the parameters could add extra exceptions to the
8807 // set, as could the default arguments for the inherited constructor. This
8808 // will be addressed when we implement the resolution of core issue 1351.
8809 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8811 // Direct base-class constructors.
8812 for (const auto &B : ClassDecl->bases()) {
8813 if (B.isVirtual()) // Handled below.
8816 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8817 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8818 if (BaseClassDecl == InheritedDecl)
8820 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8822 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8826 // Virtual base-class constructors.
8827 for (const auto &B : ClassDecl->vbases()) {
8828 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8829 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8830 if (BaseClassDecl == InheritedDecl)
8832 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8834 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8838 // Field constructors.
8839 for (const auto *F : ClassDecl->fields()) {
8840 if (F->hasInClassInitializer()) {
8841 if (Expr *E = F->getInClassInitializer())
8842 ExceptSpec.CalledExpr(E);
8843 } else if (const RecordType *RecordTy
8844 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8845 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8846 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8848 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8856 /// RAII object to register a special member as being currently declared.
8857 struct DeclaringSpecialMember {
8859 Sema::SpecialMemberDecl D;
8860 bool WasAlreadyBeingDeclared;
8862 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8863 : S(S), D(RD, CSM) {
8864 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8865 if (WasAlreadyBeingDeclared)
8866 // This almost never happens, but if it does, ensure that our cache
8867 // doesn't contain a stale result.
8868 S.SpecialMemberCache.clear();
8870 // FIXME: Register a note to be produced if we encounter an error while
8871 // declaring the special member.
8873 ~DeclaringSpecialMember() {
8874 if (!WasAlreadyBeingDeclared)
8875 S.SpecialMembersBeingDeclared.erase(D);
8878 /// \brief Are we already trying to declare this special member?
8879 bool isAlreadyBeingDeclared() const {
8880 return WasAlreadyBeingDeclared;
8885 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8886 CXXRecordDecl *ClassDecl) {
8887 // C++ [class.ctor]p5:
8888 // A default constructor for a class X is a constructor of class X
8889 // that can be called without an argument. If there is no
8890 // user-declared constructor for class X, a default constructor is
8891 // implicitly declared. An implicitly-declared default constructor
8892 // is an inline public member of its class.
8893 assert(ClassDecl->needsImplicitDefaultConstructor() &&
8894 "Should not build implicit default constructor!");
8896 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8897 if (DSM.isAlreadyBeingDeclared())
8900 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8901 CXXDefaultConstructor,
8904 // Create the actual constructor declaration.
8905 CanQualType ClassType
8906 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8907 SourceLocation ClassLoc = ClassDecl->getLocation();
8908 DeclarationName Name
8909 = Context.DeclarationNames.getCXXConstructorName(ClassType);
8910 DeclarationNameInfo NameInfo(Name, ClassLoc);
8911 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8912 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8913 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8914 /*isImplicitlyDeclared=*/true, Constexpr);
8915 DefaultCon->setAccess(AS_public);
8916 DefaultCon->setDefaulted();
8918 if (getLangOpts().CUDA) {
8919 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8921 /* ConstRHS */ false,
8922 /* Diagnose */ false);
8925 // Build an exception specification pointing back at this constructor.
8926 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8927 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8929 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8930 // constructors is easy to compute.
8931 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8933 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8934 SetDeclDeleted(DefaultCon, ClassLoc);
8936 // Note that we have declared this constructor.
8937 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8939 if (Scope *S = getScopeForContext(ClassDecl))
8940 PushOnScopeChains(DefaultCon, S, false);
8941 ClassDecl->addDecl(DefaultCon);
8946 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8947 CXXConstructorDecl *Constructor) {
8948 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8949 !Constructor->doesThisDeclarationHaveABody() &&
8950 !Constructor->isDeleted()) &&
8951 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8953 CXXRecordDecl *ClassDecl = Constructor->getParent();
8954 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8956 SynthesizedFunctionScope Scope(*this, Constructor);
8957 DiagnosticErrorTrap Trap(Diags);
8958 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8959 Trap.hasErrorOccurred()) {
8960 Diag(CurrentLocation, diag::note_member_synthesized_at)
8961 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8962 Constructor->setInvalidDecl();
8966 // The exception specification is needed because we are defining the
8968 ResolveExceptionSpec(CurrentLocation,
8969 Constructor->getType()->castAs<FunctionProtoType>());
8971 SourceLocation Loc = Constructor->getLocEnd().isValid()
8972 ? Constructor->getLocEnd()
8973 : Constructor->getLocation();
8974 Constructor->setBody(new (Context) CompoundStmt(Loc));
8976 Constructor->markUsed(Context);
8977 MarkVTableUsed(CurrentLocation, ClassDecl);
8979 if (ASTMutationListener *L = getASTMutationListener()) {
8980 L->CompletedImplicitDefinition(Constructor);
8983 DiagnoseUninitializedFields(*this, Constructor);
8986 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8987 // Perform any delayed checks on exception specifications.
8988 CheckDelayedMemberExceptionSpecs();
8992 /// Information on inheriting constructors to declare.
8993 class InheritingConstructorInfo {
8995 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8996 : SemaRef(SemaRef), Derived(Derived) {
8997 // Mark the constructors that we already have in the derived class.
8999 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9000 // unless there is a user-declared constructor with the same signature in
9001 // the class where the using-declaration appears.
9002 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9005 void inheritAll(CXXRecordDecl *RD) {
9006 visitAll(RD, &InheritingConstructorInfo::inherit);
9010 /// Information about an inheriting constructor.
9011 struct InheritingConstructor {
9012 InheritingConstructor()
9013 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9015 /// If \c true, a constructor with this signature is already declared
9016 /// in the derived class.
9017 bool DeclaredInDerived;
9019 /// The constructor which is inherited.
9020 const CXXConstructorDecl *BaseCtor;
9022 /// The derived constructor we declared.
9023 CXXConstructorDecl *DerivedCtor;
9026 /// Inheriting constructors with a given canonical type. There can be at
9027 /// most one such non-template constructor, and any number of templated
9029 struct InheritingConstructorsForType {
9030 InheritingConstructor NonTemplate;
9031 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9034 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9035 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9036 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9037 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9038 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9039 false, S.TPL_TemplateMatch))
9040 return Templates[I].second;
9041 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9042 return Templates.back().second;
9049 /// Get or create the inheriting constructor record for a constructor.
9050 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9051 QualType CtorType) {
9052 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9053 .getEntry(SemaRef, Ctor);
9056 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9058 /// Process all constructors for a class.
9059 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9060 for (const auto *Ctor : RD->ctors())
9061 (this->*Callback)(Ctor);
9062 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9063 I(RD->decls_begin()), E(RD->decls_end());
9065 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9066 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9067 (this->*Callback)(CD);
9071 /// Note that a constructor (or constructor template) was declared in Derived.
9072 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9073 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9076 /// Inherit a single constructor.
9077 void inherit(const CXXConstructorDecl *Ctor) {
9078 const FunctionProtoType *CtorType =
9079 Ctor->getType()->castAs<FunctionProtoType>();
9080 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9081 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9083 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9085 // Core issue (no number yet): the ellipsis is always discarded.
9087 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9088 SemaRef.Diag(Ctor->getLocation(),
9089 diag::note_using_decl_constructor_ellipsis);
9090 EPI.Variadic = false;
9093 // Declare a constructor for each number of parameters.
9095 // C++11 [class.inhctor]p1:
9096 // The candidate set of inherited constructors from the class X named in
9097 // the using-declaration consists of [... modulo defects ...] for each
9098 // constructor or constructor template of X, the set of constructors or
9099 // constructor templates that results from omitting any ellipsis parameter
9100 // specification and successively omitting parameters with a default
9101 // argument from the end of the parameter-type-list
9102 unsigned MinParams = minParamsToInherit(Ctor);
9103 unsigned Params = Ctor->getNumParams();
9104 if (Params >= MinParams) {
9106 declareCtor(UsingLoc, Ctor,
9107 SemaRef.Context.getFunctionType(
9108 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9109 while (Params > MinParams &&
9110 Ctor->getParamDecl(--Params)->hasDefaultArg());
9114 /// Find the using-declaration which specified that we should inherit the
9115 /// constructors of \p Base.
9116 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9117 // No fancy lookup required; just look for the base constructor name
9118 // directly within the derived class.
9119 ASTContext &Context = SemaRef.Context;
9120 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9121 Context.getCanonicalType(Context.getRecordType(Base)));
9122 DeclContext::lookup_result Decls = Derived->lookup(Name);
9123 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9126 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9127 // C++11 [class.inhctor]p3:
9128 // [F]or each constructor template in the candidate set of inherited
9129 // constructors, a constructor template is implicitly declared
9130 if (Ctor->getDescribedFunctionTemplate())
9133 // For each non-template constructor in the candidate set of inherited
9134 // constructors other than a constructor having no parameters or a
9135 // copy/move constructor having a single parameter, a constructor is
9136 // implicitly declared [...]
9137 if (Ctor->getNumParams() == 0)
9139 if (Ctor->isCopyOrMoveConstructor())
9142 // Per discussion on core reflector, never inherit a constructor which
9143 // would become a default, copy, or move constructor of Derived either.
9144 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9145 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9146 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9149 /// Declare a single inheriting constructor, inheriting the specified
9150 /// constructor, with the given type.
9151 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9152 QualType DerivedType) {
9153 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9155 // C++11 [class.inhctor]p3:
9156 // ... a constructor is implicitly declared with the same constructor
9157 // characteristics unless there is a user-declared constructor with
9158 // the same signature in the class where the using-declaration appears
9159 if (Entry.DeclaredInDerived)
9162 // C++11 [class.inhctor]p7:
9163 // If two using-declarations declare inheriting constructors with the
9164 // same signature, the program is ill-formed
9165 if (Entry.DerivedCtor) {
9166 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9167 // Only diagnose this once per constructor.
9168 if (Entry.DerivedCtor->isInvalidDecl())
9170 Entry.DerivedCtor->setInvalidDecl();
9172 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9173 SemaRef.Diag(BaseCtor->getLocation(),
9174 diag::note_using_decl_constructor_conflict_current_ctor);
9175 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9176 diag::note_using_decl_constructor_conflict_previous_ctor);
9177 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9178 diag::note_using_decl_constructor_conflict_previous_using);
9180 // Core issue (no number): if the same inheriting constructor is
9181 // produced by multiple base class constructors from the same base
9182 // class, the inheriting constructor is defined as deleted.
9183 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9189 ASTContext &Context = SemaRef.Context;
9190 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9191 Context.getCanonicalType(Context.getRecordType(Derived)));
9192 DeclarationNameInfo NameInfo(Name, UsingLoc);
9194 TemplateParameterList *TemplateParams = nullptr;
9195 if (const FunctionTemplateDecl *FTD =
9196 BaseCtor->getDescribedFunctionTemplate()) {
9197 TemplateParams = FTD->getTemplateParameters();
9198 // We're reusing template parameters from a different DeclContext. This
9199 // is questionable at best, but works out because the template depth in
9200 // both places is guaranteed to be 0.
9201 // FIXME: Rebuild the template parameters in the new context, and
9202 // transform the function type to refer to them.
9205 // Build type source info pointing at the using-declaration. This is
9206 // required by template instantiation.
9207 TypeSourceInfo *TInfo =
9208 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9209 FunctionProtoTypeLoc ProtoLoc =
9210 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9212 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9213 Context, Derived, UsingLoc, NameInfo, DerivedType,
9214 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9215 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9217 // Build an unevaluated exception specification for this constructor.
9218 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9219 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9220 EPI.ExceptionSpec.Type = EST_Unevaluated;
9221 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9222 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9223 FPT->getParamTypes(), EPI));
9225 // Build the parameter declarations.
9226 SmallVector<ParmVarDecl *, 16> ParamDecls;
9227 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9228 TypeSourceInfo *TInfo =
9229 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9230 ParmVarDecl *PD = ParmVarDecl::Create(
9231 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9232 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9233 PD->setScopeInfo(0, I);
9235 ParamDecls.push_back(PD);
9236 ProtoLoc.setParam(I, PD);
9239 // Set up the new constructor.
9240 DerivedCtor->setAccess(BaseCtor->getAccess());
9241 DerivedCtor->setParams(ParamDecls);
9242 DerivedCtor->setInheritedConstructor(BaseCtor);
9243 if (BaseCtor->isDeleted())
9244 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9246 // If this is a constructor template, build the template declaration.
9247 if (TemplateParams) {
9248 FunctionTemplateDecl *DerivedTemplate =
9249 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9250 TemplateParams, DerivedCtor);
9251 DerivedTemplate->setAccess(BaseCtor->getAccess());
9252 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9253 Derived->addDecl(DerivedTemplate);
9255 Derived->addDecl(DerivedCtor);
9258 Entry.BaseCtor = BaseCtor;
9259 Entry.DerivedCtor = DerivedCtor;
9263 CXXRecordDecl *Derived;
9264 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9269 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9270 // Defer declaring the inheriting constructors until the class is
9272 if (ClassDecl->isDependentContext())
9275 // Find base classes from which we might inherit constructors.
9276 SmallVector<CXXRecordDecl*, 4> InheritedBases;
9277 for (const auto &BaseIt : ClassDecl->bases())
9278 if (BaseIt.getInheritConstructors())
9279 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9281 // Go no further if we're not inheriting any constructors.
9282 if (InheritedBases.empty())
9285 // Declare the inherited constructors.
9286 InheritingConstructorInfo ICI(*this, ClassDecl);
9287 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9288 ICI.inheritAll(InheritedBases[I]);
9291 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9292 CXXConstructorDecl *Constructor) {
9293 CXXRecordDecl *ClassDecl = Constructor->getParent();
9294 assert(Constructor->getInheritedConstructor() &&
9295 !Constructor->doesThisDeclarationHaveABody() &&
9296 !Constructor->isDeleted());
9298 SynthesizedFunctionScope Scope(*this, Constructor);
9299 DiagnosticErrorTrap Trap(Diags);
9300 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9301 Trap.hasErrorOccurred()) {
9302 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9303 << Context.getTagDeclType(ClassDecl);
9304 Constructor->setInvalidDecl();
9308 SourceLocation Loc = Constructor->getLocation();
9309 Constructor->setBody(new (Context) CompoundStmt(Loc));
9311 Constructor->markUsed(Context);
9312 MarkVTableUsed(CurrentLocation, ClassDecl);
9314 if (ASTMutationListener *L = getASTMutationListener()) {
9315 L->CompletedImplicitDefinition(Constructor);
9320 Sema::ImplicitExceptionSpecification
9321 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9322 CXXRecordDecl *ClassDecl = MD->getParent();
9324 // C++ [except.spec]p14:
9325 // An implicitly declared special member function (Clause 12) shall have
9326 // an exception-specification.
9327 ImplicitExceptionSpecification ExceptSpec(*this);
9328 if (ClassDecl->isInvalidDecl())
9331 // Direct base-class destructors.
9332 for (const auto &B : ClassDecl->bases()) {
9333 if (B.isVirtual()) // Handled below.
9336 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9337 ExceptSpec.CalledDecl(B.getLocStart(),
9338 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9341 // Virtual base-class destructors.
9342 for (const auto &B : ClassDecl->vbases()) {
9343 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9344 ExceptSpec.CalledDecl(B.getLocStart(),
9345 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9348 // Field destructors.
9349 for (const auto *F : ClassDecl->fields()) {
9350 if (const RecordType *RecordTy
9351 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9352 ExceptSpec.CalledDecl(F->getLocation(),
9353 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9359 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9360 // C++ [class.dtor]p2:
9361 // If a class has no user-declared destructor, a destructor is
9362 // declared implicitly. An implicitly-declared destructor is an
9363 // inline public member of its class.
9364 assert(ClassDecl->needsImplicitDestructor());
9366 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9367 if (DSM.isAlreadyBeingDeclared())
9370 // Create the actual destructor declaration.
9371 CanQualType ClassType
9372 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9373 SourceLocation ClassLoc = ClassDecl->getLocation();
9374 DeclarationName Name
9375 = Context.DeclarationNames.getCXXDestructorName(ClassType);
9376 DeclarationNameInfo NameInfo(Name, ClassLoc);
9377 CXXDestructorDecl *Destructor
9378 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9379 QualType(), nullptr, /*isInline=*/true,
9380 /*isImplicitlyDeclared=*/true);
9381 Destructor->setAccess(AS_public);
9382 Destructor->setDefaulted();
9384 if (getLangOpts().CUDA) {
9385 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9387 /* ConstRHS */ false,
9388 /* Diagnose */ false);
9391 // Build an exception specification pointing back at this destructor.
9392 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9393 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9395 AddOverriddenMethods(ClassDecl, Destructor);
9397 // We don't need to use SpecialMemberIsTrivial here; triviality for
9398 // destructors is easy to compute.
9399 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9401 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9402 SetDeclDeleted(Destructor, ClassLoc);
9404 // Note that we have declared this destructor.
9405 ++ASTContext::NumImplicitDestructorsDeclared;
9407 // Introduce this destructor into its scope.
9408 if (Scope *S = getScopeForContext(ClassDecl))
9409 PushOnScopeChains(Destructor, S, false);
9410 ClassDecl->addDecl(Destructor);
9415 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9416 CXXDestructorDecl *Destructor) {
9417 assert((Destructor->isDefaulted() &&
9418 !Destructor->doesThisDeclarationHaveABody() &&
9419 !Destructor->isDeleted()) &&
9420 "DefineImplicitDestructor - call it for implicit default dtor");
9421 CXXRecordDecl *ClassDecl = Destructor->getParent();
9422 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9424 if (Destructor->isInvalidDecl())
9427 SynthesizedFunctionScope Scope(*this, Destructor);
9429 DiagnosticErrorTrap Trap(Diags);
9430 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9431 Destructor->getParent());
9433 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9434 Diag(CurrentLocation, diag::note_member_synthesized_at)
9435 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9437 Destructor->setInvalidDecl();
9441 // The exception specification is needed because we are defining the
9443 ResolveExceptionSpec(CurrentLocation,
9444 Destructor->getType()->castAs<FunctionProtoType>());
9446 SourceLocation Loc = Destructor->getLocEnd().isValid()
9447 ? Destructor->getLocEnd()
9448 : Destructor->getLocation();
9449 Destructor->setBody(new (Context) CompoundStmt(Loc));
9450 Destructor->markUsed(Context);
9451 MarkVTableUsed(CurrentLocation, ClassDecl);
9453 if (ASTMutationListener *L = getASTMutationListener()) {
9454 L->CompletedImplicitDefinition(Destructor);
9458 /// \brief Perform any semantic analysis which needs to be delayed until all
9459 /// pending class member declarations have been parsed.
9460 void Sema::ActOnFinishCXXMemberDecls() {
9461 // If the context is an invalid C++ class, just suppress these checks.
9462 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9463 if (Record->isInvalidDecl()) {
9464 DelayedDefaultedMemberExceptionSpecs.clear();
9465 DelayedExceptionSpecChecks.clear();
9471 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9472 // Don't do anything for template patterns.
9473 if (Class->getDescribedClassTemplate())
9476 for (Decl *Member : Class->decls()) {
9477 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9479 // Recurse on nested classes.
9480 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9481 getDefaultArgExprsForConstructors(S, NestedRD);
9483 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9487 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9488 // Skip any default arguments that we've already instantiated.
9489 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9492 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9493 CD->getParamDecl(I)).get();
9494 S.DiscardCleanupsInEvaluationContext();
9495 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9500 void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
9501 auto *RD = dyn_cast<CXXRecordDecl>(D);
9503 // Default constructors that are annotated with __declspec(dllexport) which
9504 // have default arguments or don't use the standard calling convention are
9505 // wrapped with a thunk called the default constructor closure.
9506 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9507 getDefaultArgExprsForConstructors(*this, RD);
9510 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9511 CXXDestructorDecl *Destructor) {
9512 assert(getLangOpts().CPlusPlus11 &&
9513 "adjusting dtor exception specs was introduced in c++11");
9515 // C++11 [class.dtor]p3:
9516 // A declaration of a destructor that does not have an exception-
9517 // specification is implicitly considered to have the same exception-
9518 // specification as an implicit declaration.
9519 const FunctionProtoType *DtorType = Destructor->getType()->
9520 getAs<FunctionProtoType>();
9521 if (DtorType->hasExceptionSpec())
9524 // Replace the destructor's type, building off the existing one. Fortunately,
9525 // the only thing of interest in the destructor type is its extended info.
9526 // The return and arguments are fixed.
9527 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9528 EPI.ExceptionSpec.Type = EST_Unevaluated;
9529 EPI.ExceptionSpec.SourceDecl = Destructor;
9530 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9532 // FIXME: If the destructor has a body that could throw, and the newly created
9533 // spec doesn't allow exceptions, we should emit a warning, because this
9534 // change in behavior can break conforming C++03 programs at runtime.
9535 // However, we don't have a body or an exception specification yet, so it
9536 // needs to be done somewhere else.
9540 /// \brief An abstract base class for all helper classes used in building the
9541 // copy/move operators. These classes serve as factory functions and help us
9542 // avoid using the same Expr* in the AST twice.
9544 ExprBuilder(const ExprBuilder&) = delete;
9545 ExprBuilder &operator=(const ExprBuilder&) = delete;
9548 static Expr *assertNotNull(Expr *E) {
9549 assert(E && "Expression construction must not fail.");
9555 virtual ~ExprBuilder() {}
9557 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9560 class RefBuilder: public ExprBuilder {
9565 Expr *build(Sema &S, SourceLocation Loc) const override {
9566 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9569 RefBuilder(VarDecl *Var, QualType VarType)
9570 : Var(Var), VarType(VarType) {}
9573 class ThisBuilder: public ExprBuilder {
9575 Expr *build(Sema &S, SourceLocation Loc) const override {
9576 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9580 class CastBuilder: public ExprBuilder {
9581 const ExprBuilder &Builder;
9584 const CXXCastPath &Path;
9587 Expr *build(Sema &S, SourceLocation Loc) const override {
9588 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9589 CK_UncheckedDerivedToBase, Kind,
9593 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9594 const CXXCastPath &Path)
9595 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9598 class DerefBuilder: public ExprBuilder {
9599 const ExprBuilder &Builder;
9602 Expr *build(Sema &S, SourceLocation Loc) const override {
9603 return assertNotNull(
9604 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9607 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9610 class MemberBuilder: public ExprBuilder {
9611 const ExprBuilder &Builder;
9615 LookupResult &MemberLookup;
9618 Expr *build(Sema &S, SourceLocation Loc) const override {
9619 return assertNotNull(S.BuildMemberReferenceExpr(
9620 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9621 nullptr, MemberLookup, nullptr).get());
9624 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9625 LookupResult &MemberLookup)
9626 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9627 MemberLookup(MemberLookup) {}
9630 class MoveCastBuilder: public ExprBuilder {
9631 const ExprBuilder &Builder;
9634 Expr *build(Sema &S, SourceLocation Loc) const override {
9635 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9638 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9641 class LvalueConvBuilder: public ExprBuilder {
9642 const ExprBuilder &Builder;
9645 Expr *build(Sema &S, SourceLocation Loc) const override {
9646 return assertNotNull(
9647 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9650 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9653 class SubscriptBuilder: public ExprBuilder {
9654 const ExprBuilder &Base;
9655 const ExprBuilder &Index;
9658 Expr *build(Sema &S, SourceLocation Loc) const override {
9659 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9660 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9663 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9664 : Base(Base), Index(Index) {}
9667 } // end anonymous namespace
9669 /// When generating a defaulted copy or move assignment operator, if a field
9670 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9671 /// do so. This optimization only applies for arrays of scalars, and for arrays
9672 /// of class type where the selected copy/move-assignment operator is trivial.
9674 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9675 const ExprBuilder &ToB, const ExprBuilder &FromB) {
9676 // Compute the size of the memory buffer to be copied.
9677 QualType SizeType = S.Context.getSizeType();
9678 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9679 S.Context.getTypeSizeInChars(T).getQuantity());
9681 // Take the address of the field references for "from" and "to". We
9682 // directly construct UnaryOperators here because semantic analysis
9683 // does not permit us to take the address of an xvalue.
9684 Expr *From = FromB.build(S, Loc);
9685 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9686 S.Context.getPointerType(From->getType()),
9687 VK_RValue, OK_Ordinary, Loc);
9688 Expr *To = ToB.build(S, Loc);
9689 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9690 S.Context.getPointerType(To->getType()),
9691 VK_RValue, OK_Ordinary, Loc);
9693 const Type *E = T->getBaseElementTypeUnsafe();
9694 bool NeedsCollectableMemCpy =
9695 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9697 // Create a reference to the __builtin_objc_memmove_collectable function
9698 StringRef MemCpyName = NeedsCollectableMemCpy ?
9699 "__builtin_objc_memmove_collectable" :
9701 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9702 Sema::LookupOrdinaryName);
9703 S.LookupName(R, S.TUScope, true);
9705 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9707 // Something went horribly wrong earlier, and we will have complained
9711 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9712 VK_RValue, Loc, nullptr);
9713 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9715 Expr *CallArgs[] = {
9716 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9718 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9719 Loc, CallArgs, Loc);
9721 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9722 return Call.getAs<Stmt>();
9725 /// \brief Builds a statement that copies/moves the given entity from \p From to
9728 /// This routine is used to copy/move the members of a class with an
9729 /// implicitly-declared copy/move assignment operator. When the entities being
9730 /// copied are arrays, this routine builds for loops to copy them.
9732 /// \param S The Sema object used for type-checking.
9734 /// \param Loc The location where the implicit copy/move is being generated.
9736 /// \param T The type of the expressions being copied/moved. Both expressions
9737 /// must have this type.
9739 /// \param To The expression we are copying/moving to.
9741 /// \param From The expression we are copying/moving from.
9743 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9744 /// Otherwise, it's a non-static member subobject.
9746 /// \param Copying Whether we're copying or moving.
9748 /// \param Depth Internal parameter recording the depth of the recursion.
9750 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9751 /// if a memcpy should be used instead.
9753 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9754 const ExprBuilder &To, const ExprBuilder &From,
9755 bool CopyingBaseSubobject, bool Copying,
9756 unsigned Depth = 0) {
9757 // C++11 [class.copy]p28:
9758 // Each subobject is assigned in the manner appropriate to its type:
9760 // - if the subobject is of class type, as if by a call to operator= with
9761 // the subobject as the object expression and the corresponding
9762 // subobject of x as a single function argument (as if by explicit
9763 // qualification; that is, ignoring any possible virtual overriding
9764 // functions in more derived classes);
9766 // C++03 [class.copy]p13:
9767 // - if the subobject is of class type, the copy assignment operator for
9768 // the class is used (as if by explicit qualification; that is,
9769 // ignoring any possible virtual overriding functions in more derived
9771 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9772 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9774 // Look for operator=.
9775 DeclarationName Name
9776 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9777 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9778 S.LookupQualifiedName(OpLookup, ClassDecl, false);
9780 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9782 if (!S.getLangOpts().CPlusPlus11) {
9783 LookupResult::Filter F = OpLookup.makeFilter();
9784 while (F.hasNext()) {
9785 NamedDecl *D = F.next();
9786 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9787 if (Method->isCopyAssignmentOperator() ||
9788 (!Copying && Method->isMoveAssignmentOperator()))
9796 // Suppress the protected check (C++ [class.protected]) for each of the
9797 // assignment operators we found. This strange dance is required when
9798 // we're assigning via a base classes's copy-assignment operator. To
9799 // ensure that we're getting the right base class subobject (without
9800 // ambiguities), we need to cast "this" to that subobject type; to
9801 // ensure that we don't go through the virtual call mechanism, we need
9802 // to qualify the operator= name with the base class (see below). However,
9803 // this means that if the base class has a protected copy assignment
9804 // operator, the protected member access check will fail. So, we
9805 // rewrite "protected" access to "public" access in this case, since we
9806 // know by construction that we're calling from a derived class.
9807 if (CopyingBaseSubobject) {
9808 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9810 if (L.getAccess() == AS_protected)
9811 L.setAccess(AS_public);
9815 // Create the nested-name-specifier that will be used to qualify the
9816 // reference to operator=; this is required to suppress the virtual
9819 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9820 SS.MakeTrivial(S.Context,
9821 NestedNameSpecifier::Create(S.Context, nullptr, false,
9825 // Create the reference to operator=.
9826 ExprResult OpEqualRef
9827 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9828 SS, /*TemplateKWLoc=*/SourceLocation(),
9829 /*FirstQualifierInScope=*/nullptr,
9831 /*TemplateArgs=*/nullptr,
9832 /*SuppressQualifierCheck=*/true);
9833 if (OpEqualRef.isInvalid())
9836 // Build the call to the assignment operator.
9838 Expr *FromInst = From.build(S, Loc);
9839 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9840 OpEqualRef.getAs<Expr>(),
9841 Loc, FromInst, Loc);
9842 if (Call.isInvalid())
9845 // If we built a call to a trivial 'operator=' while copying an array,
9846 // bail out. We'll replace the whole shebang with a memcpy.
9847 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9848 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9849 return StmtResult((Stmt*)nullptr);
9851 // Convert to an expression-statement, and clean up any produced
9853 return S.ActOnExprStmt(Call);
9856 // - if the subobject is of scalar type, the built-in assignment
9857 // operator is used.
9858 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9860 ExprResult Assignment = S.CreateBuiltinBinOp(
9861 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9862 if (Assignment.isInvalid())
9864 return S.ActOnExprStmt(Assignment);
9867 // - if the subobject is an array, each element is assigned, in the
9868 // manner appropriate to the element type;
9870 // Construct a loop over the array bounds, e.g.,
9872 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9874 // that will copy each of the array elements.
9875 QualType SizeType = S.Context.getSizeType();
9877 // Create the iteration variable.
9878 IdentifierInfo *IterationVarName = nullptr;
9881 llvm::raw_svector_ostream OS(Str);
9882 OS << "__i" << Depth;
9883 IterationVarName = &S.Context.Idents.get(OS.str());
9885 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9886 IterationVarName, SizeType,
9887 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9890 // Initialize the iteration variable to zero.
9891 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9892 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9894 // Creates a reference to the iteration variable.
9895 RefBuilder IterationVarRef(IterationVar, SizeType);
9896 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9898 // Create the DeclStmt that holds the iteration variable.
9899 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9901 // Subscript the "from" and "to" expressions with the iteration variable.
9902 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9903 MoveCastBuilder FromIndexMove(FromIndexCopy);
9904 const ExprBuilder *FromIndex;
9906 FromIndex = &FromIndexCopy;
9908 FromIndex = &FromIndexMove;
9910 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9912 // Build the copy/move for an individual element of the array.
9914 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9915 ToIndex, *FromIndex, CopyingBaseSubobject,
9916 Copying, Depth + 1);
9917 // Bail out if copying fails or if we determined that we should use memcpy.
9918 if (Copy.isInvalid() || !Copy.get())
9921 // Create the comparison against the array bound.
9923 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9925 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9926 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9927 BO_NE, S.Context.BoolTy,
9928 VK_RValue, OK_Ordinary, Loc, false);
9930 // Create the pre-increment of the iteration variable.
9932 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9933 SizeType, VK_LValue, OK_Ordinary, Loc);
9935 // Construct the loop that copies all elements of this array.
9936 return S.ActOnForStmt(Loc, Loc, InitStmt,
9937 S.MakeFullExpr(Comparison),
9938 nullptr, S.MakeFullDiscardedValueExpr(Increment),
9943 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9944 const ExprBuilder &To, const ExprBuilder &From,
9945 bool CopyingBaseSubobject, bool Copying) {
9946 // Maybe we should use a memcpy?
9947 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9948 T.isTriviallyCopyableType(S.Context))
9949 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9951 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9952 CopyingBaseSubobject,
9955 // If we ended up picking a trivial assignment operator for an array of a
9956 // non-trivially-copyable class type, just emit a memcpy.
9957 if (!Result.isInvalid() && !Result.get())
9958 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9963 Sema::ImplicitExceptionSpecification
9964 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9965 CXXRecordDecl *ClassDecl = MD->getParent();
9967 ImplicitExceptionSpecification ExceptSpec(*this);
9968 if (ClassDecl->isInvalidDecl())
9971 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9972 assert(T->getNumParams() == 1 && "not a copy assignment op");
9974 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9976 // C++ [except.spec]p14:
9977 // An implicitly declared special member function (Clause 12) shall have an
9978 // exception-specification. [...]
9980 // It is unspecified whether or not an implicit copy assignment operator
9981 // attempts to deduplicate calls to assignment operators of virtual bases are
9982 // made. As such, this exception specification is effectively unspecified.
9983 // Based on a similar decision made for constness in C++0x, we're erring on
9984 // the side of assuming such calls to be made regardless of whether they
9986 for (const auto &Base : ClassDecl->bases()) {
9987 if (Base.isVirtual())
9990 CXXRecordDecl *BaseClassDecl
9991 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9992 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9993 ArgQuals, false, 0))
9994 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9997 for (const auto &Base : ClassDecl->vbases()) {
9998 CXXRecordDecl *BaseClassDecl
9999 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10000 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10001 ArgQuals, false, 0))
10002 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10005 for (const auto *Field : ClassDecl->fields()) {
10006 QualType FieldType = Context.getBaseElementType(Field->getType());
10007 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10008 if (CXXMethodDecl *CopyAssign =
10009 LookupCopyingAssignment(FieldClassDecl,
10010 ArgQuals | FieldType.getCVRQualifiers(),
10012 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10019 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10020 // Note: The following rules are largely analoguous to the copy
10021 // constructor rules. Note that virtual bases are not taken into account
10022 // for determining the argument type of the operator. Note also that
10023 // operators taking an object instead of a reference are allowed.
10024 assert(ClassDecl->needsImplicitCopyAssignment());
10026 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10027 if (DSM.isAlreadyBeingDeclared())
10030 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10031 QualType RetType = Context.getLValueReferenceType(ArgType);
10032 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10034 ArgType = ArgType.withConst();
10035 ArgType = Context.getLValueReferenceType(ArgType);
10037 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10041 // An implicitly-declared copy assignment operator is an inline public
10042 // member of its class.
10043 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10044 SourceLocation ClassLoc = ClassDecl->getLocation();
10045 DeclarationNameInfo NameInfo(Name, ClassLoc);
10046 CXXMethodDecl *CopyAssignment =
10047 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10048 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10049 /*isInline=*/true, Constexpr, SourceLocation());
10050 CopyAssignment->setAccess(AS_public);
10051 CopyAssignment->setDefaulted();
10052 CopyAssignment->setImplicit();
10054 if (getLangOpts().CUDA) {
10055 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10057 /* ConstRHS */ Const,
10058 /* Diagnose */ false);
10061 // Build an exception specification pointing back at this member.
10062 FunctionProtoType::ExtProtoInfo EPI =
10063 getImplicitMethodEPI(*this, CopyAssignment);
10064 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10066 // Add the parameter to the operator.
10067 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10068 ClassLoc, ClassLoc,
10069 /*Id=*/nullptr, ArgType,
10070 /*TInfo=*/nullptr, SC_None,
10072 CopyAssignment->setParams(FromParam);
10074 AddOverriddenMethods(ClassDecl, CopyAssignment);
10076 CopyAssignment->setTrivial(
10077 ClassDecl->needsOverloadResolutionForCopyAssignment()
10078 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10079 : ClassDecl->hasTrivialCopyAssignment());
10081 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10082 SetDeclDeleted(CopyAssignment, ClassLoc);
10084 // Note that we have added this copy-assignment operator.
10085 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10087 if (Scope *S = getScopeForContext(ClassDecl))
10088 PushOnScopeChains(CopyAssignment, S, false);
10089 ClassDecl->addDecl(CopyAssignment);
10091 return CopyAssignment;
10094 /// Diagnose an implicit copy operation for a class which is odr-used, but
10095 /// which is deprecated because the class has a user-declared copy constructor,
10096 /// copy assignment operator, or destructor.
10097 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10098 SourceLocation UseLoc) {
10099 assert(CopyOp->isImplicit());
10101 CXXRecordDecl *RD = CopyOp->getParent();
10102 CXXMethodDecl *UserDeclaredOperation = nullptr;
10104 // In Microsoft mode, assignment operations don't affect constructors and
10106 if (RD->hasUserDeclaredDestructor()) {
10107 UserDeclaredOperation = RD->getDestructor();
10108 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10109 RD->hasUserDeclaredCopyConstructor() &&
10110 !S.getLangOpts().MSVCCompat) {
10111 // Find any user-declared copy constructor.
10112 for (auto *I : RD->ctors()) {
10113 if (I->isCopyConstructor()) {
10114 UserDeclaredOperation = I;
10118 assert(UserDeclaredOperation);
10119 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10120 RD->hasUserDeclaredCopyAssignment() &&
10121 !S.getLangOpts().MSVCCompat) {
10122 // Find any user-declared move assignment operator.
10123 for (auto *I : RD->methods()) {
10124 if (I->isCopyAssignmentOperator()) {
10125 UserDeclaredOperation = I;
10129 assert(UserDeclaredOperation);
10132 if (UserDeclaredOperation) {
10133 S.Diag(UserDeclaredOperation->getLocation(),
10134 diag::warn_deprecated_copy_operation)
10135 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10136 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10137 S.Diag(UseLoc, diag::note_member_synthesized_at)
10138 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10139 : Sema::CXXCopyAssignment)
10144 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10145 CXXMethodDecl *CopyAssignOperator) {
10146 assert((CopyAssignOperator->isDefaulted() &&
10147 CopyAssignOperator->isOverloadedOperator() &&
10148 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10149 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10150 !CopyAssignOperator->isDeleted()) &&
10151 "DefineImplicitCopyAssignment called for wrong function");
10153 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10155 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10156 CopyAssignOperator->setInvalidDecl();
10160 // C++11 [class.copy]p18:
10161 // The [definition of an implicitly declared copy assignment operator] is
10162 // deprecated if the class has a user-declared copy constructor or a
10163 // user-declared destructor.
10164 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10165 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10167 CopyAssignOperator->markUsed(Context);
10169 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10170 DiagnosticErrorTrap Trap(Diags);
10172 // C++0x [class.copy]p30:
10173 // The implicitly-defined or explicitly-defaulted copy assignment operator
10174 // for a non-union class X performs memberwise copy assignment of its
10175 // subobjects. The direct base classes of X are assigned first, in the
10176 // order of their declaration in the base-specifier-list, and then the
10177 // immediate non-static data members of X are assigned, in the order in
10178 // which they were declared in the class definition.
10180 // The statements that form the synthesized function body.
10181 SmallVector<Stmt*, 8> Statements;
10183 // The parameter for the "other" object, which we are copying from.
10184 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10185 Qualifiers OtherQuals = Other->getType().getQualifiers();
10186 QualType OtherRefType = Other->getType();
10187 if (const LValueReferenceType *OtherRef
10188 = OtherRefType->getAs<LValueReferenceType>()) {
10189 OtherRefType = OtherRef->getPointeeType();
10190 OtherQuals = OtherRefType.getQualifiers();
10193 // Our location for everything implicitly-generated.
10194 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10195 ? CopyAssignOperator->getLocEnd()
10196 : CopyAssignOperator->getLocation();
10198 // Builds a DeclRefExpr for the "other" object.
10199 RefBuilder OtherRef(Other, OtherRefType);
10201 // Builds the "this" pointer.
10204 // Assign base classes.
10205 bool Invalid = false;
10206 for (auto &Base : ClassDecl->bases()) {
10207 // Form the assignment:
10208 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10209 QualType BaseType = Base.getType().getUnqualifiedType();
10210 if (!BaseType->isRecordType()) {
10215 CXXCastPath BasePath;
10216 BasePath.push_back(&Base);
10218 // Construct the "from" expression, which is an implicit cast to the
10219 // appropriately-qualified base type.
10220 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10221 VK_LValue, BasePath);
10223 // Dereference "this".
10224 DerefBuilder DerefThis(This);
10225 CastBuilder To(DerefThis,
10226 Context.getCVRQualifiedType(
10227 BaseType, CopyAssignOperator->getTypeQualifiers()),
10228 VK_LValue, BasePath);
10231 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10233 /*CopyingBaseSubobject=*/true,
10235 if (Copy.isInvalid()) {
10236 Diag(CurrentLocation, diag::note_member_synthesized_at)
10237 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10238 CopyAssignOperator->setInvalidDecl();
10242 // Success! Record the copy.
10243 Statements.push_back(Copy.getAs<Expr>());
10246 // Assign non-static members.
10247 for (auto *Field : ClassDecl->fields()) {
10248 // FIXME: We should form some kind of AST representation for the implied
10249 // memcpy in a union copy operation.
10250 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10253 if (Field->isInvalidDecl()) {
10258 // Check for members of reference type; we can't copy those.
10259 if (Field->getType()->isReferenceType()) {
10260 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10261 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10262 Diag(Field->getLocation(), diag::note_declared_at);
10263 Diag(CurrentLocation, diag::note_member_synthesized_at)
10264 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10269 // Check for members of const-qualified, non-class type.
10270 QualType BaseType = Context.getBaseElementType(Field->getType());
10271 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10272 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10273 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10274 Diag(Field->getLocation(), diag::note_declared_at);
10275 Diag(CurrentLocation, diag::note_member_synthesized_at)
10276 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10281 // Suppress assigning zero-width bitfields.
10282 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10285 QualType FieldType = Field->getType().getNonReferenceType();
10286 if (FieldType->isIncompleteArrayType()) {
10287 assert(ClassDecl->hasFlexibleArrayMember() &&
10288 "Incomplete array type is not valid");
10292 // Build references to the field in the object we're copying from and to.
10293 CXXScopeSpec SS; // Intentionally empty
10294 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10296 MemberLookup.addDecl(Field);
10297 MemberLookup.resolveKind();
10299 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10301 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10303 // Build the copy of this field.
10304 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10306 /*CopyingBaseSubobject=*/false,
10308 if (Copy.isInvalid()) {
10309 Diag(CurrentLocation, diag::note_member_synthesized_at)
10310 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10311 CopyAssignOperator->setInvalidDecl();
10315 // Success! Record the copy.
10316 Statements.push_back(Copy.getAs<Stmt>());
10320 // Add a "return *this;"
10321 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10323 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10324 if (Return.isInvalid())
10327 Statements.push_back(Return.getAs<Stmt>());
10329 if (Trap.hasErrorOccurred()) {
10330 Diag(CurrentLocation, diag::note_member_synthesized_at)
10331 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10337 // The exception specification is needed because we are defining the
10339 ResolveExceptionSpec(CurrentLocation,
10340 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10343 CopyAssignOperator->setInvalidDecl();
10349 CompoundScopeRAII CompoundScope(*this);
10350 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10351 /*isStmtExpr=*/false);
10352 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10354 CopyAssignOperator->setBody(Body.getAs<Stmt>());
10356 if (ASTMutationListener *L = getASTMutationListener()) {
10357 L->CompletedImplicitDefinition(CopyAssignOperator);
10361 Sema::ImplicitExceptionSpecification
10362 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10363 CXXRecordDecl *ClassDecl = MD->getParent();
10365 ImplicitExceptionSpecification ExceptSpec(*this);
10366 if (ClassDecl->isInvalidDecl())
10369 // C++0x [except.spec]p14:
10370 // An implicitly declared special member function (Clause 12) shall have an
10371 // exception-specification. [...]
10373 // It is unspecified whether or not an implicit move assignment operator
10374 // attempts to deduplicate calls to assignment operators of virtual bases are
10375 // made. As such, this exception specification is effectively unspecified.
10376 // Based on a similar decision made for constness in C++0x, we're erring on
10377 // the side of assuming such calls to be made regardless of whether they
10378 // actually happen.
10379 // Note that a move constructor is not implicitly declared when there are
10380 // virtual bases, but it can still be user-declared and explicitly defaulted.
10381 for (const auto &Base : ClassDecl->bases()) {
10382 if (Base.isVirtual())
10385 CXXRecordDecl *BaseClassDecl
10386 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10387 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10389 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10392 for (const auto &Base : ClassDecl->vbases()) {
10393 CXXRecordDecl *BaseClassDecl
10394 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10395 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10397 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10400 for (const auto *Field : ClassDecl->fields()) {
10401 QualType FieldType = Context.getBaseElementType(Field->getType());
10402 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10403 if (CXXMethodDecl *MoveAssign =
10404 LookupMovingAssignment(FieldClassDecl,
10405 FieldType.getCVRQualifiers(),
10407 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10414 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10415 assert(ClassDecl->needsImplicitMoveAssignment());
10417 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10418 if (DSM.isAlreadyBeingDeclared())
10421 // Note: The following rules are largely analoguous to the move
10422 // constructor rules.
10424 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10425 QualType RetType = Context.getLValueReferenceType(ArgType);
10426 ArgType = Context.getRValueReferenceType(ArgType);
10428 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10432 // An implicitly-declared move assignment operator is an inline public
10433 // member of its class.
10434 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10435 SourceLocation ClassLoc = ClassDecl->getLocation();
10436 DeclarationNameInfo NameInfo(Name, ClassLoc);
10437 CXXMethodDecl *MoveAssignment =
10438 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10439 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10440 /*isInline=*/true, Constexpr, SourceLocation());
10441 MoveAssignment->setAccess(AS_public);
10442 MoveAssignment->setDefaulted();
10443 MoveAssignment->setImplicit();
10445 if (getLangOpts().CUDA) {
10446 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10448 /* ConstRHS */ false,
10449 /* Diagnose */ false);
10452 // Build an exception specification pointing back at this member.
10453 FunctionProtoType::ExtProtoInfo EPI =
10454 getImplicitMethodEPI(*this, MoveAssignment);
10455 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10457 // Add the parameter to the operator.
10458 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10459 ClassLoc, ClassLoc,
10460 /*Id=*/nullptr, ArgType,
10461 /*TInfo=*/nullptr, SC_None,
10463 MoveAssignment->setParams(FromParam);
10465 AddOverriddenMethods(ClassDecl, MoveAssignment);
10467 MoveAssignment->setTrivial(
10468 ClassDecl->needsOverloadResolutionForMoveAssignment()
10469 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10470 : ClassDecl->hasTrivialMoveAssignment());
10472 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10473 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10474 SetDeclDeleted(MoveAssignment, ClassLoc);
10477 // Note that we have added this copy-assignment operator.
10478 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10480 if (Scope *S = getScopeForContext(ClassDecl))
10481 PushOnScopeChains(MoveAssignment, S, false);
10482 ClassDecl->addDecl(MoveAssignment);
10484 return MoveAssignment;
10487 /// Check if we're implicitly defining a move assignment operator for a class
10488 /// with virtual bases. Such a move assignment might move-assign the virtual
10489 /// base multiple times.
10490 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10491 SourceLocation CurrentLocation) {
10492 assert(!Class->isDependentContext() && "should not define dependent move");
10494 // Only a virtual base could get implicitly move-assigned multiple times.
10495 // Only a non-trivial move assignment can observe this. We only want to
10496 // diagnose if we implicitly define an assignment operator that assigns
10497 // two base classes, both of which move-assign the same virtual base.
10498 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10499 Class->getNumBases() < 2)
10502 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10503 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10506 for (auto &BI : Class->bases()) {
10507 Worklist.push_back(&BI);
10508 while (!Worklist.empty()) {
10509 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10510 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10512 // If the base has no non-trivial move assignment operators,
10513 // we don't care about moves from it.
10514 if (!Base->hasNonTrivialMoveAssignment())
10517 // If there's nothing virtual here, skip it.
10518 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10521 // If we're not actually going to call a move assignment for this base,
10522 // or the selected move assignment is trivial, skip it.
10523 Sema::SpecialMemberOverloadResult *SMOR =
10524 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10525 /*ConstArg*/false, /*VolatileArg*/false,
10526 /*RValueThis*/true, /*ConstThis*/false,
10527 /*VolatileThis*/false);
10528 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10529 !SMOR->getMethod()->isMoveAssignmentOperator())
10532 if (BaseSpec->isVirtual()) {
10533 // We're going to move-assign this virtual base, and its move
10534 // assignment operator is not trivial. If this can happen for
10535 // multiple distinct direct bases of Class, diagnose it. (If it
10536 // only happens in one base, we'll diagnose it when synthesizing
10537 // that base class's move assignment operator.)
10538 CXXBaseSpecifier *&Existing =
10539 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10541 if (Existing && Existing != &BI) {
10542 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10544 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10545 << (Base->getCanonicalDecl() ==
10546 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10547 << Base << Existing->getType() << Existing->getSourceRange();
10548 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10549 << (Base->getCanonicalDecl() ==
10550 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10551 << Base << BI.getType() << BaseSpec->getSourceRange();
10553 // Only diagnose each vbase once.
10554 Existing = nullptr;
10557 // Only walk over bases that have defaulted move assignment operators.
10558 // We assume that any user-provided move assignment operator handles
10559 // the multiple-moves-of-vbase case itself somehow.
10560 if (!SMOR->getMethod()->isDefaulted())
10563 // We're going to move the base classes of Base. Add them to the list.
10564 for (auto &BI : Base->bases())
10565 Worklist.push_back(&BI);
10571 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10572 CXXMethodDecl *MoveAssignOperator) {
10573 assert((MoveAssignOperator->isDefaulted() &&
10574 MoveAssignOperator->isOverloadedOperator() &&
10575 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10576 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10577 !MoveAssignOperator->isDeleted()) &&
10578 "DefineImplicitMoveAssignment called for wrong function");
10580 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10582 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10583 MoveAssignOperator->setInvalidDecl();
10587 MoveAssignOperator->markUsed(Context);
10589 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10590 DiagnosticErrorTrap Trap(Diags);
10592 // C++0x [class.copy]p28:
10593 // The implicitly-defined or move assignment operator for a non-union class
10594 // X performs memberwise move assignment of its subobjects. The direct base
10595 // classes of X are assigned first, in the order of their declaration in the
10596 // base-specifier-list, and then the immediate non-static data members of X
10597 // are assigned, in the order in which they were declared in the class
10600 // Issue a warning if our implicit move assignment operator will move
10601 // from a virtual base more than once.
10602 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10604 // The statements that form the synthesized function body.
10605 SmallVector<Stmt*, 8> Statements;
10607 // The parameter for the "other" object, which we are move from.
10608 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10609 QualType OtherRefType = Other->getType()->
10610 getAs<RValueReferenceType>()->getPointeeType();
10611 assert(!OtherRefType.getQualifiers() &&
10612 "Bad argument type of defaulted move assignment");
10614 // Our location for everything implicitly-generated.
10615 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10616 ? MoveAssignOperator->getLocEnd()
10617 : MoveAssignOperator->getLocation();
10619 // Builds a reference to the "other" object.
10620 RefBuilder OtherRef(Other, OtherRefType);
10622 MoveCastBuilder MoveOther(OtherRef);
10624 // Builds the "this" pointer.
10627 // Assign base classes.
10628 bool Invalid = false;
10629 for (auto &Base : ClassDecl->bases()) {
10630 // C++11 [class.copy]p28:
10631 // It is unspecified whether subobjects representing virtual base classes
10632 // are assigned more than once by the implicitly-defined copy assignment
10634 // FIXME: Do not assign to a vbase that will be assigned by some other base
10635 // class. For a move-assignment, this can result in the vbase being moved
10638 // Form the assignment:
10639 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10640 QualType BaseType = Base.getType().getUnqualifiedType();
10641 if (!BaseType->isRecordType()) {
10646 CXXCastPath BasePath;
10647 BasePath.push_back(&Base);
10649 // Construct the "from" expression, which is an implicit cast to the
10650 // appropriately-qualified base type.
10651 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10653 // Dereference "this".
10654 DerefBuilder DerefThis(This);
10656 // Implicitly cast "this" to the appropriately-qualified base type.
10657 CastBuilder To(DerefThis,
10658 Context.getCVRQualifiedType(
10659 BaseType, MoveAssignOperator->getTypeQualifiers()),
10660 VK_LValue, BasePath);
10663 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10665 /*CopyingBaseSubobject=*/true,
10666 /*Copying=*/false);
10667 if (Move.isInvalid()) {
10668 Diag(CurrentLocation, diag::note_member_synthesized_at)
10669 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10670 MoveAssignOperator->setInvalidDecl();
10674 // Success! Record the move.
10675 Statements.push_back(Move.getAs<Expr>());
10678 // Assign non-static members.
10679 for (auto *Field : ClassDecl->fields()) {
10680 // FIXME: We should form some kind of AST representation for the implied
10681 // memcpy in a union copy operation.
10682 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10685 if (Field->isInvalidDecl()) {
10690 // Check for members of reference type; we can't move those.
10691 if (Field->getType()->isReferenceType()) {
10692 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10693 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10694 Diag(Field->getLocation(), diag::note_declared_at);
10695 Diag(CurrentLocation, diag::note_member_synthesized_at)
10696 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10701 // Check for members of const-qualified, non-class type.
10702 QualType BaseType = Context.getBaseElementType(Field->getType());
10703 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10704 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10705 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10706 Diag(Field->getLocation(), diag::note_declared_at);
10707 Diag(CurrentLocation, diag::note_member_synthesized_at)
10708 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10713 // Suppress assigning zero-width bitfields.
10714 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10717 QualType FieldType = Field->getType().getNonReferenceType();
10718 if (FieldType->isIncompleteArrayType()) {
10719 assert(ClassDecl->hasFlexibleArrayMember() &&
10720 "Incomplete array type is not valid");
10724 // Build references to the field in the object we're copying from and to.
10725 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10727 MemberLookup.addDecl(Field);
10728 MemberLookup.resolveKind();
10729 MemberBuilder From(MoveOther, OtherRefType,
10730 /*IsArrow=*/false, MemberLookup);
10731 MemberBuilder To(This, getCurrentThisType(),
10732 /*IsArrow=*/true, MemberLookup);
10734 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10735 "Member reference with rvalue base must be rvalue except for reference "
10736 "members, which aren't allowed for move assignment.");
10738 // Build the move of this field.
10739 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10741 /*CopyingBaseSubobject=*/false,
10742 /*Copying=*/false);
10743 if (Move.isInvalid()) {
10744 Diag(CurrentLocation, diag::note_member_synthesized_at)
10745 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10746 MoveAssignOperator->setInvalidDecl();
10750 // Success! Record the copy.
10751 Statements.push_back(Move.getAs<Stmt>());
10755 // Add a "return *this;"
10756 ExprResult ThisObj =
10757 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10759 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10760 if (Return.isInvalid())
10763 Statements.push_back(Return.getAs<Stmt>());
10765 if (Trap.hasErrorOccurred()) {
10766 Diag(CurrentLocation, diag::note_member_synthesized_at)
10767 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10773 // The exception specification is needed because we are defining the
10775 ResolveExceptionSpec(CurrentLocation,
10776 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10779 MoveAssignOperator->setInvalidDecl();
10785 CompoundScopeRAII CompoundScope(*this);
10786 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10787 /*isStmtExpr=*/false);
10788 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10790 MoveAssignOperator->setBody(Body.getAs<Stmt>());
10792 if (ASTMutationListener *L = getASTMutationListener()) {
10793 L->CompletedImplicitDefinition(MoveAssignOperator);
10797 Sema::ImplicitExceptionSpecification
10798 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10799 CXXRecordDecl *ClassDecl = MD->getParent();
10801 ImplicitExceptionSpecification ExceptSpec(*this);
10802 if (ClassDecl->isInvalidDecl())
10805 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10806 assert(T->getNumParams() >= 1 && "not a copy ctor");
10807 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10809 // C++ [except.spec]p14:
10810 // An implicitly declared special member function (Clause 12) shall have an
10811 // exception-specification. [...]
10812 for (const auto &Base : ClassDecl->bases()) {
10813 // Virtual bases are handled below.
10814 if (Base.isVirtual())
10817 CXXRecordDecl *BaseClassDecl
10818 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10819 if (CXXConstructorDecl *CopyConstructor =
10820 LookupCopyingConstructor(BaseClassDecl, Quals))
10821 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10823 for (const auto &Base : ClassDecl->vbases()) {
10824 CXXRecordDecl *BaseClassDecl
10825 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10826 if (CXXConstructorDecl *CopyConstructor =
10827 LookupCopyingConstructor(BaseClassDecl, Quals))
10828 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10830 for (const auto *Field : ClassDecl->fields()) {
10831 QualType FieldType = Context.getBaseElementType(Field->getType());
10832 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10833 if (CXXConstructorDecl *CopyConstructor =
10834 LookupCopyingConstructor(FieldClassDecl,
10835 Quals | FieldType.getCVRQualifiers()))
10836 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10843 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10844 CXXRecordDecl *ClassDecl) {
10845 // C++ [class.copy]p4:
10846 // If the class definition does not explicitly declare a copy
10847 // constructor, one is declared implicitly.
10848 assert(ClassDecl->needsImplicitCopyConstructor());
10850 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10851 if (DSM.isAlreadyBeingDeclared())
10854 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10855 QualType ArgType = ClassType;
10856 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10858 ArgType = ArgType.withConst();
10859 ArgType = Context.getLValueReferenceType(ArgType);
10861 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10862 CXXCopyConstructor,
10865 DeclarationName Name
10866 = Context.DeclarationNames.getCXXConstructorName(
10867 Context.getCanonicalType(ClassType));
10868 SourceLocation ClassLoc = ClassDecl->getLocation();
10869 DeclarationNameInfo NameInfo(Name, ClassLoc);
10871 // An implicitly-declared copy constructor is an inline public
10872 // member of its class.
10873 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10874 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10875 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10877 CopyConstructor->setAccess(AS_public);
10878 CopyConstructor->setDefaulted();
10880 if (getLangOpts().CUDA) {
10881 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10883 /* ConstRHS */ Const,
10884 /* Diagnose */ false);
10887 // Build an exception specification pointing back at this member.
10888 FunctionProtoType::ExtProtoInfo EPI =
10889 getImplicitMethodEPI(*this, CopyConstructor);
10890 CopyConstructor->setType(
10891 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10893 // Add the parameter to the constructor.
10894 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10895 ClassLoc, ClassLoc,
10896 /*IdentifierInfo=*/nullptr,
10897 ArgType, /*TInfo=*/nullptr,
10899 CopyConstructor->setParams(FromParam);
10901 CopyConstructor->setTrivial(
10902 ClassDecl->needsOverloadResolutionForCopyConstructor()
10903 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10904 : ClassDecl->hasTrivialCopyConstructor());
10906 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10907 SetDeclDeleted(CopyConstructor, ClassLoc);
10909 // Note that we have declared this constructor.
10910 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10912 if (Scope *S = getScopeForContext(ClassDecl))
10913 PushOnScopeChains(CopyConstructor, S, false);
10914 ClassDecl->addDecl(CopyConstructor);
10916 return CopyConstructor;
10919 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10920 CXXConstructorDecl *CopyConstructor) {
10921 assert((CopyConstructor->isDefaulted() &&
10922 CopyConstructor->isCopyConstructor() &&
10923 !CopyConstructor->doesThisDeclarationHaveABody() &&
10924 !CopyConstructor->isDeleted()) &&
10925 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10927 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10928 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10930 // C++11 [class.copy]p7:
10931 // The [definition of an implicitly declared copy constructor] is
10932 // deprecated if the class has a user-declared copy assignment operator
10933 // or a user-declared destructor.
10934 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10935 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10937 SynthesizedFunctionScope Scope(*this, CopyConstructor);
10938 DiagnosticErrorTrap Trap(Diags);
10940 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10941 Trap.hasErrorOccurred()) {
10942 Diag(CurrentLocation, diag::note_member_synthesized_at)
10943 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10944 CopyConstructor->setInvalidDecl();
10946 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10947 ? CopyConstructor->getLocEnd()
10948 : CopyConstructor->getLocation();
10949 Sema::CompoundScopeRAII CompoundScope(*this);
10950 CopyConstructor->setBody(
10951 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10954 // The exception specification is needed because we are defining the
10956 ResolveExceptionSpec(CurrentLocation,
10957 CopyConstructor->getType()->castAs<FunctionProtoType>());
10959 CopyConstructor->markUsed(Context);
10960 MarkVTableUsed(CurrentLocation, ClassDecl);
10962 if (ASTMutationListener *L = getASTMutationListener()) {
10963 L->CompletedImplicitDefinition(CopyConstructor);
10967 Sema::ImplicitExceptionSpecification
10968 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10969 CXXRecordDecl *ClassDecl = MD->getParent();
10971 // C++ [except.spec]p14:
10972 // An implicitly declared special member function (Clause 12) shall have an
10973 // exception-specification. [...]
10974 ImplicitExceptionSpecification ExceptSpec(*this);
10975 if (ClassDecl->isInvalidDecl())
10978 // Direct base-class constructors.
10979 for (const auto &B : ClassDecl->bases()) {
10980 if (B.isVirtual()) // Handled below.
10983 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10984 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10985 CXXConstructorDecl *Constructor =
10986 LookupMovingConstructor(BaseClassDecl, 0);
10987 // If this is a deleted function, add it anyway. This might be conformant
10988 // with the standard. This might not. I'm not sure. It might not matter.
10990 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10994 // Virtual base-class constructors.
10995 for (const auto &B : ClassDecl->vbases()) {
10996 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10997 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10998 CXXConstructorDecl *Constructor =
10999 LookupMovingConstructor(BaseClassDecl, 0);
11000 // If this is a deleted function, add it anyway. This might be conformant
11001 // with the standard. This might not. I'm not sure. It might not matter.
11003 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11007 // Field constructors.
11008 for (const auto *F : ClassDecl->fields()) {
11009 QualType FieldType = Context.getBaseElementType(F->getType());
11010 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11011 CXXConstructorDecl *Constructor =
11012 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11013 // If this is a deleted function, add it anyway. This might be conformant
11014 // with the standard. This might not. I'm not sure. It might not matter.
11015 // In particular, the problem is that this function never gets called. It
11016 // might just be ill-formed because this function attempts to refer to
11017 // a deleted function here.
11019 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11026 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11027 CXXRecordDecl *ClassDecl) {
11028 assert(ClassDecl->needsImplicitMoveConstructor());
11030 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11031 if (DSM.isAlreadyBeingDeclared())
11034 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11035 QualType ArgType = Context.getRValueReferenceType(ClassType);
11037 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11038 CXXMoveConstructor,
11041 DeclarationName Name
11042 = Context.DeclarationNames.getCXXConstructorName(
11043 Context.getCanonicalType(ClassType));
11044 SourceLocation ClassLoc = ClassDecl->getLocation();
11045 DeclarationNameInfo NameInfo(Name, ClassLoc);
11047 // C++11 [class.copy]p11:
11048 // An implicitly-declared copy/move constructor is an inline public
11049 // member of its class.
11050 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11051 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11052 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11054 MoveConstructor->setAccess(AS_public);
11055 MoveConstructor->setDefaulted();
11057 if (getLangOpts().CUDA) {
11058 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11060 /* ConstRHS */ false,
11061 /* Diagnose */ false);
11064 // Build an exception specification pointing back at this member.
11065 FunctionProtoType::ExtProtoInfo EPI =
11066 getImplicitMethodEPI(*this, MoveConstructor);
11067 MoveConstructor->setType(
11068 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11070 // Add the parameter to the constructor.
11071 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11072 ClassLoc, ClassLoc,
11073 /*IdentifierInfo=*/nullptr,
11074 ArgType, /*TInfo=*/nullptr,
11076 MoveConstructor->setParams(FromParam);
11078 MoveConstructor->setTrivial(
11079 ClassDecl->needsOverloadResolutionForMoveConstructor()
11080 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11081 : ClassDecl->hasTrivialMoveConstructor());
11083 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11084 ClassDecl->setImplicitMoveConstructorIsDeleted();
11085 SetDeclDeleted(MoveConstructor, ClassLoc);
11088 // Note that we have declared this constructor.
11089 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11091 if (Scope *S = getScopeForContext(ClassDecl))
11092 PushOnScopeChains(MoveConstructor, S, false);
11093 ClassDecl->addDecl(MoveConstructor);
11095 return MoveConstructor;
11098 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11099 CXXConstructorDecl *MoveConstructor) {
11100 assert((MoveConstructor->isDefaulted() &&
11101 MoveConstructor->isMoveConstructor() &&
11102 !MoveConstructor->doesThisDeclarationHaveABody() &&
11103 !MoveConstructor->isDeleted()) &&
11104 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11106 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11107 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11109 SynthesizedFunctionScope Scope(*this, MoveConstructor);
11110 DiagnosticErrorTrap Trap(Diags);
11112 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11113 Trap.hasErrorOccurred()) {
11114 Diag(CurrentLocation, diag::note_member_synthesized_at)
11115 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11116 MoveConstructor->setInvalidDecl();
11118 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11119 ? MoveConstructor->getLocEnd()
11120 : MoveConstructor->getLocation();
11121 Sema::CompoundScopeRAII CompoundScope(*this);
11122 MoveConstructor->setBody(ActOnCompoundStmt(
11123 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11126 // The exception specification is needed because we are defining the
11128 ResolveExceptionSpec(CurrentLocation,
11129 MoveConstructor->getType()->castAs<FunctionProtoType>());
11131 MoveConstructor->markUsed(Context);
11132 MarkVTableUsed(CurrentLocation, ClassDecl);
11134 if (ASTMutationListener *L = getASTMutationListener()) {
11135 L->CompletedImplicitDefinition(MoveConstructor);
11139 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11140 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11143 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11144 SourceLocation CurrentLocation,
11145 CXXConversionDecl *Conv) {
11146 CXXRecordDecl *Lambda = Conv->getParent();
11147 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11148 // If we are defining a specialization of a conversion to function-ptr
11149 // cache the deduced template arguments for this specialization
11150 // so that we can use them to retrieve the corresponding call-operator
11151 // and static-invoker.
11152 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11154 // Retrieve the corresponding call-operator specialization.
11155 if (Lambda->isGenericLambda()) {
11156 assert(Conv->isFunctionTemplateSpecialization());
11157 FunctionTemplateDecl *CallOpTemplate =
11158 CallOp->getDescribedFunctionTemplate();
11159 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11160 void *InsertPos = nullptr;
11161 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11162 DeducedTemplateArgs->asArray(),
11164 assert(CallOpSpec &&
11165 "Conversion operator must have a corresponding call operator");
11166 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11168 // Mark the call operator referenced (and add to pending instantiations
11170 // For both the conversion and static-invoker template specializations
11171 // we construct their body's in this function, so no need to add them
11172 // to the PendingInstantiations.
11173 MarkFunctionReferenced(CurrentLocation, CallOp);
11175 SynthesizedFunctionScope Scope(*this, Conv);
11176 DiagnosticErrorTrap Trap(Diags);
11178 // Retrieve the static invoker...
11179 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11180 // ... and get the corresponding specialization for a generic lambda.
11181 if (Lambda->isGenericLambda()) {
11182 assert(DeducedTemplateArgs &&
11183 "Must have deduced template arguments from Conversion Operator");
11184 FunctionTemplateDecl *InvokeTemplate =
11185 Invoker->getDescribedFunctionTemplate();
11186 void *InsertPos = nullptr;
11187 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11188 DeducedTemplateArgs->asArray(),
11190 assert(InvokeSpec &&
11191 "Must have a corresponding static invoker specialization");
11192 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11194 // Construct the body of the conversion function { return __invoke; }.
11195 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11196 VK_LValue, Conv->getLocation()).get();
11197 assert(FunctionRef && "Can't refer to __invoke function?");
11198 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11199 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11200 Conv->getLocation(),
11201 Conv->getLocation()));
11203 Conv->markUsed(Context);
11204 Conv->setReferenced();
11206 // Fill in the __invoke function with a dummy implementation. IR generation
11207 // will fill in the actual details.
11208 Invoker->markUsed(Context);
11209 Invoker->setReferenced();
11210 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11212 if (ASTMutationListener *L = getASTMutationListener()) {
11213 L->CompletedImplicitDefinition(Conv);
11214 L->CompletedImplicitDefinition(Invoker);
11220 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11221 SourceLocation CurrentLocation,
11222 CXXConversionDecl *Conv)
11224 assert(!Conv->getParent()->isGenericLambda());
11226 Conv->markUsed(Context);
11228 SynthesizedFunctionScope Scope(*this, Conv);
11229 DiagnosticErrorTrap Trap(Diags);
11231 // Copy-initialize the lambda object as needed to capture it.
11232 Expr *This = ActOnCXXThis(CurrentLocation).get();
11233 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11235 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11236 Conv->getLocation(),
11239 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11240 // behavior. Note that only the general conversion function does this
11241 // (since it's unusable otherwise); in the case where we inline the
11242 // block literal, it has block literal lifetime semantics.
11243 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11244 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11245 CK_CopyAndAutoreleaseBlockObject,
11246 BuildBlock.get(), nullptr, VK_RValue);
11248 if (BuildBlock.isInvalid()) {
11249 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11250 Conv->setInvalidDecl();
11254 // Create the return statement that returns the block from the conversion
11256 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11257 if (Return.isInvalid()) {
11258 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11259 Conv->setInvalidDecl();
11263 // Set the body of the conversion function.
11264 Stmt *ReturnS = Return.get();
11265 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11266 Conv->getLocation(),
11267 Conv->getLocation()));
11269 // We're done; notify the mutation listener, if any.
11270 if (ASTMutationListener *L = getASTMutationListener()) {
11271 L->CompletedImplicitDefinition(Conv);
11275 /// \brief Determine whether the given list arguments contains exactly one
11276 /// "real" (non-default) argument.
11277 static bool hasOneRealArgument(MultiExprArg Args) {
11278 switch (Args.size()) {
11283 if (!Args[1]->isDefaultArgument())
11288 return !Args[0]->isDefaultArgument();
11295 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11296 CXXConstructorDecl *Constructor,
11297 MultiExprArg ExprArgs,
11298 bool HadMultipleCandidates,
11299 bool IsListInitialization,
11300 bool IsStdInitListInitialization,
11301 bool RequiresZeroInit,
11302 unsigned ConstructKind,
11303 SourceRange ParenRange) {
11304 bool Elidable = false;
11306 // C++0x [class.copy]p34:
11307 // When certain criteria are met, an implementation is allowed to
11308 // omit the copy/move construction of a class object, even if the
11309 // copy/move constructor and/or destructor for the object have
11310 // side effects. [...]
11311 // - when a temporary class object that has not been bound to a
11312 // reference (12.2) would be copied/moved to a class object
11313 // with the same cv-unqualified type, the copy/move operation
11314 // can be omitted by constructing the temporary object
11315 // directly into the target of the omitted copy/move
11316 if (ConstructKind == CXXConstructExpr::CK_Complete &&
11317 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11318 Expr *SubExpr = ExprArgs[0];
11319 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11322 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11323 Elidable, ExprArgs, HadMultipleCandidates,
11324 IsListInitialization,
11325 IsStdInitListInitialization, RequiresZeroInit,
11326 ConstructKind, ParenRange);
11329 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11330 /// including handling of its default argument expressions.
11332 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11333 CXXConstructorDecl *Constructor, bool Elidable,
11334 MultiExprArg ExprArgs,
11335 bool HadMultipleCandidates,
11336 bool IsListInitialization,
11337 bool IsStdInitListInitialization,
11338 bool RequiresZeroInit,
11339 unsigned ConstructKind,
11340 SourceRange ParenRange) {
11341 MarkFunctionReferenced(ConstructLoc, Constructor);
11342 return CXXConstructExpr::Create(
11343 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11344 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11346 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11350 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11351 assert(Field->hasInClassInitializer());
11353 // If we already have the in-class initializer nothing needs to be done.
11354 if (Field->getInClassInitializer())
11355 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11357 // Maybe we haven't instantiated the in-class initializer. Go check the
11358 // pattern FieldDecl to see if it has one.
11359 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11361 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11362 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11363 DeclContext::lookup_result Lookup =
11364 ClassPattern->lookup(Field->getDeclName());
11365 assert(Lookup.size() == 1);
11366 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11367 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11368 getTemplateInstantiationArgs(Field)))
11369 return ExprError();
11370 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11374 // If the brace-or-equal-initializer of a non-static data member
11375 // invokes a defaulted default constructor of its class or of an
11376 // enclosing class in a potentially evaluated subexpression, the
11377 // program is ill-formed.
11379 // This resolution is unworkable: the exception specification of the
11380 // default constructor can be needed in an unevaluated context, in
11381 // particular, in the operand of a noexcept-expression, and we can be
11382 // unable to compute an exception specification for an enclosed class.
11384 // Any attempt to resolve the exception specification of a defaulted default
11385 // constructor before the initializer is lexically complete will ultimately
11386 // come here at which point we can diagnose it.
11387 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11388 if (OutermostClass == ParentRD) {
11389 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11390 << ParentRD << Field;
11392 Diag(Field->getLocEnd(),
11393 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11394 << ParentRD << OutermostClass << Field;
11397 return ExprError();
11400 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11401 if (VD->isInvalidDecl()) return;
11403 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11404 if (ClassDecl->isInvalidDecl()) return;
11405 if (ClassDecl->hasIrrelevantDestructor()) return;
11406 if (ClassDecl->isDependentContext()) return;
11408 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11409 MarkFunctionReferenced(VD->getLocation(), Destructor);
11410 CheckDestructorAccess(VD->getLocation(), Destructor,
11411 PDiag(diag::err_access_dtor_var)
11412 << VD->getDeclName()
11414 DiagnoseUseOfDecl(Destructor, VD->getLocation());
11416 if (Destructor->isTrivial()) return;
11417 if (!VD->hasGlobalStorage()) return;
11419 // Emit warning for non-trivial dtor in global scope (a real global,
11420 // class-static, function-static).
11421 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11423 // TODO: this should be re-enabled for static locals by !CXAAtExit
11424 if (!VD->isStaticLocal())
11425 Diag(VD->getLocation(), diag::warn_global_destructor);
11428 /// \brief Given a constructor and the set of arguments provided for the
11429 /// constructor, convert the arguments and add any required default arguments
11430 /// to form a proper call to this constructor.
11432 /// \returns true if an error occurred, false otherwise.
11434 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11435 MultiExprArg ArgsPtr,
11436 SourceLocation Loc,
11437 SmallVectorImpl<Expr*> &ConvertedArgs,
11438 bool AllowExplicit,
11439 bool IsListInitialization) {
11440 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11441 unsigned NumArgs = ArgsPtr.size();
11442 Expr **Args = ArgsPtr.data();
11444 const FunctionProtoType *Proto
11445 = Constructor->getType()->getAs<FunctionProtoType>();
11446 assert(Proto && "Constructor without a prototype?");
11447 unsigned NumParams = Proto->getNumParams();
11449 // If too few arguments are available, we'll fill in the rest with defaults.
11450 if (NumArgs < NumParams)
11451 ConvertedArgs.reserve(NumParams);
11453 ConvertedArgs.reserve(NumArgs);
11455 VariadicCallType CallType =
11456 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11457 SmallVector<Expr *, 8> AllArgs;
11458 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11460 llvm::makeArrayRef(Args, NumArgs),
11462 CallType, AllowExplicit,
11463 IsListInitialization);
11464 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11466 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11468 CheckConstructorCall(Constructor,
11469 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11476 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11477 const FunctionDecl *FnDecl) {
11478 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11479 if (isa<NamespaceDecl>(DC)) {
11480 return SemaRef.Diag(FnDecl->getLocation(),
11481 diag::err_operator_new_delete_declared_in_namespace)
11482 << FnDecl->getDeclName();
11485 if (isa<TranslationUnitDecl>(DC) &&
11486 FnDecl->getStorageClass() == SC_Static) {
11487 return SemaRef.Diag(FnDecl->getLocation(),
11488 diag::err_operator_new_delete_declared_static)
11489 << FnDecl->getDeclName();
11496 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11497 CanQualType ExpectedResultType,
11498 CanQualType ExpectedFirstParamType,
11499 unsigned DependentParamTypeDiag,
11500 unsigned InvalidParamTypeDiag) {
11501 QualType ResultType =
11502 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11504 // Check that the result type is not dependent.
11505 if (ResultType->isDependentType())
11506 return SemaRef.Diag(FnDecl->getLocation(),
11507 diag::err_operator_new_delete_dependent_result_type)
11508 << FnDecl->getDeclName() << ExpectedResultType;
11510 // Check that the result type is what we expect.
11511 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11512 return SemaRef.Diag(FnDecl->getLocation(),
11513 diag::err_operator_new_delete_invalid_result_type)
11514 << FnDecl->getDeclName() << ExpectedResultType;
11516 // A function template must have at least 2 parameters.
11517 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11518 return SemaRef.Diag(FnDecl->getLocation(),
11519 diag::err_operator_new_delete_template_too_few_parameters)
11520 << FnDecl->getDeclName();
11522 // The function decl must have at least 1 parameter.
11523 if (FnDecl->getNumParams() == 0)
11524 return SemaRef.Diag(FnDecl->getLocation(),
11525 diag::err_operator_new_delete_too_few_parameters)
11526 << FnDecl->getDeclName();
11528 // Check the first parameter type is not dependent.
11529 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11530 if (FirstParamType->isDependentType())
11531 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11532 << FnDecl->getDeclName() << ExpectedFirstParamType;
11534 // Check that the first parameter type is what we expect.
11535 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11536 ExpectedFirstParamType)
11537 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11538 << FnDecl->getDeclName() << ExpectedFirstParamType;
11544 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11545 // C++ [basic.stc.dynamic.allocation]p1:
11546 // A program is ill-formed if an allocation function is declared in a
11547 // namespace scope other than global scope or declared static in global
11549 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11552 CanQualType SizeTy =
11553 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11555 // C++ [basic.stc.dynamic.allocation]p1:
11556 // The return type shall be void*. The first parameter shall have type
11558 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11560 diag::err_operator_new_dependent_param_type,
11561 diag::err_operator_new_param_type))
11564 // C++ [basic.stc.dynamic.allocation]p1:
11565 // The first parameter shall not have an associated default argument.
11566 if (FnDecl->getParamDecl(0)->hasDefaultArg())
11567 return SemaRef.Diag(FnDecl->getLocation(),
11568 diag::err_operator_new_default_arg)
11569 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11575 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11576 // C++ [basic.stc.dynamic.deallocation]p1:
11577 // A program is ill-formed if deallocation functions are declared in a
11578 // namespace scope other than global scope or declared static in global
11580 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11583 // C++ [basic.stc.dynamic.deallocation]p2:
11584 // Each deallocation function shall return void and its first parameter
11586 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11587 SemaRef.Context.VoidPtrTy,
11588 diag::err_operator_delete_dependent_param_type,
11589 diag::err_operator_delete_param_type))
11595 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11596 /// of this overloaded operator is well-formed. If so, returns false;
11597 /// otherwise, emits appropriate diagnostics and returns true.
11598 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11599 assert(FnDecl && FnDecl->isOverloadedOperator() &&
11600 "Expected an overloaded operator declaration");
11602 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11604 // C++ [over.oper]p5:
11605 // The allocation and deallocation functions, operator new,
11606 // operator new[], operator delete and operator delete[], are
11607 // described completely in 3.7.3. The attributes and restrictions
11608 // found in the rest of this subclause do not apply to them unless
11609 // explicitly stated in 3.7.3.
11610 if (Op == OO_Delete || Op == OO_Array_Delete)
11611 return CheckOperatorDeleteDeclaration(*this, FnDecl);
11613 if (Op == OO_New || Op == OO_Array_New)
11614 return CheckOperatorNewDeclaration(*this, FnDecl);
11616 // C++ [over.oper]p6:
11617 // An operator function shall either be a non-static member
11618 // function or be a non-member function and have at least one
11619 // parameter whose type is a class, a reference to a class, an
11620 // enumeration, or a reference to an enumeration.
11621 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11622 if (MethodDecl->isStatic())
11623 return Diag(FnDecl->getLocation(),
11624 diag::err_operator_overload_static) << FnDecl->getDeclName();
11626 bool ClassOrEnumParam = false;
11627 for (auto Param : FnDecl->params()) {
11628 QualType ParamType = Param->getType().getNonReferenceType();
11629 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11630 ParamType->isEnumeralType()) {
11631 ClassOrEnumParam = true;
11636 if (!ClassOrEnumParam)
11637 return Diag(FnDecl->getLocation(),
11638 diag::err_operator_overload_needs_class_or_enum)
11639 << FnDecl->getDeclName();
11642 // C++ [over.oper]p8:
11643 // An operator function cannot have default arguments (8.3.6),
11644 // except where explicitly stated below.
11646 // Only the function-call operator allows default arguments
11647 // (C++ [over.call]p1).
11648 if (Op != OO_Call) {
11649 for (auto Param : FnDecl->params()) {
11650 if (Param->hasDefaultArg())
11651 return Diag(Param->getLocation(),
11652 diag::err_operator_overload_default_arg)
11653 << FnDecl->getDeclName() << Param->getDefaultArgRange();
11657 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11658 { false, false, false }
11659 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11660 , { Unary, Binary, MemberOnly }
11661 #include "clang/Basic/OperatorKinds.def"
11664 bool CanBeUnaryOperator = OperatorUses[Op][0];
11665 bool CanBeBinaryOperator = OperatorUses[Op][1];
11666 bool MustBeMemberOperator = OperatorUses[Op][2];
11668 // C++ [over.oper]p8:
11669 // [...] Operator functions cannot have more or fewer parameters
11670 // than the number required for the corresponding operator, as
11671 // described in the rest of this subclause.
11672 unsigned NumParams = FnDecl->getNumParams()
11673 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11674 if (Op != OO_Call &&
11675 ((NumParams == 1 && !CanBeUnaryOperator) ||
11676 (NumParams == 2 && !CanBeBinaryOperator) ||
11677 (NumParams < 1) || (NumParams > 2))) {
11678 // We have the wrong number of parameters.
11679 unsigned ErrorKind;
11680 if (CanBeUnaryOperator && CanBeBinaryOperator) {
11681 ErrorKind = 2; // 2 -> unary or binary.
11682 } else if (CanBeUnaryOperator) {
11683 ErrorKind = 0; // 0 -> unary
11685 assert(CanBeBinaryOperator &&
11686 "All non-call overloaded operators are unary or binary!");
11687 ErrorKind = 1; // 1 -> binary
11690 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11691 << FnDecl->getDeclName() << NumParams << ErrorKind;
11694 // Overloaded operators other than operator() cannot be variadic.
11695 if (Op != OO_Call &&
11696 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11697 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11698 << FnDecl->getDeclName();
11701 // Some operators must be non-static member functions.
11702 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11703 return Diag(FnDecl->getLocation(),
11704 diag::err_operator_overload_must_be_member)
11705 << FnDecl->getDeclName();
11708 // C++ [over.inc]p1:
11709 // The user-defined function called operator++ implements the
11710 // prefix and postfix ++ operator. If this function is a member
11711 // function with no parameters, or a non-member function with one
11712 // parameter of class or enumeration type, it defines the prefix
11713 // increment operator ++ for objects of that type. If the function
11714 // is a member function with one parameter (which shall be of type
11715 // int) or a non-member function with two parameters (the second
11716 // of which shall be of type int), it defines the postfix
11717 // increment operator ++ for objects of that type.
11718 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11719 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11720 QualType ParamType = LastParam->getType();
11722 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11723 !ParamType->isDependentType())
11724 return Diag(LastParam->getLocation(),
11725 diag::err_operator_overload_post_incdec_must_be_int)
11726 << LastParam->getType() << (Op == OO_MinusMinus);
11732 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11733 /// of this literal operator function is well-formed. If so, returns
11734 /// false; otherwise, emits appropriate diagnostics and returns true.
11735 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11736 if (isa<CXXMethodDecl>(FnDecl)) {
11737 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11738 << FnDecl->getDeclName();
11742 if (FnDecl->isExternC()) {
11743 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11747 bool Valid = false;
11749 // This might be the definition of a literal operator template.
11750 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11751 // This might be a specialization of a literal operator template.
11753 TpDecl = FnDecl->getPrimaryTemplate();
11755 // template <char...> type operator "" name() and
11756 // template <class T, T...> type operator "" name() are the only valid
11757 // template signatures, and the only valid signatures with no parameters.
11759 if (FnDecl->param_size() == 0) {
11760 // Must have one or two template parameters
11761 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11762 if (Params->size() == 1) {
11763 NonTypeTemplateParmDecl *PmDecl =
11764 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11766 // The template parameter must be a char parameter pack.
11767 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11768 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11770 } else if (Params->size() == 2) {
11771 TemplateTypeParmDecl *PmType =
11772 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11773 NonTypeTemplateParmDecl *PmArgs =
11774 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11776 // The second template parameter must be a parameter pack with the
11777 // first template parameter as its type.
11778 if (PmType && PmArgs &&
11779 !PmType->isTemplateParameterPack() &&
11780 PmArgs->isTemplateParameterPack()) {
11781 const TemplateTypeParmType *TArgs =
11782 PmArgs->getType()->getAs<TemplateTypeParmType>();
11783 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11784 TArgs->getIndex() == PmType->getIndex()) {
11786 if (ActiveTemplateInstantiations.empty())
11787 Diag(FnDecl->getLocation(),
11788 diag::ext_string_literal_operator_template);
11793 } else if (FnDecl->param_size()) {
11794 // Check the first parameter
11795 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11797 QualType T = (*Param)->getType().getUnqualifiedType();
11799 // unsigned long long int, long double, and any character type are allowed
11800 // as the only parameters.
11801 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11802 Context.hasSameType(T, Context.LongDoubleTy) ||
11803 Context.hasSameType(T, Context.CharTy) ||
11804 Context.hasSameType(T, Context.WideCharTy) ||
11805 Context.hasSameType(T, Context.Char16Ty) ||
11806 Context.hasSameType(T, Context.Char32Ty)) {
11807 if (++Param == FnDecl->param_end())
11809 goto FinishedParams;
11812 // Otherwise it must be a pointer to const; let's strip those qualifiers.
11813 const PointerType *PT = T->getAs<PointerType>();
11815 goto FinishedParams;
11816 T = PT->getPointeeType();
11817 if (!T.isConstQualified() || T.isVolatileQualified())
11818 goto FinishedParams;
11819 T = T.getUnqualifiedType();
11821 // Move on to the second parameter;
11824 // If there is no second parameter, the first must be a const char *
11825 if (Param == FnDecl->param_end()) {
11826 if (Context.hasSameType(T, Context.CharTy))
11828 goto FinishedParams;
11831 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11832 // are allowed as the first parameter to a two-parameter function
11833 if (!(Context.hasSameType(T, Context.CharTy) ||
11834 Context.hasSameType(T, Context.WideCharTy) ||
11835 Context.hasSameType(T, Context.Char16Ty) ||
11836 Context.hasSameType(T, Context.Char32Ty)))
11837 goto FinishedParams;
11839 // The second and final parameter must be an std::size_t
11840 T = (*Param)->getType().getUnqualifiedType();
11841 if (Context.hasSameType(T, Context.getSizeType()) &&
11842 ++Param == FnDecl->param_end())
11846 // FIXME: This diagnostic is absolutely terrible.
11849 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11850 << FnDecl->getDeclName();
11854 // A parameter-declaration-clause containing a default argument is not
11855 // equivalent to any of the permitted forms.
11856 for (auto Param : FnDecl->params()) {
11857 if (Param->hasDefaultArg()) {
11858 Diag(Param->getDefaultArgRange().getBegin(),
11859 diag::err_literal_operator_default_argument)
11860 << Param->getDefaultArgRange();
11865 StringRef LiteralName
11866 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11867 if (LiteralName[0] != '_') {
11868 // C++11 [usrlit.suffix]p1:
11869 // Literal suffix identifiers that do not start with an underscore
11870 // are reserved for future standardization.
11871 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11872 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11878 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11879 /// linkage specification, including the language and (if present)
11880 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11881 /// language string literal. LBraceLoc, if valid, provides the location of
11882 /// the '{' brace. Otherwise, this linkage specification does not
11883 /// have any braces.
11884 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11886 SourceLocation LBraceLoc) {
11887 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11888 if (!Lit->isAscii()) {
11889 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11890 << LangStr->getSourceRange();
11894 StringRef Lang = Lit->getString();
11895 LinkageSpecDecl::LanguageIDs Language;
11897 Language = LinkageSpecDecl::lang_c;
11898 else if (Lang == "C++")
11899 Language = LinkageSpecDecl::lang_cxx;
11901 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11902 << LangStr->getSourceRange();
11906 // FIXME: Add all the various semantics of linkage specifications
11908 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11909 LangStr->getExprLoc(), Language,
11910 LBraceLoc.isValid());
11911 CurContext->addDecl(D);
11912 PushDeclContext(S, D);
11916 /// ActOnFinishLinkageSpecification - Complete the definition of
11917 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11918 /// valid, it's the position of the closing '}' brace in a linkage
11919 /// specification that uses braces.
11920 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11922 SourceLocation RBraceLoc) {
11923 if (RBraceLoc.isValid()) {
11924 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11925 LSDecl->setRBraceLoc(RBraceLoc);
11928 return LinkageSpec;
11931 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11932 AttributeList *AttrList,
11933 SourceLocation SemiLoc) {
11934 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11935 // Attribute declarations appertain to empty declaration so we handle
11938 ProcessDeclAttributeList(S, ED, AttrList);
11940 CurContext->addDecl(ED);
11944 /// \brief Perform semantic analysis for the variable declaration that
11945 /// occurs within a C++ catch clause, returning the newly-created
11947 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11948 TypeSourceInfo *TInfo,
11949 SourceLocation StartLoc,
11950 SourceLocation Loc,
11951 IdentifierInfo *Name) {
11952 bool Invalid = false;
11953 QualType ExDeclType = TInfo->getType();
11955 // Arrays and functions decay.
11956 if (ExDeclType->isArrayType())
11957 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11958 else if (ExDeclType->isFunctionType())
11959 ExDeclType = Context.getPointerType(ExDeclType);
11961 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11962 // The exception-declaration shall not denote a pointer or reference to an
11963 // incomplete type, other than [cv] void*.
11964 // N2844 forbids rvalue references.
11965 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11966 Diag(Loc, diag::err_catch_rvalue_ref);
11970 QualType BaseType = ExDeclType;
11971 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11972 unsigned DK = diag::err_catch_incomplete;
11973 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11974 BaseType = Ptr->getPointeeType();
11976 DK = diag::err_catch_incomplete_ptr;
11977 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11978 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11979 BaseType = Ref->getPointeeType();
11981 DK = diag::err_catch_incomplete_ref;
11983 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11984 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11987 if (!Invalid && !ExDeclType->isDependentType() &&
11988 RequireNonAbstractType(Loc, ExDeclType,
11989 diag::err_abstract_type_in_decl,
11990 AbstractVariableType))
11993 // Only the non-fragile NeXT runtime currently supports C++ catches
11994 // of ObjC types, and no runtime supports catching ObjC types by value.
11995 if (!Invalid && getLangOpts().ObjC1) {
11996 QualType T = ExDeclType;
11997 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11998 T = RT->getPointeeType();
12000 if (T->isObjCObjectType()) {
12001 Diag(Loc, diag::err_objc_object_catch);
12003 } else if (T->isObjCObjectPointerType()) {
12004 // FIXME: should this be a test for macosx-fragile specifically?
12005 if (getLangOpts().ObjCRuntime.isFragile())
12006 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12010 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12011 ExDeclType, TInfo, SC_None);
12012 ExDecl->setExceptionVariable(true);
12014 // In ARC, infer 'retaining' for variables of retainable type.
12015 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12018 if (!Invalid && !ExDeclType->isDependentType()) {
12019 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12020 // Insulate this from anything else we might currently be parsing.
12021 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12023 // C++ [except.handle]p16:
12024 // The object declared in an exception-declaration or, if the
12025 // exception-declaration does not specify a name, a temporary (12.2) is
12026 // copy-initialized (8.5) from the exception object. [...]
12027 // The object is destroyed when the handler exits, after the destruction
12028 // of any automatic objects initialized within the handler.
12030 // We just pretend to initialize the object with itself, then make sure
12031 // it can be destroyed later.
12032 QualType initType = Context.getExceptionObjectType(ExDeclType);
12034 InitializedEntity entity =
12035 InitializedEntity::InitializeVariable(ExDecl);
12036 InitializationKind initKind =
12037 InitializationKind::CreateCopy(Loc, SourceLocation());
12039 Expr *opaqueValue =
12040 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12041 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12042 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12043 if (result.isInvalid())
12046 // If the constructor used was non-trivial, set this as the
12048 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12049 if (!construct->getConstructor()->isTrivial()) {
12050 Expr *init = MaybeCreateExprWithCleanups(construct);
12051 ExDecl->setInit(init);
12054 // And make sure it's destructable.
12055 FinalizeVarWithDestructor(ExDecl, recordType);
12061 ExDecl->setInvalidDecl();
12066 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12068 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12069 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12070 bool Invalid = D.isInvalidType();
12072 // Check for unexpanded parameter packs.
12073 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12074 UPPC_ExceptionType)) {
12075 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12076 D.getIdentifierLoc());
12080 IdentifierInfo *II = D.getIdentifier();
12081 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12082 LookupOrdinaryName,
12083 ForRedeclaration)) {
12084 // The scope should be freshly made just for us. There is just no way
12085 // it contains any previous declaration, except for function parameters in
12086 // a function-try-block's catch statement.
12087 assert(!S->isDeclScope(PrevDecl));
12088 if (isDeclInScope(PrevDecl, CurContext, S)) {
12089 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12090 << D.getIdentifier();
12091 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12093 } else if (PrevDecl->isTemplateParameter())
12094 // Maybe we will complain about the shadowed template parameter.
12095 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12098 if (D.getCXXScopeSpec().isSet() && !Invalid) {
12099 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12100 << D.getCXXScopeSpec().getRange();
12104 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12106 D.getIdentifierLoc(),
12107 D.getIdentifier());
12109 ExDecl->setInvalidDecl();
12111 // Add the exception declaration into this scope.
12113 PushOnScopeChains(ExDecl, S);
12115 CurContext->addDecl(ExDecl);
12117 ProcessDeclAttributes(S, ExDecl, D);
12121 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12123 Expr *AssertMessageExpr,
12124 SourceLocation RParenLoc) {
12125 StringLiteral *AssertMessage =
12126 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12128 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12131 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12132 AssertMessage, RParenLoc, false);
12135 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12137 StringLiteral *AssertMessage,
12138 SourceLocation RParenLoc,
12140 assert(AssertExpr != nullptr && "Expected non-null condition");
12141 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12143 // In a static_assert-declaration, the constant-expression shall be a
12144 // constant expression that can be contextually converted to bool.
12145 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12146 if (Converted.isInvalid())
12150 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12151 diag::err_static_assert_expression_is_not_constant,
12152 /*AllowFold=*/false).isInvalid())
12155 if (!Failed && !Cond) {
12156 SmallString<256> MsgBuffer;
12157 llvm::raw_svector_ostream Msg(MsgBuffer);
12159 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12160 Diag(StaticAssertLoc, diag::err_static_assert_failed)
12161 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12166 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12167 AssertExpr, AssertMessage, RParenLoc,
12170 CurContext->addDecl(Decl);
12174 /// \brief Perform semantic analysis of the given friend type declaration.
12176 /// \returns A friend declaration that.
12177 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12178 SourceLocation FriendLoc,
12179 TypeSourceInfo *TSInfo) {
12180 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12182 QualType T = TSInfo->getType();
12183 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12185 // C++03 [class.friend]p2:
12186 // An elaborated-type-specifier shall be used in a friend declaration
12189 // * The class-key of the elaborated-type-specifier is required.
12190 if (!ActiveTemplateInstantiations.empty()) {
12191 // Do not complain about the form of friend template types during
12192 // template instantiation; we will already have complained when the
12193 // template was declared.
12195 if (!T->isElaboratedTypeSpecifier()) {
12196 // If we evaluated the type to a record type, suggest putting
12198 if (const RecordType *RT = T->getAs<RecordType>()) {
12199 RecordDecl *RD = RT->getDecl();
12201 SmallString<16> InsertionText(" ");
12202 InsertionText += RD->getKindName();
12204 Diag(TypeRange.getBegin(),
12205 getLangOpts().CPlusPlus11 ?
12206 diag::warn_cxx98_compat_unelaborated_friend_type :
12207 diag::ext_unelaborated_friend_type)
12208 << (unsigned) RD->getTagKind()
12210 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12214 getLangOpts().CPlusPlus11 ?
12215 diag::warn_cxx98_compat_nonclass_type_friend :
12216 diag::ext_nonclass_type_friend)
12220 } else if (T->getAs<EnumType>()) {
12222 getLangOpts().CPlusPlus11 ?
12223 diag::warn_cxx98_compat_enum_friend :
12224 diag::ext_enum_friend)
12229 // C++11 [class.friend]p3:
12230 // A friend declaration that does not declare a function shall have one
12231 // of the following forms:
12232 // friend elaborated-type-specifier ;
12233 // friend simple-type-specifier ;
12234 // friend typename-specifier ;
12235 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12236 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12239 // If the type specifier in a friend declaration designates a (possibly
12240 // cv-qualified) class type, that class is declared as a friend; otherwise,
12241 // the friend declaration is ignored.
12242 return FriendDecl::Create(Context, CurContext,
12243 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12247 /// Handle a friend tag declaration where the scope specifier was
12249 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12250 unsigned TagSpec, SourceLocation TagLoc,
12252 IdentifierInfo *Name,
12253 SourceLocation NameLoc,
12254 AttributeList *Attr,
12255 MultiTemplateParamsArg TempParamLists) {
12256 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12258 bool isExplicitSpecialization = false;
12259 bool Invalid = false;
12261 if (TemplateParameterList *TemplateParams =
12262 MatchTemplateParametersToScopeSpecifier(
12263 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12264 isExplicitSpecialization, Invalid)) {
12265 if (TemplateParams->size() > 0) {
12266 // This is a declaration of a class template.
12270 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12271 NameLoc, Attr, TemplateParams, AS_public,
12272 /*ModulePrivateLoc=*/SourceLocation(),
12273 FriendLoc, TempParamLists.size() - 1,
12274 TempParamLists.data()).get();
12276 // The "template<>" header is extraneous.
12277 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12278 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12279 isExplicitSpecialization = true;
12283 if (Invalid) return nullptr;
12285 bool isAllExplicitSpecializations = true;
12286 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12287 if (TempParamLists[I]->size()) {
12288 isAllExplicitSpecializations = false;
12293 // FIXME: don't ignore attributes.
12295 // If it's explicit specializations all the way down, just forget
12296 // about the template header and build an appropriate non-templated
12297 // friend. TODO: for source fidelity, remember the headers.
12298 if (isAllExplicitSpecializations) {
12299 if (SS.isEmpty()) {
12300 bool Owned = false;
12301 bool IsDependent = false;
12302 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12304 /*ModulePrivateLoc=*/SourceLocation(),
12305 MultiTemplateParamsArg(), Owned, IsDependent,
12306 /*ScopedEnumKWLoc=*/SourceLocation(),
12307 /*ScopedEnumUsesClassTag=*/false,
12308 /*UnderlyingType=*/TypeResult(),
12309 /*IsTypeSpecifier=*/false);
12312 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12313 ElaboratedTypeKeyword Keyword
12314 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12315 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12320 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12321 if (isa<DependentNameType>(T)) {
12322 DependentNameTypeLoc TL =
12323 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12324 TL.setElaboratedKeywordLoc(TagLoc);
12325 TL.setQualifierLoc(QualifierLoc);
12326 TL.setNameLoc(NameLoc);
12328 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12329 TL.setElaboratedKeywordLoc(TagLoc);
12330 TL.setQualifierLoc(QualifierLoc);
12331 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12334 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12335 TSI, FriendLoc, TempParamLists);
12336 Friend->setAccess(AS_public);
12337 CurContext->addDecl(Friend);
12341 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12345 // Handle the case of a templated-scope friend class. e.g.
12346 // template <class T> class A<T>::B;
12347 // FIXME: we don't support these right now.
12348 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12349 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12350 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12351 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12352 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12353 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12354 TL.setElaboratedKeywordLoc(TagLoc);
12355 TL.setQualifierLoc(SS.getWithLocInContext(Context));
12356 TL.setNameLoc(NameLoc);
12358 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12359 TSI, FriendLoc, TempParamLists);
12360 Friend->setAccess(AS_public);
12361 Friend->setUnsupportedFriend(true);
12362 CurContext->addDecl(Friend);
12367 /// Handle a friend type declaration. This works in tandem with
12370 /// Notes on friend class templates:
12372 /// We generally treat friend class declarations as if they were
12373 /// declaring a class. So, for example, the elaborated type specifier
12374 /// in a friend declaration is required to obey the restrictions of a
12375 /// class-head (i.e. no typedefs in the scope chain), template
12376 /// parameters are required to match up with simple template-ids, &c.
12377 /// However, unlike when declaring a template specialization, it's
12378 /// okay to refer to a template specialization without an empty
12379 /// template parameter declaration, e.g.
12380 /// friend class A<T>::B<unsigned>;
12381 /// We permit this as a special case; if there are any template
12382 /// parameters present at all, require proper matching, i.e.
12383 /// template <> template \<class T> friend class A<int>::B;
12384 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12385 MultiTemplateParamsArg TempParams) {
12386 SourceLocation Loc = DS.getLocStart();
12388 assert(DS.isFriendSpecified());
12389 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12391 // Try to convert the decl specifier to a type. This works for
12392 // friend templates because ActOnTag never produces a ClassTemplateDecl
12393 // for a TUK_Friend.
12394 Declarator TheDeclarator(DS, Declarator::MemberContext);
12395 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12396 QualType T = TSI->getType();
12397 if (TheDeclarator.isInvalidType())
12400 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12403 // This is definitely an error in C++98. It's probably meant to
12404 // be forbidden in C++0x, too, but the specification is just
12407 // The problem is with declarations like the following:
12408 // template <T> friend A<T>::foo;
12409 // where deciding whether a class C is a friend or not now hinges
12410 // on whether there exists an instantiation of A that causes
12411 // 'foo' to equal C. There are restrictions on class-heads
12412 // (which we declare (by fiat) elaborated friend declarations to
12413 // be) that makes this tractable.
12415 // FIXME: handle "template <> friend class A<T>;", which
12416 // is possibly well-formed? Who even knows?
12417 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12418 Diag(Loc, diag::err_tagless_friend_type_template)
12419 << DS.getSourceRange();
12423 // C++98 [class.friend]p1: A friend of a class is a function
12424 // or class that is not a member of the class . . .
12425 // This is fixed in DR77, which just barely didn't make the C++03
12426 // deadline. It's also a very silly restriction that seriously
12427 // affects inner classes and which nobody else seems to implement;
12428 // thus we never diagnose it, not even in -pedantic.
12430 // But note that we could warn about it: it's always useless to
12431 // friend one of your own members (it's not, however, worthless to
12432 // friend a member of an arbitrary specialization of your template).
12435 if (unsigned NumTempParamLists = TempParams.size())
12436 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12440 DS.getFriendSpecLoc());
12442 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12447 D->setAccess(AS_public);
12448 CurContext->addDecl(D);
12453 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12454 MultiTemplateParamsArg TemplateParams) {
12455 const DeclSpec &DS = D.getDeclSpec();
12457 assert(DS.isFriendSpecified());
12458 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12460 SourceLocation Loc = D.getIdentifierLoc();
12461 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12463 // C++ [class.friend]p1
12464 // A friend of a class is a function or class....
12465 // Note that this sees through typedefs, which is intended.
12466 // It *doesn't* see through dependent types, which is correct
12467 // according to [temp.arg.type]p3:
12468 // If a declaration acquires a function type through a
12469 // type dependent on a template-parameter and this causes
12470 // a declaration that does not use the syntactic form of a
12471 // function declarator to have a function type, the program
12473 if (!TInfo->getType()->isFunctionType()) {
12474 Diag(Loc, diag::err_unexpected_friend);
12476 // It might be worthwhile to try to recover by creating an
12477 // appropriate declaration.
12481 // C++ [namespace.memdef]p3
12482 // - If a friend declaration in a non-local class first declares a
12483 // class or function, the friend class or function is a member
12484 // of the innermost enclosing namespace.
12485 // - The name of the friend is not found by simple name lookup
12486 // until a matching declaration is provided in that namespace
12487 // scope (either before or after the class declaration granting
12489 // - If a friend function is called, its name may be found by the
12490 // name lookup that considers functions from namespaces and
12491 // classes associated with the types of the function arguments.
12492 // - When looking for a prior declaration of a class or a function
12493 // declared as a friend, scopes outside the innermost enclosing
12494 // namespace scope are not considered.
12496 CXXScopeSpec &SS = D.getCXXScopeSpec();
12497 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12498 DeclarationName Name = NameInfo.getName();
12501 // Check for unexpanded parameter packs.
12502 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12503 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12504 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12507 // The context we found the declaration in, or in which we should
12508 // create the declaration.
12510 Scope *DCScope = S;
12511 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12514 // There are five cases here.
12515 // - There's no scope specifier and we're in a local class. Only look
12516 // for functions declared in the immediately-enclosing block scope.
12517 // We recover from invalid scope qualifiers as if they just weren't there.
12518 FunctionDecl *FunctionContainingLocalClass = nullptr;
12519 if ((SS.isInvalid() || !SS.isSet()) &&
12520 (FunctionContainingLocalClass =
12521 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12522 // C++11 [class.friend]p11:
12523 // If a friend declaration appears in a local class and the name
12524 // specified is an unqualified name, a prior declaration is
12525 // looked up without considering scopes that are outside the
12526 // innermost enclosing non-class scope. For a friend function
12527 // declaration, if there is no prior declaration, the program is
12530 // Find the innermost enclosing non-class scope. This is the block
12531 // scope containing the local class definition (or for a nested class,
12532 // the outer local class).
12533 DCScope = S->getFnParent();
12535 // Look up the function name in the scope.
12536 Previous.clear(LookupLocalFriendName);
12537 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12539 if (!Previous.empty()) {
12540 // All possible previous declarations must have the same context:
12541 // either they were declared at block scope or they are members of
12542 // one of the enclosing local classes.
12543 DC = Previous.getRepresentativeDecl()->getDeclContext();
12545 // This is ill-formed, but provide the context that we would have
12546 // declared the function in, if we were permitted to, for error recovery.
12547 DC = FunctionContainingLocalClass;
12549 adjustContextForLocalExternDecl(DC);
12551 // C++ [class.friend]p6:
12552 // A function can be defined in a friend declaration of a class if and
12553 // only if the class is a non-local class (9.8), the function name is
12554 // unqualified, and the function has namespace scope.
12555 if (D.isFunctionDefinition()) {
12556 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12559 // - There's no scope specifier, in which case we just go to the
12560 // appropriate scope and look for a function or function template
12561 // there as appropriate.
12562 } else if (SS.isInvalid() || !SS.isSet()) {
12563 // C++11 [namespace.memdef]p3:
12564 // If the name in a friend declaration is neither qualified nor
12565 // a template-id and the declaration is a function or an
12566 // elaborated-type-specifier, the lookup to determine whether
12567 // the entity has been previously declared shall not consider
12568 // any scopes outside the innermost enclosing namespace.
12569 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12571 // Find the appropriate context according to the above.
12574 // Skip class contexts. If someone can cite chapter and verse
12575 // for this behavior, that would be nice --- it's what GCC and
12576 // EDG do, and it seems like a reasonable intent, but the spec
12577 // really only says that checks for unqualified existing
12578 // declarations should stop at the nearest enclosing namespace,
12579 // not that they should only consider the nearest enclosing
12581 while (DC->isRecord())
12582 DC = DC->getParent();
12584 DeclContext *LookupDC = DC;
12585 while (LookupDC->isTransparentContext())
12586 LookupDC = LookupDC->getParent();
12589 LookupQualifiedName(Previous, LookupDC);
12591 if (!Previous.empty()) {
12596 if (isTemplateId) {
12597 if (isa<TranslationUnitDecl>(LookupDC)) break;
12599 if (LookupDC->isFileContext()) break;
12601 LookupDC = LookupDC->getParent();
12604 DCScope = getScopeForDeclContext(S, DC);
12606 // - There's a non-dependent scope specifier, in which case we
12607 // compute it and do a previous lookup there for a function
12608 // or function template.
12609 } else if (!SS.getScopeRep()->isDependent()) {
12610 DC = computeDeclContext(SS);
12611 if (!DC) return nullptr;
12613 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12615 LookupQualifiedName(Previous, DC);
12617 // Ignore things found implicitly in the wrong scope.
12618 // TODO: better diagnostics for this case. Suggesting the right
12619 // qualified scope would be nice...
12620 LookupResult::Filter F = Previous.makeFilter();
12621 while (F.hasNext()) {
12622 NamedDecl *D = F.next();
12623 if (!DC->InEnclosingNamespaceSetOf(
12624 D->getDeclContext()->getRedeclContext()))
12629 if (Previous.empty()) {
12630 D.setInvalidType();
12631 Diag(Loc, diag::err_qualified_friend_not_found)
12632 << Name << TInfo->getType();
12636 // C++ [class.friend]p1: A friend of a class is a function or
12637 // class that is not a member of the class . . .
12638 if (DC->Equals(CurContext))
12639 Diag(DS.getFriendSpecLoc(),
12640 getLangOpts().CPlusPlus11 ?
12641 diag::warn_cxx98_compat_friend_is_member :
12642 diag::err_friend_is_member);
12644 if (D.isFunctionDefinition()) {
12645 // C++ [class.friend]p6:
12646 // A function can be defined in a friend declaration of a class if and
12647 // only if the class is a non-local class (9.8), the function name is
12648 // unqualified, and the function has namespace scope.
12649 SemaDiagnosticBuilder DB
12650 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12652 DB << SS.getScopeRep();
12653 if (DC->isFileContext())
12654 DB << FixItHint::CreateRemoval(SS.getRange());
12658 // - There's a scope specifier that does not match any template
12659 // parameter lists, in which case we use some arbitrary context,
12660 // create a method or method template, and wait for instantiation.
12661 // - There's a scope specifier that does match some template
12662 // parameter lists, which we don't handle right now.
12664 if (D.isFunctionDefinition()) {
12665 // C++ [class.friend]p6:
12666 // A function can be defined in a friend declaration of a class if and
12667 // only if the class is a non-local class (9.8), the function name is
12668 // unqualified, and the function has namespace scope.
12669 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12670 << SS.getScopeRep();
12674 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12677 if (!DC->isRecord()) {
12678 // This implies that it has to be an operator or function.
12679 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12680 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12681 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12682 Diag(Loc, diag::err_introducing_special_friend) <<
12683 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12684 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12689 // FIXME: This is an egregious hack to cope with cases where the scope stack
12690 // does not contain the declaration context, i.e., in an out-of-line
12691 // definition of a class.
12692 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12694 FakeDCScope.setEntity(DC);
12695 DCScope = &FakeDCScope;
12698 bool AddToScope = true;
12699 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12700 TemplateParams, AddToScope);
12701 if (!ND) return nullptr;
12703 assert(ND->getLexicalDeclContext() == CurContext);
12705 // If we performed typo correction, we might have added a scope specifier
12706 // and changed the decl context.
12707 DC = ND->getDeclContext();
12709 // Add the function declaration to the appropriate lookup tables,
12710 // adjusting the redeclarations list as necessary. We don't
12711 // want to do this yet if the friending class is dependent.
12713 // Also update the scope-based lookup if the target context's
12714 // lookup context is in lexical scope.
12715 if (!CurContext->isDependentContext()) {
12716 DC = DC->getRedeclContext();
12717 DC->makeDeclVisibleInContext(ND);
12718 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12719 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12722 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12723 D.getIdentifierLoc(), ND,
12724 DS.getFriendSpecLoc());
12725 FrD->setAccess(AS_public);
12726 CurContext->addDecl(FrD);
12728 if (ND->isInvalidDecl()) {
12729 FrD->setInvalidDecl();
12731 if (DC->isRecord()) CheckFriendAccess(ND);
12734 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12735 FD = FTD->getTemplatedDecl();
12737 FD = cast<FunctionDecl>(ND);
12739 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12740 // default argument expression, that declaration shall be a definition
12741 // and shall be the only declaration of the function or function
12742 // template in the translation unit.
12743 if (functionDeclHasDefaultArgument(FD)) {
12744 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12745 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12746 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12747 } else if (!D.isFunctionDefinition())
12748 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12751 // Mark templated-scope function declarations as unsupported.
12752 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12753 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12754 << SS.getScopeRep() << SS.getRange()
12755 << cast<CXXRecordDecl>(CurContext);
12756 FrD->setUnsupportedFriend(true);
12763 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12764 AdjustDeclIfTemplate(Dcl);
12766 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12768 Diag(DelLoc, diag::err_deleted_non_function);
12772 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12773 // Don't consider the implicit declaration we generate for explicit
12774 // specializations. FIXME: Do not generate these implicit declarations.
12775 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12776 Prev->getPreviousDecl()) &&
12777 !Prev->isDefined()) {
12778 Diag(DelLoc, diag::err_deleted_decl_not_first);
12779 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12780 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12781 : diag::note_previous_declaration);
12783 // If the declaration wasn't the first, we delete the function anyway for
12785 Fn = Fn->getCanonicalDecl();
12788 // dllimport/dllexport cannot be deleted.
12789 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12790 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12791 Fn->setInvalidDecl();
12794 if (Fn->isDeleted())
12797 // See if we're deleting a function which is already known to override a
12798 // non-deleted virtual function.
12799 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12800 bool IssuedDiagnostic = false;
12801 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12802 E = MD->end_overridden_methods();
12804 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12805 if (!IssuedDiagnostic) {
12806 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12807 IssuedDiagnostic = true;
12809 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12814 // C++11 [basic.start.main]p3:
12815 // A program that defines main as deleted [...] is ill-formed.
12817 Diag(DelLoc, diag::err_deleted_main);
12819 Fn->setDeletedAsWritten();
12822 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12823 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12826 if (MD->getParent()->isDependentType()) {
12827 MD->setDefaulted();
12828 MD->setExplicitlyDefaulted();
12832 CXXSpecialMember Member = getSpecialMember(MD);
12833 if (Member == CXXInvalid) {
12834 if (!MD->isInvalidDecl())
12835 Diag(DefaultLoc, diag::err_default_special_members);
12839 MD->setDefaulted();
12840 MD->setExplicitlyDefaulted();
12842 // If this definition appears within the record, do the checking when
12843 // the record is complete.
12844 const FunctionDecl *Primary = MD;
12845 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12846 // Find the uninstantiated declaration that actually had the '= default'
12848 Pattern->isDefined(Primary);
12850 // If the method was defaulted on its first declaration, we will have
12851 // already performed the checking in CheckCompletedCXXClass. Such a
12852 // declaration doesn't trigger an implicit definition.
12853 if (Primary == Primary->getCanonicalDecl())
12856 CheckExplicitlyDefaultedSpecialMember(MD);
12858 if (MD->isInvalidDecl())
12862 case CXXDefaultConstructor:
12863 DefineImplicitDefaultConstructor(DefaultLoc,
12864 cast<CXXConstructorDecl>(MD));
12866 case CXXCopyConstructor:
12867 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12869 case CXXCopyAssignment:
12870 DefineImplicitCopyAssignment(DefaultLoc, MD);
12872 case CXXDestructor:
12873 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12875 case CXXMoveConstructor:
12876 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12878 case CXXMoveAssignment:
12879 DefineImplicitMoveAssignment(DefaultLoc, MD);
12882 llvm_unreachable("Invalid special member.");
12885 Diag(DefaultLoc, diag::err_default_special_members);
12889 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12890 for (Stmt *SubStmt : S->children()) {
12893 if (isa<ReturnStmt>(SubStmt))
12894 Self.Diag(SubStmt->getLocStart(),
12895 diag::err_return_in_constructor_handler);
12896 if (!isa<Expr>(SubStmt))
12897 SearchForReturnInStmt(Self, SubStmt);
12901 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12902 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12903 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12904 SearchForReturnInStmt(*this, Handler);
12908 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12909 const CXXMethodDecl *Old) {
12910 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12911 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12913 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12915 // If the calling conventions match, everything is fine
12916 if (NewCC == OldCC)
12919 // If the calling conventions mismatch because the new function is static,
12920 // suppress the calling convention mismatch error; the error about static
12921 // function override (err_static_overrides_virtual from
12922 // Sema::CheckFunctionDeclaration) is more clear.
12923 if (New->getStorageClass() == SC_Static)
12926 Diag(New->getLocation(),
12927 diag::err_conflicting_overriding_cc_attributes)
12928 << New->getDeclName() << New->getType() << Old->getType();
12929 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12933 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12934 const CXXMethodDecl *Old) {
12935 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12936 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12938 if (Context.hasSameType(NewTy, OldTy) ||
12939 NewTy->isDependentType() || OldTy->isDependentType())
12942 // Check if the return types are covariant
12943 QualType NewClassTy, OldClassTy;
12945 /// Both types must be pointers or references to classes.
12946 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12947 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12948 NewClassTy = NewPT->getPointeeType();
12949 OldClassTy = OldPT->getPointeeType();
12951 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12952 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12953 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12954 NewClassTy = NewRT->getPointeeType();
12955 OldClassTy = OldRT->getPointeeType();
12960 // The return types aren't either both pointers or references to a class type.
12961 if (NewClassTy.isNull()) {
12962 Diag(New->getLocation(),
12963 diag::err_different_return_type_for_overriding_virtual_function)
12964 << New->getDeclName() << NewTy << OldTy
12965 << New->getReturnTypeSourceRange();
12966 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12967 << Old->getReturnTypeSourceRange();
12972 // C++ [class.virtual]p6:
12973 // If the return type of D::f differs from the return type of B::f, the
12974 // class type in the return type of D::f shall be complete at the point of
12975 // declaration of D::f or shall be the class type D.
12976 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12977 if (!RT->isBeingDefined() &&
12978 RequireCompleteType(New->getLocation(), NewClassTy,
12979 diag::err_covariant_return_incomplete,
12980 New->getDeclName()))
12984 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12985 // Check if the new class derives from the old class.
12986 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12987 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12988 << New->getDeclName() << NewTy << OldTy
12989 << New->getReturnTypeSourceRange();
12990 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12991 << Old->getReturnTypeSourceRange();
12995 // Check if we the conversion from derived to base is valid.
12996 if (CheckDerivedToBaseConversion(
12997 NewClassTy, OldClassTy,
12998 diag::err_covariant_return_inaccessible_base,
12999 diag::err_covariant_return_ambiguous_derived_to_base_conv,
13000 New->getLocation(), New->getReturnTypeSourceRange(),
13001 New->getDeclName(), nullptr)) {
13002 // FIXME: this note won't trigger for delayed access control
13003 // diagnostics, and it's impossible to get an undelayed error
13004 // here from access control during the original parse because
13005 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13006 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13007 << Old->getReturnTypeSourceRange();
13012 // The qualifiers of the return types must be the same.
13013 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13014 Diag(New->getLocation(),
13015 diag::err_covariant_return_type_different_qualifications)
13016 << New->getDeclName() << NewTy << OldTy
13017 << New->getReturnTypeSourceRange();
13018 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13019 << Old->getReturnTypeSourceRange();
13024 // The new class type must have the same or less qualifiers as the old type.
13025 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13026 Diag(New->getLocation(),
13027 diag::err_covariant_return_type_class_type_more_qualified)
13028 << New->getDeclName() << NewTy << OldTy
13029 << New->getReturnTypeSourceRange();
13030 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13031 << Old->getReturnTypeSourceRange();
13038 /// \brief Mark the given method pure.
13040 /// \param Method the method to be marked pure.
13042 /// \param InitRange the source range that covers the "0" initializer.
13043 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13044 SourceLocation EndLoc = InitRange.getEnd();
13045 if (EndLoc.isValid())
13046 Method->setRangeEnd(EndLoc);
13048 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13053 if (!Method->isInvalidDecl())
13054 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13055 << Method->getDeclName() << InitRange;
13059 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13060 if (D->getFriendObjectKind())
13061 Diag(D->getLocation(), diag::err_pure_friend);
13062 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13063 CheckPureMethod(M, ZeroLoc);
13065 Diag(D->getLocation(), diag::err_illegal_initializer);
13068 /// \brief Determine whether the given declaration is a static data member.
13069 static bool isStaticDataMember(const Decl *D) {
13070 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13071 return Var->isStaticDataMember();
13076 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13077 /// an initializer for the out-of-line declaration 'Dcl'. The scope
13078 /// is a fresh scope pushed for just this purpose.
13080 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13081 /// static data member of class X, names should be looked up in the scope of
13083 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13084 // If there is no declaration, there was an error parsing it.
13085 if (!D || D->isInvalidDecl())
13088 // We will always have a nested name specifier here, but this declaration
13089 // might not be out of line if the specifier names the current namespace:
13092 if (D->isOutOfLine())
13093 EnterDeclaratorContext(S, D->getDeclContext());
13095 // If we are parsing the initializer for a static data member, push a
13096 // new expression evaluation context that is associated with this static
13098 if (isStaticDataMember(D))
13099 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13102 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13103 /// initializer for the out-of-line declaration 'D'.
13104 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13105 // If there is no declaration, there was an error parsing it.
13106 if (!D || D->isInvalidDecl())
13109 if (isStaticDataMember(D))
13110 PopExpressionEvaluationContext();
13112 if (D->isOutOfLine())
13113 ExitDeclaratorContext(S);
13116 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13117 /// C++ if/switch/while/for statement.
13118 /// e.g: "if (int x = f()) {...}"
13119 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13121 // The declarator shall not specify a function or an array.
13122 // The type-specifier-seq shall not contain typedef and shall not declare a
13123 // new class or enumeration.
13124 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13125 "Parser allowed 'typedef' as storage class of condition decl.");
13127 Decl *Dcl = ActOnDeclarator(S, D);
13131 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13132 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13133 << D.getSourceRange();
13140 void Sema::LoadExternalVTableUses() {
13141 if (!ExternalSource)
13144 SmallVector<ExternalVTableUse, 4> VTables;
13145 ExternalSource->ReadUsedVTables(VTables);
13146 SmallVector<VTableUse, 4> NewUses;
13147 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13148 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13149 = VTablesUsed.find(VTables[I].Record);
13150 // Even if a definition wasn't required before, it may be required now.
13151 if (Pos != VTablesUsed.end()) {
13152 if (!Pos->second && VTables[I].DefinitionRequired)
13153 Pos->second = true;
13157 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13158 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13161 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13164 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13165 bool DefinitionRequired) {
13166 // Ignore any vtable uses in unevaluated operands or for classes that do
13167 // not have a vtable.
13168 if (!Class->isDynamicClass() || Class->isDependentContext() ||
13169 CurContext->isDependentContext() || isUnevaluatedContext())
13172 // Try to insert this class into the map.
13173 LoadExternalVTableUses();
13174 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13175 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13176 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13178 // If we already had an entry, check to see if we are promoting this vtable
13179 // to require a definition. If so, we need to reappend to the VTableUses
13180 // list, since we may have already processed the first entry.
13181 if (DefinitionRequired && !Pos.first->second) {
13182 Pos.first->second = true;
13184 // Otherwise, we can early exit.
13188 // The Microsoft ABI requires that we perform the destructor body
13189 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13190 // the deleting destructor is emitted with the vtable, not with the
13191 // destructor definition as in the Itanium ABI.
13192 // If it has a definition, we do the check at that point instead.
13193 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13194 Class->hasUserDeclaredDestructor() &&
13195 !Class->getDestructor()->isDefined() &&
13196 !Class->getDestructor()->isDeleted()) {
13197 CXXDestructorDecl *DD = Class->getDestructor();
13198 ContextRAII SavedContext(*this, DD);
13199 CheckDestructor(DD);
13203 // Local classes need to have their virtual members marked
13204 // immediately. For all other classes, we mark their virtual members
13205 // at the end of the translation unit.
13206 if (Class->isLocalClass())
13207 MarkVirtualMembersReferenced(Loc, Class);
13209 VTableUses.push_back(std::make_pair(Class, Loc));
13212 bool Sema::DefineUsedVTables() {
13213 LoadExternalVTableUses();
13214 if (VTableUses.empty())
13217 // Note: The VTableUses vector could grow as a result of marking
13218 // the members of a class as "used", so we check the size each
13219 // time through the loop and prefer indices (which are stable) to
13220 // iterators (which are not).
13221 bool DefinedAnything = false;
13222 for (unsigned I = 0; I != VTableUses.size(); ++I) {
13223 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13227 SourceLocation Loc = VTableUses[I].second;
13229 bool DefineVTable = true;
13231 // If this class has a key function, but that key function is
13232 // defined in another translation unit, we don't need to emit the
13233 // vtable even though we're using it.
13234 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13235 if (KeyFunction && !KeyFunction->hasBody()) {
13236 // The key function is in another translation unit.
13237 DefineVTable = false;
13238 TemplateSpecializationKind TSK =
13239 KeyFunction->getTemplateSpecializationKind();
13240 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13241 TSK != TSK_ImplicitInstantiation &&
13242 "Instantiations don't have key functions");
13244 } else if (!KeyFunction) {
13245 // If we have a class with no key function that is the subject
13246 // of an explicit instantiation declaration, suppress the
13247 // vtable; it will live with the explicit instantiation
13249 bool IsExplicitInstantiationDeclaration
13250 = Class->getTemplateSpecializationKind()
13251 == TSK_ExplicitInstantiationDeclaration;
13252 for (auto R : Class->redecls()) {
13253 TemplateSpecializationKind TSK
13254 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13255 if (TSK == TSK_ExplicitInstantiationDeclaration)
13256 IsExplicitInstantiationDeclaration = true;
13257 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13258 IsExplicitInstantiationDeclaration = false;
13263 if (IsExplicitInstantiationDeclaration)
13264 DefineVTable = false;
13267 // The exception specifications for all virtual members may be needed even
13268 // if we are not providing an authoritative form of the vtable in this TU.
13269 // We may choose to emit it available_externally anyway.
13270 if (!DefineVTable) {
13271 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13275 // Mark all of the virtual members of this class as referenced, so
13276 // that we can build a vtable. Then, tell the AST consumer that a
13277 // vtable for this class is required.
13278 DefinedAnything = true;
13279 MarkVirtualMembersReferenced(Loc, Class);
13280 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13281 if (VTablesUsed[Canonical])
13282 Consumer.HandleVTable(Class);
13284 // Optionally warn if we're emitting a weak vtable.
13285 if (Class->isExternallyVisible() &&
13286 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13287 const FunctionDecl *KeyFunctionDef = nullptr;
13288 if (!KeyFunction ||
13289 (KeyFunction->hasBody(KeyFunctionDef) &&
13290 KeyFunctionDef->isInlined()))
13291 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13292 TSK_ExplicitInstantiationDefinition
13293 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13297 VTableUses.clear();
13299 return DefinedAnything;
13302 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13303 const CXXRecordDecl *RD) {
13304 for (const auto *I : RD->methods())
13305 if (I->isVirtual() && !I->isPure())
13306 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13309 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13310 const CXXRecordDecl *RD) {
13311 // Mark all functions which will appear in RD's vtable as used.
13312 CXXFinalOverriderMap FinalOverriders;
13313 RD->getFinalOverriders(FinalOverriders);
13314 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13315 E = FinalOverriders.end();
13317 for (OverridingMethods::const_iterator OI = I->second.begin(),
13318 OE = I->second.end();
13320 assert(OI->second.size() > 0 && "no final overrider");
13321 CXXMethodDecl *Overrider = OI->second.front().Method;
13323 // C++ [basic.def.odr]p2:
13324 // [...] A virtual member function is used if it is not pure. [...]
13325 if (!Overrider->isPure())
13326 MarkFunctionReferenced(Loc, Overrider);
13330 // Only classes that have virtual bases need a VTT.
13331 if (RD->getNumVBases() == 0)
13334 for (const auto &I : RD->bases()) {
13335 const CXXRecordDecl *Base =
13336 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13337 if (Base->getNumVBases() == 0)
13339 MarkVirtualMembersReferenced(Loc, Base);
13343 /// SetIvarInitializers - This routine builds initialization ASTs for the
13344 /// Objective-C implementation whose ivars need be initialized.
13345 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13346 if (!getLangOpts().CPlusPlus)
13348 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13349 SmallVector<ObjCIvarDecl*, 8> ivars;
13350 CollectIvarsToConstructOrDestruct(OID, ivars);
13353 SmallVector<CXXCtorInitializer*, 32> AllToInit;
13354 for (unsigned i = 0; i < ivars.size(); i++) {
13355 FieldDecl *Field = ivars[i];
13356 if (Field->isInvalidDecl())
13359 CXXCtorInitializer *Member;
13360 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13361 InitializationKind InitKind =
13362 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13364 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13365 ExprResult MemberInit =
13366 InitSeq.Perform(*this, InitEntity, InitKind, None);
13367 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13368 // Note, MemberInit could actually come back empty if no initialization
13369 // is required (e.g., because it would call a trivial default constructor)
13370 if (!MemberInit.get() || MemberInit.isInvalid())
13374 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13376 MemberInit.getAs<Expr>(),
13378 AllToInit.push_back(Member);
13380 // Be sure that the destructor is accessible and is marked as referenced.
13381 if (const RecordType *RecordTy =
13382 Context.getBaseElementType(Field->getType())
13383 ->getAs<RecordType>()) {
13384 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13385 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13386 MarkFunctionReferenced(Field->getLocation(), Destructor);
13387 CheckDestructorAccess(Field->getLocation(), Destructor,
13388 PDiag(diag::err_access_dtor_ivar)
13389 << Context.getBaseElementType(Field->getType()));
13393 ObjCImplementation->setIvarInitializers(Context,
13394 AllToInit.data(), AllToInit.size());
13399 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13400 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13401 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13402 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13404 if (Ctor->isInvalidDecl())
13407 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13409 // Target may not be determinable yet, for instance if this is a dependent
13410 // call in an uninstantiated template.
13412 const FunctionDecl *FNTarget = nullptr;
13413 (void)Target->hasBody(FNTarget);
13414 Target = const_cast<CXXConstructorDecl*>(
13415 cast_or_null<CXXConstructorDecl>(FNTarget));
13418 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13419 // Avoid dereferencing a null pointer here.
13420 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13422 if (!Current.insert(Canonical).second)
13425 // We know that beyond here, we aren't chaining into a cycle.
13426 if (!Target || !Target->isDelegatingConstructor() ||
13427 Target->isInvalidDecl() || Valid.count(TCanonical)) {
13428 Valid.insert(Current.begin(), Current.end());
13430 // We've hit a cycle.
13431 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13432 Current.count(TCanonical)) {
13433 // If we haven't diagnosed this cycle yet, do so now.
13434 if (!Invalid.count(TCanonical)) {
13435 S.Diag((*Ctor->init_begin())->getSourceLocation(),
13436 diag::warn_delegating_ctor_cycle)
13439 // Don't add a note for a function delegating directly to itself.
13440 if (TCanonical != Canonical)
13441 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13443 CXXConstructorDecl *C = Target;
13444 while (C->getCanonicalDecl() != Canonical) {
13445 const FunctionDecl *FNTarget = nullptr;
13446 (void)C->getTargetConstructor()->hasBody(FNTarget);
13447 assert(FNTarget && "Ctor cycle through bodiless function");
13449 C = const_cast<CXXConstructorDecl*>(
13450 cast<CXXConstructorDecl>(FNTarget));
13451 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13455 Invalid.insert(Current.begin(), Current.end());
13458 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13463 void Sema::CheckDelegatingCtorCycles() {
13464 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13466 for (DelegatingCtorDeclsType::iterator
13467 I = DelegatingCtorDecls.begin(ExternalSource),
13468 E = DelegatingCtorDecls.end();
13470 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13472 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13473 CE = Invalid.end();
13475 (*CI)->setInvalidDecl();
13479 /// \brief AST visitor that finds references to the 'this' expression.
13480 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13484 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13486 bool VisitCXXThisExpr(CXXThisExpr *E) {
13487 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13488 << E->isImplicit();
13494 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13495 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13499 TypeLoc TL = TSInfo->getTypeLoc();
13500 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13504 // C++11 [expr.prim.general]p3:
13505 // [The expression this] shall not appear before the optional
13506 // cv-qualifier-seq and it shall not appear within the declaration of a
13507 // static member function (although its type and value category are defined
13508 // within a static member function as they are within a non-static member
13509 // function). [ Note: this is because declaration matching does not occur
13510 // until the complete declarator is known. - end note ]
13511 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13512 FindCXXThisExpr Finder(*this);
13514 // If the return type came after the cv-qualifier-seq, check it now.
13515 if (Proto->hasTrailingReturn() &&
13516 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13519 // Check the exception specification.
13520 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13523 return checkThisInStaticMemberFunctionAttributes(Method);
13526 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13527 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13531 TypeLoc TL = TSInfo->getTypeLoc();
13532 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13536 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13537 FindCXXThisExpr Finder(*this);
13539 switch (Proto->getExceptionSpecType()) {
13541 case EST_Uninstantiated:
13542 case EST_Unevaluated:
13543 case EST_BasicNoexcept:
13544 case EST_DynamicNone:
13549 case EST_ComputedNoexcept:
13550 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13554 for (const auto &E : Proto->exceptions()) {
13555 if (!Finder.TraverseType(E))
13564 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13565 FindCXXThisExpr Finder(*this);
13567 // Check attributes.
13568 for (const auto *A : Method->attrs()) {
13569 // FIXME: This should be emitted by tblgen.
13570 Expr *Arg = nullptr;
13571 ArrayRef<Expr *> Args;
13572 if (const auto *G = dyn_cast<GuardedByAttr>(A))
13574 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13576 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13577 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13578 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13579 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13580 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13581 Arg = ETLF->getSuccessValue();
13582 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13583 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13584 Arg = STLF->getSuccessValue();
13585 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13586 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13587 Arg = LR->getArg();
13588 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13589 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13590 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13591 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13592 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13593 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13594 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13595 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13596 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13597 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13599 if (Arg && !Finder.TraverseStmt(Arg))
13602 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13603 if (!Finder.TraverseStmt(Args[I]))
13611 void Sema::checkExceptionSpecification(
13612 bool IsTopLevel, ExceptionSpecificationType EST,
13613 ArrayRef<ParsedType> DynamicExceptions,
13614 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13615 SmallVectorImpl<QualType> &Exceptions,
13616 FunctionProtoType::ExceptionSpecInfo &ESI) {
13617 Exceptions.clear();
13619 if (EST == EST_Dynamic) {
13620 Exceptions.reserve(DynamicExceptions.size());
13621 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13622 // FIXME: Preserve type source info.
13623 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13626 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13627 collectUnexpandedParameterPacks(ET, Unexpanded);
13628 if (!Unexpanded.empty()) {
13629 DiagnoseUnexpandedParameterPacks(
13630 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13636 // Check that the type is valid for an exception spec, and
13638 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13639 Exceptions.push_back(ET);
13641 ESI.Exceptions = Exceptions;
13645 if (EST == EST_ComputedNoexcept) {
13646 // If an error occurred, there's no expression here.
13647 if (NoexceptExpr) {
13648 assert((NoexceptExpr->isTypeDependent() ||
13649 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13651 "Parser should have made sure that the expression is boolean");
13652 if (IsTopLevel && NoexceptExpr &&
13653 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13654 ESI.Type = EST_BasicNoexcept;
13658 if (!NoexceptExpr->isValueDependent())
13659 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13660 diag::err_noexcept_needs_constant_expression,
13661 /*AllowFold*/ false).get();
13662 ESI.NoexceptExpr = NoexceptExpr;
13668 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13669 ExceptionSpecificationType EST,
13670 SourceRange SpecificationRange,
13671 ArrayRef<ParsedType> DynamicExceptions,
13672 ArrayRef<SourceRange> DynamicExceptionRanges,
13673 Expr *NoexceptExpr) {
13677 // Dig out the method we're referring to.
13678 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13679 MethodD = FunTmpl->getTemplatedDecl();
13681 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13685 // Check the exception specification.
13686 llvm::SmallVector<QualType, 4> Exceptions;
13687 FunctionProtoType::ExceptionSpecInfo ESI;
13688 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13689 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13692 // Update the exception specification on the function type.
13693 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13695 if (Method->isStatic())
13696 checkThisInStaticMemberFunctionExceptionSpec(Method);
13698 if (Method->isVirtual()) {
13699 // Check overrides, which we previously had to delay.
13700 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13701 OEnd = Method->end_overridden_methods();
13703 CheckOverridingFunctionExceptionSpec(Method, *O);
13707 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13709 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13710 SourceLocation DeclStart,
13711 Declarator &D, Expr *BitWidth,
13712 InClassInitStyle InitStyle,
13713 AccessSpecifier AS,
13714 AttributeList *MSPropertyAttr) {
13715 IdentifierInfo *II = D.getIdentifier();
13717 Diag(DeclStart, diag::err_anonymous_property);
13720 SourceLocation Loc = D.getIdentifierLoc();
13722 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13723 QualType T = TInfo->getType();
13724 if (getLangOpts().CPlusPlus) {
13725 CheckExtraCXXDefaultArguments(D);
13727 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13728 UPPC_DataMemberType)) {
13729 D.setInvalidType();
13731 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13735 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13737 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13738 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13739 diag::err_invalid_thread)
13740 << DeclSpec::getSpecifierName(TSCS);
13742 // Check to see if this name was declared as a member previously
13743 NamedDecl *PrevDecl = nullptr;
13744 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13745 LookupName(Previous, S);
13746 switch (Previous.getResultKind()) {
13747 case LookupResult::Found:
13748 case LookupResult::FoundUnresolvedValue:
13749 PrevDecl = Previous.getAsSingle<NamedDecl>();
13752 case LookupResult::FoundOverloaded:
13753 PrevDecl = Previous.getRepresentativeDecl();
13756 case LookupResult::NotFound:
13757 case LookupResult::NotFoundInCurrentInstantiation:
13758 case LookupResult::Ambiguous:
13762 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13763 // Maybe we will complain about the shadowed template parameter.
13764 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13765 // Just pretend that we didn't see the previous declaration.
13766 PrevDecl = nullptr;
13769 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13770 PrevDecl = nullptr;
13772 SourceLocation TSSL = D.getLocStart();
13773 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13774 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13775 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13776 ProcessDeclAttributes(TUScope, NewPD, D);
13777 NewPD->setAccess(AS);
13779 if (NewPD->isInvalidDecl())
13780 Record->setInvalidDecl();
13782 if (D.getDeclSpec().isModulePrivateSpecified())
13783 NewPD->setModulePrivate();
13785 if (NewPD->isInvalidDecl() && PrevDecl) {
13786 // Don't introduce NewFD into scope; there's already something
13787 // with the same name in the same scope.
13789 PushOnScopeChains(NewPD, S);
13791 Record->addDecl(NewPD);