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/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclVisitor.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/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallString.h"
43 using namespace clang;
45 //===----------------------------------------------------------------------===//
46 // CheckDefaultArgumentVisitor
47 //===----------------------------------------------------------------------===//
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
55 class CheckDefaultArgumentVisitor
56 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62 : DefaultArg(defarg), S(s) {}
64 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
66 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67 bool VisitLambdaExpr(LambdaExpr *Lambda);
70 /// VisitExpr - Visit all of the children of this expression.
71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
73 for (Stmt::child_range I = Node->children(); I; ++I)
74 IsInvalid |= Visit(*I);
78 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
82 NamedDecl *Decl = DRE->getDecl();
83 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
92 return S->Diag(DRE->getLocStart(),
93 diag::err_param_default_argument_references_param)
94 << Param->getDeclName() << DefaultArg->getSourceRange();
95 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
96 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
99 if (VDecl->isLocalVarDecl())
100 return S->Diag(DRE->getLocStart(),
101 diag::err_param_default_argument_references_local)
102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
113 return S->Diag(ThisE->getLocStart(),
114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
130 void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
144 // If this function can throw any exceptions, make a note of that.
145 if (EST == EST_MSAny || EST == EST_None) {
151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
183 ComputedEST = EST_None;
185 // noexcept(true) won't change anything either.
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
198 Exceptions.push_back(*E);
201 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
202 if (!E || ComputedEST == EST_MSAny)
207 // C++0x [except.spec]p14:
208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
226 if (Self->canThrow(E))
227 ComputedEST = EST_None;
231 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
232 SourceLocation EqualLoc) {
233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
251 if (Result.isInvalid())
253 Arg = Result.takeAs<Expr>();
255 CheckCompletedExpr(Arg, EqualLoc);
256 Arg = MaybeCreateExprWithCleanups(Arg);
258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
276 /// ActOnParamDefaultArgument - Check whether the default argument
277 /// provided for a function parameter is well-formed. If so, attach it
278 /// to the parameter declaration.
280 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
282 if (!param || !DefaultArg)
285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
286 UnparsedDefaultArgLocs.erase(Param);
288 // Default arguments are only permitted in C++
289 if (!getLangOpts().CPlusPlus) {
290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
292 Param->setInvalidDecl();
296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
302 // Check that the default argument is well-formed
303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
305 Param->setInvalidDecl();
309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
312 /// ActOnParamUnparsedDefaultArgument - We've seen a default
313 /// argument for a function parameter, but we can't parse it yet
314 /// because we're inside a class definition. Note that this default
315 /// argument will be parsed later.
316 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
324 Param->setUnparsedDefaultArg();
326 UnparsedDefaultArgLocs[Param] = ArgLoc;
329 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330 /// the default argument for the parameter param failed.
331 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
337 Param->setInvalidDecl();
339 UnparsedDefaultArgLocs.erase(Param);
342 /// CheckExtraCXXDefaultArguments - Check for any extra default
343 /// arguments in the declarator, which is not a function declaration
344 /// or definition and therefore is not permitted to have default
345 /// arguments. This routine should be invoked for every declarator
346 /// that is not a function declaration or definition.
347 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
355 bool MightBeFunction = D.isFunctionDeclarationContext();
356 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
357 DeclaratorChunk &chunk = D.getTypeObject(i);
358 if (chunk.Kind == DeclaratorChunk::Function) {
359 if (MightBeFunction) {
360 // This is a function declaration. It can have default arguments, but
361 // keep looking in case its return type is a function type with default
363 MightBeFunction = false;
366 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
368 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
369 if (Param->hasUnparsedDefaultArg()) {
370 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
371 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
372 << SourceRange((*Toks)[1].getLocation(),
373 Toks->back().getLocation());
375 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
376 } else if (Param->getDefaultArg()) {
377 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
378 << Param->getDefaultArg()->getSourceRange();
379 Param->setDefaultArg(0);
382 } else if (chunk.Kind != DeclaratorChunk::Paren) {
383 MightBeFunction = false;
388 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
389 /// function, once we already know that they have the same
390 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
391 /// error, false otherwise.
392 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
394 bool Invalid = false;
396 // C++ [dcl.fct.default]p4:
397 // For non-template functions, default arguments can be added in
398 // later declarations of a function in the same
399 // scope. Declarations in different scopes have completely
400 // distinct sets of default arguments. That is, declarations in
401 // inner scopes do not acquire default arguments from
402 // declarations in outer scopes, and vice versa. In a given
403 // function declaration, all parameters subsequent to a
404 // parameter with a default argument shall have default
405 // arguments supplied in this or previous declarations. A
406 // default argument shall not be redefined by a later
407 // declaration (not even to the same value).
409 // C++ [dcl.fct.default]p6:
410 // Except for member functions of class templates, the default arguments
411 // in a member function definition that appears outside of the class
412 // definition are added to the set of default arguments provided by the
413 // member function declaration in the class definition.
414 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
415 ParmVarDecl *OldParam = Old->getParamDecl(p);
416 ParmVarDecl *NewParam = New->getParamDecl(p);
418 bool OldParamHasDfl = OldParam->hasDefaultArg();
419 bool NewParamHasDfl = NewParam->hasDefaultArg();
422 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
423 // Ignore default parameters of old decl if they are not in
425 OldParamHasDfl = false;
427 if (OldParamHasDfl && NewParamHasDfl) {
429 unsigned DiagDefaultParamID =
430 diag::err_param_default_argument_redefinition;
432 // MSVC accepts that default parameters be redefined for member functions
433 // of template class. The new default parameter's value is ignored.
435 if (getLangOpts().MicrosoftExt) {
436 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
437 if (MD && MD->getParent()->getDescribedClassTemplate()) {
438 // Merge the old default argument into the new parameter.
439 NewParam->setHasInheritedDefaultArg();
440 if (OldParam->hasUninstantiatedDefaultArg())
441 NewParam->setUninstantiatedDefaultArg(
442 OldParam->getUninstantiatedDefaultArg());
444 NewParam->setDefaultArg(OldParam->getInit());
445 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
450 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
451 // hint here. Alternatively, we could walk the type-source information
452 // for NewParam to find the last source location in the type... but it
453 // isn't worth the effort right now. This is the kind of test case that
454 // is hard to get right:
456 // void g(int (*fp)(int) = f);
457 // void g(int (*fp)(int) = &f);
458 Diag(NewParam->getLocation(), DiagDefaultParamID)
459 << NewParam->getDefaultArgRange();
461 // Look for the function declaration where the default argument was
462 // actually written, which may be a declaration prior to Old.
463 for (FunctionDecl *Older = Old->getPreviousDecl();
464 Older; Older = Older->getPreviousDecl()) {
465 if (!Older->getParamDecl(p)->hasDefaultArg())
468 OldParam = Older->getParamDecl(p);
471 Diag(OldParam->getLocation(), diag::note_previous_definition)
472 << OldParam->getDefaultArgRange();
473 } else if (OldParamHasDfl) {
474 // Merge the old default argument into the new parameter.
475 // It's important to use getInit() here; getDefaultArg()
476 // strips off any top-level ExprWithCleanups.
477 NewParam->setHasInheritedDefaultArg();
478 if (OldParam->hasUninstantiatedDefaultArg())
479 NewParam->setUninstantiatedDefaultArg(
480 OldParam->getUninstantiatedDefaultArg());
482 NewParam->setDefaultArg(OldParam->getInit());
483 } else if (NewParamHasDfl) {
484 if (New->getDescribedFunctionTemplate()) {
485 // Paragraph 4, quoted above, only applies to non-template functions.
486 Diag(NewParam->getLocation(),
487 diag::err_param_default_argument_template_redecl)
488 << NewParam->getDefaultArgRange();
489 Diag(Old->getLocation(), diag::note_template_prev_declaration)
491 } else if (New->getTemplateSpecializationKind()
492 != TSK_ImplicitInstantiation &&
493 New->getTemplateSpecializationKind() != TSK_Undeclared) {
494 // C++ [temp.expr.spec]p21:
495 // Default function arguments shall not be specified in a declaration
496 // or a definition for one of the following explicit specializations:
497 // - the explicit specialization of a function template;
498 // - the explicit specialization of a member function template;
499 // - the explicit specialization of a member function of a class
500 // template where the class template specialization to which the
501 // member function specialization belongs is implicitly
503 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
504 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
505 << New->getDeclName()
506 << NewParam->getDefaultArgRange();
507 } else if (New->getDeclContext()->isDependentContext()) {
508 // C++ [dcl.fct.default]p6 (DR217):
509 // Default arguments for a member function of a class template shall
510 // be specified on the initial declaration of the member function
511 // within the class template.
513 // Reading the tea leaves a bit in DR217 and its reference to DR205
514 // leads me to the conclusion that one cannot add default function
515 // arguments for an out-of-line definition of a member function of a
518 if (CXXRecordDecl *Record
519 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
520 if (Record->getDescribedClassTemplate())
522 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
528 Diag(NewParam->getLocation(),
529 diag::err_param_default_argument_member_template_redecl)
531 << NewParam->getDefaultArgRange();
536 // DR1344: If a default argument is added outside a class definition and that
537 // default argument makes the function a special member function, the program
538 // is ill-formed. This can only happen for constructors.
539 if (isa<CXXConstructorDecl>(New) &&
540 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
541 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
542 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
543 if (NewSM != OldSM) {
544 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
545 assert(NewParam->hasDefaultArg());
546 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
547 << NewParam->getDefaultArgRange() << NewSM;
548 Diag(Old->getLocation(), diag::note_previous_declaration);
552 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
553 // template has a constexpr specifier then all its declarations shall
554 // contain the constexpr specifier.
555 if (New->isConstexpr() != Old->isConstexpr()) {
556 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
557 << New << New->isConstexpr();
558 Diag(Old->getLocation(), diag::note_previous_declaration);
562 if (CheckEquivalentExceptionSpec(Old, New))
568 /// \brief Merge the exception specifications of two variable declarations.
570 /// This is called when there's a redeclaration of a VarDecl. The function
571 /// checks if the redeclaration might have an exception specification and
572 /// validates compatibility and merges the specs if necessary.
573 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
574 // Shortcut if exceptions are disabled.
575 if (!getLangOpts().CXXExceptions)
578 assert(Context.hasSameType(New->getType(), Old->getType()) &&
579 "Should only be called if types are otherwise the same.");
581 QualType NewType = New->getType();
582 QualType OldType = Old->getType();
584 // We're only interested in pointers and references to functions, as well
585 // as pointers to member functions.
586 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
587 NewType = R->getPointeeType();
588 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
589 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
590 NewType = P->getPointeeType();
591 OldType = OldType->getAs<PointerType>()->getPointeeType();
592 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
593 NewType = M->getPointeeType();
594 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
597 if (!NewType->isFunctionProtoType())
600 // There's lots of special cases for functions. For function pointers, system
601 // libraries are hopefully not as broken so that we don't need these
603 if (CheckEquivalentExceptionSpec(
604 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
605 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
606 New->setInvalidDecl();
610 /// CheckCXXDefaultArguments - Verify that the default arguments for a
611 /// function declaration are well-formed according to C++
612 /// [dcl.fct.default].
613 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
614 unsigned NumParams = FD->getNumParams();
617 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
618 isa<CXXMethodDecl>(FD) &&
619 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
621 // Find first parameter with a default argument
622 for (p = 0; p < NumParams; ++p) {
623 ParmVarDecl *Param = FD->getParamDecl(p);
624 if (Param->hasDefaultArg()) {
625 // C++11 [expr.prim.lambda]p5:
626 // [...] Default arguments (8.3.6) shall not be specified in the
627 // parameter-declaration-clause of a lambda-declarator.
629 // FIXME: Core issue 974 strikes this sentence, we only provide an
630 // extension warning.
632 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
633 << Param->getDefaultArgRange();
638 // C++ [dcl.fct.default]p4:
639 // In a given function declaration, all parameters
640 // subsequent to a parameter with a default argument shall
641 // have default arguments supplied in this or previous
642 // declarations. A default argument shall not be redefined
643 // by a later declaration (not even to the same value).
644 unsigned LastMissingDefaultArg = 0;
645 for (; p < NumParams; ++p) {
646 ParmVarDecl *Param = FD->getParamDecl(p);
647 if (!Param->hasDefaultArg()) {
648 if (Param->isInvalidDecl())
649 /* We already complained about this parameter. */;
650 else if (Param->getIdentifier())
651 Diag(Param->getLocation(),
652 diag::err_param_default_argument_missing_name)
653 << Param->getIdentifier();
655 Diag(Param->getLocation(),
656 diag::err_param_default_argument_missing);
658 LastMissingDefaultArg = p;
662 if (LastMissingDefaultArg > 0) {
663 // Some default arguments were missing. Clear out all of the
664 // default arguments up to (and including) the last missing
665 // default argument, so that we leave the function parameters
666 // in a semantically valid state.
667 for (p = 0; p <= LastMissingDefaultArg; ++p) {
668 ParmVarDecl *Param = FD->getParamDecl(p);
669 if (Param->hasDefaultArg()) {
670 Param->setDefaultArg(0);
676 // CheckConstexprParameterTypes - Check whether a function's parameter types
677 // are all literal types. If so, return true. If not, produce a suitable
678 // diagnostic and return false.
679 static bool CheckConstexprParameterTypes(Sema &SemaRef,
680 const FunctionDecl *FD) {
681 unsigned ArgIndex = 0;
682 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
683 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
684 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
685 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
686 SourceLocation ParamLoc = PD->getLocation();
687 if (!(*i)->isDependentType() &&
688 SemaRef.RequireLiteralType(ParamLoc, *i,
689 diag::err_constexpr_non_literal_param,
690 ArgIndex+1, PD->getSourceRange(),
691 isa<CXXConstructorDecl>(FD)))
697 /// \brief Get diagnostic %select index for tag kind for
698 /// record diagnostic message.
699 /// WARNING: Indexes apply to particular diagnostics only!
701 /// \returns diagnostic %select index.
702 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
704 case TTK_Struct: return 0;
705 case TTK_Interface: return 1;
706 case TTK_Class: return 2;
707 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
711 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
712 // the requirements of a constexpr function definition or a constexpr
713 // constructor definition. If so, return true. If not, produce appropriate
714 // diagnostics and return false.
716 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
717 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
718 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
719 if (MD && MD->isInstance()) {
720 // C++11 [dcl.constexpr]p4:
721 // The definition of a constexpr constructor shall satisfy the following
723 // - the class shall not have any virtual base classes;
724 const CXXRecordDecl *RD = MD->getParent();
725 if (RD->getNumVBases()) {
726 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
727 << isa<CXXConstructorDecl>(NewFD)
728 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
729 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
730 E = RD->vbases_end(); I != E; ++I)
731 Diag(I->getLocStart(),
732 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
737 if (!isa<CXXConstructorDecl>(NewFD)) {
738 // C++11 [dcl.constexpr]p3:
739 // The definition of a constexpr function shall satisfy the following
741 // - it shall not be virtual;
742 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
743 if (Method && Method->isVirtual()) {
744 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
746 // If it's not obvious why this function is virtual, find an overridden
747 // function which uses the 'virtual' keyword.
748 const CXXMethodDecl *WrittenVirtual = Method;
749 while (!WrittenVirtual->isVirtualAsWritten())
750 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
751 if (WrittenVirtual != Method)
752 Diag(WrittenVirtual->getLocation(),
753 diag::note_overridden_virtual_function);
757 // - its return type shall be a literal type;
758 QualType RT = NewFD->getResultType();
759 if (!RT->isDependentType() &&
760 RequireLiteralType(NewFD->getLocation(), RT,
761 diag::err_constexpr_non_literal_return))
765 // - each of its parameter types shall be a literal type;
766 if (!CheckConstexprParameterTypes(*this, NewFD))
772 /// Check the given declaration statement is legal within a constexpr function
773 /// body. C++0x [dcl.constexpr]p3,p4.
775 /// \return true if the body is OK, false if we have diagnosed a problem.
776 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
778 // C++0x [dcl.constexpr]p3 and p4:
779 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
781 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
782 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
783 switch ((*DclIt)->getKind()) {
784 case Decl::StaticAssert:
786 case Decl::UsingShadow:
787 case Decl::UsingDirective:
788 case Decl::UnresolvedUsingTypename:
789 // - static_assert-declarations
790 // - using-declarations,
791 // - using-directives,
795 case Decl::TypeAlias: {
796 // - typedef declarations and alias-declarations that do not define
797 // classes or enumerations,
798 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
799 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
800 // Don't allow variably-modified types in constexpr functions.
801 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
802 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
803 << TL.getSourceRange() << TL.getType()
804 << isa<CXXConstructorDecl>(Dcl);
811 case Decl::CXXRecord:
812 // As an extension, we allow the declaration (but not the definition) of
813 // classes and enumerations in all declarations, not just in typedef and
814 // alias declarations.
815 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
817 << isa<CXXConstructorDecl>(Dcl);
823 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
824 << isa<CXXConstructorDecl>(Dcl);
828 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
829 << isa<CXXConstructorDecl>(Dcl);
837 /// Check that the given field is initialized within a constexpr constructor.
839 /// \param Dcl The constexpr constructor being checked.
840 /// \param Field The field being checked. This may be a member of an anonymous
841 /// struct or union nested within the class being checked.
842 /// \param Inits All declarations, including anonymous struct/union members and
843 /// indirect members, for which any initialization was provided.
844 /// \param Diagnosed Set to true if an error is produced.
845 static void CheckConstexprCtorInitializer(Sema &SemaRef,
846 const FunctionDecl *Dcl,
848 llvm::SmallSet<Decl*, 16> &Inits,
850 if (Field->isUnnamedBitfield())
853 if (Field->isAnonymousStructOrUnion() &&
854 Field->getType()->getAsCXXRecordDecl()->isEmpty())
857 if (!Inits.count(Field)) {
859 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
862 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
863 } else if (Field->isAnonymousStructOrUnion()) {
864 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
865 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
867 // If an anonymous union contains an anonymous struct of which any member
868 // is initialized, all members must be initialized.
869 if (!RD->isUnion() || Inits.count(*I))
870 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
874 /// Check the body for the given constexpr function declaration only contains
875 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
877 /// \return true if the body is OK, false if we have diagnosed a problem.
878 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
879 if (isa<CXXTryStmt>(Body)) {
880 // C++11 [dcl.constexpr]p3:
881 // The definition of a constexpr function shall satisfy the following
882 // constraints: [...]
883 // - its function-body shall be = delete, = default, or a
884 // compound-statement
886 // C++11 [dcl.constexpr]p4:
887 // In the definition of a constexpr constructor, [...]
888 // - its function-body shall not be a function-try-block;
889 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
890 << isa<CXXConstructorDecl>(Dcl);
894 // - its function-body shall be [...] a compound-statement that contains only
895 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
897 SmallVector<SourceLocation, 4> ReturnStmts;
898 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
899 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
900 switch ((*BodyIt)->getStmtClass()) {
901 case Stmt::NullStmtClass:
902 // - null statements,
905 case Stmt::DeclStmtClass:
906 // - static_assert-declarations
907 // - using-declarations,
908 // - using-directives,
909 // - typedef declarations and alias-declarations that do not define
910 // classes or enumerations,
911 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
915 case Stmt::ReturnStmtClass:
916 // - and exactly one return statement;
917 if (isa<CXXConstructorDecl>(Dcl))
920 ReturnStmts.push_back((*BodyIt)->getLocStart());
927 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
932 if (const CXXConstructorDecl *Constructor
933 = dyn_cast<CXXConstructorDecl>(Dcl)) {
934 const CXXRecordDecl *RD = Constructor->getParent();
936 // - every non-variant non-static data member and base class sub-object
937 // shall be initialized;
938 // - if the class is a non-empty union, or for each non-empty anonymous
939 // union member of a non-union class, exactly one non-static data member
940 // shall be initialized;
942 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
943 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
946 } else if (!Constructor->isDependentContext() &&
947 !Constructor->isDelegatingConstructor()) {
948 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
950 // Skip detailed checking if we have enough initializers, and we would
951 // allow at most one initializer per member.
952 bool AnyAnonStructUnionMembers = false;
954 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
955 E = RD->field_end(); I != E; ++I, ++Fields) {
956 if (I->isAnonymousStructOrUnion()) {
957 AnyAnonStructUnionMembers = true;
961 if (AnyAnonStructUnionMembers ||
962 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
963 // Check initialization of non-static data members. Base classes are
964 // always initialized so do not need to be checked. Dependent bases
965 // might not have initializers in the member initializer list.
966 llvm::SmallSet<Decl*, 16> Inits;
967 for (CXXConstructorDecl::init_const_iterator
968 I = Constructor->init_begin(), E = Constructor->init_end();
970 if (FieldDecl *FD = (*I)->getMember())
972 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
973 Inits.insert(ID->chain_begin(), ID->chain_end());
976 bool Diagnosed = false;
977 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
978 E = RD->field_end(); I != E; ++I)
979 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
985 if (ReturnStmts.empty()) {
986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
989 if (ReturnStmts.size() > 1) {
990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
997 // C++11 [dcl.constexpr]p5:
998 // if no function argument values exist such that the function invocation
999 // substitution would produce a constant expression, the program is
1000 // ill-formed; no diagnostic required.
1001 // C++11 [dcl.constexpr]p3:
1002 // - every constructor call and implicit conversion used in initializing the
1003 // return value shall be one of those allowed in a constant expression.
1004 // C++11 [dcl.constexpr]p4:
1005 // - every constructor involved in initializing non-static data members and
1006 // base class sub-objects shall be a constexpr constructor.
1007 SmallVector<PartialDiagnosticAt, 8> Diags;
1008 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1009 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1010 << isa<CXXConstructorDecl>(Dcl);
1011 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012 Diag(Diags[I].first, Diags[I].second);
1013 // Don't return false here: we allow this for compatibility in
1020 /// isCurrentClassName - Determine whether the identifier II is the
1021 /// name of the class type currently being defined. In the case of
1022 /// nested classes, this will only return true if II is the name of
1023 /// the innermost class.
1024 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1025 const CXXScopeSpec *SS) {
1026 assert(getLangOpts().CPlusPlus && "No class names in C!");
1028 CXXRecordDecl *CurDecl;
1029 if (SS && SS->isSet() && !SS->isInvalid()) {
1030 DeclContext *DC = computeDeclContext(*SS, true);
1031 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1033 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1035 if (CurDecl && CurDecl->getIdentifier())
1036 return &II == CurDecl->getIdentifier();
1041 /// \brief Determine whether the given class is a base class of the given
1042 /// class, including looking at dependent bases.
1043 static bool findCircularInheritance(const CXXRecordDecl *Class,
1044 const CXXRecordDecl *Current) {
1045 SmallVector<const CXXRecordDecl*, 8> Queue;
1047 Class = Class->getCanonicalDecl();
1049 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1050 E = Current->bases_end();
1052 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1056 Base = Base->getDefinition();
1060 if (Base->getCanonicalDecl() == Class)
1063 Queue.push_back(Base);
1069 Current = Queue.back();
1076 /// \brief Check the validity of a C++ base class specifier.
1078 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1079 /// and returns NULL otherwise.
1081 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1082 SourceRange SpecifierRange,
1083 bool Virtual, AccessSpecifier Access,
1084 TypeSourceInfo *TInfo,
1085 SourceLocation EllipsisLoc) {
1086 QualType BaseType = TInfo->getType();
1088 // C++ [class.union]p1:
1089 // A union shall not have base classes.
1090 if (Class->isUnion()) {
1091 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1096 if (EllipsisLoc.isValid() &&
1097 !TInfo->getType()->containsUnexpandedParameterPack()) {
1098 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1099 << TInfo->getTypeLoc().getSourceRange();
1100 EllipsisLoc = SourceLocation();
1103 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1105 if (BaseType->isDependentType()) {
1106 // Make sure that we don't have circular inheritance among our dependent
1107 // bases. For non-dependent bases, the check for completeness below handles
1109 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1110 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1111 ((BaseDecl = BaseDecl->getDefinition()) &&
1112 findCircularInheritance(Class, BaseDecl))) {
1113 Diag(BaseLoc, diag::err_circular_inheritance)
1114 << BaseType << Context.getTypeDeclType(Class);
1116 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1117 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1124 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1125 Class->getTagKind() == TTK_Class,
1126 Access, TInfo, EllipsisLoc);
1129 // Base specifiers must be record types.
1130 if (!BaseType->isRecordType()) {
1131 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1135 // C++ [class.union]p1:
1136 // A union shall not be used as a base class.
1137 if (BaseType->isUnionType()) {
1138 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1142 // C++ [class.derived]p2:
1143 // The class-name in a base-specifier shall not be an incompletely
1145 if (RequireCompleteType(BaseLoc, BaseType,
1146 diag::err_incomplete_base_class, SpecifierRange)) {
1147 Class->setInvalidDecl();
1151 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1152 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1153 assert(BaseDecl && "Record type has no declaration");
1154 BaseDecl = BaseDecl->getDefinition();
1155 assert(BaseDecl && "Base type is not incomplete, but has no definition");
1156 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1157 assert(CXXBaseDecl && "Base type is not a C++ type");
1160 // If a class is marked final and it appears as a base-type-specifier in
1161 // base-clause, the program is ill-formed.
1162 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1163 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1164 << CXXBaseDecl->getDeclName();
1165 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1166 << CXXBaseDecl->getDeclName();
1170 if (BaseDecl->isInvalidDecl())
1171 Class->setInvalidDecl();
1173 // Create the base specifier.
1174 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1175 Class->getTagKind() == TTK_Class,
1176 Access, TInfo, EllipsisLoc);
1179 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1180 /// one entry in the base class list of a class specifier, for
1182 /// class foo : public bar, virtual private baz {
1183 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1185 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1186 ParsedAttributes &Attributes,
1187 bool Virtual, AccessSpecifier Access,
1188 ParsedType basetype, SourceLocation BaseLoc,
1189 SourceLocation EllipsisLoc) {
1193 AdjustDeclIfTemplate(classdecl);
1194 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1198 // We do not support any C++11 attributes on base-specifiers yet.
1199 // Diagnose any attributes we see.
1200 if (!Attributes.empty()) {
1201 for (AttributeList *Attr = Attributes.getList(); Attr;
1202 Attr = Attr->getNext()) {
1203 if (Attr->isInvalid() ||
1204 Attr->getKind() == AttributeList::IgnoredAttribute)
1206 Diag(Attr->getLoc(),
1207 Attr->getKind() == AttributeList::UnknownAttribute
1208 ? diag::warn_unknown_attribute_ignored
1209 : diag::err_base_specifier_attribute)
1214 TypeSourceInfo *TInfo = 0;
1215 GetTypeFromParser(basetype, &TInfo);
1217 if (EllipsisLoc.isInvalid() &&
1218 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1222 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1223 Virtual, Access, TInfo,
1227 Class->setInvalidDecl();
1232 /// \brief Performs the actual work of attaching the given base class
1233 /// specifiers to a C++ class.
1234 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1235 unsigned NumBases) {
1239 // Used to keep track of which base types we have already seen, so
1240 // that we can properly diagnose redundant direct base types. Note
1241 // that the key is always the unqualified canonical type of the base
1243 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1245 // Copy non-redundant base specifiers into permanent storage.
1246 unsigned NumGoodBases = 0;
1247 bool Invalid = false;
1248 for (unsigned idx = 0; idx < NumBases; ++idx) {
1249 QualType NewBaseType
1250 = Context.getCanonicalType(Bases[idx]->getType());
1251 NewBaseType = NewBaseType.getLocalUnqualifiedType();
1253 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1255 // C++ [class.mi]p3:
1256 // A class shall not be specified as a direct base class of a
1257 // derived class more than once.
1258 Diag(Bases[idx]->getLocStart(),
1259 diag::err_duplicate_base_class)
1260 << KnownBase->getType()
1261 << Bases[idx]->getSourceRange();
1263 // Delete the duplicate base class specifier; we're going to
1264 // overwrite its pointer later.
1265 Context.Deallocate(Bases[idx]);
1269 // Okay, add this new base class.
1270 KnownBase = Bases[idx];
1271 Bases[NumGoodBases++] = Bases[idx];
1272 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1273 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1274 if (Class->isInterface() &&
1275 (!RD->isInterface() ||
1276 KnownBase->getAccessSpecifier() != AS_public)) {
1277 // The Microsoft extension __interface does not permit bases that
1278 // are not themselves public interfaces.
1279 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1280 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1281 << RD->getSourceRange();
1284 if (RD->hasAttr<WeakAttr>())
1285 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1290 // Attach the remaining base class specifiers to the derived class.
1291 Class->setBases(Bases, NumGoodBases);
1293 // Delete the remaining (good) base class specifiers, since their
1294 // data has been copied into the CXXRecordDecl.
1295 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1296 Context.Deallocate(Bases[idx]);
1301 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1302 /// class, after checking whether there are any duplicate base
1304 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1305 unsigned NumBases) {
1306 if (!ClassDecl || !Bases || !NumBases)
1309 AdjustDeclIfTemplate(ClassDecl);
1310 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1311 (CXXBaseSpecifier**)(Bases), NumBases);
1314 /// \brief Determine whether the type \p Derived is a C++ class that is
1315 /// derived from the type \p Base.
1316 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1317 if (!getLangOpts().CPlusPlus)
1320 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1324 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1328 // If either the base or the derived type is invalid, don't try to
1329 // check whether one is derived from the other.
1330 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1333 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1334 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1337 /// \brief Determine whether the type \p Derived is a C++ class that is
1338 /// derived from the type \p Base.
1339 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1340 if (!getLangOpts().CPlusPlus)
1343 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1347 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1351 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1354 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1355 CXXCastPath &BasePathArray) {
1356 assert(BasePathArray.empty() && "Base path array must be empty!");
1357 assert(Paths.isRecordingPaths() && "Must record paths!");
1359 const CXXBasePath &Path = Paths.front();
1361 // We first go backward and check if we have a virtual base.
1362 // FIXME: It would be better if CXXBasePath had the base specifier for
1363 // the nearest virtual base.
1365 for (unsigned I = Path.size(); I != 0; --I) {
1366 if (Path[I - 1].Base->isVirtual()) {
1372 // Now add all bases.
1373 for (unsigned I = Start, E = Path.size(); I != E; ++I)
1374 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1377 /// \brief Determine whether the given base path includes a virtual
1379 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1380 for (CXXCastPath::const_iterator B = BasePath.begin(),
1381 BEnd = BasePath.end();
1383 if ((*B)->isVirtual())
1389 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1390 /// conversion (where Derived and Base are class types) is
1391 /// well-formed, meaning that the conversion is unambiguous (and
1392 /// that all of the base classes are accessible). Returns true
1393 /// and emits a diagnostic if the code is ill-formed, returns false
1394 /// otherwise. Loc is the location where this routine should point to
1395 /// if there is an error, and Range is the source range to highlight
1396 /// if there is an error.
1398 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1399 unsigned InaccessibleBaseID,
1400 unsigned AmbigiousBaseConvID,
1401 SourceLocation Loc, SourceRange Range,
1402 DeclarationName Name,
1403 CXXCastPath *BasePath) {
1404 // First, determine whether the path from Derived to Base is
1405 // ambiguous. This is slightly more expensive than checking whether
1406 // the Derived to Base conversion exists, because here we need to
1407 // explore multiple paths to determine if there is an ambiguity.
1408 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1409 /*DetectVirtual=*/false);
1410 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1411 assert(DerivationOkay &&
1412 "Can only be used with a derived-to-base conversion");
1413 (void)DerivationOkay;
1415 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1416 if (InaccessibleBaseID) {
1417 // Check that the base class can be accessed.
1418 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1419 InaccessibleBaseID)) {
1420 case AR_inaccessible:
1429 // Build a base path if necessary.
1431 BuildBasePathArray(Paths, *BasePath);
1435 // We know that the derived-to-base conversion is ambiguous, and
1436 // we're going to produce a diagnostic. Perform the derived-to-base
1437 // search just one more time to compute all of the possible paths so
1438 // that we can print them out. This is more expensive than any of
1439 // the previous derived-to-base checks we've done, but at this point
1440 // performance isn't as much of an issue.
1442 Paths.setRecordingPaths(true);
1443 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1444 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1447 // Build up a textual representation of the ambiguous paths, e.g.,
1448 // D -> B -> A, that will be used to illustrate the ambiguous
1449 // conversions in the diagnostic. We only print one of the paths
1450 // to each base class subobject.
1451 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1453 Diag(Loc, AmbigiousBaseConvID)
1454 << Derived << Base << PathDisplayStr << Range << Name;
1459 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1460 SourceLocation Loc, SourceRange Range,
1461 CXXCastPath *BasePath,
1462 bool IgnoreAccess) {
1463 return CheckDerivedToBaseConversion(Derived, Base,
1465 : diag::err_upcast_to_inaccessible_base,
1466 diag::err_ambiguous_derived_to_base_conv,
1467 Loc, Range, DeclarationName(),
1472 /// @brief Builds a string representing ambiguous paths from a
1473 /// specific derived class to different subobjects of the same base
1476 /// This function builds a string that can be used in error messages
1477 /// to show the different paths that one can take through the
1478 /// inheritance hierarchy to go from the derived class to different
1479 /// subobjects of a base class. The result looks something like this:
1481 /// struct D -> struct B -> struct A
1482 /// struct D -> struct C -> struct A
1484 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1485 std::string PathDisplayStr;
1486 std::set<unsigned> DisplayedPaths;
1487 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1488 Path != Paths.end(); ++Path) {
1489 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1490 // We haven't displayed a path to this particular base
1491 // class subobject yet.
1492 PathDisplayStr += "\n ";
1493 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1494 for (CXXBasePath::const_iterator Element = Path->begin();
1495 Element != Path->end(); ++Element)
1496 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1500 return PathDisplayStr;
1503 //===----------------------------------------------------------------------===//
1504 // C++ class member Handling
1505 //===----------------------------------------------------------------------===//
1507 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1508 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1509 SourceLocation ASLoc,
1510 SourceLocation ColonLoc,
1511 AttributeList *Attrs) {
1512 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1513 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1515 CurContext->addHiddenDecl(ASDecl);
1516 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1519 /// CheckOverrideControl - Check C++11 override control semantics.
1520 void Sema::CheckOverrideControl(Decl *D) {
1521 if (D->isInvalidDecl())
1524 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1526 // Do we know which functions this declaration might be overriding?
1527 bool OverridesAreKnown = !MD ||
1528 (!MD->getParent()->hasAnyDependentBases() &&
1529 !MD->getType()->isDependentType());
1531 if (!MD || !MD->isVirtual()) {
1532 if (OverridesAreKnown) {
1533 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1534 Diag(OA->getLocation(),
1535 diag::override_keyword_only_allowed_on_virtual_member_functions)
1536 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1537 D->dropAttr<OverrideAttr>();
1539 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1540 Diag(FA->getLocation(),
1541 diag::override_keyword_only_allowed_on_virtual_member_functions)
1542 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1543 D->dropAttr<FinalAttr>();
1549 if (!OverridesAreKnown)
1552 // C++11 [class.virtual]p5:
1553 // If a virtual function is marked with the virt-specifier override and
1554 // does not override a member function of a base class, the program is
1556 bool HasOverriddenMethods =
1557 MD->begin_overridden_methods() != MD->end_overridden_methods();
1558 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1559 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1560 << MD->getDeclName();
1563 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1564 /// function overrides a virtual member function marked 'final', according to
1565 /// C++11 [class.virtual]p4.
1566 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1567 const CXXMethodDecl *Old) {
1568 if (!Old->hasAttr<FinalAttr>())
1571 Diag(New->getLocation(), diag::err_final_function_overridden)
1572 << New->getDeclName();
1573 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1577 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1578 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1579 // FIXME: Destruction of ObjC lifetime types has side-effects.
1580 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1581 return !RD->isCompleteDefinition() ||
1582 !RD->hasTrivialDefaultConstructor() ||
1583 !RD->hasTrivialDestructor();
1587 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1588 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1589 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1590 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1591 /// present (but parsing it has been deferred).
1593 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1594 MultiTemplateParamsArg TemplateParameterLists,
1595 Expr *BW, const VirtSpecifiers &VS,
1596 InClassInitStyle InitStyle) {
1597 const DeclSpec &DS = D.getDeclSpec();
1598 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1599 DeclarationName Name = NameInfo.getName();
1600 SourceLocation Loc = NameInfo.getLoc();
1602 // For anonymous bitfields, the location should point to the type.
1603 if (Loc.isInvalid())
1604 Loc = D.getLocStart();
1606 Expr *BitWidth = static_cast<Expr*>(BW);
1608 assert(isa<CXXRecordDecl>(CurContext));
1609 assert(!DS.isFriendSpecified());
1611 bool isFunc = D.isDeclarationOfFunction();
1613 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1614 // The Microsoft extension __interface only permits public member functions
1615 // and prohibits constructors, destructors, operators, non-public member
1616 // functions, static methods and data members.
1617 unsigned InvalidDecl;
1618 bool ShowDeclName = true;
1620 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1621 else if (AS != AS_public)
1623 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1625 else switch (Name.getNameKind()) {
1626 case DeclarationName::CXXConstructorName:
1628 ShowDeclName = false;
1631 case DeclarationName::CXXDestructorName:
1633 ShowDeclName = false;
1636 case DeclarationName::CXXOperatorName:
1637 case DeclarationName::CXXConversionFunctionName:
1648 Diag(Loc, diag::err_invalid_member_in_interface)
1649 << (InvalidDecl-1) << Name;
1651 Diag(Loc, diag::err_invalid_member_in_interface)
1652 << (InvalidDecl-1) << "";
1657 // C++ 9.2p6: A member shall not be declared to have automatic storage
1658 // duration (auto, register) or with the extern storage-class-specifier.
1659 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1660 // data members and cannot be applied to names declared const or static,
1661 // and cannot be applied to reference members.
1662 switch (DS.getStorageClassSpec()) {
1663 case DeclSpec::SCS_unspecified:
1664 case DeclSpec::SCS_typedef:
1665 case DeclSpec::SCS_static:
1668 case DeclSpec::SCS_mutable:
1670 if (DS.getStorageClassSpecLoc().isValid())
1671 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1673 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1675 // FIXME: It would be nicer if the keyword was ignored only for this
1676 // declarator. Otherwise we could get follow-up errors.
1677 D.getMutableDeclSpec().ClearStorageClassSpecs();
1681 if (DS.getStorageClassSpecLoc().isValid())
1682 Diag(DS.getStorageClassSpecLoc(),
1683 diag::err_storageclass_invalid_for_member);
1685 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1686 D.getMutableDeclSpec().ClearStorageClassSpecs();
1689 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1690 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1693 if (DS.isConstexprSpecified() && isInstField) {
1694 SemaDiagnosticBuilder B =
1695 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1696 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1697 if (InitStyle == ICIS_NoInit) {
1698 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1699 D.getMutableDeclSpec().ClearConstexprSpec();
1700 const char *PrevSpec;
1702 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1703 PrevSpec, DiagID, getLangOpts());
1705 assert(!Failed && "Making a constexpr member const shouldn't fail");
1708 const char *PrevSpec;
1710 if (D.getMutableDeclSpec().SetStorageClassSpec(
1711 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1712 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1713 "This is the only DeclSpec that should fail to be applied");
1716 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1717 isInstField = false;
1724 CXXScopeSpec &SS = D.getCXXScopeSpec();
1726 // Data members must have identifiers for names.
1727 if (!Name.isIdentifier()) {
1728 Diag(Loc, diag::err_bad_variable_name)
1733 IdentifierInfo *II = Name.getAsIdentifierInfo();
1735 // Member field could not be with "template" keyword.
1736 // So TemplateParameterLists should be empty in this case.
1737 if (TemplateParameterLists.size()) {
1738 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1739 if (TemplateParams->size()) {
1740 // There is no such thing as a member field template.
1741 Diag(D.getIdentifierLoc(), diag::err_template_member)
1743 << SourceRange(TemplateParams->getTemplateLoc(),
1744 TemplateParams->getRAngleLoc());
1746 // There is an extraneous 'template<>' for this member.
1747 Diag(TemplateParams->getTemplateLoc(),
1748 diag::err_template_member_noparams)
1750 << SourceRange(TemplateParams->getTemplateLoc(),
1751 TemplateParams->getRAngleLoc());
1756 if (SS.isSet() && !SS.isInvalid()) {
1757 // The user provided a superfluous scope specifier inside a class
1763 if (DeclContext *DC = computeDeclContext(SS, false))
1764 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1766 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1767 << Name << SS.getRange();
1772 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1774 assert(Member && "HandleField never returns null");
1776 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1778 Member = HandleDeclarator(S, D, TemplateParameterLists);
1783 // Non-instance-fields can't have a bitfield.
1785 if (Member->isInvalidDecl()) {
1786 // don't emit another diagnostic.
1787 } else if (isa<VarDecl>(Member)) {
1788 // C++ 9.6p3: A bit-field shall not be a static member.
1789 // "static member 'A' cannot be a bit-field"
1790 Diag(Loc, diag::err_static_not_bitfield)
1791 << Name << BitWidth->getSourceRange();
1792 } else if (isa<TypedefDecl>(Member)) {
1793 // "typedef member 'x' cannot be a bit-field"
1794 Diag(Loc, diag::err_typedef_not_bitfield)
1795 << Name << BitWidth->getSourceRange();
1797 // A function typedef ("typedef int f(); f a;").
1798 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1799 Diag(Loc, diag::err_not_integral_type_bitfield)
1800 << Name << cast<ValueDecl>(Member)->getType()
1801 << BitWidth->getSourceRange();
1805 Member->setInvalidDecl();
1808 Member->setAccess(AS);
1810 // If we have declared a member function template, set the access of the
1811 // templated declaration as well.
1812 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1813 FunTmpl->getTemplatedDecl()->setAccess(AS);
1816 if (VS.isOverrideSpecified())
1817 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1818 if (VS.isFinalSpecified())
1819 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1821 if (VS.getLastLocation().isValid()) {
1822 // Update the end location of a method that has a virt-specifiers.
1823 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1824 MD->setRangeEnd(VS.getLastLocation());
1827 CheckOverrideControl(Member);
1829 assert((Name || isInstField) && "No identifier for non-field ?");
1832 FieldDecl *FD = cast<FieldDecl>(Member);
1833 FieldCollector->Add(FD);
1835 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1837 != DiagnosticsEngine::Ignored) {
1838 // Remember all explicit private FieldDecls that have a name, no side
1839 // effects and are not part of a dependent type declaration.
1840 if (!FD->isImplicit() && FD->getDeclName() &&
1841 FD->getAccess() == AS_private &&
1842 !FD->hasAttr<UnusedAttr>() &&
1843 !FD->getParent()->isDependentContext() &&
1844 !InitializationHasSideEffects(*FD))
1845 UnusedPrivateFields.insert(FD);
1853 class UninitializedFieldVisitor
1854 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1858 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1859 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
1861 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1862 this->VD = IFD->getAnonField();
1867 void HandleExpr(Expr *E) {
1870 // Expressions like x(x) sometimes lack the surrounding expressions
1871 // but need to be checked anyways.
1876 void HandleValue(Expr *E) {
1877 E = E->IgnoreParens();
1879 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1880 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
1883 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1885 MemberExpr *FieldME = ME;
1888 while (isa<MemberExpr>(Base)) {
1889 ME = cast<MemberExpr>(Base);
1891 if (isa<VarDecl>(ME->getMemberDecl()))
1894 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1895 if (!FD->isAnonymousStructOrUnion())
1898 Base = ME->getBase();
1901 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
1902 unsigned diag = VD->getType()->isReferenceType()
1903 ? diag::warn_reference_field_is_uninit
1904 : diag::warn_field_is_uninit;
1905 S.Diag(FieldME->getExprLoc(), diag) << VD;
1910 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1911 HandleValue(CO->getTrueExpr());
1912 HandleValue(CO->getFalseExpr());
1916 if (BinaryConditionalOperator *BCO =
1917 dyn_cast<BinaryConditionalOperator>(E)) {
1918 HandleValue(BCO->getCommon());
1919 HandleValue(BCO->getFalseExpr());
1923 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1924 switch (BO->getOpcode()) {
1929 HandleValue(BO->getLHS());
1932 HandleValue(BO->getRHS());
1938 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1939 if (E->getCastKind() == CK_LValueToRValue)
1940 HandleValue(E->getSubExpr());
1942 Inherited::VisitImplicitCastExpr(E);
1945 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1946 Expr *Callee = E->getCallee();
1947 if (isa<MemberExpr>(Callee))
1948 HandleValue(Callee);
1950 Inherited::VisitCXXMemberCallExpr(E);
1953 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1955 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1959 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1960 /// in-class initializer for a non-static C++ class member, and after
1961 /// instantiating an in-class initializer in a class template. Such actions
1962 /// are deferred until the class is complete.
1964 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1966 FieldDecl *FD = cast<FieldDecl>(D);
1967 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1968 "must set init style when field is created");
1971 FD->setInvalidDecl();
1972 FD->removeInClassInitializer();
1976 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1977 FD->setInvalidDecl();
1978 FD->removeInClassInitializer();
1982 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1983 != DiagnosticsEngine::Ignored) {
1984 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1987 ExprResult Init = InitExpr;
1988 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1989 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1990 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1991 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1993 Expr **Inits = &InitExpr;
1994 unsigned NumInits = 1;
1995 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1996 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1997 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1998 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1999 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2000 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
2001 if (Init.isInvalid()) {
2002 FD->setInvalidDecl();
2007 // C++11 [class.base.init]p7:
2008 // The initialization of each base and member constitutes a
2010 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2011 if (Init.isInvalid()) {
2012 FD->setInvalidDecl();
2016 InitExpr = Init.release();
2018 FD->setInClassInitializer(InitExpr);
2021 /// \brief Find the direct and/or virtual base specifiers that
2022 /// correspond to the given base type, for use in base initialization
2023 /// within a constructor.
2024 static bool FindBaseInitializer(Sema &SemaRef,
2025 CXXRecordDecl *ClassDecl,
2027 const CXXBaseSpecifier *&DirectBaseSpec,
2028 const CXXBaseSpecifier *&VirtualBaseSpec) {
2029 // First, check for a direct base class.
2031 for (CXXRecordDecl::base_class_const_iterator Base
2032 = ClassDecl->bases_begin();
2033 Base != ClassDecl->bases_end(); ++Base) {
2034 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2035 // We found a direct base of this type. That's what we're
2037 DirectBaseSpec = &*Base;
2042 // Check for a virtual base class.
2043 // FIXME: We might be able to short-circuit this if we know in advance that
2044 // there are no virtual bases.
2045 VirtualBaseSpec = 0;
2046 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2047 // We haven't found a base yet; search the class hierarchy for a
2048 // virtual base class.
2049 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2050 /*DetectVirtual=*/false);
2051 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2053 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2054 Path != Paths.end(); ++Path) {
2055 if (Path->back().Base->isVirtual()) {
2056 VirtualBaseSpec = Path->back().Base;
2063 return DirectBaseSpec || VirtualBaseSpec;
2066 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2068 Sema::ActOnMemInitializer(Decl *ConstructorD,
2071 IdentifierInfo *MemberOrBase,
2072 ParsedType TemplateTypeTy,
2074 SourceLocation IdLoc,
2076 SourceLocation EllipsisLoc) {
2077 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2078 DS, IdLoc, InitList,
2082 /// \brief Handle a C++ member initializer using parentheses syntax.
2084 Sema::ActOnMemInitializer(Decl *ConstructorD,
2087 IdentifierInfo *MemberOrBase,
2088 ParsedType TemplateTypeTy,
2090 SourceLocation IdLoc,
2091 SourceLocation LParenLoc,
2092 Expr **Args, unsigned NumArgs,
2093 SourceLocation RParenLoc,
2094 SourceLocation EllipsisLoc) {
2095 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2096 llvm::makeArrayRef(Args, NumArgs),
2098 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2099 DS, IdLoc, List, EllipsisLoc);
2104 // Callback to only accept typo corrections that can be a valid C++ member
2105 // intializer: either a non-static field member or a base class.
2106 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2108 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2109 : ClassDecl(ClassDecl) {}
2111 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2112 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2113 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2114 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2116 return isa<TypeDecl>(ND);
2122 CXXRecordDecl *ClassDecl;
2127 /// \brief Handle a C++ member initializer.
2129 Sema::BuildMemInitializer(Decl *ConstructorD,
2132 IdentifierInfo *MemberOrBase,
2133 ParsedType TemplateTypeTy,
2135 SourceLocation IdLoc,
2137 SourceLocation EllipsisLoc) {
2141 AdjustDeclIfTemplate(ConstructorD);
2143 CXXConstructorDecl *Constructor
2144 = dyn_cast<CXXConstructorDecl>(ConstructorD);
2146 // The user wrote a constructor initializer on a function that is
2147 // not a C++ constructor. Ignore the error for now, because we may
2148 // have more member initializers coming; we'll diagnose it just
2149 // once in ActOnMemInitializers.
2153 CXXRecordDecl *ClassDecl = Constructor->getParent();
2155 // C++ [class.base.init]p2:
2156 // Names in a mem-initializer-id are looked up in the scope of the
2157 // constructor's class and, if not found in that scope, are looked
2158 // up in the scope containing the constructor's definition.
2159 // [Note: if the constructor's class contains a member with the
2160 // same name as a direct or virtual base class of the class, a
2161 // mem-initializer-id naming the member or base class and composed
2162 // of a single identifier refers to the class member. A
2163 // mem-initializer-id for the hidden base class may be specified
2164 // using a qualified name. ]
2165 if (!SS.getScopeRep() && !TemplateTypeTy) {
2166 // Look for a member, first.
2167 DeclContext::lookup_result Result
2168 = ClassDecl->lookup(MemberOrBase);
2169 if (!Result.empty()) {
2171 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2172 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2173 if (EllipsisLoc.isValid())
2174 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2176 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2178 return BuildMemberInitializer(Member, Init, IdLoc);
2182 // It didn't name a member, so see if it names a class.
2184 TypeSourceInfo *TInfo = 0;
2186 if (TemplateTypeTy) {
2187 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2188 } else if (DS.getTypeSpecType() == TST_decltype) {
2189 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2191 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2192 LookupParsedName(R, S, &SS);
2194 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2196 if (R.isAmbiguous()) return true;
2198 // We don't want access-control diagnostics here.
2199 R.suppressDiagnostics();
2201 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2202 bool NotUnknownSpecialization = false;
2203 DeclContext *DC = computeDeclContext(SS, false);
2204 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2205 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2207 if (!NotUnknownSpecialization) {
2208 // When the scope specifier can refer to a member of an unknown
2209 // specialization, we take it as a type name.
2210 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2211 SS.getWithLocInContext(Context),
2212 *MemberOrBase, IdLoc);
2213 if (BaseType.isNull())
2217 R.setLookupName(MemberOrBase);
2221 // If no results were found, try to correct typos.
2222 TypoCorrection Corr;
2223 MemInitializerValidatorCCC Validator(ClassDecl);
2224 if (R.empty() && BaseType.isNull() &&
2225 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2226 Validator, ClassDecl))) {
2227 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2228 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2229 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2230 // We have found a non-static data member with a similar
2231 // name to what was typed; complain and initialize that
2233 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2234 << MemberOrBase << true << CorrectedQuotedStr
2235 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2236 Diag(Member->getLocation(), diag::note_previous_decl)
2237 << CorrectedQuotedStr;
2239 return BuildMemberInitializer(Member, Init, IdLoc);
2240 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2241 const CXXBaseSpecifier *DirectBaseSpec;
2242 const CXXBaseSpecifier *VirtualBaseSpec;
2243 if (FindBaseInitializer(*this, ClassDecl,
2244 Context.getTypeDeclType(Type),
2245 DirectBaseSpec, VirtualBaseSpec)) {
2246 // We have found a direct or virtual base class with a
2247 // similar name to what was typed; complain and initialize
2249 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2250 << MemberOrBase << false << CorrectedQuotedStr
2251 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2253 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2255 Diag(BaseSpec->getLocStart(),
2256 diag::note_base_class_specified_here)
2257 << BaseSpec->getType()
2258 << BaseSpec->getSourceRange();
2265 if (!TyD && BaseType.isNull()) {
2266 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2267 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2272 if (BaseType.isNull()) {
2273 BaseType = Context.getTypeDeclType(TyD);
2275 NestedNameSpecifier *Qualifier =
2276 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2278 // FIXME: preserve source range information
2279 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2285 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2287 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2290 /// Checks a member initializer expression for cases where reference (or
2291 /// pointer) members are bound to by-value parameters (or their addresses).
2292 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2294 SourceLocation IdLoc) {
2295 QualType MemberTy = Member->getType();
2297 // We only handle pointers and references currently.
2298 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2299 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2302 const bool IsPointer = MemberTy->isPointerType();
2304 if (const UnaryOperator *Op
2305 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2306 // The only case we're worried about with pointers requires taking the
2308 if (Op->getOpcode() != UO_AddrOf)
2311 Init = Op->getSubExpr();
2313 // We only handle address-of expression initializers for pointers.
2318 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2319 // Taking the address of a temporary will be diagnosed as a hard error.
2323 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2324 << Member << Init->getSourceRange();
2325 } else if (const DeclRefExpr *DRE
2326 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2327 // We only warn when referring to a non-reference parameter declaration.
2328 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2329 if (!Parameter || Parameter->getType()->isReferenceType())
2332 S.Diag(Init->getExprLoc(),
2333 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2334 : diag::warn_bind_ref_member_to_parameter)
2335 << Member << Parameter << Init->getSourceRange();
2337 // Other initializers are fine.
2341 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2342 << (unsigned)IsPointer;
2346 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2347 SourceLocation IdLoc) {
2348 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2349 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2350 assert((DirectMember || IndirectMember) &&
2351 "Member must be a FieldDecl or IndirectFieldDecl");
2353 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2356 if (Member->isInvalidDecl())
2359 // Diagnose value-uses of fields to initialize themselves, e.g.
2361 // where foo is not also a parameter to the constructor.
2362 // TODO: implement -Wuninitialized and fold this into that framework.
2365 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2366 Args = ParenList->getExprs();
2367 NumArgs = ParenList->getNumExprs();
2368 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2369 Args = InitList->getInits();
2370 NumArgs = InitList->getNumInits();
2372 // Template instantiation doesn't reconstruct ParenListExprs for us.
2377 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2378 != DiagnosticsEngine::Ignored)
2379 for (unsigned i = 0; i < NumArgs; ++i)
2380 // FIXME: Warn about the case when other fields are used before being
2381 // initialized. For example, let this field be the i'th field. When
2382 // initializing the i'th field, throw a warning if any of the >= i'th
2383 // fields are used, as they are not yet initialized.
2384 // Right now we are only handling the case where the i'th field uses
2385 // itself in its initializer.
2386 // Also need to take into account that some fields may be initialized by
2387 // in-class initializers, see C++11 [class.base.init]p9.
2388 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2390 SourceRange InitRange = Init->getSourceRange();
2392 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2393 // Can't check initialization for a member of dependent type or when
2394 // any of the arguments are type-dependent expressions.
2395 DiscardCleanupsInEvaluationContext();
2397 bool InitList = false;
2398 if (isa<InitListExpr>(Init)) {
2403 if (isStdInitializerList(Member->getType(), 0)) {
2404 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2405 << /*at end of ctor*/1 << InitRange;
2409 // Initialize the member.
2410 InitializedEntity MemberEntity =
2411 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2412 : InitializedEntity::InitializeMember(IndirectMember, 0);
2413 InitializationKind Kind =
2414 InitList ? InitializationKind::CreateDirectList(IdLoc)
2415 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2416 InitRange.getEnd());
2418 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2419 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2420 MultiExprArg(Args, NumArgs),
2422 if (MemberInit.isInvalid())
2425 // C++11 [class.base.init]p7:
2426 // The initialization of each base and member constitutes a
2428 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2429 if (MemberInit.isInvalid())
2432 Init = MemberInit.get();
2433 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2437 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2438 InitRange.getBegin(), Init,
2439 InitRange.getEnd());
2441 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2442 InitRange.getBegin(), Init,
2443 InitRange.getEnd());
2448 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2449 CXXRecordDecl *ClassDecl) {
2450 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2451 if (!LangOpts.CPlusPlus11)
2452 return Diag(NameLoc, diag::err_delegating_ctor)
2453 << TInfo->getTypeLoc().getLocalSourceRange();
2454 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2456 bool InitList = true;
2457 Expr **Args = &Init;
2458 unsigned NumArgs = 1;
2459 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2461 Args = ParenList->getExprs();
2462 NumArgs = ParenList->getNumExprs();
2465 SourceRange InitRange = Init->getSourceRange();
2466 // Initialize the object.
2467 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2468 QualType(ClassDecl->getTypeForDecl(), 0));
2469 InitializationKind Kind =
2470 InitList ? InitializationKind::CreateDirectList(NameLoc)
2471 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2472 InitRange.getEnd());
2473 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2474 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2475 MultiExprArg(Args, NumArgs),
2477 if (DelegationInit.isInvalid())
2480 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2481 "Delegating constructor with no target?");
2483 // C++11 [class.base.init]p7:
2484 // The initialization of each base and member constitutes a
2486 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2487 InitRange.getBegin());
2488 if (DelegationInit.isInvalid())
2491 // If we are in a dependent context, template instantiation will
2492 // perform this type-checking again. Just save the arguments that we
2493 // received in a ParenListExpr.
2494 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2495 // of the information that we have about the base
2496 // initializer. However, deconstructing the ASTs is a dicey process,
2497 // and this approach is far more likely to get the corner cases right.
2498 if (CurContext->isDependentContext())
2499 DelegationInit = Owned(Init);
2501 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2502 DelegationInit.takeAs<Expr>(),
2503 InitRange.getEnd());
2507 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2508 Expr *Init, CXXRecordDecl *ClassDecl,
2509 SourceLocation EllipsisLoc) {
2510 SourceLocation BaseLoc
2511 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2513 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2514 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2515 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2517 // C++ [class.base.init]p2:
2518 // [...] Unless the mem-initializer-id names a nonstatic data
2519 // member of the constructor's class or a direct or virtual base
2520 // of that class, the mem-initializer is ill-formed. A
2521 // mem-initializer-list can initialize a base class using any
2522 // name that denotes that base class type.
2523 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2525 SourceRange InitRange = Init->getSourceRange();
2526 if (EllipsisLoc.isValid()) {
2527 // This is a pack expansion.
2528 if (!BaseType->containsUnexpandedParameterPack()) {
2529 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2530 << SourceRange(BaseLoc, InitRange.getEnd());
2532 EllipsisLoc = SourceLocation();
2535 // Check for any unexpanded parameter packs.
2536 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2539 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2543 // Check for direct and virtual base classes.
2544 const CXXBaseSpecifier *DirectBaseSpec = 0;
2545 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2547 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2549 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2551 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2554 // C++ [base.class.init]p2:
2555 // Unless the mem-initializer-id names a nonstatic data member of the
2556 // constructor's class or a direct or virtual base of that class, the
2557 // mem-initializer is ill-formed.
2558 if (!DirectBaseSpec && !VirtualBaseSpec) {
2559 // If the class has any dependent bases, then it's possible that
2560 // one of those types will resolve to the same type as
2561 // BaseType. Therefore, just treat this as a dependent base
2562 // class initialization. FIXME: Should we try to check the
2563 // initialization anyway? It seems odd.
2564 if (ClassDecl->hasAnyDependentBases())
2567 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2568 << BaseType << Context.getTypeDeclType(ClassDecl)
2569 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2574 DiscardCleanupsInEvaluationContext();
2576 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2577 /*IsVirtual=*/false,
2578 InitRange.getBegin(), Init,
2579 InitRange.getEnd(), EllipsisLoc);
2582 // C++ [base.class.init]p2:
2583 // If a mem-initializer-id is ambiguous because it designates both
2584 // a direct non-virtual base class and an inherited virtual base
2585 // class, the mem-initializer is ill-formed.
2586 if (DirectBaseSpec && VirtualBaseSpec)
2587 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2588 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2590 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2592 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2594 // Initialize the base.
2595 bool InitList = true;
2596 Expr **Args = &Init;
2597 unsigned NumArgs = 1;
2598 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2600 Args = ParenList->getExprs();
2601 NumArgs = ParenList->getNumExprs();
2604 InitializedEntity BaseEntity =
2605 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2606 InitializationKind Kind =
2607 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2608 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2609 InitRange.getEnd());
2610 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2611 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2612 MultiExprArg(Args, NumArgs), 0);
2613 if (BaseInit.isInvalid())
2616 // C++11 [class.base.init]p7:
2617 // The initialization of each base and member constitutes a
2619 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2620 if (BaseInit.isInvalid())
2623 // If we are in a dependent context, template instantiation will
2624 // perform this type-checking again. Just save the arguments that we
2625 // received in a ParenListExpr.
2626 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2627 // of the information that we have about the base
2628 // initializer. However, deconstructing the ASTs is a dicey process,
2629 // and this approach is far more likely to get the corner cases right.
2630 if (CurContext->isDependentContext())
2631 BaseInit = Owned(Init);
2633 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2634 BaseSpec->isVirtual(),
2635 InitRange.getBegin(),
2636 BaseInit.takeAs<Expr>(),
2637 InitRange.getEnd(), EllipsisLoc);
2640 // Create a static_cast\<T&&>(expr).
2641 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2642 if (T.isNull()) T = E->getType();
2643 QualType TargetType = SemaRef.BuildReferenceType(
2644 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2645 SourceLocation ExprLoc = E->getLocStart();
2646 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2647 TargetType, ExprLoc);
2649 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2650 SourceRange(ExprLoc, ExprLoc),
2651 E->getSourceRange()).take();
2654 /// ImplicitInitializerKind - How an implicit base or member initializer should
2655 /// initialize its base or member.
2656 enum ImplicitInitializerKind {
2664 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2665 ImplicitInitializerKind ImplicitInitKind,
2666 CXXBaseSpecifier *BaseSpec,
2667 bool IsInheritedVirtualBase,
2668 CXXCtorInitializer *&CXXBaseInit) {
2669 InitializedEntity InitEntity
2670 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2671 IsInheritedVirtualBase);
2673 ExprResult BaseInit;
2675 switch (ImplicitInitKind) {
2677 const CXXRecordDecl *Inherited =
2678 Constructor->getInheritedConstructor()->getParent();
2679 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2680 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2681 // C++11 [class.inhctor]p8:
2682 // Each expression in the expression-list is of the form
2683 // static_cast<T&&>(p), where p is the name of the corresponding
2684 // constructor parameter and T is the declared type of p.
2685 SmallVector<Expr*, 16> Args;
2686 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2687 ParmVarDecl *PD = Constructor->getParamDecl(I);
2688 ExprResult ArgExpr =
2689 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2690 VK_LValue, SourceLocation());
2691 if (ArgExpr.isInvalid())
2693 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2696 InitializationKind InitKind = InitializationKind::CreateDirect(
2697 Constructor->getLocation(), SourceLocation(), SourceLocation());
2698 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2699 Args.data(), Args.size());
2700 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2706 InitializationKind InitKind
2707 = InitializationKind::CreateDefault(Constructor->getLocation());
2708 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2709 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2715 bool Moving = ImplicitInitKind == IIK_Move;
2716 ParmVarDecl *Param = Constructor->getParamDecl(0);
2717 QualType ParamType = Param->getType().getNonReferenceType();
2720 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2721 SourceLocation(), Param, false,
2722 Constructor->getLocation(), ParamType,
2725 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2727 // Cast to the base class to avoid ambiguities.
2729 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2730 ParamType.getQualifiers());
2733 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2736 CXXCastPath BasePath;
2737 BasePath.push_back(BaseSpec);
2738 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2739 CK_UncheckedDerivedToBase,
2740 Moving ? VK_XValue : VK_LValue,
2743 InitializationKind InitKind
2744 = InitializationKind::CreateDirect(Constructor->getLocation(),
2745 SourceLocation(), SourceLocation());
2746 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2748 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2749 MultiExprArg(&CopyCtorArg, 1));
2754 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2755 if (BaseInit.isInvalid())
2759 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2760 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2762 BaseSpec->isVirtual(),
2764 BaseInit.takeAs<Expr>(),
2771 static bool RefersToRValueRef(Expr *MemRef) {
2772 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2773 return Referenced->getType()->isRValueReferenceType();
2777 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2778 ImplicitInitializerKind ImplicitInitKind,
2779 FieldDecl *Field, IndirectFieldDecl *Indirect,
2780 CXXCtorInitializer *&CXXMemberInit) {
2781 if (Field->isInvalidDecl())
2784 SourceLocation Loc = Constructor->getLocation();
2786 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2787 bool Moving = ImplicitInitKind == IIK_Move;
2788 ParmVarDecl *Param = Constructor->getParamDecl(0);
2789 QualType ParamType = Param->getType().getNonReferenceType();
2791 // Suppress copying zero-width bitfields.
2792 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2795 Expr *MemberExprBase =
2796 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2797 SourceLocation(), Param, false,
2798 Loc, ParamType, VK_LValue, 0);
2800 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2803 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2806 // Build a reference to this field within the parameter.
2808 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2809 Sema::LookupMemberName);
2810 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2811 : cast<ValueDecl>(Field), AS_public);
2812 MemberLookup.resolveKind();
2814 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2818 /*TemplateKWLoc=*/SourceLocation(),
2819 /*FirstQualifierInScope=*/0,
2821 /*TemplateArgs=*/0);
2822 if (CtorArg.isInvalid())
2825 // C++11 [class.copy]p15:
2826 // - if a member m has rvalue reference type T&&, it is direct-initialized
2827 // with static_cast<T&&>(x.m);
2828 if (RefersToRValueRef(CtorArg.get())) {
2829 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2832 // When the field we are copying is an array, create index variables for
2833 // each dimension of the array. We use these index variables to subscript
2834 // the source array, and other clients (e.g., CodeGen) will perform the
2835 // necessary iteration with these index variables.
2836 SmallVector<VarDecl *, 4> IndexVariables;
2837 QualType BaseType = Field->getType();
2838 QualType SizeType = SemaRef.Context.getSizeType();
2839 bool InitializingArray = false;
2840 while (const ConstantArrayType *Array
2841 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2842 InitializingArray = true;
2843 // Create the iteration variable for this array index.
2844 IdentifierInfo *IterationVarName = 0;
2847 llvm::raw_svector_ostream OS(Str);
2848 OS << "__i" << IndexVariables.size();
2849 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2851 VarDecl *IterationVar
2852 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2853 IterationVarName, SizeType,
2854 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2856 IndexVariables.push_back(IterationVar);
2858 // Create a reference to the iteration variable.
2859 ExprResult IterationVarRef
2860 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2861 assert(!IterationVarRef.isInvalid() &&
2862 "Reference to invented variable cannot fail!");
2863 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2864 assert(!IterationVarRef.isInvalid() &&
2865 "Conversion of invented variable cannot fail!");
2867 // Subscript the array with this iteration variable.
2868 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2869 IterationVarRef.take(),
2871 if (CtorArg.isInvalid())
2874 BaseType = Array->getElementType();
2877 // The array subscript expression is an lvalue, which is wrong for moving.
2878 if (Moving && InitializingArray)
2879 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2881 // Construct the entity that we will be initializing. For an array, this
2882 // will be first element in the array, which may require several levels
2883 // of array-subscript entities.
2884 SmallVector<InitializedEntity, 4> Entities;
2885 Entities.reserve(1 + IndexVariables.size());
2887 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2889 Entities.push_back(InitializedEntity::InitializeMember(Field));
2890 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2891 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2895 // Direct-initialize to use the copy constructor.
2896 InitializationKind InitKind =
2897 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2899 Expr *CtorArgE = CtorArg.takeAs<Expr>();
2900 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2903 ExprResult MemberInit
2904 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2905 MultiExprArg(&CtorArgE, 1));
2906 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2907 if (MemberInit.isInvalid())
2911 assert(IndexVariables.size() == 0 &&
2912 "Indirect field improperly initialized");
2914 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2916 MemberInit.takeAs<Expr>(),
2919 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2920 Loc, MemberInit.takeAs<Expr>(),
2922 IndexVariables.data(),
2923 IndexVariables.size());
2927 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2928 "Unhandled implicit init kind!");
2930 QualType FieldBaseElementType =
2931 SemaRef.Context.getBaseElementType(Field->getType());
2933 if (FieldBaseElementType->isRecordType()) {
2934 InitializedEntity InitEntity
2935 = Indirect? InitializedEntity::InitializeMember(Indirect)
2936 : InitializedEntity::InitializeMember(Field);
2937 InitializationKind InitKind =
2938 InitializationKind::CreateDefault(Loc);
2940 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2941 ExprResult MemberInit =
2942 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2944 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2945 if (MemberInit.isInvalid())
2949 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2955 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2962 if (!Field->getParent()->isUnion()) {
2963 if (FieldBaseElementType->isReferenceType()) {
2964 SemaRef.Diag(Constructor->getLocation(),
2965 diag::err_uninitialized_member_in_ctor)
2966 << (int)Constructor->isImplicit()
2967 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2968 << 0 << Field->getDeclName();
2969 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2973 if (FieldBaseElementType.isConstQualified()) {
2974 SemaRef.Diag(Constructor->getLocation(),
2975 diag::err_uninitialized_member_in_ctor)
2976 << (int)Constructor->isImplicit()
2977 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2978 << 1 << Field->getDeclName();
2979 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2984 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2985 FieldBaseElementType->isObjCRetainableType() &&
2986 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2987 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2989 // Default-initialize Objective-C pointers to NULL.
2991 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2993 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2998 // Nothing to initialize.
3004 struct BaseAndFieldInfo {
3006 CXXConstructorDecl *Ctor;
3007 bool AnyErrorsInInits;
3008 ImplicitInitializerKind IIK;
3009 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3010 SmallVector<CXXCtorInitializer*, 8> AllToInit;
3012 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3013 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3014 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3015 if (Generated && Ctor->isCopyConstructor())
3017 else if (Generated && Ctor->isMoveConstructor())
3019 else if (Ctor->getInheritedConstructor())
3025 bool isImplicitCopyOrMove() const {
3036 llvm_unreachable("Invalid ImplicitInitializerKind!");
3039 bool addFieldInitializer(CXXCtorInitializer *Init) {
3040 AllToInit.push_back(Init);
3042 // Check whether this initializer makes the field "used".
3043 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3044 S.UnusedPrivateFields.remove(Init->getAnyMember());
3051 /// \brief Determine whether the given indirect field declaration is somewhere
3052 /// within an anonymous union.
3053 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3054 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3055 CEnd = F->chain_end();
3057 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3058 if (Record->isUnion())
3064 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3066 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3067 if (T->isIncompleteArrayType())
3070 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3071 if (!ArrayT->getSize())
3074 T = ArrayT->getElementType();
3080 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3082 IndirectFieldDecl *Indirect = 0) {
3084 // Overwhelmingly common case: we have a direct initializer for this field.
3085 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3086 return Info.addFieldInitializer(Init);
3088 // C++11 [class.base.init]p8: if the entity is a non-static data member that
3089 // has a brace-or-equal-initializer, the entity is initialized as specified
3091 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3092 CXXCtorInitializer *Init;
3094 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3096 SourceLocation(), 0,
3099 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3101 SourceLocation(), 0,
3103 return Info.addFieldInitializer(Init);
3106 // Don't build an implicit initializer for union members if none was
3107 // explicitly specified.
3108 if (Field->getParent()->isUnion() ||
3109 (Indirect && isWithinAnonymousUnion(Indirect)))
3112 // Don't initialize incomplete or zero-length arrays.
3113 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3116 // Don't try to build an implicit initializer if there were semantic
3117 // errors in any of the initializers (and therefore we might be
3118 // missing some that the user actually wrote).
3119 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3122 CXXCtorInitializer *Init = 0;
3123 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3130 return Info.addFieldInitializer(Init);
3134 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3135 CXXCtorInitializer *Initializer) {
3136 assert(Initializer->isDelegatingInitializer());
3137 Constructor->setNumCtorInitializers(1);
3138 CXXCtorInitializer **initializer =
3139 new (Context) CXXCtorInitializer*[1];
3140 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3141 Constructor->setCtorInitializers(initializer);
3143 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3144 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3145 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3148 DelegatingCtorDecls.push_back(Constructor);
3153 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3154 ArrayRef<CXXCtorInitializer *> Initializers) {
3155 if (Constructor->isDependentContext()) {
3156 // Just store the initializers as written, they will be checked during
3158 if (!Initializers.empty()) {
3159 Constructor->setNumCtorInitializers(Initializers.size());
3160 CXXCtorInitializer **baseOrMemberInitializers =
3161 new (Context) CXXCtorInitializer*[Initializers.size()];
3162 memcpy(baseOrMemberInitializers, Initializers.data(),
3163 Initializers.size() * sizeof(CXXCtorInitializer*));
3164 Constructor->setCtorInitializers(baseOrMemberInitializers);
3167 // Let template instantiation know whether we had errors.
3169 Constructor->setInvalidDecl();
3174 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3176 // We need to build the initializer AST according to order of construction
3177 // and not what user specified in the Initializers list.
3178 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3182 bool HadError = false;
3184 for (unsigned i = 0; i < Initializers.size(); i++) {
3185 CXXCtorInitializer *Member = Initializers[i];
3187 if (Member->isBaseInitializer())
3188 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3190 Info.AllBaseFields[Member->getAnyMember()] = Member;
3193 // Keep track of the direct virtual bases.
3194 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3195 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3196 E = ClassDecl->bases_end(); I != E; ++I) {
3198 DirectVBases.insert(I);
3201 // Push virtual bases before others.
3202 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3203 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3205 if (CXXCtorInitializer *Value
3206 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3207 Info.AllToInit.push_back(Value);
3208 } else if (!AnyErrors) {
3209 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3210 CXXCtorInitializer *CXXBaseInit;
3211 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3212 VBase, IsInheritedVirtualBase,
3218 Info.AllToInit.push_back(CXXBaseInit);
3222 // Non-virtual bases.
3223 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3224 E = ClassDecl->bases_end(); Base != E; ++Base) {
3225 // Virtuals are in the virtual base list and already constructed.
3226 if (Base->isVirtual())
3229 if (CXXCtorInitializer *Value
3230 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3231 Info.AllToInit.push_back(Value);
3232 } else if (!AnyErrors) {
3233 CXXCtorInitializer *CXXBaseInit;
3234 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3235 Base, /*IsInheritedVirtualBase=*/false,
3241 Info.AllToInit.push_back(CXXBaseInit);
3246 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3247 MemEnd = ClassDecl->decls_end();
3248 Mem != MemEnd; ++Mem) {
3249 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3250 // C++ [class.bit]p2:
3251 // A declaration for a bit-field that omits the identifier declares an
3252 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3254 if (F->isUnnamedBitfield())
3257 // If we're not generating the implicit copy/move constructor, then we'll
3258 // handle anonymous struct/union fields based on their individual
3260 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3263 if (CollectFieldInitializer(*this, Info, F))
3268 // Beyond this point, we only consider default initialization.
3269 if (Info.isImplicitCopyOrMove())
3272 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3273 if (F->getType()->isIncompleteArrayType()) {
3274 assert(ClassDecl->hasFlexibleArrayMember() &&
3275 "Incomplete array type is not valid");
3279 // Initialize each field of an anonymous struct individually.
3280 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3287 unsigned NumInitializers = Info.AllToInit.size();
3288 if (NumInitializers > 0) {
3289 Constructor->setNumCtorInitializers(NumInitializers);
3290 CXXCtorInitializer **baseOrMemberInitializers =
3291 new (Context) CXXCtorInitializer*[NumInitializers];
3292 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3293 NumInitializers * sizeof(CXXCtorInitializer*));
3294 Constructor->setCtorInitializers(baseOrMemberInitializers);
3296 // Constructors implicitly reference the base and member
3298 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3299 Constructor->getParent());
3305 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3306 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3307 const RecordDecl *RD = RT->getDecl();
3308 if (RD->isAnonymousStructOrUnion()) {
3309 for (RecordDecl::field_iterator Field = RD->field_begin(),
3310 E = RD->field_end(); Field != E; ++Field)
3311 PopulateKeysForFields(*Field, IdealInits);
3315 IdealInits.push_back(Field);
3318 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3319 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3322 static void *GetKeyForMember(ASTContext &Context,
3323 CXXCtorInitializer *Member) {
3324 if (!Member->isAnyMemberInitializer())
3325 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3327 return Member->getAnyMember();
3330 static void DiagnoseBaseOrMemInitializerOrder(
3331 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3332 ArrayRef<CXXCtorInitializer *> Inits) {
3333 if (Constructor->getDeclContext()->isDependentContext())
3336 // Don't check initializers order unless the warning is enabled at the
3337 // location of at least one initializer.
3338 bool ShouldCheckOrder = false;
3339 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3340 CXXCtorInitializer *Init = Inits[InitIndex];
3341 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3342 Init->getSourceLocation())
3343 != DiagnosticsEngine::Ignored) {
3344 ShouldCheckOrder = true;
3348 if (!ShouldCheckOrder)
3351 // Build the list of bases and members in the order that they'll
3352 // actually be initialized. The explicit initializers should be in
3353 // this same order but may be missing things.
3354 SmallVector<const void*, 32> IdealInitKeys;
3356 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3358 // 1. Virtual bases.
3359 for (CXXRecordDecl::base_class_const_iterator VBase =
3360 ClassDecl->vbases_begin(),
3361 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3362 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3364 // 2. Non-virtual bases.
3365 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3366 E = ClassDecl->bases_end(); Base != E; ++Base) {
3367 if (Base->isVirtual())
3369 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3372 // 3. Direct fields.
3373 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3374 E = ClassDecl->field_end(); Field != E; ++Field) {
3375 if (Field->isUnnamedBitfield())
3378 PopulateKeysForFields(*Field, IdealInitKeys);
3381 unsigned NumIdealInits = IdealInitKeys.size();
3382 unsigned IdealIndex = 0;
3384 CXXCtorInitializer *PrevInit = 0;
3385 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3386 CXXCtorInitializer *Init = Inits[InitIndex];
3387 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3389 // Scan forward to try to find this initializer in the idealized
3390 // initializers list.
3391 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3392 if (InitKey == IdealInitKeys[IdealIndex])
3395 // If we didn't find this initializer, it must be because we
3396 // scanned past it on a previous iteration. That can only
3397 // happen if we're out of order; emit a warning.
3398 if (IdealIndex == NumIdealInits && PrevInit) {
3399 Sema::SemaDiagnosticBuilder D =
3400 SemaRef.Diag(PrevInit->getSourceLocation(),
3401 diag::warn_initializer_out_of_order);
3403 if (PrevInit->isAnyMemberInitializer())
3404 D << 0 << PrevInit->getAnyMember()->getDeclName();
3406 D << 1 << PrevInit->getTypeSourceInfo()->getType();
3408 if (Init->isAnyMemberInitializer())
3409 D << 0 << Init->getAnyMember()->getDeclName();
3411 D << 1 << Init->getTypeSourceInfo()->getType();
3413 // Move back to the initializer's location in the ideal list.
3414 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3415 if (InitKey == IdealInitKeys[IdealIndex])
3418 assert(IdealIndex != NumIdealInits &&
3419 "initializer not found in initializer list");
3427 bool CheckRedundantInit(Sema &S,
3428 CXXCtorInitializer *Init,
3429 CXXCtorInitializer *&PrevInit) {
3435 if (FieldDecl *Field = Init->getAnyMember())
3436 S.Diag(Init->getSourceLocation(),
3437 diag::err_multiple_mem_initialization)
3438 << Field->getDeclName()
3439 << Init->getSourceRange();
3441 const Type *BaseClass = Init->getBaseClass();
3442 assert(BaseClass && "neither field nor base");
3443 S.Diag(Init->getSourceLocation(),
3444 diag::err_multiple_base_initialization)
3445 << QualType(BaseClass, 0)
3446 << Init->getSourceRange();
3448 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3449 << 0 << PrevInit->getSourceRange();
3454 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3455 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3457 bool CheckRedundantUnionInit(Sema &S,
3458 CXXCtorInitializer *Init,
3459 RedundantUnionMap &Unions) {
3460 FieldDecl *Field = Init->getAnyMember();
3461 RecordDecl *Parent = Field->getParent();
3462 NamedDecl *Child = Field;
3464 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3465 if (Parent->isUnion()) {
3466 UnionEntry &En = Unions[Parent];
3467 if (En.first && En.first != Child) {
3468 S.Diag(Init->getSourceLocation(),
3469 diag::err_multiple_mem_union_initialization)
3470 << Field->getDeclName()
3471 << Init->getSourceRange();
3472 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3473 << 0 << En.second->getSourceRange();
3480 if (!Parent->isAnonymousStructOrUnion())
3485 Parent = cast<RecordDecl>(Parent->getDeclContext());
3492 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3493 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3494 SourceLocation ColonLoc,
3495 ArrayRef<CXXCtorInitializer*> MemInits,
3497 if (!ConstructorDecl)
3500 AdjustDeclIfTemplate(ConstructorDecl);
3502 CXXConstructorDecl *Constructor
3503 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3506 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3510 // Mapping for the duplicate initializers check.
3511 // For member initializers, this is keyed with a FieldDecl*.
3512 // For base initializers, this is keyed with a Type*.
3513 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3515 // Mapping for the inconsistent anonymous-union initializers check.
3516 RedundantUnionMap MemberUnions;
3518 bool HadError = false;
3519 for (unsigned i = 0; i < MemInits.size(); i++) {
3520 CXXCtorInitializer *Init = MemInits[i];
3522 // Set the source order index.
3523 Init->setSourceOrder(i);
3525 if (Init->isAnyMemberInitializer()) {
3526 FieldDecl *Field = Init->getAnyMember();
3527 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3528 CheckRedundantUnionInit(*this, Init, MemberUnions))
3530 } else if (Init->isBaseInitializer()) {
3531 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3532 if (CheckRedundantInit(*this, Init, Members[Key]))
3535 assert(Init->isDelegatingInitializer());
3536 // This must be the only initializer
3537 if (MemInits.size() != 1) {
3538 Diag(Init->getSourceLocation(),
3539 diag::err_delegating_initializer_alone)
3540 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3541 // We will treat this as being the only initializer.
3543 SetDelegatingInitializer(Constructor, MemInits[i]);
3544 // Return immediately as the initializer is set.
3552 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3554 SetCtorInitializers(Constructor, AnyErrors, MemInits);
3558 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3559 CXXRecordDecl *ClassDecl) {
3560 // Ignore dependent contexts. Also ignore unions, since their members never
3561 // have destructors implicitly called.
3562 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3565 // FIXME: all the access-control diagnostics are positioned on the
3566 // field/base declaration. That's probably good; that said, the
3567 // user might reasonably want to know why the destructor is being
3568 // emitted, and we currently don't say.
3570 // Non-static data members.
3571 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3572 E = ClassDecl->field_end(); I != E; ++I) {
3573 FieldDecl *Field = *I;
3574 if (Field->isInvalidDecl())
3577 // Don't destroy incomplete or zero-length arrays.
3578 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3581 QualType FieldType = Context.getBaseElementType(Field->getType());
3583 const RecordType* RT = FieldType->getAs<RecordType>();
3587 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3588 if (FieldClassDecl->isInvalidDecl())
3590 if (FieldClassDecl->hasIrrelevantDestructor())
3592 // The destructor for an implicit anonymous union member is never invoked.
3593 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3596 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3597 assert(Dtor && "No dtor found for FieldClassDecl!");
3598 CheckDestructorAccess(Field->getLocation(), Dtor,
3599 PDiag(diag::err_access_dtor_field)
3600 << Field->getDeclName()
3603 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3604 DiagnoseUseOfDecl(Dtor, Location);
3607 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3610 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3611 E = ClassDecl->bases_end(); Base != E; ++Base) {
3612 // Bases are always records in a well-formed non-dependent class.
3613 const RecordType *RT = Base->getType()->getAs<RecordType>();
3615 // Remember direct virtual bases.
3616 if (Base->isVirtual())
3617 DirectVirtualBases.insert(RT);
3619 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3620 // If our base class is invalid, we probably can't get its dtor anyway.
3621 if (BaseClassDecl->isInvalidDecl())
3623 if (BaseClassDecl->hasIrrelevantDestructor())
3626 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3627 assert(Dtor && "No dtor found for BaseClassDecl!");
3629 // FIXME: caret should be on the start of the class name
3630 CheckDestructorAccess(Base->getLocStart(), Dtor,
3631 PDiag(diag::err_access_dtor_base)
3633 << Base->getSourceRange(),
3634 Context.getTypeDeclType(ClassDecl));
3636 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3637 DiagnoseUseOfDecl(Dtor, Location);
3641 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3642 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3644 // Bases are always records in a well-formed non-dependent class.
3645 const RecordType *RT = VBase->getType()->castAs<RecordType>();
3647 // Ignore direct virtual bases.
3648 if (DirectVirtualBases.count(RT))
3651 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3652 // If our base class is invalid, we probably can't get its dtor anyway.
3653 if (BaseClassDecl->isInvalidDecl())
3655 if (BaseClassDecl->hasIrrelevantDestructor())
3658 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3659 assert(Dtor && "No dtor found for BaseClassDecl!");
3660 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3661 PDiag(diag::err_access_dtor_vbase)
3662 << VBase->getType(),
3663 Context.getTypeDeclType(ClassDecl));
3665 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3666 DiagnoseUseOfDecl(Dtor, Location);
3670 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3674 if (CXXConstructorDecl *Constructor
3675 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3676 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3679 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3680 unsigned DiagID, AbstractDiagSelID SelID) {
3681 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3683 AbstractDiagSelID SelID;
3686 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3687 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3689 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3690 if (Suppressed) return;
3692 S.Diag(Loc, DiagID) << T;
3694 S.Diag(Loc, DiagID) << SelID << T;
3696 } Diagnoser(DiagID, SelID);
3698 return RequireNonAbstractType(Loc, T, Diagnoser);
3701 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3702 TypeDiagnoser &Diagnoser) {
3703 if (!getLangOpts().CPlusPlus)
3706 if (const ArrayType *AT = Context.getAsArrayType(T))
3707 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3709 if (const PointerType *PT = T->getAs<PointerType>()) {
3710 // Find the innermost pointer type.
3711 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3714 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3715 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3718 const RecordType *RT = T->getAs<RecordType>();
3722 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3724 // We can't answer whether something is abstract until it has a
3725 // definition. If it's currently being defined, we'll walk back
3726 // over all the declarations when we have a full definition.
3727 const CXXRecordDecl *Def = RD->getDefinition();
3728 if (!Def || Def->isBeingDefined())
3731 if (!RD->isAbstract())
3734 Diagnoser.diagnose(*this, Loc, T);
3735 DiagnoseAbstractType(RD);
3740 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3741 // Check if we've already emitted the list of pure virtual functions
3743 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3746 CXXFinalOverriderMap FinalOverriders;
3747 RD->getFinalOverriders(FinalOverriders);
3749 // Keep a set of seen pure methods so we won't diagnose the same method
3751 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3753 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3754 MEnd = FinalOverriders.end();
3757 for (OverridingMethods::iterator SO = M->second.begin(),
3758 SOEnd = M->second.end();
3759 SO != SOEnd; ++SO) {
3760 // C++ [class.abstract]p4:
3761 // A class is abstract if it contains or inherits at least one
3762 // pure virtual function for which the final overrider is pure
3766 if (SO->second.size() != 1)
3769 if (!SO->second.front().Method->isPure())
3772 if (!SeenPureMethods.insert(SO->second.front().Method))
3775 Diag(SO->second.front().Method->getLocation(),
3776 diag::note_pure_virtual_function)
3777 << SO->second.front().Method->getDeclName() << RD->getDeclName();
3781 if (!PureVirtualClassDiagSet)
3782 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3783 PureVirtualClassDiagSet->insert(RD);
3787 struct AbstractUsageInfo {
3789 CXXRecordDecl *Record;
3790 CanQualType AbstractType;
3793 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3794 : S(S), Record(Record),
3795 AbstractType(S.Context.getCanonicalType(
3796 S.Context.getTypeDeclType(Record))),
3799 void DiagnoseAbstractType() {
3800 if (Invalid) return;
3801 S.DiagnoseAbstractType(Record);
3805 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3808 struct CheckAbstractUsage {
3809 AbstractUsageInfo &Info;
3810 const NamedDecl *Ctx;
3812 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3813 : Info(Info), Ctx(Ctx) {}
3815 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3816 switch (TL.getTypeLocClass()) {
3817 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3818 #define TYPELOC(CLASS, PARENT) \
3819 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3820 #include "clang/AST/TypeLocNodes.def"
3824 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3825 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3826 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3830 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3831 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3835 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3836 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3839 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3840 // Visit the type parameters from a permissive context.
3841 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3842 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3843 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3844 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3845 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3846 // TODO: other template argument types?
3850 // Visit pointee types from a permissive context.
3851 #define CheckPolymorphic(Type) \
3852 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3853 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3855 CheckPolymorphic(PointerTypeLoc)
3856 CheckPolymorphic(ReferenceTypeLoc)
3857 CheckPolymorphic(MemberPointerTypeLoc)
3858 CheckPolymorphic(BlockPointerTypeLoc)
3859 CheckPolymorphic(AtomicTypeLoc)
3861 /// Handle all the types we haven't given a more specific
3862 /// implementation for above.
3863 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3864 // Every other kind of type that we haven't called out already
3865 // that has an inner type is either (1) sugar or (2) contains that
3866 // inner type in some way as a subobject.
3867 if (TypeLoc Next = TL.getNextTypeLoc())
3868 return Visit(Next, Sel);
3870 // If there's no inner type and we're in a permissive context,
3872 if (Sel == Sema::AbstractNone) return;
3874 // Check whether the type matches the abstract type.
3875 QualType T = TL.getType();
3876 if (T->isArrayType()) {
3877 Sel = Sema::AbstractArrayType;
3878 T = Info.S.Context.getBaseElementType(T);
3880 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3881 if (CT != Info.AbstractType) return;
3883 // It matched; do some magic.
3884 if (Sel == Sema::AbstractArrayType) {
3885 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3886 << T << TL.getSourceRange();
3888 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3889 << Sel << T << TL.getSourceRange();
3891 Info.DiagnoseAbstractType();
3895 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3896 Sema::AbstractDiagSelID Sel) {
3897 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3902 /// Check for invalid uses of an abstract type in a method declaration.
3903 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3904 CXXMethodDecl *MD) {
3905 // No need to do the check on definitions, which require that
3906 // the return/param types be complete.
3907 if (MD->doesThisDeclarationHaveABody())
3910 // For safety's sake, just ignore it if we don't have type source
3911 // information. This should never happen for non-implicit methods,
3913 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3914 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3917 /// Check for invalid uses of an abstract type within a class definition.
3918 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3919 CXXRecordDecl *RD) {
3920 for (CXXRecordDecl::decl_iterator
3921 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3923 if (D->isImplicit()) continue;
3925 // Methods and method templates.
3926 if (isa<CXXMethodDecl>(D)) {
3927 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3928 } else if (isa<FunctionTemplateDecl>(D)) {
3929 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3930 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3932 // Fields and static variables.
3933 } else if (isa<FieldDecl>(D)) {
3934 FieldDecl *FD = cast<FieldDecl>(D);
3935 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3936 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3937 } else if (isa<VarDecl>(D)) {
3938 VarDecl *VD = cast<VarDecl>(D);
3939 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3940 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3942 // Nested classes and class templates.
3943 } else if (isa<CXXRecordDecl>(D)) {
3944 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3945 } else if (isa<ClassTemplateDecl>(D)) {
3946 CheckAbstractClassUsage(Info,
3947 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3952 /// \brief Perform semantic checks on a class definition that has been
3953 /// completing, introducing implicitly-declared members, checking for
3954 /// abstract types, etc.
3955 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3959 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3960 AbstractUsageInfo Info(*this, Record);
3961 CheckAbstractClassUsage(Info, Record);
3964 // If this is not an aggregate type and has no user-declared constructor,
3965 // complain about any non-static data members of reference or const scalar
3966 // type, since they will never get initializers.
3967 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3968 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3969 !Record->isLambda()) {
3970 bool Complained = false;
3971 for (RecordDecl::field_iterator F = Record->field_begin(),
3972 FEnd = Record->field_end();
3974 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3977 if (F->getType()->isReferenceType() ||
3978 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3980 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3981 << Record->getTagKind() << Record;
3985 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3986 << F->getType()->isReferenceType()
3987 << F->getDeclName();
3992 if (Record->isDynamicClass() && !Record->isDependentType())
3993 DynamicClasses.push_back(Record);
3995 if (Record->getIdentifier()) {
3996 // C++ [class.mem]p13:
3997 // If T is the name of a class, then each of the following shall have a
3998 // name different from T:
3999 // - every member of every anonymous union that is a member of class T.
4001 // C++ [class.mem]p14:
4002 // In addition, if class T has a user-declared constructor (12.1), every
4003 // non-static data member of class T shall have a name different from T.
4004 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4005 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4008 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4009 isa<IndirectFieldDecl>(D)) {
4010 Diag(D->getLocation(), diag::err_member_name_of_class)
4011 << D->getDeclName();
4017 // Warn if the class has virtual methods but non-virtual public destructor.
4018 if (Record->isPolymorphic() && !Record->isDependentType()) {
4019 CXXDestructorDecl *dtor = Record->getDestructor();
4020 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4021 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4022 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4025 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4026 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4027 DiagnoseAbstractType(Record);
4030 if (!Record->isDependentType()) {
4031 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4032 MEnd = Record->method_end();
4034 // See if a method overloads virtual methods in a base
4035 // class without overriding any.
4037 DiagnoseHiddenVirtualMethods(Record, *M);
4039 // Check whether the explicitly-defaulted special members are valid.
4040 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4041 CheckExplicitlyDefaultedSpecialMember(*M);
4043 // For an explicitly defaulted or deleted special member, we defer
4044 // determining triviality until the class is complete. That time is now!
4045 if (!M->isImplicit() && !M->isUserProvided()) {
4046 CXXSpecialMember CSM = getSpecialMember(*M);
4047 if (CSM != CXXInvalid) {
4048 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4050 // Inform the class that we've finished declaring this member.
4051 Record->finishedDefaultedOrDeletedMember(*M);
4057 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4058 // function that is not a constructor declares that member function to be
4059 // const. [...] The class of which that function is a member shall be
4062 // If the class has virtual bases, any constexpr members will already have
4063 // been diagnosed by the checks performed on the member declaration, so
4064 // suppress this (less useful) diagnostic.
4066 // We delay this until we know whether an explicitly-defaulted (or deleted)
4067 // destructor for the class is trivial.
4068 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4069 !Record->isLiteral() && !Record->getNumVBases()) {
4070 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4071 MEnd = Record->method_end();
4073 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4074 switch (Record->getTemplateSpecializationKind()) {
4075 case TSK_ImplicitInstantiation:
4076 case TSK_ExplicitInstantiationDeclaration:
4077 case TSK_ExplicitInstantiationDefinition:
4078 // If a template instantiates to a non-literal type, but its members
4079 // instantiate to constexpr functions, the template is technically
4080 // ill-formed, but we allow it for sanity.
4083 case TSK_Undeclared:
4084 case TSK_ExplicitSpecialization:
4085 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4086 diag::err_constexpr_method_non_literal);
4090 // Only produce one error per class.
4096 // Declare inheriting constructors. We do this eagerly here because:
4097 // - The standard requires an eager diagnostic for conflicting inheriting
4098 // constructors from different classes.
4099 // - The lazy declaration of the other implicit constructors is so as to not
4100 // waste space and performance on classes that are not meant to be
4101 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4102 // have inheriting constructors.
4103 DeclareInheritingConstructors(Record);
4106 /// Is the special member function which would be selected to perform the
4107 /// specified operation on the specified class type a constexpr constructor?
4108 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4109 Sema::CXXSpecialMember CSM,
4111 Sema::SpecialMemberOverloadResult *SMOR =
4112 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4113 false, false, false, false);
4114 if (!SMOR || !SMOR->getMethod())
4115 // A constructor we wouldn't select can't be "involved in initializing"
4118 return SMOR->getMethod()->isConstexpr();
4121 /// Determine whether the specified special member function would be constexpr
4122 /// if it were implicitly defined.
4123 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4124 Sema::CXXSpecialMember CSM,
4126 if (!S.getLangOpts().CPlusPlus11)
4129 // C++11 [dcl.constexpr]p4:
4130 // In the definition of a constexpr constructor [...]
4132 case Sema::CXXDefaultConstructor:
4133 // Since default constructor lookup is essentially trivial (and cannot
4134 // involve, for instance, template instantiation), we compute whether a
4135 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4137 // This is important for performance; we need to know whether the default
4138 // constructor is constexpr to determine whether the type is a literal type.
4139 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4141 case Sema::CXXCopyConstructor:
4142 case Sema::CXXMoveConstructor:
4143 // For copy or move constructors, we need to perform overload resolution.
4146 case Sema::CXXCopyAssignment:
4147 case Sema::CXXMoveAssignment:
4148 case Sema::CXXDestructor:
4149 case Sema::CXXInvalid:
4153 // -- if the class is a non-empty union, or for each non-empty anonymous
4154 // union member of a non-union class, exactly one non-static data member
4155 // shall be initialized; [DR1359]
4157 // If we squint, this is guaranteed, since exactly one non-static data member
4158 // will be initialized (if the constructor isn't deleted), we just don't know
4160 if (ClassDecl->isUnion())
4163 // -- the class shall not have any virtual base classes;
4164 if (ClassDecl->getNumVBases())
4167 // -- every constructor involved in initializing [...] base class
4168 // sub-objects shall be a constexpr constructor;
4169 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4170 BEnd = ClassDecl->bases_end();
4172 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4173 if (!BaseType) continue;
4175 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4176 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4180 // -- every constructor involved in initializing non-static data members
4181 // [...] shall be a constexpr constructor;
4182 // -- every non-static data member and base class sub-object shall be
4184 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4185 FEnd = ClassDecl->field_end();
4187 if (F->isInvalidDecl())
4189 if (const RecordType *RecordTy =
4190 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4191 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4192 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4197 // All OK, it's constexpr!
4201 static Sema::ImplicitExceptionSpecification
4202 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4203 switch (S.getSpecialMember(MD)) {
4204 case Sema::CXXDefaultConstructor:
4205 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4206 case Sema::CXXCopyConstructor:
4207 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4208 case Sema::CXXCopyAssignment:
4209 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4210 case Sema::CXXMoveConstructor:
4211 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4212 case Sema::CXXMoveAssignment:
4213 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4214 case Sema::CXXDestructor:
4215 return S.ComputeDefaultedDtorExceptionSpec(MD);
4216 case Sema::CXXInvalid:
4219 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4220 "only special members have implicit exception specs");
4221 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4225 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4226 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4227 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4228 ExceptSpec.getEPI(EPI);
4229 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4230 S.Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI));
4231 FD->setType(QualType(NewFPT, 0));
4234 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4235 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4236 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4239 // Evaluate the exception specification.
4240 ImplicitExceptionSpecification ExceptSpec =
4241 computeImplicitExceptionSpec(*this, Loc, MD);
4243 // Update the type of the special member to use it.
4244 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4246 // A user-provided destructor can be defined outside the class. When that
4247 // happens, be sure to update the exception specification on both
4249 const FunctionProtoType *CanonicalFPT =
4250 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4251 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4252 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4253 CanonicalFPT, ExceptSpec);
4256 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4257 CXXRecordDecl *RD = MD->getParent();
4258 CXXSpecialMember CSM = getSpecialMember(MD);
4260 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4261 "not an explicitly-defaulted special member");
4263 // Whether this was the first-declared instance of the constructor.
4264 // This affects whether we implicitly add an exception spec and constexpr.
4265 bool First = MD == MD->getCanonicalDecl();
4267 bool HadError = false;
4269 // C++11 [dcl.fct.def.default]p1:
4270 // A function that is explicitly defaulted shall
4271 // -- be a special member function (checked elsewhere),
4272 // -- have the same type (except for ref-qualifiers, and except that a
4273 // copy operation can take a non-const reference) as an implicit
4275 // -- not have default arguments.
4276 unsigned ExpectedParams = 1;
4277 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4279 if (MD->getNumParams() != ExpectedParams) {
4280 // This also checks for default arguments: a copy or move constructor with a
4281 // default argument is classified as a default constructor, and assignment
4282 // operations and destructors can't have default arguments.
4283 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4284 << CSM << MD->getSourceRange();
4286 } else if (MD->isVariadic()) {
4287 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4288 << CSM << MD->getSourceRange();
4292 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4294 bool CanHaveConstParam = false;
4295 if (CSM == CXXCopyConstructor)
4296 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4297 else if (CSM == CXXCopyAssignment)
4298 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4300 QualType ReturnType = Context.VoidTy;
4301 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4302 // Check for return type matching.
4303 ReturnType = Type->getResultType();
4304 QualType ExpectedReturnType =
4305 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4306 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4307 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4308 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4312 // A defaulted special member cannot have cv-qualifiers.
4313 if (Type->getTypeQuals()) {
4314 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4315 << (CSM == CXXMoveAssignment);
4320 // Check for parameter type matching.
4321 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4322 bool HasConstParam = false;
4323 if (ExpectedParams && ArgType->isReferenceType()) {
4324 // Argument must be reference to possibly-const T.
4325 QualType ReferentType = ArgType->getPointeeType();
4326 HasConstParam = ReferentType.isConstQualified();
4328 if (ReferentType.isVolatileQualified()) {
4329 Diag(MD->getLocation(),
4330 diag::err_defaulted_special_member_volatile_param) << CSM;
4334 if (HasConstParam && !CanHaveConstParam) {
4335 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4336 Diag(MD->getLocation(),
4337 diag::err_defaulted_special_member_copy_const_param)
4338 << (CSM == CXXCopyAssignment);
4339 // FIXME: Explain why this special member can't be const.
4341 Diag(MD->getLocation(),
4342 diag::err_defaulted_special_member_move_const_param)
4343 << (CSM == CXXMoveAssignment);
4347 } else if (ExpectedParams) {
4348 // A copy assignment operator can take its argument by value, but a
4349 // defaulted one cannot.
4350 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4351 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4355 // C++11 [dcl.fct.def.default]p2:
4356 // An explicitly-defaulted function may be declared constexpr only if it
4357 // would have been implicitly declared as constexpr,
4358 // Do not apply this rule to members of class templates, since core issue 1358
4359 // makes such functions always instantiate to constexpr functions. For
4360 // non-constructors, this is checked elsewhere.
4361 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4363 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4364 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4365 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4366 // FIXME: Explain why the constructor can't be constexpr.
4370 // and may have an explicit exception-specification only if it is compatible
4371 // with the exception-specification on the implicit declaration.
4372 if (Type->hasExceptionSpec()) {
4373 // Delay the check if this is the first declaration of the special member,
4374 // since we may not have parsed some necessary in-class initializers yet.
4376 // If the exception specification needs to be instantiated, do so now,
4377 // before we clobber it with an EST_Unevaluated specification below.
4378 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4379 InstantiateExceptionSpec(MD->getLocStart(), MD);
4380 Type = MD->getType()->getAs<FunctionProtoType>();
4382 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4384 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4387 // If a function is explicitly defaulted on its first declaration,
4389 // -- it is implicitly considered to be constexpr if the implicit
4390 // definition would be,
4391 MD->setConstexpr(Constexpr);
4393 // -- it is implicitly considered to have the same exception-specification
4394 // as if it had been implicitly declared,
4395 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4396 EPI.ExceptionSpecType = EST_Unevaluated;
4397 EPI.ExceptionSpecDecl = MD;
4398 MD->setType(Context.getFunctionType(ReturnType,
4399 ArrayRef<QualType>(&ArgType,
4404 if (ShouldDeleteSpecialMember(MD, CSM)) {
4406 SetDeclDeleted(MD, MD->getLocation());
4408 // C++11 [dcl.fct.def.default]p4:
4409 // [For a] user-provided explicitly-defaulted function [...] if such a
4410 // function is implicitly defined as deleted, the program is ill-formed.
4411 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4417 MD->setInvalidDecl();
4420 /// Check whether the exception specification provided for an
4421 /// explicitly-defaulted special member matches the exception specification
4422 /// that would have been generated for an implicit special member, per
4423 /// C++11 [dcl.fct.def.default]p2.
4424 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4425 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4426 // Compute the implicit exception specification.
4427 FunctionProtoType::ExtProtoInfo EPI;
4428 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4429 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4430 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
4432 // Ensure that it matches.
4433 CheckEquivalentExceptionSpec(
4434 PDiag(diag::err_incorrect_defaulted_exception_spec)
4435 << getSpecialMember(MD), PDiag(),
4436 ImplicitType, SourceLocation(),
4437 SpecifiedType, MD->getLocation());
4440 void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4441 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4443 CheckExplicitlyDefaultedMemberExceptionSpec(
4444 DelayedDefaultedMemberExceptionSpecs[I].first,
4445 DelayedDefaultedMemberExceptionSpecs[I].second);
4447 DelayedDefaultedMemberExceptionSpecs.clear();
4451 struct SpecialMemberDeletionInfo {
4454 Sema::CXXSpecialMember CSM;
4457 // Properties of the special member, computed for convenience.
4458 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4461 bool AllFieldsAreConst;
4463 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4464 Sema::CXXSpecialMember CSM, bool Diagnose)
4465 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4466 IsConstructor(false), IsAssignment(false), IsMove(false),
4467 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4468 AllFieldsAreConst(true) {
4470 case Sema::CXXDefaultConstructor:
4471 case Sema::CXXCopyConstructor:
4472 IsConstructor = true;
4474 case Sema::CXXMoveConstructor:
4475 IsConstructor = true;
4478 case Sema::CXXCopyAssignment:
4479 IsAssignment = true;
4481 case Sema::CXXMoveAssignment:
4482 IsAssignment = true;
4485 case Sema::CXXDestructor:
4487 case Sema::CXXInvalid:
4488 llvm_unreachable("invalid special member kind");
4491 if (MD->getNumParams()) {
4492 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4493 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4497 bool inUnion() const { return MD->getParent()->isUnion(); }
4499 /// Look up the corresponding special member in the given class.
4500 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4502 unsigned TQ = MD->getTypeQualifiers();
4503 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4504 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4506 return S.LookupSpecialMember(Class, CSM,
4507 ConstArg || (Quals & Qualifiers::Const),
4508 VolatileArg || (Quals & Qualifiers::Volatile),
4509 MD->getRefQualifier() == RQ_RValue,
4510 TQ & Qualifiers::Const,
4511 TQ & Qualifiers::Volatile);
4514 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4516 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4517 bool shouldDeleteForField(FieldDecl *FD);
4518 bool shouldDeleteForAllConstMembers();
4520 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4522 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4523 Sema::SpecialMemberOverloadResult *SMOR,
4524 bool IsDtorCallInCtor);
4526 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4530 /// Is the given special member inaccessible when used on the given
4532 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4533 CXXMethodDecl *target) {
4534 /// If we're operating on a base class, the object type is the
4535 /// type of this special member.
4537 AccessSpecifier access = target->getAccess();
4538 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4539 objectTy = S.Context.getTypeDeclType(MD->getParent());
4540 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4542 // If we're operating on a field, the object type is the type of the field.
4544 objectTy = S.Context.getTypeDeclType(target->getParent());
4547 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4550 /// Check whether we should delete a special member due to the implicit
4551 /// definition containing a call to a special member of a subobject.
4552 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4553 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4554 bool IsDtorCallInCtor) {
4555 CXXMethodDecl *Decl = SMOR->getMethod();
4556 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4560 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4561 DiagKind = !Decl ? 0 : 1;
4562 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4564 else if (!isAccessible(Subobj, Decl))
4566 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4567 !Decl->isTrivial()) {
4568 // A member of a union must have a trivial corresponding special member.
4569 // As a weird special case, a destructor call from a union's constructor
4570 // must be accessible and non-deleted, but need not be trivial. Such a
4571 // destructor is never actually called, but is semantically checked as
4581 S.Diag(Field->getLocation(),
4582 diag::note_deleted_special_member_class_subobject)
4583 << CSM << MD->getParent() << /*IsField*/true
4584 << Field << DiagKind << IsDtorCallInCtor;
4586 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4587 S.Diag(Base->getLocStart(),
4588 diag::note_deleted_special_member_class_subobject)
4589 << CSM << MD->getParent() << /*IsField*/false
4590 << Base->getType() << DiagKind << IsDtorCallInCtor;
4594 S.NoteDeletedFunction(Decl);
4595 // FIXME: Explain inaccessibility if DiagKind == 3.
4601 /// Check whether we should delete a special member function due to having a
4602 /// direct or virtual base class or non-static data member of class type M.
4603 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4604 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4605 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4607 // C++11 [class.ctor]p5:
4608 // -- any direct or virtual base class, or non-static data member with no
4609 // brace-or-equal-initializer, has class type M (or array thereof) and
4610 // either M has no default constructor or overload resolution as applied
4611 // to M's default constructor results in an ambiguity or in a function
4612 // that is deleted or inaccessible
4613 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4614 // -- a direct or virtual base class B that cannot be copied/moved because
4615 // overload resolution, as applied to B's corresponding special member,
4616 // results in an ambiguity or a function that is deleted or inaccessible
4617 // from the defaulted special member
4618 // C++11 [class.dtor]p5:
4619 // -- any direct or virtual base class [...] has a type with a destructor
4620 // that is deleted or inaccessible
4621 if (!(CSM == Sema::CXXDefaultConstructor &&
4622 Field && Field->hasInClassInitializer()) &&
4623 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4626 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4627 // -- any direct or virtual base class or non-static data member has a
4628 // type with a destructor that is deleted or inaccessible
4629 if (IsConstructor) {
4630 Sema::SpecialMemberOverloadResult *SMOR =
4631 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4632 false, false, false, false, false);
4633 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4640 /// Check whether we should delete a special member function due to the class
4641 /// having a particular direct or virtual base class.
4642 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4643 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4644 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4647 /// Check whether we should delete a special member function due to the class
4648 /// having a particular non-static data member.
4649 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4650 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4651 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4653 if (CSM == Sema::CXXDefaultConstructor) {
4654 // For a default constructor, all references must be initialized in-class
4655 // and, if a union, it must have a non-const member.
4656 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4658 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4659 << MD->getParent() << FD << FieldType << /*Reference*/0;
4662 // C++11 [class.ctor]p5: any non-variant non-static data member of
4663 // const-qualified type (or array thereof) with no
4664 // brace-or-equal-initializer does not have a user-provided default
4666 if (!inUnion() && FieldType.isConstQualified() &&
4667 !FD->hasInClassInitializer() &&
4668 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4670 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4671 << MD->getParent() << FD << FD->getType() << /*Const*/1;
4675 if (inUnion() && !FieldType.isConstQualified())
4676 AllFieldsAreConst = false;
4677 } else if (CSM == Sema::CXXCopyConstructor) {
4678 // For a copy constructor, data members must not be of rvalue reference
4680 if (FieldType->isRValueReferenceType()) {
4682 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4683 << MD->getParent() << FD << FieldType;
4686 } else if (IsAssignment) {
4687 // For an assignment operator, data members must not be of reference type.
4688 if (FieldType->isReferenceType()) {
4690 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4691 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4694 if (!FieldRecord && FieldType.isConstQualified()) {
4695 // C++11 [class.copy]p23:
4696 // -- a non-static data member of const non-class type (or array thereof)
4698 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4699 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4705 // Some additional restrictions exist on the variant members.
4706 if (!inUnion() && FieldRecord->isUnion() &&
4707 FieldRecord->isAnonymousStructOrUnion()) {
4708 bool AllVariantFieldsAreConst = true;
4710 // FIXME: Handle anonymous unions declared within anonymous unions.
4711 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4712 UE = FieldRecord->field_end();
4714 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4716 if (!UnionFieldType.isConstQualified())
4717 AllVariantFieldsAreConst = false;
4719 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4720 if (UnionFieldRecord &&
4721 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4722 UnionFieldType.getCVRQualifiers()))
4726 // At least one member in each anonymous union must be non-const
4727 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4728 FieldRecord->field_begin() != FieldRecord->field_end()) {
4730 S.Diag(FieldRecord->getLocation(),
4731 diag::note_deleted_default_ctor_all_const)
4732 << MD->getParent() << /*anonymous union*/1;
4736 // Don't check the implicit member of the anonymous union type.
4737 // This is technically non-conformant, but sanity demands it.
4741 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4742 FieldType.getCVRQualifiers()))
4749 /// C++11 [class.ctor] p5:
4750 /// A defaulted default constructor for a class X is defined as deleted if
4751 /// X is a union and all of its variant members are of const-qualified type.
4752 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4753 // This is a silly definition, because it gives an empty union a deleted
4754 // default constructor. Don't do that.
4755 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4756 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4758 S.Diag(MD->getParent()->getLocation(),
4759 diag::note_deleted_default_ctor_all_const)
4760 << MD->getParent() << /*not anonymous union*/0;
4766 /// Determine whether a defaulted special member function should be defined as
4767 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4768 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4769 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4771 if (MD->isInvalidDecl())
4773 CXXRecordDecl *RD = MD->getParent();
4774 assert(!RD->isDependentType() && "do deletion after instantiation");
4775 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4778 // C++11 [expr.lambda.prim]p19:
4779 // The closure type associated with a lambda-expression has a
4780 // deleted (8.4.3) default constructor and a deleted copy
4781 // assignment operator.
4782 if (RD->isLambda() &&
4783 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4785 Diag(RD->getLocation(), diag::note_lambda_decl);
4789 // For an anonymous struct or union, the copy and assignment special members
4790 // will never be used, so skip the check. For an anonymous union declared at
4791 // namespace scope, the constructor and destructor are used.
4792 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4793 RD->isAnonymousStructOrUnion())
4796 // C++11 [class.copy]p7, p18:
4797 // If the class definition declares a move constructor or move assignment
4798 // operator, an implicitly declared copy constructor or copy assignment
4799 // operator is defined as deleted.
4800 if (MD->isImplicit() &&
4801 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4802 CXXMethodDecl *UserDeclaredMove = 0;
4804 // In Microsoft mode, a user-declared move only causes the deletion of the
4805 // corresponding copy operation, not both copy operations.
4806 if (RD->hasUserDeclaredMoveConstructor() &&
4807 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4808 if (!Diagnose) return true;
4810 // Find any user-declared move constructor.
4811 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4812 E = RD->ctor_end(); I != E; ++I) {
4813 if (I->isMoveConstructor()) {
4814 UserDeclaredMove = *I;
4818 assert(UserDeclaredMove);
4819 } else if (RD->hasUserDeclaredMoveAssignment() &&
4820 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4821 if (!Diagnose) return true;
4823 // Find any user-declared move assignment operator.
4824 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4825 E = RD->method_end(); I != E; ++I) {
4826 if (I->isMoveAssignmentOperator()) {
4827 UserDeclaredMove = *I;
4831 assert(UserDeclaredMove);
4834 if (UserDeclaredMove) {
4835 Diag(UserDeclaredMove->getLocation(),
4836 diag::note_deleted_copy_user_declared_move)
4837 << (CSM == CXXCopyAssignment) << RD
4838 << UserDeclaredMove->isMoveAssignmentOperator();
4843 // Do access control from the special member function
4844 ContextRAII MethodContext(*this, MD);
4846 // C++11 [class.dtor]p5:
4847 // -- for a virtual destructor, lookup of the non-array deallocation function
4848 // results in an ambiguity or in a function that is deleted or inaccessible
4849 if (CSM == CXXDestructor && MD->isVirtual()) {
4850 FunctionDecl *OperatorDelete = 0;
4851 DeclarationName Name =
4852 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4853 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4854 OperatorDelete, false)) {
4856 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4861 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4863 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4864 BE = RD->bases_end(); BI != BE; ++BI)
4865 if (!BI->isVirtual() &&
4866 SMI.shouldDeleteForBase(BI))
4869 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4870 BE = RD->vbases_end(); BI != BE; ++BI)
4871 if (SMI.shouldDeleteForBase(BI))
4874 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4875 FE = RD->field_end(); FI != FE; ++FI)
4876 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4877 SMI.shouldDeleteForField(*FI))
4880 if (SMI.shouldDeleteForAllConstMembers())
4886 /// Perform lookup for a special member of the specified kind, and determine
4887 /// whether it is trivial. If the triviality can be determined without the
4888 /// lookup, skip it. This is intended for use when determining whether a
4889 /// special member of a containing object is trivial, and thus does not ever
4890 /// perform overload resolution for default constructors.
4892 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4893 /// member that was most likely to be intended to be trivial, if any.
4894 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4895 Sema::CXXSpecialMember CSM, unsigned Quals,
4896 CXXMethodDecl **Selected) {
4901 case Sema::CXXInvalid:
4902 llvm_unreachable("not a special member");
4904 case Sema::CXXDefaultConstructor:
4905 // C++11 [class.ctor]p5:
4906 // A default constructor is trivial if:
4907 // - all the [direct subobjects] have trivial default constructors
4909 // Note, no overload resolution is performed in this case.
4910 if (RD->hasTrivialDefaultConstructor())
4914 // If there's a default constructor which could have been trivial, dig it
4915 // out. Otherwise, if there's any user-provided default constructor, point
4916 // to that as an example of why there's not a trivial one.
4917 CXXConstructorDecl *DefCtor = 0;
4918 if (RD->needsImplicitDefaultConstructor())
4919 S.DeclareImplicitDefaultConstructor(RD);
4920 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4921 CE = RD->ctor_end(); CI != CE; ++CI) {
4922 if (!CI->isDefaultConstructor())
4925 if (!DefCtor->isUserProvided())
4929 *Selected = DefCtor;
4934 case Sema::CXXDestructor:
4935 // C++11 [class.dtor]p5:
4936 // A destructor is trivial if:
4937 // - all the direct [subobjects] have trivial destructors
4938 if (RD->hasTrivialDestructor())
4942 if (RD->needsImplicitDestructor())
4943 S.DeclareImplicitDestructor(RD);
4944 *Selected = RD->getDestructor();
4949 case Sema::CXXCopyConstructor:
4950 // C++11 [class.copy]p12:
4951 // A copy constructor is trivial if:
4952 // - the constructor selected to copy each direct [subobject] is trivial
4953 if (RD->hasTrivialCopyConstructor()) {
4954 if (Quals == Qualifiers::Const)
4955 // We must either select the trivial copy constructor or reach an
4956 // ambiguity; no need to actually perform overload resolution.
4958 } else if (!Selected) {
4961 // In C++98, we are not supposed to perform overload resolution here, but we
4962 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4963 // cases like B as having a non-trivial copy constructor:
4964 // struct A { template<typename T> A(T&); };
4965 // struct B { mutable A a; };
4966 goto NeedOverloadResolution;
4968 case Sema::CXXCopyAssignment:
4969 // C++11 [class.copy]p25:
4970 // A copy assignment operator is trivial if:
4971 // - the assignment operator selected to copy each direct [subobject] is
4973 if (RD->hasTrivialCopyAssignment()) {
4974 if (Quals == Qualifiers::Const)
4976 } else if (!Selected) {
4979 // In C++98, we are not supposed to perform overload resolution here, but we
4980 // treat that as a language defect.
4981 goto NeedOverloadResolution;
4983 case Sema::CXXMoveConstructor:
4984 case Sema::CXXMoveAssignment:
4985 NeedOverloadResolution:
4986 Sema::SpecialMemberOverloadResult *SMOR =
4987 S.LookupSpecialMember(RD, CSM,
4988 Quals & Qualifiers::Const,
4989 Quals & Qualifiers::Volatile,
4990 /*RValueThis*/false, /*ConstThis*/false,
4991 /*VolatileThis*/false);
4993 // The standard doesn't describe how to behave if the lookup is ambiguous.
4994 // We treat it as not making the member non-trivial, just like the standard
4995 // mandates for the default constructor. This should rarely matter, because
4996 // the member will also be deleted.
4997 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5000 if (!SMOR->getMethod()) {
5001 assert(SMOR->getKind() ==
5002 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5006 // We deliberately don't check if we found a deleted special member. We're
5009 *Selected = SMOR->getMethod();
5010 return SMOR->getMethod()->isTrivial();
5013 llvm_unreachable("unknown special method kind");
5016 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5017 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5019 if (!CI->isImplicit())
5022 // Look for constructor templates.
5023 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5024 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5025 if (CXXConstructorDecl *CD =
5026 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5033 /// The kind of subobject we are checking for triviality. The values of this
5034 /// enumeration are used in diagnostics.
5035 enum TrivialSubobjectKind {
5036 /// The subobject is a base class.
5038 /// The subobject is a non-static data member.
5040 /// The object is actually the complete object.
5044 /// Check whether the special member selected for a given type would be trivial.
5045 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5047 Sema::CXXSpecialMember CSM,
5048 TrivialSubobjectKind Kind,
5050 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5054 CXXMethodDecl *Selected;
5055 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5056 Diagnose ? &Selected : 0))
5060 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5061 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5062 << Kind << SubType.getUnqualifiedType();
5063 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5064 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5065 } else if (!Selected)
5066 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5067 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5068 else if (Selected->isUserProvided()) {
5069 if (Kind == TSK_CompleteObject)
5070 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5071 << Kind << SubType.getUnqualifiedType() << CSM;
5073 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5074 << Kind << SubType.getUnqualifiedType() << CSM;
5075 S.Diag(Selected->getLocation(), diag::note_declared_at);
5078 if (Kind != TSK_CompleteObject)
5079 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5080 << Kind << SubType.getUnqualifiedType() << CSM;
5082 // Explain why the defaulted or deleted special member isn't trivial.
5083 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5090 /// Check whether the members of a class type allow a special member to be
5092 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5093 Sema::CXXSpecialMember CSM,
5094 bool ConstArg, bool Diagnose) {
5095 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5096 FE = RD->field_end(); FI != FE; ++FI) {
5097 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5100 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5102 // Pretend anonymous struct or union members are members of this class.
5103 if (FI->isAnonymousStructOrUnion()) {
5104 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5105 CSM, ConstArg, Diagnose))
5110 // C++11 [class.ctor]p5:
5111 // A default constructor is trivial if [...]
5112 // -- no non-static data member of its class has a
5113 // brace-or-equal-initializer
5114 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5116 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5120 // Objective C ARC 4.3.5:
5121 // [...] nontrivally ownership-qualified types are [...] not trivially
5122 // default constructible, copy constructible, move constructible, copy
5123 // assignable, move assignable, or destructible [...]
5124 if (S.getLangOpts().ObjCAutoRefCount &&
5125 FieldType.hasNonTrivialObjCLifetime()) {
5127 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5128 << RD << FieldType.getObjCLifetime();
5132 if (ConstArg && !FI->isMutable())
5133 FieldType.addConst();
5134 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5135 TSK_Field, Diagnose))
5142 /// Diagnose why the specified class does not have a trivial special member of
5144 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5145 QualType Ty = Context.getRecordType(RD);
5146 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5149 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5150 TSK_CompleteObject, /*Diagnose*/true);
5153 /// Determine whether a defaulted or deleted special member function is trivial,
5154 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5155 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5156 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5158 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5160 CXXRecordDecl *RD = MD->getParent();
5162 bool ConstArg = false;
5164 // C++11 [class.copy]p12, p25:
5165 // A [special member] is trivial if its declared parameter type is the same
5166 // as if it had been implicitly declared [...]
5168 case CXXDefaultConstructor:
5170 // Trivial default constructors and destructors cannot have parameters.
5173 case CXXCopyConstructor:
5174 case CXXCopyAssignment: {
5175 // Trivial copy operations always have const, non-volatile parameter types.
5177 const ParmVarDecl *Param0 = MD->getParamDecl(0);
5178 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5179 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5181 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5182 << Param0->getSourceRange() << Param0->getType()
5183 << Context.getLValueReferenceType(
5184 Context.getRecordType(RD).withConst());
5190 case CXXMoveConstructor:
5191 case CXXMoveAssignment: {
5192 // Trivial move operations always have non-cv-qualified parameters.
5193 const ParmVarDecl *Param0 = MD->getParamDecl(0);
5194 const RValueReferenceType *RT =
5195 Param0->getType()->getAs<RValueReferenceType>();
5196 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5198 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5199 << Param0->getSourceRange() << Param0->getType()
5200 << Context.getRValueReferenceType(Context.getRecordType(RD));
5207 llvm_unreachable("not a special member");
5210 // FIXME: We require that the parameter-declaration-clause is equivalent to
5211 // that of an implicit declaration, not just that the declared parameter type
5212 // matches, in order to prevent absuridities like a function simultaneously
5213 // being a trivial copy constructor and a non-trivial default constructor.
5214 // This issue has not yet been assigned a core issue number.
5215 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5217 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5218 diag::note_nontrivial_default_arg)
5219 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5222 if (MD->isVariadic()) {
5224 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5228 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5229 // A copy/move [constructor or assignment operator] is trivial if
5230 // -- the [member] selected to copy/move each direct base class subobject
5233 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5234 // A [default constructor or destructor] is trivial if
5235 // -- all the direct base classes have trivial [default constructors or
5237 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5238 BE = RD->bases_end(); BI != BE; ++BI)
5239 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5240 ConstArg ? BI->getType().withConst()
5242 CSM, TSK_BaseClass, Diagnose))
5245 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5246 // A copy/move [constructor or assignment operator] for a class X is
5248 // -- for each non-static data member of X that is of class type (or array
5249 // thereof), the constructor selected to copy/move that member is
5252 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5253 // A [default constructor or destructor] is trivial if
5254 // -- for all of the non-static data members of its class that are of class
5255 // type (or array thereof), each such class has a trivial [default
5256 // constructor or destructor]
5257 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5260 // C++11 [class.dtor]p5:
5261 // A destructor is trivial if [...]
5262 // -- the destructor is not virtual
5263 if (CSM == CXXDestructor && MD->isVirtual()) {
5265 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5269 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5270 // A [special member] for class X is trivial if [...]
5271 // -- class X has no virtual functions and no virtual base classes
5272 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5276 if (RD->getNumVBases()) {
5277 // Check for virtual bases. We already know that the corresponding
5278 // member in all bases is trivial, so vbases must all be direct.
5279 CXXBaseSpecifier &BS = *RD->vbases_begin();
5280 assert(BS.isVirtual());
5281 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5285 // Must have a virtual method.
5286 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5287 ME = RD->method_end(); MI != ME; ++MI) {
5288 if (MI->isVirtual()) {
5289 SourceLocation MLoc = MI->getLocStart();
5290 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5295 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5298 // Looks like it's trivial!
5302 /// \brief Data used with FindHiddenVirtualMethod
5304 struct FindHiddenVirtualMethodData {
5306 CXXMethodDecl *Method;
5307 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5308 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5312 /// \brief Check whether any most overriden method from MD in Methods
5313 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5314 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5315 if (MD->size_overridden_methods() == 0)
5316 return Methods.count(MD->getCanonicalDecl());
5317 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5318 E = MD->end_overridden_methods();
5320 if (CheckMostOverridenMethods(*I, Methods))
5325 /// \brief Member lookup function that determines whether a given C++
5326 /// method overloads virtual methods in a base class without overriding any,
5327 /// to be used with CXXRecordDecl::lookupInBases().
5328 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5331 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5333 FindHiddenVirtualMethodData &Data
5334 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5336 DeclarationName Name = Data.Method->getDeclName();
5337 assert(Name.getNameKind() == DeclarationName::Identifier);
5339 bool foundSameNameMethod = false;
5340 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5341 for (Path.Decls = BaseRecord->lookup(Name);
5342 !Path.Decls.empty();
5343 Path.Decls = Path.Decls.slice(1)) {
5344 NamedDecl *D = Path.Decls.front();
5345 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5346 MD = MD->getCanonicalDecl();
5347 foundSameNameMethod = true;
5348 // Interested only in hidden virtual methods.
5349 if (!MD->isVirtual())
5351 // If the method we are checking overrides a method from its base
5352 // don't warn about the other overloaded methods.
5353 if (!Data.S->IsOverload(Data.Method, MD, false))
5355 // Collect the overload only if its hidden.
5356 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5357 overloadedMethods.push_back(MD);
5361 if (foundSameNameMethod)
5362 Data.OverloadedMethods.append(overloadedMethods.begin(),
5363 overloadedMethods.end());
5364 return foundSameNameMethod;
5367 /// \brief Add the most overriden methods from MD to Methods
5368 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5369 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5370 if (MD->size_overridden_methods() == 0)
5371 Methods.insert(MD->getCanonicalDecl());
5372 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5373 E = MD->end_overridden_methods();
5375 AddMostOverridenMethods(*I, Methods);
5378 /// \brief See if a method overloads virtual methods in a base class without
5380 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5381 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5382 MD->getLocation()) == DiagnosticsEngine::Ignored)
5384 if (!MD->getDeclName().isIdentifier())
5387 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5388 /*bool RecordPaths=*/false,
5389 /*bool DetectVirtual=*/false);
5390 FindHiddenVirtualMethodData Data;
5394 // Keep the base methods that were overriden or introduced in the subclass
5395 // by 'using' in a set. A base method not in this set is hidden.
5396 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5397 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5399 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5400 ND = shad->getTargetDecl();
5401 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5402 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5405 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5406 !Data.OverloadedMethods.empty()) {
5407 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5408 << MD << (Data.OverloadedMethods.size() > 1);
5410 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5411 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5412 Diag(overloadedMD->getLocation(),
5413 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5418 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5420 SourceLocation LBrac,
5421 SourceLocation RBrac,
5422 AttributeList *AttrList) {
5426 AdjustDeclIfTemplate(TagDecl);
5428 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5429 if (l->getKind() != AttributeList::AT_Visibility)
5432 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5436 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5437 // strict aliasing violation!
5438 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5439 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5441 CheckCompletedCXXClass(
5442 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5445 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5446 /// special functions, such as the default constructor, copy
5447 /// constructor, or destructor, to the given C++ class (C++
5448 /// [special]p1). This routine can only be executed just before the
5449 /// definition of the class is complete.
5450 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5451 if (!ClassDecl->hasUserDeclaredConstructor())
5452 ++ASTContext::NumImplicitDefaultConstructors;
5454 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5455 ++ASTContext::NumImplicitCopyConstructors;
5457 // If the properties or semantics of the copy constructor couldn't be
5458 // determined while the class was being declared, force a declaration
5460 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5461 DeclareImplicitCopyConstructor(ClassDecl);
5464 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5465 ++ASTContext::NumImplicitMoveConstructors;
5467 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5468 DeclareImplicitMoveConstructor(ClassDecl);
5471 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5472 ++ASTContext::NumImplicitCopyAssignmentOperators;
5474 // If we have a dynamic class, then the copy assignment operator may be
5475 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5476 // it shows up in the right place in the vtable and that we diagnose
5477 // problems with the implicit exception specification.
5478 if (ClassDecl->isDynamicClass() ||
5479 ClassDecl->needsOverloadResolutionForCopyAssignment())
5480 DeclareImplicitCopyAssignment(ClassDecl);
5483 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5484 ++ASTContext::NumImplicitMoveAssignmentOperators;
5486 // Likewise for the move assignment operator.
5487 if (ClassDecl->isDynamicClass() ||
5488 ClassDecl->needsOverloadResolutionForMoveAssignment())
5489 DeclareImplicitMoveAssignment(ClassDecl);
5492 if (!ClassDecl->hasUserDeclaredDestructor()) {
5493 ++ASTContext::NumImplicitDestructors;
5495 // If we have a dynamic class, then the destructor may be virtual, so we
5496 // have to declare the destructor immediately. This ensures that, e.g., it
5497 // shows up in the right place in the vtable and that we diagnose problems
5498 // with the implicit exception specification.
5499 if (ClassDecl->isDynamicClass() ||
5500 ClassDecl->needsOverloadResolutionForDestructor())
5501 DeclareImplicitDestructor(ClassDecl);
5505 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5509 int NumParamList = D->getNumTemplateParameterLists();
5510 for (int i = 0; i < NumParamList; i++) {
5511 TemplateParameterList* Params = D->getTemplateParameterList(i);
5512 for (TemplateParameterList::iterator Param = Params->begin(),
5513 ParamEnd = Params->end();
5514 Param != ParamEnd; ++Param) {
5515 NamedDecl *Named = cast<NamedDecl>(*Param);
5516 if (Named->getDeclName()) {
5518 IdResolver.AddDecl(Named);
5524 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5528 TemplateParameterList *Params = 0;
5529 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5530 Params = Template->getTemplateParameters();
5531 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5532 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5533 Params = PartialSpec->getTemplateParameters();
5537 for (TemplateParameterList::iterator Param = Params->begin(),
5538 ParamEnd = Params->end();
5539 Param != ParamEnd; ++Param) {
5540 NamedDecl *Named = cast<NamedDecl>(*Param);
5541 if (Named->getDeclName()) {
5543 IdResolver.AddDecl(Named);
5548 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5549 if (!RecordD) return;
5550 AdjustDeclIfTemplate(RecordD);
5551 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5552 PushDeclContext(S, Record);
5555 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5556 if (!RecordD) return;
5560 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
5561 /// parsing a top-level (non-nested) C++ class, and we are now
5562 /// parsing those parts of the given Method declaration that could
5563 /// not be parsed earlier (C++ [class.mem]p2), such as default
5564 /// arguments. This action should enter the scope of the given
5565 /// Method declaration as if we had just parsed the qualified method
5566 /// name. However, it should not bring the parameters into scope;
5567 /// that will be performed by ActOnDelayedCXXMethodParameter.
5568 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5571 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
5572 /// C++ method declaration. We're (re-)introducing the given
5573 /// function parameter into scope for use in parsing later parts of
5574 /// the method declaration. For example, we could see an
5575 /// ActOnParamDefaultArgument event for this parameter.
5576 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5580 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5582 // If this parameter has an unparsed default argument, clear it out
5583 // to make way for the parsed default argument.
5584 if (Param->hasUnparsedDefaultArg())
5585 Param->setDefaultArg(0);
5588 if (Param->getDeclName())
5589 IdResolver.AddDecl(Param);
5592 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5593 /// processing the delayed method declaration for Method. The method
5594 /// declaration is now considered finished. There may be a separate
5595 /// ActOnStartOfFunctionDef action later (not necessarily
5596 /// immediately!) for this method, if it was also defined inside the
5598 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5602 AdjustDeclIfTemplate(MethodD);
5604 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5606 // Now that we have our default arguments, check the constructor
5607 // again. It could produce additional diagnostics or affect whether
5608 // the class has implicitly-declared destructors, among other
5610 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5611 CheckConstructor(Constructor);
5613 // Check the default arguments, which we may have added.
5614 if (!Method->isInvalidDecl())
5615 CheckCXXDefaultArguments(Method);
5618 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5619 /// the well-formedness of the constructor declarator @p D with type @p
5620 /// R. If there are any errors in the declarator, this routine will
5621 /// emit diagnostics and set the invalid bit to true. In any case, the type
5622 /// will be updated to reflect a well-formed type for the constructor and
5624 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5626 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5628 // C++ [class.ctor]p3:
5629 // A constructor shall not be virtual (10.3) or static (9.4). A
5630 // constructor can be invoked for a const, volatile or const
5631 // volatile object. A constructor shall not be declared const,
5632 // volatile, or const volatile (9.3.2).
5634 if (!D.isInvalidType())
5635 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5636 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5637 << SourceRange(D.getIdentifierLoc());
5640 if (SC == SC_Static) {
5641 if (!D.isInvalidType())
5642 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5643 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5644 << SourceRange(D.getIdentifierLoc());
5649 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5650 if (FTI.TypeQuals != 0) {
5651 if (FTI.TypeQuals & Qualifiers::Const)
5652 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5653 << "const" << SourceRange(D.getIdentifierLoc());
5654 if (FTI.TypeQuals & Qualifiers::Volatile)
5655 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5656 << "volatile" << SourceRange(D.getIdentifierLoc());
5657 if (FTI.TypeQuals & Qualifiers::Restrict)
5658 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5659 << "restrict" << SourceRange(D.getIdentifierLoc());
5663 // C++0x [class.ctor]p4:
5664 // A constructor shall not be declared with a ref-qualifier.
5665 if (FTI.hasRefQualifier()) {
5666 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5667 << FTI.RefQualifierIsLValueRef
5668 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5672 // Rebuild the function type "R" without any type qualifiers (in
5673 // case any of the errors above fired) and with "void" as the
5674 // return type, since constructors don't have return types.
5675 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5676 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5679 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5681 EPI.RefQualifier = RQ_None;
5683 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5686 /// CheckConstructor - Checks a fully-formed constructor for
5687 /// well-formedness, issuing any diagnostics required. Returns true if
5688 /// the constructor declarator is invalid.
5689 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5690 CXXRecordDecl *ClassDecl
5691 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5693 return Constructor->setInvalidDecl();
5695 // C++ [class.copy]p3:
5696 // A declaration of a constructor for a class X is ill-formed if
5697 // its first parameter is of type (optionally cv-qualified) X and
5698 // either there are no other parameters or else all other
5699 // parameters have default arguments.
5700 if (!Constructor->isInvalidDecl() &&
5701 ((Constructor->getNumParams() == 1) ||
5702 (Constructor->getNumParams() > 1 &&
5703 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5704 Constructor->getTemplateSpecializationKind()
5705 != TSK_ImplicitInstantiation) {
5706 QualType ParamType = Constructor->getParamDecl(0)->getType();
5707 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5708 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5709 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5710 const char *ConstRef
5711 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5713 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5714 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5716 // FIXME: Rather that making the constructor invalid, we should endeavor
5718 Constructor->setInvalidDecl();
5723 /// CheckDestructor - Checks a fully-formed destructor definition for
5724 /// well-formedness, issuing any diagnostics required. Returns true
5726 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5727 CXXRecordDecl *RD = Destructor->getParent();
5729 if (Destructor->isVirtual()) {
5732 if (!Destructor->isImplicit())
5733 Loc = Destructor->getLocation();
5735 Loc = RD->getLocation();
5737 // If we have a virtual destructor, look up the deallocation function
5738 FunctionDecl *OperatorDelete = 0;
5739 DeclarationName Name =
5740 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5741 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5744 MarkFunctionReferenced(Loc, OperatorDelete);
5746 Destructor->setOperatorDelete(OperatorDelete);
5753 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5754 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5755 FTI.ArgInfo[0].Param &&
5756 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5759 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5760 /// the well-formednes of the destructor declarator @p D with type @p
5761 /// R. If there are any errors in the declarator, this routine will
5762 /// emit diagnostics and set the declarator to invalid. Even if this happens,
5763 /// will be updated to reflect a well-formed type for the destructor and
5765 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5767 // C++ [class.dtor]p1:
5768 // [...] A typedef-name that names a class is a class-name
5769 // (7.1.3); however, a typedef-name that names a class shall not
5770 // be used as the identifier in the declarator for a destructor
5772 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5773 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5774 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5775 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5776 else if (const TemplateSpecializationType *TST =
5777 DeclaratorType->getAs<TemplateSpecializationType>())
5778 if (TST->isTypeAlias())
5779 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5780 << DeclaratorType << 1;
5782 // C++ [class.dtor]p2:
5783 // A destructor is used to destroy objects of its class type. A
5784 // destructor takes no parameters, and no return type can be
5785 // specified for it (not even void). The address of a destructor
5786 // shall not be taken. A destructor shall not be static. A
5787 // destructor can be invoked for a const, volatile or const
5788 // volatile object. A destructor shall not be declared const,
5789 // volatile or const volatile (9.3.2).
5790 if (SC == SC_Static) {
5791 if (!D.isInvalidType())
5792 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5793 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5794 << SourceRange(D.getIdentifierLoc())
5795 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5799 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5800 // Destructors don't have return types, but the parser will
5801 // happily parse something like:
5807 // The return type will be eliminated later.
5808 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5809 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5810 << SourceRange(D.getIdentifierLoc());
5813 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5814 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5815 if (FTI.TypeQuals & Qualifiers::Const)
5816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5817 << "const" << SourceRange(D.getIdentifierLoc());
5818 if (FTI.TypeQuals & Qualifiers::Volatile)
5819 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5820 << "volatile" << SourceRange(D.getIdentifierLoc());
5821 if (FTI.TypeQuals & Qualifiers::Restrict)
5822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5823 << "restrict" << SourceRange(D.getIdentifierLoc());
5827 // C++0x [class.dtor]p2:
5828 // A destructor shall not be declared with a ref-qualifier.
5829 if (FTI.hasRefQualifier()) {
5830 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5831 << FTI.RefQualifierIsLValueRef
5832 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5836 // Make sure we don't have any parameters.
5837 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5838 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5840 // Delete the parameters.
5845 // Make sure the destructor isn't variadic.
5846 if (FTI.isVariadic) {
5847 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5851 // Rebuild the function type "R" without any type qualifiers or
5852 // parameters (in case any of the errors above fired) and with
5853 // "void" as the return type, since destructors don't have return
5855 if (!D.isInvalidType())
5858 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5859 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5860 EPI.Variadic = false;
5862 EPI.RefQualifier = RQ_None;
5863 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
5866 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5867 /// well-formednes of the conversion function declarator @p D with
5868 /// type @p R. If there are any errors in the declarator, this routine
5869 /// will emit diagnostics and return true. Otherwise, it will return
5870 /// false. Either way, the type @p R will be updated to reflect a
5871 /// well-formed type for the conversion operator.
5872 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5874 // C++ [class.conv.fct]p1:
5875 // Neither parameter types nor return type can be specified. The
5876 // type of a conversion function (8.3.5) is "function taking no
5877 // parameter returning conversion-type-id."
5878 if (SC == SC_Static) {
5879 if (!D.isInvalidType())
5880 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5881 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5882 << SourceRange(D.getIdentifierLoc());
5887 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5889 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5890 // Conversion functions don't have return types, but the parser will
5891 // happily parse something like:
5894 // float operator bool();
5897 // The return type will be changed later anyway.
5898 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5899 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5900 << SourceRange(D.getIdentifierLoc());
5904 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5906 // Make sure we don't have any parameters.
5907 if (Proto->getNumArgs() > 0) {
5908 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5910 // Delete the parameters.
5911 D.getFunctionTypeInfo().freeArgs();
5913 } else if (Proto->isVariadic()) {
5914 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5918 // Diagnose "&operator bool()" and other such nonsense. This
5919 // is actually a gcc extension which we don't support.
5920 if (Proto->getResultType() != ConvType) {
5921 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5922 << Proto->getResultType();
5924 ConvType = Proto->getResultType();
5927 // C++ [class.conv.fct]p4:
5928 // The conversion-type-id shall not represent a function type nor
5930 if (ConvType->isArrayType()) {
5931 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5932 ConvType = Context.getPointerType(ConvType);
5934 } else if (ConvType->isFunctionType()) {
5935 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5936 ConvType = Context.getPointerType(ConvType);
5940 // Rebuild the function type "R" without any parameters (in case any
5941 // of the errors above fired) and with the conversion type as the
5943 if (D.isInvalidType())
5944 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5945 Proto->getExtProtoInfo());
5947 // C++0x explicit conversion operators.
5948 if (D.getDeclSpec().isExplicitSpecified())
5949 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5950 getLangOpts().CPlusPlus11 ?
5951 diag::warn_cxx98_compat_explicit_conversion_functions :
5952 diag::ext_explicit_conversion_functions)
5953 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5956 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5957 /// the declaration of the given C++ conversion function. This routine
5958 /// is responsible for recording the conversion function in the C++
5959 /// class, if possible.
5960 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5961 assert(Conversion && "Expected to receive a conversion function declaration");
5963 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5965 // Make sure we aren't redeclaring the conversion function.
5966 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5968 // C++ [class.conv.fct]p1:
5969 // [...] A conversion function is never used to convert a
5970 // (possibly cv-qualified) object to the (possibly cv-qualified)
5971 // same object type (or a reference to it), to a (possibly
5972 // cv-qualified) base class of that type (or a reference to it),
5973 // or to (possibly cv-qualified) void.
5974 // FIXME: Suppress this warning if the conversion function ends up being a
5975 // virtual function that overrides a virtual function in a base class.
5977 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5978 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5979 ConvType = ConvTypeRef->getPointeeType();
5980 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5981 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5982 /* Suppress diagnostics for instantiations. */;
5983 else if (ConvType->isRecordType()) {
5984 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5985 if (ConvType == ClassType)
5986 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5988 else if (IsDerivedFrom(ClassType, ConvType))
5989 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5990 << ClassType << ConvType;
5991 } else if (ConvType->isVoidType()) {
5992 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5993 << ClassType << ConvType;
5996 if (FunctionTemplateDecl *ConversionTemplate
5997 = Conversion->getDescribedFunctionTemplate())
5998 return ConversionTemplate;
6003 //===----------------------------------------------------------------------===//
6004 // Namespace Handling
6005 //===----------------------------------------------------------------------===//
6007 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6009 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6011 IdentifierInfo *II, bool *IsInline,
6012 NamespaceDecl *PrevNS) {
6013 assert(*IsInline != PrevNS->isInline());
6015 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6016 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6017 // inline namespaces, with the intention of bringing names into namespace std.
6019 // We support this just well enough to get that case working; this is not
6020 // sufficient to support reopening namespaces as inline in general.
6021 if (*IsInline && II && II->getName().startswith("__atomic") &&
6022 S.getSourceManager().isInSystemHeader(Loc)) {
6023 // Mark all prior declarations of the namespace as inline.
6024 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6025 NS = NS->getPreviousDecl())
6026 NS->setInline(*IsInline);
6027 // Patch up the lookup table for the containing namespace. This isn't really
6028 // correct, but it's good enough for this particular case.
6029 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6030 E = PrevNS->decls_end(); I != E; ++I)
6031 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6032 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6036 if (PrevNS->isInline())
6037 // The user probably just forgot the 'inline', so suggest that it
6039 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6040 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6042 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6045 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6046 *IsInline = PrevNS->isInline();
6049 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6051 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6052 SourceLocation InlineLoc,
6053 SourceLocation NamespaceLoc,
6054 SourceLocation IdentLoc,
6056 SourceLocation LBrace,
6057 AttributeList *AttrList) {
6058 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6059 // For anonymous namespace, take the location of the left brace.
6060 SourceLocation Loc = II ? IdentLoc : LBrace;
6061 bool IsInline = InlineLoc.isValid();
6062 bool IsInvalid = false;
6064 bool AddToKnown = false;
6065 Scope *DeclRegionScope = NamespcScope->getParent();
6067 NamespaceDecl *PrevNS = 0;
6069 // C++ [namespace.def]p2:
6070 // The identifier in an original-namespace-definition shall not
6071 // have been previously defined in the declarative region in
6072 // which the original-namespace-definition appears. The
6073 // identifier in an original-namespace-definition is the name of
6074 // the namespace. Subsequently in that declarative region, it is
6075 // treated as an original-namespace-name.
6077 // Since namespace names are unique in their scope, and we don't
6078 // look through using directives, just look for any ordinary names.
6080 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6081 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6082 Decl::IDNS_Namespace;
6083 NamedDecl *PrevDecl = 0;
6084 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6085 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6087 if ((*I)->getIdentifierNamespace() & IDNS) {
6093 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6096 // This is an extended namespace definition.
6097 if (IsInline != PrevNS->isInline())
6098 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6100 } else if (PrevDecl) {
6101 // This is an invalid name redefinition.
6102 Diag(Loc, diag::err_redefinition_different_kind)
6104 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6106 // Continue on to push Namespc as current DeclContext and return it.
6107 } else if (II->isStr("std") &&
6108 CurContext->getRedeclContext()->isTranslationUnit()) {
6109 // This is the first "real" definition of the namespace "std", so update
6110 // our cache of the "std" namespace to point at this definition.
6111 PrevNS = getStdNamespace();
6113 AddToKnown = !IsInline;
6115 // We've seen this namespace for the first time.
6116 AddToKnown = !IsInline;
6119 // Anonymous namespaces.
6121 // Determine whether the parent already has an anonymous namespace.
6122 DeclContext *Parent = CurContext->getRedeclContext();
6123 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6124 PrevNS = TU->getAnonymousNamespace();
6126 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6127 PrevNS = ND->getAnonymousNamespace();
6130 if (PrevNS && IsInline != PrevNS->isInline())
6131 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6135 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6136 StartLoc, Loc, II, PrevNS);
6138 Namespc->setInvalidDecl();
6140 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6142 // FIXME: Should we be merging attributes?
6143 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6144 PushNamespaceVisibilityAttr(Attr, Loc);
6147 StdNamespace = Namespc;
6149 KnownNamespaces[Namespc] = false;
6152 PushOnScopeChains(Namespc, DeclRegionScope);
6154 // Link the anonymous namespace into its parent.
6155 DeclContext *Parent = CurContext->getRedeclContext();
6156 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6157 TU->setAnonymousNamespace(Namespc);
6159 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6162 CurContext->addDecl(Namespc);
6164 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6165 // behaves as if it were replaced by
6166 // namespace unique { /* empty body */ }
6167 // using namespace unique;
6168 // namespace unique { namespace-body }
6169 // where all occurrences of 'unique' in a translation unit are
6170 // replaced by the same identifier and this identifier differs
6171 // from all other identifiers in the entire program.
6173 // We just create the namespace with an empty name and then add an
6174 // implicit using declaration, just like the standard suggests.
6176 // CodeGen enforces the "universally unique" aspect by giving all
6177 // declarations semantically contained within an anonymous
6178 // namespace internal linkage.
6181 UsingDirectiveDecl* UD
6182 = UsingDirectiveDecl::Create(Context, Parent,
6183 /* 'using' */ LBrace,
6184 /* 'namespace' */ SourceLocation(),
6185 /* qualifier */ NestedNameSpecifierLoc(),
6186 /* identifier */ SourceLocation(),
6188 /* Ancestor */ Parent);
6190 Parent->addDecl(UD);
6194 ActOnDocumentableDecl(Namespc);
6196 // Although we could have an invalid decl (i.e. the namespace name is a
6197 // redefinition), push it as current DeclContext and try to continue parsing.
6198 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6199 // for the namespace has the declarations that showed up in that particular
6200 // namespace definition.
6201 PushDeclContext(NamespcScope, Namespc);
6205 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6206 /// is a namespace alias, returns the namespace it points to.
6207 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6208 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6209 return AD->getNamespace();
6210 return dyn_cast_or_null<NamespaceDecl>(D);
6213 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6214 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6215 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6216 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6217 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6218 Namespc->setRBraceLoc(RBrace);
6220 if (Namespc->hasAttr<VisibilityAttr>())
6221 PopPragmaVisibility(true, RBrace);
6224 CXXRecordDecl *Sema::getStdBadAlloc() const {
6225 return cast_or_null<CXXRecordDecl>(
6226 StdBadAlloc.get(Context.getExternalSource()));
6229 NamespaceDecl *Sema::getStdNamespace() const {
6230 return cast_or_null<NamespaceDecl>(
6231 StdNamespace.get(Context.getExternalSource()));
6234 /// \brief Retrieve the special "std" namespace, which may require us to
6235 /// implicitly define the namespace.
6236 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6237 if (!StdNamespace) {
6238 // The "std" namespace has not yet been defined, so build one implicitly.
6239 StdNamespace = NamespaceDecl::Create(Context,
6240 Context.getTranslationUnitDecl(),
6242 SourceLocation(), SourceLocation(),
6243 &PP.getIdentifierTable().get("std"),
6245 getStdNamespace()->setImplicit(true);
6248 return getStdNamespace();
6251 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6252 assert(getLangOpts().CPlusPlus &&
6253 "Looking for std::initializer_list outside of C++.");
6255 // We're looking for implicit instantiations of
6256 // template <typename E> class std::initializer_list.
6258 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6261 ClassTemplateDecl *Template = 0;
6262 const TemplateArgument *Arguments = 0;
6264 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6266 ClassTemplateSpecializationDecl *Specialization =
6267 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6268 if (!Specialization)
6271 Template = Specialization->getSpecializedTemplate();
6272 Arguments = Specialization->getTemplateArgs().data();
6273 } else if (const TemplateSpecializationType *TST =
6274 Ty->getAs<TemplateSpecializationType>()) {
6275 Template = dyn_cast_or_null<ClassTemplateDecl>(
6276 TST->getTemplateName().getAsTemplateDecl());
6277 Arguments = TST->getArgs();
6282 if (!StdInitializerList) {
6283 // Haven't recognized std::initializer_list yet, maybe this is it.
6284 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6285 if (TemplateClass->getIdentifier() !=
6286 &PP.getIdentifierTable().get("initializer_list") ||
6287 !getStdNamespace()->InEnclosingNamespaceSetOf(
6288 TemplateClass->getDeclContext()))
6290 // This is a template called std::initializer_list, but is it the right
6292 TemplateParameterList *Params = Template->getTemplateParameters();
6293 if (Params->getMinRequiredArguments() != 1)
6295 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6298 // It's the right template.
6299 StdInitializerList = Template;
6302 if (Template != StdInitializerList)
6305 // This is an instance of std::initializer_list. Find the argument type.
6307 *Element = Arguments[0].getAsType();
6311 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6312 NamespaceDecl *Std = S.getStdNamespace();
6314 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6318 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6319 Loc, Sema::LookupOrdinaryName);
6320 if (!S.LookupQualifiedName(Result, Std)) {
6321 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6324 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6326 Result.suppressDiagnostics();
6327 // We found something weird. Complain about the first thing we found.
6328 NamedDecl *Found = *Result.begin();
6329 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6333 // We found some template called std::initializer_list. Now verify that it's
6335 TemplateParameterList *Params = Template->getTemplateParameters();
6336 if (Params->getMinRequiredArguments() != 1 ||
6337 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6338 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6345 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6346 if (!StdInitializerList) {
6347 StdInitializerList = LookupStdInitializerList(*this, Loc);
6348 if (!StdInitializerList)
6352 TemplateArgumentListInfo Args(Loc, Loc);
6353 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6354 Context.getTrivialTypeSourceInfo(Element,
6356 return Context.getCanonicalType(
6357 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6360 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6361 // C++ [dcl.init.list]p2:
6362 // A constructor is an initializer-list constructor if its first parameter
6363 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6364 // std::initializer_list<E> for some type E, and either there are no other
6365 // parameters or else all other parameters have default arguments.
6366 if (Ctor->getNumParams() < 1 ||
6367 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6370 QualType ArgType = Ctor->getParamDecl(0)->getType();
6371 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6372 ArgType = RT->getPointeeType().getUnqualifiedType();
6374 return isStdInitializerList(ArgType, 0);
6377 /// \brief Determine whether a using statement is in a context where it will be
6378 /// apply in all contexts.
6379 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6380 switch (CurContext->getDeclKind()) {
6381 case Decl::TranslationUnit:
6383 case Decl::LinkageSpec:
6384 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6392 // Callback to only accept typo corrections that are namespaces.
6393 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6395 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6396 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6397 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6405 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6407 SourceLocation IdentLoc,
6408 IdentifierInfo *Ident) {
6409 NamespaceValidatorCCC Validator;
6411 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6412 R.getLookupKind(), Sc, &SS,
6414 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6415 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6416 if (DeclContext *DC = S.computeDeclContext(SS, false))
6417 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6418 << Ident << DC << CorrectedQuotedStr << SS.getRange()
6419 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6422 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6423 << Ident << CorrectedQuotedStr
6424 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6426 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6427 diag::note_namespace_defined_here) << CorrectedQuotedStr;
6429 R.addDecl(Corrected.getCorrectionDecl());
6435 Decl *Sema::ActOnUsingDirective(Scope *S,
6436 SourceLocation UsingLoc,
6437 SourceLocation NamespcLoc,
6439 SourceLocation IdentLoc,
6440 IdentifierInfo *NamespcName,
6441 AttributeList *AttrList) {
6442 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6443 assert(NamespcName && "Invalid NamespcName.");
6444 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6446 // This can only happen along a recovery path.
6447 while (S->getFlags() & Scope::TemplateParamScope)
6449 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6451 UsingDirectiveDecl *UDir = 0;
6452 NestedNameSpecifier *Qualifier = 0;
6454 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6456 // Lookup namespace name.
6457 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6458 LookupParsedName(R, S, &SS);
6459 if (R.isAmbiguous())
6464 // Allow "using namespace std;" or "using namespace ::std;" even if
6465 // "std" hasn't been defined yet, for GCC compatibility.
6466 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6467 NamespcName->isStr("std")) {
6468 Diag(IdentLoc, diag::ext_using_undefined_std);
6469 R.addDecl(getOrCreateStdNamespace());
6472 // Otherwise, attempt typo correction.
6473 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6477 NamedDecl *Named = R.getFoundDecl();
6478 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6479 && "expected namespace decl");
6480 // C++ [namespace.udir]p1:
6481 // A using-directive specifies that the names in the nominated
6482 // namespace can be used in the scope in which the
6483 // using-directive appears after the using-directive. During
6484 // unqualified name lookup (3.4.1), the names appear as if they
6485 // were declared in the nearest enclosing namespace which
6486 // contains both the using-directive and the nominated
6487 // namespace. [Note: in this context, "contains" means "contains
6488 // directly or indirectly". ]
6490 // Find enclosing context containing both using-directive and
6491 // nominated namespace.
6492 NamespaceDecl *NS = getNamespaceDecl(Named);
6493 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6494 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6495 CommonAncestor = CommonAncestor->getParent();
6497 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6498 SS.getWithLocInContext(Context),
6499 IdentLoc, Named, CommonAncestor);
6501 if (IsUsingDirectiveInToplevelContext(CurContext) &&
6502 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6503 Diag(IdentLoc, diag::warn_using_directive_in_header);
6506 PushUsingDirective(S, UDir);
6508 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6512 ProcessDeclAttributeList(S, UDir, AttrList);
6517 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6518 // If the scope has an associated entity and the using directive is at
6519 // namespace or translation unit scope, add the UsingDirectiveDecl into
6520 // its lookup structure so qualified name lookup can find it.
6521 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6522 if (Ctx && !Ctx->isFunctionOrMethod())
6525 // Otherwise, it is at block sope. The using-directives will affect lookup
6526 // only to the end of the scope.
6527 S->PushUsingDirective(UDir);
6531 Decl *Sema::ActOnUsingDeclaration(Scope *S,
6533 bool HasUsingKeyword,
6534 SourceLocation UsingLoc,
6536 UnqualifiedId &Name,
6537 AttributeList *AttrList,
6539 SourceLocation TypenameLoc) {
6540 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6542 switch (Name.getKind()) {
6543 case UnqualifiedId::IK_ImplicitSelfParam:
6544 case UnqualifiedId::IK_Identifier:
6545 case UnqualifiedId::IK_OperatorFunctionId:
6546 case UnqualifiedId::IK_LiteralOperatorId:
6547 case UnqualifiedId::IK_ConversionFunctionId:
6550 case UnqualifiedId::IK_ConstructorName:
6551 case UnqualifiedId::IK_ConstructorTemplateId:
6552 // C++11 inheriting constructors.
6553 Diag(Name.getLocStart(),
6554 getLangOpts().CPlusPlus11 ?
6555 diag::warn_cxx98_compat_using_decl_constructor :
6556 diag::err_using_decl_constructor)
6559 if (getLangOpts().CPlusPlus11) break;
6563 case UnqualifiedId::IK_DestructorName:
6564 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6568 case UnqualifiedId::IK_TemplateId:
6569 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6570 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6574 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6575 DeclarationName TargetName = TargetNameInfo.getName();
6579 // Warn about access declarations.
6580 // TODO: store that the declaration was written without 'using' and
6581 // talk about access decls instead of using decls in the
6583 if (!HasUsingKeyword) {
6584 UsingLoc = Name.getLocStart();
6586 Diag(UsingLoc, diag::warn_access_decl_deprecated)
6587 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6590 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6591 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6594 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6595 TargetNameInfo, AttrList,
6596 /* IsInstantiation */ false,
6597 IsTypeName, TypenameLoc);
6599 PushOnScopeChains(UD, S, /*AddToContext*/ false);
6604 /// \brief Determine whether a using declaration considers the given
6605 /// declarations as "equivalent", e.g., if they are redeclarations of
6606 /// the same entity or are both typedefs of the same type.
6608 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6609 bool &SuppressRedeclaration) {
6610 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6611 SuppressRedeclaration = false;
6615 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6616 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6617 SuppressRedeclaration = true;
6618 return Context.hasSameType(TD1->getUnderlyingType(),
6619 TD2->getUnderlyingType());
6626 /// Determines whether to create a using shadow decl for a particular
6627 /// decl, given the set of decls existing prior to this using lookup.
6628 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6629 const LookupResult &Previous) {
6630 // Diagnose finding a decl which is not from a base class of the
6631 // current class. We do this now because there are cases where this
6632 // function will silently decide not to build a shadow decl, which
6633 // will pre-empt further diagnostics.
6635 // We don't need to do this in C++0x because we do the check once on
6638 // FIXME: diagnose the following if we care enough:
6639 // struct A { int foo; };
6640 // struct B : A { using A::foo; };
6641 // template <class T> struct C : A {};
6642 // template <class T> struct D : C<T> { using B::foo; } // <---
6643 // This is invalid (during instantiation) in C++03 because B::foo
6644 // resolves to the using decl in B, which is not a base class of D<T>.
6645 // We can't diagnose it immediately because C<T> is an unknown
6646 // specialization. The UsingShadowDecl in D<T> then points directly
6647 // to A::foo, which will look well-formed when we instantiate.
6648 // The right solution is to not collapse the shadow-decl chain.
6649 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6650 DeclContext *OrigDC = Orig->getDeclContext();
6652 // Handle enums and anonymous structs.
6653 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6654 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6655 while (OrigRec->isAnonymousStructOrUnion())
6656 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6658 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6659 if (OrigDC == CurContext) {
6660 Diag(Using->getLocation(),
6661 diag::err_using_decl_nested_name_specifier_is_current_class)
6662 << Using->getQualifierLoc().getSourceRange();
6663 Diag(Orig->getLocation(), diag::note_using_decl_target);
6667 Diag(Using->getQualifierLoc().getBeginLoc(),
6668 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6669 << Using->getQualifier()
6670 << cast<CXXRecordDecl>(CurContext)
6671 << Using->getQualifierLoc().getSourceRange();
6672 Diag(Orig->getLocation(), diag::note_using_decl_target);
6677 if (Previous.empty()) return false;
6679 NamedDecl *Target = Orig;
6680 if (isa<UsingShadowDecl>(Target))
6681 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6683 // If the target happens to be one of the previous declarations, we
6684 // don't have a conflict.
6686 // FIXME: but we might be increasing its access, in which case we
6687 // should redeclare it.
6688 NamedDecl *NonTag = 0, *Tag = 0;
6689 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6691 NamedDecl *D = (*I)->getUnderlyingDecl();
6693 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6696 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6699 if (Target->isFunctionOrFunctionTemplate()) {
6701 if (isa<FunctionTemplateDecl>(Target))
6702 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6704 FD = cast<FunctionDecl>(Target);
6706 NamedDecl *OldDecl = 0;
6707 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6711 case Ovl_NonFunction:
6712 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6715 // We found a decl with the exact signature.
6717 // If we're in a record, we want to hide the target, so we
6718 // return true (without a diagnostic) to tell the caller not to
6719 // build a shadow decl.
6720 if (CurContext->isRecord())
6723 // If we're not in a record, this is an error.
6724 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6728 Diag(Target->getLocation(), diag::note_using_decl_target);
6729 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6733 // Target is not a function.
6735 if (isa<TagDecl>(Target)) {
6736 // No conflict between a tag and a non-tag.
6737 if (!Tag) return false;
6739 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6740 Diag(Target->getLocation(), diag::note_using_decl_target);
6741 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6745 // No conflict between a tag and a non-tag.
6746 if (!NonTag) return false;
6748 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6749 Diag(Target->getLocation(), diag::note_using_decl_target);
6750 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6754 /// Builds a shadow declaration corresponding to a 'using' declaration.
6755 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6759 // If we resolved to another shadow declaration, just coalesce them.
6760 NamedDecl *Target = Orig;
6761 if (isa<UsingShadowDecl>(Target)) {
6762 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6763 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6766 UsingShadowDecl *Shadow
6767 = UsingShadowDecl::Create(Context, CurContext,
6768 UD->getLocation(), UD, Target);
6769 UD->addShadowDecl(Shadow);
6771 Shadow->setAccess(UD->getAccess());
6772 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6773 Shadow->setInvalidDecl();
6776 PushOnScopeChains(Shadow, S);
6778 CurContext->addDecl(Shadow);
6784 /// Hides a using shadow declaration. This is required by the current
6785 /// using-decl implementation when a resolvable using declaration in a
6786 /// class is followed by a declaration which would hide or override
6787 /// one or more of the using decl's targets; for example:
6789 /// struct Base { void foo(int); };
6790 /// struct Derived : Base {
6791 /// using Base::foo;
6795 /// The governing language is C++03 [namespace.udecl]p12:
6797 /// When a using-declaration brings names from a base class into a
6798 /// derived class scope, member functions in the derived class
6799 /// override and/or hide member functions with the same name and
6800 /// parameter types in a base class (rather than conflicting).
6802 /// There are two ways to implement this:
6803 /// (1) optimistically create shadow decls when they're not hidden
6804 /// by existing declarations, or
6805 /// (2) don't create any shadow decls (or at least don't make them
6806 /// visible) until we've fully parsed/instantiated the class.
6807 /// The problem with (1) is that we might have to retroactively remove
6808 /// a shadow decl, which requires several O(n) operations because the
6809 /// decl structures are (very reasonably) not designed for removal.
6810 /// (2) avoids this but is very fiddly and phase-dependent.
6811 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6812 if (Shadow->getDeclName().getNameKind() ==
6813 DeclarationName::CXXConversionFunctionName)
6814 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6816 // Remove it from the DeclContext...
6817 Shadow->getDeclContext()->removeDecl(Shadow);
6819 // ...and the scope, if applicable...
6821 S->RemoveDecl(Shadow);
6822 IdResolver.RemoveDecl(Shadow);
6825 // ...and the using decl.
6826 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6828 // TODO: complain somehow if Shadow was used. It shouldn't
6829 // be possible for this to happen, because...?
6832 /// Builds a using declaration.
6834 /// \param IsInstantiation - Whether this call arises from an
6835 /// instantiation of an unresolved using declaration. We treat
6836 /// the lookup differently for these declarations.
6837 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6838 SourceLocation UsingLoc,
6840 const DeclarationNameInfo &NameInfo,
6841 AttributeList *AttrList,
6842 bool IsInstantiation,
6844 SourceLocation TypenameLoc) {
6845 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6846 SourceLocation IdentLoc = NameInfo.getLoc();
6847 assert(IdentLoc.isValid() && "Invalid TargetName location.");
6849 // FIXME: We ignore attributes for now.
6852 Diag(IdentLoc, diag::err_using_requires_qualname);
6856 // Do the redeclaration lookup in the current scope.
6857 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6859 Previous.setHideTags(false);
6861 LookupName(Previous, S);
6863 // It is really dumb that we have to do this.
6864 LookupResult::Filter F = Previous.makeFilter();
6865 while (F.hasNext()) {
6866 NamedDecl *D = F.next();
6867 if (!isDeclInScope(D, CurContext, S))
6872 assert(IsInstantiation && "no scope in non-instantiation");
6873 assert(CurContext->isRecord() && "scope not record in instantiation");
6874 LookupQualifiedName(Previous, CurContext);
6877 // Check for invalid redeclarations.
6878 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6881 // Check for bad qualifiers.
6882 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6885 DeclContext *LookupContext = computeDeclContext(SS);
6887 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6888 if (!LookupContext) {
6890 // FIXME: not all declaration name kinds are legal here
6891 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6892 UsingLoc, TypenameLoc,
6894 IdentLoc, NameInfo.getName());
6896 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6897 QualifierLoc, NameInfo);
6900 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6901 NameInfo, IsTypeName);
6904 CurContext->addDecl(D);
6906 if (!LookupContext) return D;
6907 UsingDecl *UD = cast<UsingDecl>(D);
6909 if (RequireCompleteDeclContext(SS, LookupContext)) {
6910 UD->setInvalidDecl();
6914 // The normal rules do not apply to inheriting constructor declarations.
6915 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6916 if (CheckInheritingConstructorUsingDecl(UD))
6917 UD->setInvalidDecl();
6921 // Otherwise, look up the target name.
6923 LookupResult R(*this, NameInfo, LookupOrdinaryName);
6925 // Unlike most lookups, we don't always want to hide tag
6926 // declarations: tag names are visible through the using declaration
6927 // even if hidden by ordinary names, *except* in a dependent context
6928 // where it's important for the sanity of two-phase lookup.
6929 if (!IsInstantiation)
6930 R.setHideTags(false);
6932 // For the purposes of this lookup, we have a base object type
6933 // equal to that of the current context.
6934 if (CurContext->isRecord()) {
6935 R.setBaseObjectType(
6936 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6939 LookupQualifiedName(R, LookupContext);
6942 Diag(IdentLoc, diag::err_no_member)
6943 << NameInfo.getName() << LookupContext << SS.getRange();
6944 UD->setInvalidDecl();
6948 if (R.isAmbiguous()) {
6949 UD->setInvalidDecl();
6954 // If we asked for a typename and got a non-type decl, error out.
6955 if (!R.getAsSingle<TypeDecl>()) {
6956 Diag(IdentLoc, diag::err_using_typename_non_type);
6957 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6958 Diag((*I)->getUnderlyingDecl()->getLocation(),
6959 diag::note_using_decl_target);
6960 UD->setInvalidDecl();
6964 // If we asked for a non-typename and we got a type, error out,
6965 // but only if this is an instantiation of an unresolved using
6966 // decl. Otherwise just silently find the type name.
6967 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6968 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6969 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6970 UD->setInvalidDecl();
6975 // C++0x N2914 [namespace.udecl]p6:
6976 // A using-declaration shall not name a namespace.
6977 if (R.getAsSingle<NamespaceDecl>()) {
6978 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6980 UD->setInvalidDecl();
6984 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6985 if (!CheckUsingShadowDecl(UD, *I, Previous))
6986 BuildUsingShadowDecl(S, UD, *I);
6992 /// Additional checks for a using declaration referring to a constructor name.
6993 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6994 assert(!UD->isTypeName() && "expecting a constructor name");
6996 const Type *SourceType = UD->getQualifier()->getAsType();
6997 assert(SourceType &&
6998 "Using decl naming constructor doesn't have type in scope spec.");
6999 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7001 // Check whether the named type is a direct base class.
7002 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7003 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7004 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7005 BaseIt != BaseE; ++BaseIt) {
7006 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7007 if (CanonicalSourceType == BaseType)
7009 if (BaseIt->getType()->isDependentType())
7013 if (BaseIt == BaseE) {
7014 // Did not find SourceType in the bases.
7015 Diag(UD->getUsingLocation(),
7016 diag::err_using_decl_constructor_not_in_direct_base)
7017 << UD->getNameInfo().getSourceRange()
7018 << QualType(SourceType, 0) << TargetClass;
7022 if (!CurContext->isDependentContext())
7023 BaseIt->setInheritConstructors();
7028 /// Checks that the given using declaration is not an invalid
7029 /// redeclaration. Note that this is checking only for the using decl
7030 /// itself, not for any ill-formedness among the UsingShadowDecls.
7031 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7033 const CXXScopeSpec &SS,
7034 SourceLocation NameLoc,
7035 const LookupResult &Prev) {
7036 // C++03 [namespace.udecl]p8:
7037 // C++0x [namespace.udecl]p10:
7038 // A using-declaration is a declaration and can therefore be used
7039 // repeatedly where (and only where) multiple declarations are
7042 // That's in non-member contexts.
7043 if (!CurContext->getRedeclContext()->isRecord())
7046 NestedNameSpecifier *Qual
7047 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7049 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7053 NestedNameSpecifier *DQual;
7054 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7055 DTypename = UD->isTypeName();
7056 DQual = UD->getQualifier();
7057 } else if (UnresolvedUsingValueDecl *UD
7058 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7060 DQual = UD->getQualifier();
7061 } else if (UnresolvedUsingTypenameDecl *UD
7062 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7064 DQual = UD->getQualifier();
7067 // using decls differ if one says 'typename' and the other doesn't.
7068 // FIXME: non-dependent using decls?
7069 if (isTypeName != DTypename) continue;
7071 // using decls differ if they name different scopes (but note that
7072 // template instantiation can cause this check to trigger when it
7073 // didn't before instantiation).
7074 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7075 Context.getCanonicalNestedNameSpecifier(DQual))
7078 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7079 Diag(D->getLocation(), diag::note_using_decl) << 1;
7087 /// Checks that the given nested-name qualifier used in a using decl
7088 /// in the current context is appropriately related to the current
7089 /// scope. If an error is found, diagnoses it and returns true.
7090 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7091 const CXXScopeSpec &SS,
7092 SourceLocation NameLoc) {
7093 DeclContext *NamedContext = computeDeclContext(SS);
7095 if (!CurContext->isRecord()) {
7096 // C++03 [namespace.udecl]p3:
7097 // C++0x [namespace.udecl]p8:
7098 // A using-declaration for a class member shall be a member-declaration.
7100 // If we weren't able to compute a valid scope, it must be a
7101 // dependent class scope.
7102 if (!NamedContext || NamedContext->isRecord()) {
7103 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7108 // Otherwise, everything is known to be fine.
7112 // The current scope is a record.
7114 // If the named context is dependent, we can't decide much.
7115 if (!NamedContext) {
7116 // FIXME: in C++0x, we can diagnose if we can prove that the
7117 // nested-name-specifier does not refer to a base class, which is
7118 // still possible in some cases.
7120 // Otherwise we have to conservatively report that things might be
7125 if (!NamedContext->isRecord()) {
7126 // Ideally this would point at the last name in the specifier,
7127 // but we don't have that level of source info.
7128 Diag(SS.getRange().getBegin(),
7129 diag::err_using_decl_nested_name_specifier_is_not_class)
7130 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7134 if (!NamedContext->isDependentContext() &&
7135 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7138 if (getLangOpts().CPlusPlus11) {
7139 // C++0x [namespace.udecl]p3:
7140 // In a using-declaration used as a member-declaration, the
7141 // nested-name-specifier shall name a base class of the class
7144 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7145 cast<CXXRecordDecl>(NamedContext))) {
7146 if (CurContext == NamedContext) {
7148 diag::err_using_decl_nested_name_specifier_is_current_class)
7153 Diag(SS.getRange().getBegin(),
7154 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7155 << (NestedNameSpecifier*) SS.getScopeRep()
7156 << cast<CXXRecordDecl>(CurContext)
7164 // C++03 [namespace.udecl]p4:
7165 // A using-declaration used as a member-declaration shall refer
7166 // to a member of a base class of the class being defined [etc.].
7168 // Salient point: SS doesn't have to name a base class as long as
7169 // lookup only finds members from base classes. Therefore we can
7170 // diagnose here only if we can prove that that can't happen,
7171 // i.e. if the class hierarchies provably don't intersect.
7173 // TODO: it would be nice if "definitely valid" results were cached
7174 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7175 // need to be repeated.
7178 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7180 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7181 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7182 Data->Bases.insert(Base);
7186 bool hasDependentBases(const CXXRecordDecl *Class) {
7187 return !Class->forallBases(collect, this);
7190 /// Returns true if the base is dependent or is one of the
7191 /// accumulated base classes.
7192 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7193 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7194 return !Data->Bases.count(Base);
7197 bool mightShareBases(const CXXRecordDecl *Class) {
7198 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7204 // Returns false if we find a dependent base.
7205 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7208 // Returns false if the class has a dependent base or if it or one
7209 // of its bases is present in the base set of the current context.
7210 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7213 Diag(SS.getRange().getBegin(),
7214 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7215 << (NestedNameSpecifier*) SS.getScopeRep()
7216 << cast<CXXRecordDecl>(CurContext)
7222 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7224 MultiTemplateParamsArg TemplateParamLists,
7225 SourceLocation UsingLoc,
7226 UnqualifiedId &Name,
7227 AttributeList *AttrList,
7229 // Skip up to the relevant declaration scope.
7230 while (S->getFlags() & Scope::TemplateParamScope)
7232 assert((S->getFlags() & Scope::DeclScope) &&
7233 "got alias-declaration outside of declaration scope");
7235 if (Type.isInvalid())
7238 bool Invalid = false;
7239 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7240 TypeSourceInfo *TInfo = 0;
7241 GetTypeFromParser(Type.get(), &TInfo);
7243 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7246 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7247 UPPC_DeclarationType)) {
7249 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7250 TInfo->getTypeLoc().getBeginLoc());
7253 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7254 LookupName(Previous, S);
7256 // Warn about shadowing the name of a template parameter.
7257 if (Previous.isSingleResult() &&
7258 Previous.getFoundDecl()->isTemplateParameter()) {
7259 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7263 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7264 "name in alias declaration must be an identifier");
7265 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7267 Name.Identifier, TInfo);
7269 NewTD->setAccess(AS);
7272 NewTD->setInvalidDecl();
7274 ProcessDeclAttributeList(S, NewTD, AttrList);
7276 CheckTypedefForVariablyModifiedType(S, NewTD);
7277 Invalid |= NewTD->isInvalidDecl();
7279 bool Redeclaration = false;
7282 if (TemplateParamLists.size()) {
7283 TypeAliasTemplateDecl *OldDecl = 0;
7284 TemplateParameterList *OldTemplateParams = 0;
7286 if (TemplateParamLists.size() != 1) {
7287 Diag(UsingLoc, diag::err_alias_template_extra_headers)
7288 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7289 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7291 TemplateParameterList *TemplateParams = TemplateParamLists[0];
7293 // Only consider previous declarations in the same scope.
7294 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7295 /*ExplicitInstantiationOrSpecialization*/false);
7296 if (!Previous.empty()) {
7297 Redeclaration = true;
7299 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7300 if (!OldDecl && !Invalid) {
7301 Diag(UsingLoc, diag::err_redefinition_different_kind)
7304 NamedDecl *OldD = Previous.getRepresentativeDecl();
7305 if (OldD->getLocation().isValid())
7306 Diag(OldD->getLocation(), diag::note_previous_definition);
7311 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7312 if (TemplateParameterListsAreEqual(TemplateParams,
7313 OldDecl->getTemplateParameters(),
7316 OldTemplateParams = OldDecl->getTemplateParameters();
7320 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7322 !Context.hasSameType(OldTD->getUnderlyingType(),
7323 NewTD->getUnderlyingType())) {
7324 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7325 // but we can't reasonably accept it.
7326 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7327 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7328 if (OldTD->getLocation().isValid())
7329 Diag(OldTD->getLocation(), diag::note_previous_definition);
7335 // Merge any previous default template arguments into our parameters,
7336 // and check the parameter list.
7337 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7338 TPC_TypeAliasTemplate))
7341 TypeAliasTemplateDecl *NewDecl =
7342 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7343 Name.Identifier, TemplateParams,
7346 NewDecl->setAccess(AS);
7349 NewDecl->setInvalidDecl();
7351 NewDecl->setPreviousDeclaration(OldDecl);
7355 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7360 PushOnScopeChains(NewND, S);
7362 ActOnDocumentableDecl(NewND);
7366 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7367 SourceLocation NamespaceLoc,
7368 SourceLocation AliasLoc,
7369 IdentifierInfo *Alias,
7371 SourceLocation IdentLoc,
7372 IdentifierInfo *Ident) {
7374 // Lookup the namespace name.
7375 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7376 LookupParsedName(R, S, &SS);
7378 // Check if we have a previous declaration with the same name.
7380 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7382 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7386 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7387 // We already have an alias with the same name that points to the same
7388 // namespace, so don't create a new one.
7389 // FIXME: At some point, we'll want to create the (redundant)
7390 // declaration to maintain better source information.
7391 if (!R.isAmbiguous() && !R.empty() &&
7392 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7396 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7397 diag::err_redefinition_different_kind;
7398 Diag(AliasLoc, DiagID) << Alias;
7399 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7403 if (R.isAmbiguous())
7407 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7408 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7413 NamespaceAliasDecl *AliasDecl =
7414 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7415 Alias, SS.getWithLocInContext(Context),
7416 IdentLoc, R.getFoundDecl());
7418 PushOnScopeChains(AliasDecl, S);
7422 Sema::ImplicitExceptionSpecification
7423 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7424 CXXMethodDecl *MD) {
7425 CXXRecordDecl *ClassDecl = MD->getParent();
7427 // C++ [except.spec]p14:
7428 // An implicitly declared special member function (Clause 12) shall have an
7429 // exception-specification. [...]
7430 ImplicitExceptionSpecification ExceptSpec(*this);
7431 if (ClassDecl->isInvalidDecl())
7434 // Direct base-class constructors.
7435 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7436 BEnd = ClassDecl->bases_end();
7438 if (B->isVirtual()) // Handled below.
7441 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7442 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7443 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7444 // If this is a deleted function, add it anyway. This might be conformant
7445 // with the standard. This might not. I'm not sure. It might not matter.
7447 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7451 // Virtual base-class constructors.
7452 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7453 BEnd = ClassDecl->vbases_end();
7455 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7456 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7457 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7458 // If this is a deleted function, add it anyway. This might be conformant
7459 // with the standard. This might not. I'm not sure. It might not matter.
7461 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7465 // Field constructors.
7466 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7467 FEnd = ClassDecl->field_end();
7469 if (F->hasInClassInitializer()) {
7470 if (Expr *E = F->getInClassInitializer())
7471 ExceptSpec.CalledExpr(E);
7472 else if (!F->isInvalidDecl())
7474 // If the brace-or-equal-initializer of a non-static data member
7475 // invokes a defaulted default constructor of its class or of an
7476 // enclosing class in a potentially evaluated subexpression, the
7477 // program is ill-formed.
7479 // This resolution is unworkable: the exception specification of the
7480 // default constructor can be needed in an unevaluated context, in
7481 // particular, in the operand of a noexcept-expression, and we can be
7482 // unable to compute an exception specification for an enclosed class.
7484 // We do not allow an in-class initializer to require the evaluation
7485 // of the exception specification for any in-class initializer whose
7486 // definition is not lexically complete.
7487 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7488 } else if (const RecordType *RecordTy
7489 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7490 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7491 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7492 // If this is a deleted function, add it anyway. This might be conformant
7493 // with the standard. This might not. I'm not sure. It might not matter.
7494 // In particular, the problem is that this function never gets called. It
7495 // might just be ill-formed because this function attempts to refer to
7496 // a deleted function here.
7498 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7505 Sema::ImplicitExceptionSpecification
7506 Sema::ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD) {
7507 ImplicitExceptionSpecification ExceptSpec(*this);
7508 // FIXME: Compute the exception spec.
7513 /// RAII object to register a special member as being currently declared.
7514 struct DeclaringSpecialMember {
7516 Sema::SpecialMemberDecl D;
7517 bool WasAlreadyBeingDeclared;
7519 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7520 : S(S), D(RD, CSM) {
7521 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7522 if (WasAlreadyBeingDeclared)
7523 // This almost never happens, but if it does, ensure that our cache
7524 // doesn't contain a stale result.
7525 S.SpecialMemberCache.clear();
7527 // FIXME: Register a note to be produced if we encounter an error while
7528 // declaring the special member.
7530 ~DeclaringSpecialMember() {
7531 if (!WasAlreadyBeingDeclared)
7532 S.SpecialMembersBeingDeclared.erase(D);
7535 /// \brief Are we already trying to declare this special member?
7536 bool isAlreadyBeingDeclared() const {
7537 return WasAlreadyBeingDeclared;
7542 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7543 CXXRecordDecl *ClassDecl) {
7544 // C++ [class.ctor]p5:
7545 // A default constructor for a class X is a constructor of class X
7546 // that can be called without an argument. If there is no
7547 // user-declared constructor for class X, a default constructor is
7548 // implicitly declared. An implicitly-declared default constructor
7549 // is an inline public member of its class.
7550 assert(ClassDecl->needsImplicitDefaultConstructor() &&
7551 "Should not build implicit default constructor!");
7553 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7554 if (DSM.isAlreadyBeingDeclared())
7557 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7558 CXXDefaultConstructor,
7561 // Create the actual constructor declaration.
7562 CanQualType ClassType
7563 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7564 SourceLocation ClassLoc = ClassDecl->getLocation();
7565 DeclarationName Name
7566 = Context.DeclarationNames.getCXXConstructorName(ClassType);
7567 DeclarationNameInfo NameInfo(Name, ClassLoc);
7568 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7569 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7570 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7572 DefaultCon->setAccess(AS_public);
7573 DefaultCon->setDefaulted();
7574 DefaultCon->setImplicit();
7576 // Build an exception specification pointing back at this constructor.
7577 FunctionProtoType::ExtProtoInfo EPI;
7578 EPI.ExceptionSpecType = EST_Unevaluated;
7579 EPI.ExceptionSpecDecl = DefaultCon;
7580 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7581 ArrayRef<QualType>(),
7584 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7585 // constructors is easy to compute.
7586 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7588 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7589 SetDeclDeleted(DefaultCon, ClassLoc);
7591 // Note that we have declared this constructor.
7592 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7594 if (Scope *S = getScopeForContext(ClassDecl))
7595 PushOnScopeChains(DefaultCon, S, false);
7596 ClassDecl->addDecl(DefaultCon);
7601 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7602 CXXConstructorDecl *Constructor) {
7603 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7604 !Constructor->doesThisDeclarationHaveABody() &&
7605 !Constructor->isDeleted()) &&
7606 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7608 CXXRecordDecl *ClassDecl = Constructor->getParent();
7609 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7611 SynthesizedFunctionScope Scope(*this, Constructor);
7612 DiagnosticErrorTrap Trap(Diags);
7613 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7614 Trap.hasErrorOccurred()) {
7615 Diag(CurrentLocation, diag::note_member_synthesized_at)
7616 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7617 Constructor->setInvalidDecl();
7621 SourceLocation Loc = Constructor->getLocation();
7622 Constructor->setBody(new (Context) CompoundStmt(Loc));
7624 Constructor->setUsed();
7625 MarkVTableUsed(CurrentLocation, ClassDecl);
7627 if (ASTMutationListener *L = getASTMutationListener()) {
7628 L->CompletedImplicitDefinition(Constructor);
7632 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7633 // Check that any explicitly-defaulted methods have exception specifications
7634 // compatible with their implicit exception specifications.
7635 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7638 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
7639 // We start with an initial pass over the base classes to collect those that
7640 // inherit constructors from. If there are none, we can forgo all further
7642 typedef SmallVector<const RecordType *, 4> BasesVector;
7643 BasesVector BasesToInheritFrom;
7644 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7645 BaseE = ClassDecl->bases_end();
7646 BaseIt != BaseE; ++BaseIt) {
7647 if (BaseIt->getInheritConstructors()) {
7648 QualType Base = BaseIt->getType();
7649 if (Base->isDependentType()) {
7650 // If we inherit constructors from anything that is dependent, just
7651 // abort processing altogether. We'll get another chance for the
7653 // FIXME: We need to ensure that any call to a constructor of this class
7654 // is considered instantiation-dependent in this case.
7657 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7660 if (BasesToInheritFrom.empty())
7663 // FIXME: Constructor templates.
7665 // Now collect the constructors that we already have in the current class.
7666 // Those take precedence over inherited constructors.
7667 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7668 // unless there is a user-declared constructor with the same signature in
7669 // the class where the using-declaration appears.
7670 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7671 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7672 CtorE = ClassDecl->ctor_end();
7673 CtorIt != CtorE; ++CtorIt)
7674 ExistingConstructors.insert(
7675 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7677 DeclarationName CreatedCtorName =
7678 Context.DeclarationNames.getCXXConstructorName(
7679 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7681 // Now comes the true work.
7682 // First, we keep a map from constructor types to the base that introduced
7683 // them. Needed for finding conflicting constructors. We also keep the
7684 // actually inserted declarations in there, for pretty diagnostics.
7685 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7686 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7687 ConstructorToSourceMap InheritedConstructors;
7688 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7689 BaseE = BasesToInheritFrom.end();
7690 BaseIt != BaseE; ++BaseIt) {
7691 const RecordType *Base = *BaseIt;
7692 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7693 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7694 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7695 CtorE = BaseDecl->ctor_end();
7696 CtorIt != CtorE; ++CtorIt) {
7697 // Find the using declaration for inheriting this base's constructors.
7698 // FIXME: Don't perform name lookup just to obtain a source location!
7699 DeclarationName Name =
7700 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7701 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7702 LookupQualifiedName(Result, CurContext);
7703 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
7704 SourceLocation UsingLoc = UD ? UD->getLocation() :
7705 ClassDecl->getLocation();
7707 // C++11 [class.inhctor]p1:
7708 // The candidate set of inherited constructors from the class X named in
7709 // the using-declaration consists of actual constructors and notional
7710 // constructors that result from the transformation of defaulted
7711 // parameters as follows:
7712 // - all non-template constructors of X, and
7713 // - for each non-template constructor of X that has at least one
7714 // parameter with a default argument, the set of constructors that
7715 // results from omitting any ellipsis parameter specification and
7716 // successively omitting parameters with a default argument from the
7717 // end of the parameter-type-list, and
7718 // FIXME: ...also constructor templates.
7719 CXXConstructorDecl *BaseCtor = *CtorIt;
7720 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7721 const FunctionProtoType *BaseCtorType =
7722 BaseCtor->getType()->getAs<FunctionProtoType>();
7724 // Determine whether this would be a copy or move constructor for the
7726 if (BaseCtorType->getNumArgs() >= 1 &&
7727 BaseCtorType->getArgType(0)->isReferenceType() &&
7728 Context.hasSameUnqualifiedType(
7729 BaseCtorType->getArgType(0)->getPointeeType(),
7730 Context.getTagDeclType(ClassDecl)))
7731 CanBeCopyOrMove = true;
7733 ArrayRef<QualType> ArgTypes(BaseCtorType->getArgTypes());
7734 FunctionProtoType::ExtProtoInfo EPI = BaseCtorType->getExtProtoInfo();
7735 // Core issue (no number yet): the ellipsis is always discarded.
7737 Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7738 Diag(BaseCtor->getLocation(),
7739 diag::note_using_decl_constructor_ellipsis);
7740 EPI.Variadic = false;
7743 for (unsigned Params = BaseCtor->getMinRequiredArguments(),
7744 MaxParams = BaseCtor->getNumParams();
7745 Params <= MaxParams; ++Params) {
7746 // Skip default constructors. They're never inherited.
7750 // Skip copy and move constructors for both base and derived class
7751 // for the same reason.
7752 if (CanBeCopyOrMove && Params == 1)
7755 // Build up a function type for this particular constructor.
7756 QualType NewCtorType =
7757 Context.getFunctionType(Context.VoidTy, ArgTypes.slice(0, Params),
7759 const Type *CanonicalNewCtorType =
7760 Context.getCanonicalType(NewCtorType).getTypePtr();
7762 // C++11 [class.inhctor]p3:
7763 // ... a constructor is implicitly declared with the same constructor
7764 // characteristics unless there is a user-declared constructor with
7765 // the same signature in the class where the using-declaration appears
7766 if (ExistingConstructors.count(CanonicalNewCtorType))
7769 // C++11 [class.inhctor]p7:
7770 // If two using-declarations declare inheriting constructors with the
7771 // same signature, the program is ill-formed
7772 std::pair<ConstructorToSourceMap::iterator, bool> result =
7773 InheritedConstructors.insert(std::make_pair(
7774 CanonicalNewCtorType,
7775 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7776 if (!result.second) {
7777 // Already in the map. If it came from a different class, that's an
7778 // error. Not if it's from the same.
7779 CanQualType PreviousBase = result.first->second.first;
7780 if (CanonicalBase != PreviousBase) {
7781 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7782 const CXXConstructorDecl *PrevBaseCtor =
7783 PrevCtor->getInheritedConstructor();
7784 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7786 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7787 Diag(BaseCtor->getLocation(),
7788 diag::note_using_decl_constructor_conflict_current_ctor);
7789 Diag(PrevBaseCtor->getLocation(),
7790 diag::note_using_decl_constructor_conflict_previous_ctor);
7791 Diag(PrevCtor->getLocation(),
7792 diag::note_using_decl_constructor_conflict_previous_using);
7794 // Core issue (no number): if the same inheriting constructor is
7795 // produced by multiple base class constructors from the same base
7796 // class, the inheriting constructor is defined as deleted.
7797 SetDeclDeleted(result.first->second.second, UsingLoc);
7802 // OK, we're there, now add the constructor.
7803 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7804 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7805 Context, ClassDecl, UsingLoc, DNI, NewCtorType,
7806 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7807 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7808 NewCtor->setAccess(BaseCtor->getAccess());
7810 // Build an unevaluated exception specification for this constructor.
7811 EPI.ExceptionSpecType = EST_Unevaluated;
7812 EPI.ExceptionSpecDecl = NewCtor;
7813 NewCtor->setType(Context.getFunctionType(Context.VoidTy,
7814 ArgTypes.slice(0, Params),
7817 // Build up the parameter decls and add them.
7818 SmallVector<ParmVarDecl *, 16> ParamDecls;
7819 for (unsigned i = 0; i < Params; ++i) {
7820 ParmVarDecl *PD = ParmVarDecl::Create(Context, NewCtor,
7822 /*IdentifierInfo=*/0,
7823 BaseCtorType->getArgType(i),
7824 /*TInfo=*/0, SC_None,
7826 PD->setScopeInfo(0, i);
7828 ParamDecls.push_back(PD);
7830 NewCtor->setParams(ParamDecls);
7831 NewCtor->setInheritedConstructor(BaseCtor);
7832 if (BaseCtor->isDeleted())
7833 SetDeclDeleted(NewCtor, UsingLoc);
7835 ClassDecl->addDecl(NewCtor);
7836 result.first->second.second = NewCtor;
7842 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
7843 CXXConstructorDecl *Constructor) {
7844 CXXRecordDecl *ClassDecl = Constructor->getParent();
7845 assert(Constructor->getInheritedConstructor() &&
7846 !Constructor->doesThisDeclarationHaveABody() &&
7847 !Constructor->isDeleted());
7849 SynthesizedFunctionScope Scope(*this, Constructor);
7850 DiagnosticErrorTrap Trap(Diags);
7851 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7852 Trap.hasErrorOccurred()) {
7853 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
7854 << Context.getTagDeclType(ClassDecl);
7855 Constructor->setInvalidDecl();
7859 SourceLocation Loc = Constructor->getLocation();
7860 Constructor->setBody(new (Context) CompoundStmt(Loc));
7862 Constructor->setUsed();
7863 MarkVTableUsed(CurrentLocation, ClassDecl);
7865 if (ASTMutationListener *L = getASTMutationListener()) {
7866 L->CompletedImplicitDefinition(Constructor);
7871 Sema::ImplicitExceptionSpecification
7872 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7873 CXXRecordDecl *ClassDecl = MD->getParent();
7875 // C++ [except.spec]p14:
7876 // An implicitly declared special member function (Clause 12) shall have
7877 // an exception-specification.
7878 ImplicitExceptionSpecification ExceptSpec(*this);
7879 if (ClassDecl->isInvalidDecl())
7882 // Direct base-class destructors.
7883 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7884 BEnd = ClassDecl->bases_end();
7886 if (B->isVirtual()) // Handled below.
7889 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7890 ExceptSpec.CalledDecl(B->getLocStart(),
7891 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7894 // Virtual base-class destructors.
7895 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7896 BEnd = ClassDecl->vbases_end();
7898 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7899 ExceptSpec.CalledDecl(B->getLocStart(),
7900 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7903 // Field destructors.
7904 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7905 FEnd = ClassDecl->field_end();
7907 if (const RecordType *RecordTy
7908 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7909 ExceptSpec.CalledDecl(F->getLocation(),
7910 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7916 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7917 // C++ [class.dtor]p2:
7918 // If a class has no user-declared destructor, a destructor is
7919 // declared implicitly. An implicitly-declared destructor is an
7920 // inline public member of its class.
7921 assert(ClassDecl->needsImplicitDestructor());
7923 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7924 if (DSM.isAlreadyBeingDeclared())
7927 // Create the actual destructor declaration.
7928 CanQualType ClassType
7929 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7930 SourceLocation ClassLoc = ClassDecl->getLocation();
7931 DeclarationName Name
7932 = Context.DeclarationNames.getCXXDestructorName(ClassType);
7933 DeclarationNameInfo NameInfo(Name, ClassLoc);
7934 CXXDestructorDecl *Destructor
7935 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7936 QualType(), 0, /*isInline=*/true,
7937 /*isImplicitlyDeclared=*/true);
7938 Destructor->setAccess(AS_public);
7939 Destructor->setDefaulted();
7940 Destructor->setImplicit();
7942 // Build an exception specification pointing back at this destructor.
7943 FunctionProtoType::ExtProtoInfo EPI;
7944 EPI.ExceptionSpecType = EST_Unevaluated;
7945 EPI.ExceptionSpecDecl = Destructor;
7946 Destructor->setType(Context.getFunctionType(Context.VoidTy,
7947 ArrayRef<QualType>(),
7950 AddOverriddenMethods(ClassDecl, Destructor);
7952 // We don't need to use SpecialMemberIsTrivial here; triviality for
7953 // destructors is easy to compute.
7954 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7956 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7957 SetDeclDeleted(Destructor, ClassLoc);
7959 // Note that we have declared this destructor.
7960 ++ASTContext::NumImplicitDestructorsDeclared;
7962 // Introduce this destructor into its scope.
7963 if (Scope *S = getScopeForContext(ClassDecl))
7964 PushOnScopeChains(Destructor, S, false);
7965 ClassDecl->addDecl(Destructor);
7970 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7971 CXXDestructorDecl *Destructor) {
7972 assert((Destructor->isDefaulted() &&
7973 !Destructor->doesThisDeclarationHaveABody() &&
7974 !Destructor->isDeleted()) &&
7975 "DefineImplicitDestructor - call it for implicit default dtor");
7976 CXXRecordDecl *ClassDecl = Destructor->getParent();
7977 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7979 if (Destructor->isInvalidDecl())
7982 SynthesizedFunctionScope Scope(*this, Destructor);
7984 DiagnosticErrorTrap Trap(Diags);
7985 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7986 Destructor->getParent());
7988 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7989 Diag(CurrentLocation, diag::note_member_synthesized_at)
7990 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7992 Destructor->setInvalidDecl();
7996 SourceLocation Loc = Destructor->getLocation();
7997 Destructor->setBody(new (Context) CompoundStmt(Loc));
7998 Destructor->setImplicitlyDefined(true);
7999 Destructor->setUsed();
8000 MarkVTableUsed(CurrentLocation, ClassDecl);
8002 if (ASTMutationListener *L = getASTMutationListener()) {
8003 L->CompletedImplicitDefinition(Destructor);
8007 /// \brief Perform any semantic analysis which needs to be delayed until all
8008 /// pending class member declarations have been parsed.
8009 void Sema::ActOnFinishCXXMemberDecls() {
8010 // If the context is an invalid C++ class, just suppress these checks.
8011 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8012 if (Record->isInvalidDecl()) {
8013 DelayedDestructorExceptionSpecChecks.clear();
8018 // Perform any deferred checking of exception specifications for virtual
8020 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8022 const CXXDestructorDecl *Dtor =
8023 DelayedDestructorExceptionSpecChecks[i].first;
8024 assert(!Dtor->getParent()->isDependentType() &&
8025 "Should not ever add destructors of templates into the list.");
8026 CheckOverridingFunctionExceptionSpec(Dtor,
8027 DelayedDestructorExceptionSpecChecks[i].second);
8029 DelayedDestructorExceptionSpecChecks.clear();
8032 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8033 CXXDestructorDecl *Destructor) {
8034 assert(getLangOpts().CPlusPlus11 &&
8035 "adjusting dtor exception specs was introduced in c++11");
8037 // C++11 [class.dtor]p3:
8038 // A declaration of a destructor that does not have an exception-
8039 // specification is implicitly considered to have the same exception-
8040 // specification as an implicit declaration.
8041 const FunctionProtoType *DtorType = Destructor->getType()->
8042 getAs<FunctionProtoType>();
8043 if (DtorType->hasExceptionSpec())
8046 // Replace the destructor's type, building off the existing one. Fortunately,
8047 // the only thing of interest in the destructor type is its extended info.
8048 // The return and arguments are fixed.
8049 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8050 EPI.ExceptionSpecType = EST_Unevaluated;
8051 EPI.ExceptionSpecDecl = Destructor;
8052 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8053 ArrayRef<QualType>(),
8056 // FIXME: If the destructor has a body that could throw, and the newly created
8057 // spec doesn't allow exceptions, we should emit a warning, because this
8058 // change in behavior can break conforming C++03 programs at runtime.
8059 // However, we don't have a body or an exception specification yet, so it
8060 // needs to be done somewhere else.
8063 /// When generating a defaulted copy or move assignment operator, if a field
8064 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8065 /// do so. This optimization only applies for arrays of scalars, and for arrays
8066 /// of class type where the selected copy/move-assignment operator is trivial.
8068 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8069 Expr *To, Expr *From) {
8070 // Compute the size of the memory buffer to be copied.
8071 QualType SizeType = S.Context.getSizeType();
8072 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8073 S.Context.getTypeSizeInChars(T).getQuantity());
8075 // Take the address of the field references for "from" and "to". We
8076 // directly construct UnaryOperators here because semantic analysis
8077 // does not permit us to take the address of an xvalue.
8078 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8079 S.Context.getPointerType(From->getType()),
8080 VK_RValue, OK_Ordinary, Loc);
8081 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8082 S.Context.getPointerType(To->getType()),
8083 VK_RValue, OK_Ordinary, Loc);
8085 const Type *E = T->getBaseElementTypeUnsafe();
8086 bool NeedsCollectableMemCpy =
8087 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8089 // Create a reference to the __builtin_objc_memmove_collectable function
8090 StringRef MemCpyName = NeedsCollectableMemCpy ?
8091 "__builtin_objc_memmove_collectable" :
8093 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8094 Sema::LookupOrdinaryName);
8095 S.LookupName(R, S.TUScope, true);
8097 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8099 // Something went horribly wrong earlier, and we will have complained
8103 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8105 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8107 Expr *CallArgs[] = {
8108 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8110 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8111 Loc, CallArgs, Loc);
8113 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8114 return S.Owned(Call.takeAs<Stmt>());
8117 /// \brief Builds a statement that copies/moves the given entity from \p From to
8120 /// This routine is used to copy/move the members of a class with an
8121 /// implicitly-declared copy/move assignment operator. When the entities being
8122 /// copied are arrays, this routine builds for loops to copy them.
8124 /// \param S The Sema object used for type-checking.
8126 /// \param Loc The location where the implicit copy/move is being generated.
8128 /// \param T The type of the expressions being copied/moved. Both expressions
8129 /// must have this type.
8131 /// \param To The expression we are copying/moving to.
8133 /// \param From The expression we are copying/moving from.
8135 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8136 /// Otherwise, it's a non-static member subobject.
8138 /// \param Copying Whether we're copying or moving.
8140 /// \param Depth Internal parameter recording the depth of the recursion.
8142 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8143 /// if a memcpy should be used instead.
8145 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8146 Expr *To, Expr *From,
8147 bool CopyingBaseSubobject, bool Copying,
8148 unsigned Depth = 0) {
8149 // C++11 [class.copy]p28:
8150 // Each subobject is assigned in the manner appropriate to its type:
8152 // - if the subobject is of class type, as if by a call to operator= with
8153 // the subobject as the object expression and the corresponding
8154 // subobject of x as a single function argument (as if by explicit
8155 // qualification; that is, ignoring any possible virtual overriding
8156 // functions in more derived classes);
8158 // C++03 [class.copy]p13:
8159 // - if the subobject is of class type, the copy assignment operator for
8160 // the class is used (as if by explicit qualification; that is,
8161 // ignoring any possible virtual overriding functions in more derived
8163 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8164 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8166 // Look for operator=.
8167 DeclarationName Name
8168 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8169 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8170 S.LookupQualifiedName(OpLookup, ClassDecl, false);
8172 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8174 if (!S.getLangOpts().CPlusPlus11) {
8175 LookupResult::Filter F = OpLookup.makeFilter();
8176 while (F.hasNext()) {
8177 NamedDecl *D = F.next();
8178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8179 if (Method->isCopyAssignmentOperator() ||
8180 (!Copying && Method->isMoveAssignmentOperator()))
8188 // Suppress the protected check (C++ [class.protected]) for each of the
8189 // assignment operators we found. This strange dance is required when
8190 // we're assigning via a base classes's copy-assignment operator. To
8191 // ensure that we're getting the right base class subobject (without
8192 // ambiguities), we need to cast "this" to that subobject type; to
8193 // ensure that we don't go through the virtual call mechanism, we need
8194 // to qualify the operator= name with the base class (see below). However,
8195 // this means that if the base class has a protected copy assignment
8196 // operator, the protected member access check will fail. So, we
8197 // rewrite "protected" access to "public" access in this case, since we
8198 // know by construction that we're calling from a derived class.
8199 if (CopyingBaseSubobject) {
8200 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8202 if (L.getAccess() == AS_protected)
8203 L.setAccess(AS_public);
8207 // Create the nested-name-specifier that will be used to qualify the
8208 // reference to operator=; this is required to suppress the virtual
8211 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8212 SS.MakeTrivial(S.Context,
8213 NestedNameSpecifier::Create(S.Context, 0, false,
8217 // Create the reference to operator=.
8218 ExprResult OpEqualRef
8219 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8220 /*TemplateKWLoc=*/SourceLocation(),
8221 /*FirstQualifierInScope=*/0,
8224 /*SuppressQualifierCheck=*/true);
8225 if (OpEqualRef.isInvalid())
8228 // Build the call to the assignment operator.
8230 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8231 OpEqualRef.takeAs<Expr>(),
8232 Loc, &From, 1, Loc);
8233 if (Call.isInvalid())
8236 // If we built a call to a trivial 'operator=' while copying an array,
8237 // bail out. We'll replace the whole shebang with a memcpy.
8238 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8239 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8240 return StmtResult((Stmt*)0);
8242 // Convert to an expression-statement, and clean up any produced
8244 return S.ActOnExprStmt(Call);
8247 // - if the subobject is of scalar type, the built-in assignment
8248 // operator is used.
8249 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8251 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8252 if (Assignment.isInvalid())
8254 return S.ActOnExprStmt(Assignment);
8257 // - if the subobject is an array, each element is assigned, in the
8258 // manner appropriate to the element type;
8260 // Construct a loop over the array bounds, e.g.,
8262 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8264 // that will copy each of the array elements.
8265 QualType SizeType = S.Context.getSizeType();
8267 // Create the iteration variable.
8268 IdentifierInfo *IterationVarName = 0;
8271 llvm::raw_svector_ostream OS(Str);
8272 OS << "__i" << Depth;
8273 IterationVarName = &S.Context.Idents.get(OS.str());
8275 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8276 IterationVarName, SizeType,
8277 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8280 // Initialize the iteration variable to zero.
8281 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8282 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8284 // Create a reference to the iteration variable; we'll use this several
8285 // times throughout.
8286 Expr *IterationVarRef
8287 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8288 assert(IterationVarRef && "Reference to invented variable cannot fail!");
8289 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8290 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8292 // Create the DeclStmt that holds the iteration variable.
8293 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8295 // Subscript the "from" and "to" expressions with the iteration variable.
8296 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8297 IterationVarRefRVal,
8299 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8300 IterationVarRefRVal,
8302 if (!Copying) // Cast to rvalue
8303 From = CastForMoving(S, From);
8305 // Build the copy/move for an individual element of the array.
8307 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8308 To, From, CopyingBaseSubobject,
8309 Copying, Depth + 1);
8310 // Bail out if copying fails or if we determined that we should use memcpy.
8311 if (Copy.isInvalid() || !Copy.get())
8314 // Create the comparison against the array bound.
8316 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8318 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8319 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8320 BO_NE, S.Context.BoolTy,
8321 VK_RValue, OK_Ordinary, Loc, false);
8323 // Create the pre-increment of the iteration variable.
8325 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8326 VK_LValue, OK_Ordinary, Loc);
8328 // Construct the loop that copies all elements of this array.
8329 return S.ActOnForStmt(Loc, Loc, InitStmt,
8330 S.MakeFullExpr(Comparison),
8331 0, S.MakeFullDiscardedValueExpr(Increment),
8336 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8337 Expr *To, Expr *From,
8338 bool CopyingBaseSubobject, bool Copying) {
8339 // Maybe we should use a memcpy?
8340 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8341 T.isTriviallyCopyableType(S.Context))
8342 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8344 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8345 CopyingBaseSubobject,
8348 // If we ended up picking a trivial assignment operator for an array of a
8349 // non-trivially-copyable class type, just emit a memcpy.
8350 if (!Result.isInvalid() && !Result.get())
8351 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8356 Sema::ImplicitExceptionSpecification
8357 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8358 CXXRecordDecl *ClassDecl = MD->getParent();
8360 ImplicitExceptionSpecification ExceptSpec(*this);
8361 if (ClassDecl->isInvalidDecl())
8364 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8365 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8366 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8368 // C++ [except.spec]p14:
8369 // An implicitly declared special member function (Clause 12) shall have an
8370 // exception-specification. [...]
8372 // It is unspecified whether or not an implicit copy assignment operator
8373 // attempts to deduplicate calls to assignment operators of virtual bases are
8374 // made. As such, this exception specification is effectively unspecified.
8375 // Based on a similar decision made for constness in C++0x, we're erring on
8376 // the side of assuming such calls to be made regardless of whether they
8378 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8379 BaseEnd = ClassDecl->bases_end();
8380 Base != BaseEnd; ++Base) {
8381 if (Base->isVirtual())
8384 CXXRecordDecl *BaseClassDecl
8385 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8386 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8387 ArgQuals, false, 0))
8388 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8391 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8392 BaseEnd = ClassDecl->vbases_end();
8393 Base != BaseEnd; ++Base) {
8394 CXXRecordDecl *BaseClassDecl
8395 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8396 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8397 ArgQuals, false, 0))
8398 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8401 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8402 FieldEnd = ClassDecl->field_end();
8405 QualType FieldType = Context.getBaseElementType(Field->getType());
8406 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8407 if (CXXMethodDecl *CopyAssign =
8408 LookupCopyingAssignment(FieldClassDecl,
8409 ArgQuals | FieldType.getCVRQualifiers(),
8411 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8418 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8419 // Note: The following rules are largely analoguous to the copy
8420 // constructor rules. Note that virtual bases are not taken into account
8421 // for determining the argument type of the operator. Note also that
8422 // operators taking an object instead of a reference are allowed.
8423 assert(ClassDecl->needsImplicitCopyAssignment());
8425 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8426 if (DSM.isAlreadyBeingDeclared())
8429 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8430 QualType RetType = Context.getLValueReferenceType(ArgType);
8431 if (ClassDecl->implicitCopyAssignmentHasConstParam())
8432 ArgType = ArgType.withConst();
8433 ArgType = Context.getLValueReferenceType(ArgType);
8435 // An implicitly-declared copy assignment operator is an inline public
8436 // member of its class.
8437 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8438 SourceLocation ClassLoc = ClassDecl->getLocation();
8439 DeclarationNameInfo NameInfo(Name, ClassLoc);
8440 CXXMethodDecl *CopyAssignment
8441 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8443 /*StorageClass=*/SC_None,
8444 /*isInline=*/true, /*isConstexpr=*/false,
8446 CopyAssignment->setAccess(AS_public);
8447 CopyAssignment->setDefaulted();
8448 CopyAssignment->setImplicit();
8450 // Build an exception specification pointing back at this member.
8451 FunctionProtoType::ExtProtoInfo EPI;
8452 EPI.ExceptionSpecType = EST_Unevaluated;
8453 EPI.ExceptionSpecDecl = CopyAssignment;
8454 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8456 // Add the parameter to the operator.
8457 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8458 ClassLoc, ClassLoc, /*Id=*/0,
8459 ArgType, /*TInfo=*/0,
8461 CopyAssignment->setParams(FromParam);
8463 AddOverriddenMethods(ClassDecl, CopyAssignment);
8465 CopyAssignment->setTrivial(
8466 ClassDecl->needsOverloadResolutionForCopyAssignment()
8467 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8468 : ClassDecl->hasTrivialCopyAssignment());
8470 // C++0x [class.copy]p19:
8471 // .... If the class definition does not explicitly declare a copy
8472 // assignment operator, there is no user-declared move constructor, and
8473 // there is no user-declared move assignment operator, a copy assignment
8474 // operator is implicitly declared as defaulted.
8475 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8476 SetDeclDeleted(CopyAssignment, ClassLoc);
8478 // Note that we have added this copy-assignment operator.
8479 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8481 if (Scope *S = getScopeForContext(ClassDecl))
8482 PushOnScopeChains(CopyAssignment, S, false);
8483 ClassDecl->addDecl(CopyAssignment);
8485 return CopyAssignment;
8488 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8489 CXXMethodDecl *CopyAssignOperator) {
8490 assert((CopyAssignOperator->isDefaulted() &&
8491 CopyAssignOperator->isOverloadedOperator() &&
8492 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8493 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8494 !CopyAssignOperator->isDeleted()) &&
8495 "DefineImplicitCopyAssignment called for wrong function");
8497 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8499 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8500 CopyAssignOperator->setInvalidDecl();
8504 CopyAssignOperator->setUsed();
8506 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8507 DiagnosticErrorTrap Trap(Diags);
8509 // C++0x [class.copy]p30:
8510 // The implicitly-defined or explicitly-defaulted copy assignment operator
8511 // for a non-union class X performs memberwise copy assignment of its
8512 // subobjects. The direct base classes of X are assigned first, in the
8513 // order of their declaration in the base-specifier-list, and then the
8514 // immediate non-static data members of X are assigned, in the order in
8515 // which they were declared in the class definition.
8517 // The statements that form the synthesized function body.
8518 SmallVector<Stmt*, 8> Statements;
8520 // The parameter for the "other" object, which we are copying from.
8521 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8522 Qualifiers OtherQuals = Other->getType().getQualifiers();
8523 QualType OtherRefType = Other->getType();
8524 if (const LValueReferenceType *OtherRef
8525 = OtherRefType->getAs<LValueReferenceType>()) {
8526 OtherRefType = OtherRef->getPointeeType();
8527 OtherQuals = OtherRefType.getQualifiers();
8530 // Our location for everything implicitly-generated.
8531 SourceLocation Loc = CopyAssignOperator->getLocation();
8533 // Construct a reference to the "other" object. We'll be using this
8534 // throughout the generated ASTs.
8535 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8536 assert(OtherRef && "Reference to parameter cannot fail!");
8538 // Construct the "this" pointer. We'll be using this throughout the generated
8540 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8541 assert(This && "Reference to this cannot fail!");
8543 // Assign base classes.
8544 bool Invalid = false;
8545 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8546 E = ClassDecl->bases_end(); Base != E; ++Base) {
8547 // Form the assignment:
8548 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8549 QualType BaseType = Base->getType().getUnqualifiedType();
8550 if (!BaseType->isRecordType()) {
8555 CXXCastPath BasePath;
8556 BasePath.push_back(Base);
8558 // Construct the "from" expression, which is an implicit cast to the
8559 // appropriately-qualified base type.
8560 Expr *From = OtherRef;
8561 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8562 CK_UncheckedDerivedToBase,
8563 VK_LValue, &BasePath).take();
8565 // Dereference "this".
8566 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8568 // Implicitly cast "this" to the appropriately-qualified base type.
8569 To = ImpCastExprToType(To.take(),
8570 Context.getCVRQualifiedType(BaseType,
8571 CopyAssignOperator->getTypeQualifiers()),
8572 CK_UncheckedDerivedToBase,
8573 VK_LValue, &BasePath);
8576 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8578 /*CopyingBaseSubobject=*/true,
8580 if (Copy.isInvalid()) {
8581 Diag(CurrentLocation, diag::note_member_synthesized_at)
8582 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8583 CopyAssignOperator->setInvalidDecl();
8587 // Success! Record the copy.
8588 Statements.push_back(Copy.takeAs<Expr>());
8591 // Assign non-static members.
8592 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8593 FieldEnd = ClassDecl->field_end();
8594 Field != FieldEnd; ++Field) {
8595 if (Field->isUnnamedBitfield())
8598 // Check for members of reference type; we can't copy those.
8599 if (Field->getType()->isReferenceType()) {
8600 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8601 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8602 Diag(Field->getLocation(), diag::note_declared_at);
8603 Diag(CurrentLocation, diag::note_member_synthesized_at)
8604 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8609 // Check for members of const-qualified, non-class type.
8610 QualType BaseType = Context.getBaseElementType(Field->getType());
8611 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8612 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8613 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8614 Diag(Field->getLocation(), diag::note_declared_at);
8615 Diag(CurrentLocation, diag::note_member_synthesized_at)
8616 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8621 // Suppress assigning zero-width bitfields.
8622 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8625 QualType FieldType = Field->getType().getNonReferenceType();
8626 if (FieldType->isIncompleteArrayType()) {
8627 assert(ClassDecl->hasFlexibleArrayMember() &&
8628 "Incomplete array type is not valid");
8632 // Build references to the field in the object we're copying from and to.
8633 CXXScopeSpec SS; // Intentionally empty
8634 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8636 MemberLookup.addDecl(*Field);
8637 MemberLookup.resolveKind();
8638 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8639 Loc, /*IsArrow=*/false,
8640 SS, SourceLocation(), 0,
8642 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8643 Loc, /*IsArrow=*/true,
8644 SS, SourceLocation(), 0,
8646 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8647 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8649 // Build the copy of this field.
8650 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8651 To.get(), From.get(),
8652 /*CopyingBaseSubobject=*/false,
8654 if (Copy.isInvalid()) {
8655 Diag(CurrentLocation, diag::note_member_synthesized_at)
8656 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8657 CopyAssignOperator->setInvalidDecl();
8661 // Success! Record the copy.
8662 Statements.push_back(Copy.takeAs<Stmt>());
8666 // Add a "return *this;"
8667 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8669 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8670 if (Return.isInvalid())
8673 Statements.push_back(Return.takeAs<Stmt>());
8675 if (Trap.hasErrorOccurred()) {
8676 Diag(CurrentLocation, diag::note_member_synthesized_at)
8677 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8684 CopyAssignOperator->setInvalidDecl();
8690 CompoundScopeRAII CompoundScope(*this);
8691 Body = ActOnCompoundStmt(Loc, Loc, Statements,
8692 /*isStmtExpr=*/false);
8693 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8695 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8697 if (ASTMutationListener *L = getASTMutationListener()) {
8698 L->CompletedImplicitDefinition(CopyAssignOperator);
8702 Sema::ImplicitExceptionSpecification
8703 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8704 CXXRecordDecl *ClassDecl = MD->getParent();
8706 ImplicitExceptionSpecification ExceptSpec(*this);
8707 if (ClassDecl->isInvalidDecl())
8710 // C++0x [except.spec]p14:
8711 // An implicitly declared special member function (Clause 12) shall have an
8712 // exception-specification. [...]
8714 // It is unspecified whether or not an implicit move assignment operator
8715 // attempts to deduplicate calls to assignment operators of virtual bases are
8716 // made. As such, this exception specification is effectively unspecified.
8717 // Based on a similar decision made for constness in C++0x, we're erring on
8718 // the side of assuming such calls to be made regardless of whether they
8720 // Note that a move constructor is not implicitly declared when there are
8721 // virtual bases, but it can still be user-declared and explicitly defaulted.
8722 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8723 BaseEnd = ClassDecl->bases_end();
8724 Base != BaseEnd; ++Base) {
8725 if (Base->isVirtual())
8728 CXXRecordDecl *BaseClassDecl
8729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8730 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8732 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8736 BaseEnd = ClassDecl->vbases_end();
8737 Base != BaseEnd; ++Base) {
8738 CXXRecordDecl *BaseClassDecl
8739 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8740 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8742 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8745 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8746 FieldEnd = ClassDecl->field_end();
8749 QualType FieldType = Context.getBaseElementType(Field->getType());
8750 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8751 if (CXXMethodDecl *MoveAssign =
8752 LookupMovingAssignment(FieldClassDecl,
8753 FieldType.getCVRQualifiers(),
8755 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8762 /// Determine whether the class type has any direct or indirect virtual base
8763 /// classes which have a non-trivial move assignment operator.
8765 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8766 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8767 BaseEnd = ClassDecl->vbases_end();
8768 Base != BaseEnd; ++Base) {
8769 CXXRecordDecl *BaseClass =
8770 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8772 // Try to declare the move assignment. If it would be deleted, then the
8773 // class does not have a non-trivial move assignment.
8774 if (BaseClass->needsImplicitMoveAssignment())
8775 S.DeclareImplicitMoveAssignment(BaseClass);
8777 if (BaseClass->hasNonTrivialMoveAssignment())
8784 /// Determine whether the given type either has a move constructor or is
8785 /// trivially copyable.
8787 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8788 Type = S.Context.getBaseElementType(Type);
8790 // FIXME: Technically, non-trivially-copyable non-class types, such as
8791 // reference types, are supposed to return false here, but that appears
8792 // to be a standard defect.
8793 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8794 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
8797 if (Type.isTriviallyCopyableType(S.Context))
8800 if (IsConstructor) {
8801 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8802 // give the right answer.
8803 if (ClassDecl->needsImplicitMoveConstructor())
8804 S.DeclareImplicitMoveConstructor(ClassDecl);
8805 return ClassDecl->hasMoveConstructor();
8808 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8809 // give the right answer.
8810 if (ClassDecl->needsImplicitMoveAssignment())
8811 S.DeclareImplicitMoveAssignment(ClassDecl);
8812 return ClassDecl->hasMoveAssignment();
8815 /// Determine whether all non-static data members and direct or virtual bases
8816 /// of class \p ClassDecl have either a move operation, or are trivially
8818 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8819 bool IsConstructor) {
8820 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8821 BaseEnd = ClassDecl->bases_end();
8822 Base != BaseEnd; ++Base) {
8823 if (Base->isVirtual())
8826 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8830 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8831 BaseEnd = ClassDecl->vbases_end();
8832 Base != BaseEnd; ++Base) {
8833 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8837 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8838 FieldEnd = ClassDecl->field_end();
8839 Field != FieldEnd; ++Field) {
8840 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8847 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8848 // C++11 [class.copy]p20:
8849 // If the definition of a class X does not explicitly declare a move
8850 // assignment operator, one will be implicitly declared as defaulted
8853 // - [first 4 bullets]
8854 assert(ClassDecl->needsImplicitMoveAssignment());
8856 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8857 if (DSM.isAlreadyBeingDeclared())
8860 // [Checked after we build the declaration]
8861 // - the move assignment operator would not be implicitly defined as
8865 // - X has no direct or indirect virtual base class with a non-trivial
8866 // move assignment operator, and
8867 // - each of X's non-static data members and direct or virtual base classes
8868 // has a type that either has a move assignment operator or is trivially
8870 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8871 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8872 ClassDecl->setFailedImplicitMoveAssignment();
8876 // Note: The following rules are largely analoguous to the move
8877 // constructor rules.
8879 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8880 QualType RetType = Context.getLValueReferenceType(ArgType);
8881 ArgType = Context.getRValueReferenceType(ArgType);
8883 // An implicitly-declared move assignment operator is an inline public
8884 // member of its class.
8885 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8886 SourceLocation ClassLoc = ClassDecl->getLocation();
8887 DeclarationNameInfo NameInfo(Name, ClassLoc);
8888 CXXMethodDecl *MoveAssignment
8889 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8891 /*StorageClass=*/SC_None,
8893 /*isConstexpr=*/false,
8895 MoveAssignment->setAccess(AS_public);
8896 MoveAssignment->setDefaulted();
8897 MoveAssignment->setImplicit();
8899 // Build an exception specification pointing back at this member.
8900 FunctionProtoType::ExtProtoInfo EPI;
8901 EPI.ExceptionSpecType = EST_Unevaluated;
8902 EPI.ExceptionSpecDecl = MoveAssignment;
8903 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8905 // Add the parameter to the operator.
8906 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8907 ClassLoc, ClassLoc, /*Id=*/0,
8908 ArgType, /*TInfo=*/0,
8910 MoveAssignment->setParams(FromParam);
8912 AddOverriddenMethods(ClassDecl, MoveAssignment);
8914 MoveAssignment->setTrivial(
8915 ClassDecl->needsOverloadResolutionForMoveAssignment()
8916 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8917 : ClassDecl->hasTrivialMoveAssignment());
8919 // C++0x [class.copy]p9:
8920 // If the definition of a class X does not explicitly declare a move
8921 // assignment operator, one will be implicitly declared as defaulted if and
8924 // - the move assignment operator would not be implicitly defined as
8926 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8927 // Cache this result so that we don't try to generate this over and over
8928 // on every lookup, leaking memory and wasting time.
8929 ClassDecl->setFailedImplicitMoveAssignment();
8933 // Note that we have added this copy-assignment operator.
8934 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8936 if (Scope *S = getScopeForContext(ClassDecl))
8937 PushOnScopeChains(MoveAssignment, S, false);
8938 ClassDecl->addDecl(MoveAssignment);
8940 return MoveAssignment;
8943 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8944 CXXMethodDecl *MoveAssignOperator) {
8945 assert((MoveAssignOperator->isDefaulted() &&
8946 MoveAssignOperator->isOverloadedOperator() &&
8947 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8948 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8949 !MoveAssignOperator->isDeleted()) &&
8950 "DefineImplicitMoveAssignment called for wrong function");
8952 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8954 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8955 MoveAssignOperator->setInvalidDecl();
8959 MoveAssignOperator->setUsed();
8961 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
8962 DiagnosticErrorTrap Trap(Diags);
8964 // C++0x [class.copy]p28:
8965 // The implicitly-defined or move assignment operator for a non-union class
8966 // X performs memberwise move assignment of its subobjects. The direct base
8967 // classes of X are assigned first, in the order of their declaration in the
8968 // base-specifier-list, and then the immediate non-static data members of X
8969 // are assigned, in the order in which they were declared in the class
8972 // The statements that form the synthesized function body.
8973 SmallVector<Stmt*, 8> Statements;
8975 // The parameter for the "other" object, which we are move from.
8976 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8977 QualType OtherRefType = Other->getType()->
8978 getAs<RValueReferenceType>()->getPointeeType();
8979 assert(OtherRefType.getQualifiers() == 0 &&
8980 "Bad argument type of defaulted move assignment");
8982 // Our location for everything implicitly-generated.
8983 SourceLocation Loc = MoveAssignOperator->getLocation();
8985 // Construct a reference to the "other" object. We'll be using this
8986 // throughout the generated ASTs.
8987 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8988 assert(OtherRef && "Reference to parameter cannot fail!");
8990 OtherRef = CastForMoving(*this, OtherRef);
8992 // Construct the "this" pointer. We'll be using this throughout the generated
8994 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8995 assert(This && "Reference to this cannot fail!");
8997 // Assign base classes.
8998 bool Invalid = false;
8999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9000 E = ClassDecl->bases_end(); Base != E; ++Base) {
9001 // Form the assignment:
9002 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9003 QualType BaseType = Base->getType().getUnqualifiedType();
9004 if (!BaseType->isRecordType()) {
9009 CXXCastPath BasePath;
9010 BasePath.push_back(Base);
9012 // Construct the "from" expression, which is an implicit cast to the
9013 // appropriately-qualified base type.
9014 Expr *From = OtherRef;
9015 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9016 VK_XValue, &BasePath).take();
9018 // Dereference "this".
9019 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9021 // Implicitly cast "this" to the appropriately-qualified base type.
9022 To = ImpCastExprToType(To.take(),
9023 Context.getCVRQualifiedType(BaseType,
9024 MoveAssignOperator->getTypeQualifiers()),
9025 CK_UncheckedDerivedToBase,
9026 VK_LValue, &BasePath);
9029 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9031 /*CopyingBaseSubobject=*/true,
9033 if (Move.isInvalid()) {
9034 Diag(CurrentLocation, diag::note_member_synthesized_at)
9035 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9036 MoveAssignOperator->setInvalidDecl();
9040 // Success! Record the move.
9041 Statements.push_back(Move.takeAs<Expr>());
9044 // Assign non-static members.
9045 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9046 FieldEnd = ClassDecl->field_end();
9047 Field != FieldEnd; ++Field) {
9048 if (Field->isUnnamedBitfield())
9051 // Check for members of reference type; we can't move those.
9052 if (Field->getType()->isReferenceType()) {
9053 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9054 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9055 Diag(Field->getLocation(), diag::note_declared_at);
9056 Diag(CurrentLocation, diag::note_member_synthesized_at)
9057 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9062 // Check for members of const-qualified, non-class type.
9063 QualType BaseType = Context.getBaseElementType(Field->getType());
9064 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9065 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9066 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9067 Diag(Field->getLocation(), diag::note_declared_at);
9068 Diag(CurrentLocation, diag::note_member_synthesized_at)
9069 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9074 // Suppress assigning zero-width bitfields.
9075 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9078 QualType FieldType = Field->getType().getNonReferenceType();
9079 if (FieldType->isIncompleteArrayType()) {
9080 assert(ClassDecl->hasFlexibleArrayMember() &&
9081 "Incomplete array type is not valid");
9085 // Build references to the field in the object we're copying from and to.
9086 CXXScopeSpec SS; // Intentionally empty
9087 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9089 MemberLookup.addDecl(*Field);
9090 MemberLookup.resolveKind();
9091 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9092 Loc, /*IsArrow=*/false,
9093 SS, SourceLocation(), 0,
9095 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9096 Loc, /*IsArrow=*/true,
9097 SS, SourceLocation(), 0,
9099 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9100 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9102 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9103 "Member reference with rvalue base must be rvalue except for reference "
9104 "members, which aren't allowed for move assignment.");
9106 // Build the move of this field.
9107 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9108 To.get(), From.get(),
9109 /*CopyingBaseSubobject=*/false,
9111 if (Move.isInvalid()) {
9112 Diag(CurrentLocation, diag::note_member_synthesized_at)
9113 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9114 MoveAssignOperator->setInvalidDecl();
9118 // Success! Record the copy.
9119 Statements.push_back(Move.takeAs<Stmt>());
9123 // Add a "return *this;"
9124 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9126 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9127 if (Return.isInvalid())
9130 Statements.push_back(Return.takeAs<Stmt>());
9132 if (Trap.hasErrorOccurred()) {
9133 Diag(CurrentLocation, diag::note_member_synthesized_at)
9134 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9141 MoveAssignOperator->setInvalidDecl();
9147 CompoundScopeRAII CompoundScope(*this);
9148 Body = ActOnCompoundStmt(Loc, Loc, Statements,
9149 /*isStmtExpr=*/false);
9150 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9152 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9154 if (ASTMutationListener *L = getASTMutationListener()) {
9155 L->CompletedImplicitDefinition(MoveAssignOperator);
9159 Sema::ImplicitExceptionSpecification
9160 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9161 CXXRecordDecl *ClassDecl = MD->getParent();
9163 ImplicitExceptionSpecification ExceptSpec(*this);
9164 if (ClassDecl->isInvalidDecl())
9167 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9168 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9169 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9171 // C++ [except.spec]p14:
9172 // An implicitly declared special member function (Clause 12) shall have an
9173 // exception-specification. [...]
9174 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9175 BaseEnd = ClassDecl->bases_end();
9178 // Virtual bases are handled below.
9179 if (Base->isVirtual())
9182 CXXRecordDecl *BaseClassDecl
9183 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9184 if (CXXConstructorDecl *CopyConstructor =
9185 LookupCopyingConstructor(BaseClassDecl, Quals))
9186 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9188 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9189 BaseEnd = ClassDecl->vbases_end();
9192 CXXRecordDecl *BaseClassDecl
9193 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9194 if (CXXConstructorDecl *CopyConstructor =
9195 LookupCopyingConstructor(BaseClassDecl, Quals))
9196 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9198 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9199 FieldEnd = ClassDecl->field_end();
9202 QualType FieldType = Context.getBaseElementType(Field->getType());
9203 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9204 if (CXXConstructorDecl *CopyConstructor =
9205 LookupCopyingConstructor(FieldClassDecl,
9206 Quals | FieldType.getCVRQualifiers()))
9207 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9214 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9215 CXXRecordDecl *ClassDecl) {
9216 // C++ [class.copy]p4:
9217 // If the class definition does not explicitly declare a copy
9218 // constructor, one is declared implicitly.
9219 assert(ClassDecl->needsImplicitCopyConstructor());
9221 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9222 if (DSM.isAlreadyBeingDeclared())
9225 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9226 QualType ArgType = ClassType;
9227 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9229 ArgType = ArgType.withConst();
9230 ArgType = Context.getLValueReferenceType(ArgType);
9232 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9236 DeclarationName Name
9237 = Context.DeclarationNames.getCXXConstructorName(
9238 Context.getCanonicalType(ClassType));
9239 SourceLocation ClassLoc = ClassDecl->getLocation();
9240 DeclarationNameInfo NameInfo(Name, ClassLoc);
9242 // An implicitly-declared copy constructor is an inline public
9243 // member of its class.
9244 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9245 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9246 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9248 CopyConstructor->setAccess(AS_public);
9249 CopyConstructor->setDefaulted();
9251 // Build an exception specification pointing back at this member.
9252 FunctionProtoType::ExtProtoInfo EPI;
9253 EPI.ExceptionSpecType = EST_Unevaluated;
9254 EPI.ExceptionSpecDecl = CopyConstructor;
9255 CopyConstructor->setType(
9256 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9258 // Add the parameter to the constructor.
9259 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9261 /*IdentifierInfo=*/0,
9262 ArgType, /*TInfo=*/0,
9264 CopyConstructor->setParams(FromParam);
9266 CopyConstructor->setTrivial(
9267 ClassDecl->needsOverloadResolutionForCopyConstructor()
9268 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9269 : ClassDecl->hasTrivialCopyConstructor());
9271 // C++11 [class.copy]p8:
9272 // ... If the class definition does not explicitly declare a copy
9273 // constructor, there is no user-declared move constructor, and there is no
9274 // user-declared move assignment operator, a copy constructor is implicitly
9275 // declared as defaulted.
9276 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9277 SetDeclDeleted(CopyConstructor, ClassLoc);
9279 // Note that we have declared this constructor.
9280 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9282 if (Scope *S = getScopeForContext(ClassDecl))
9283 PushOnScopeChains(CopyConstructor, S, false);
9284 ClassDecl->addDecl(CopyConstructor);
9286 return CopyConstructor;
9289 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9290 CXXConstructorDecl *CopyConstructor) {
9291 assert((CopyConstructor->isDefaulted() &&
9292 CopyConstructor->isCopyConstructor() &&
9293 !CopyConstructor->doesThisDeclarationHaveABody() &&
9294 !CopyConstructor->isDeleted()) &&
9295 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9297 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9298 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9300 SynthesizedFunctionScope Scope(*this, CopyConstructor);
9301 DiagnosticErrorTrap Trap(Diags);
9303 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9304 Trap.hasErrorOccurred()) {
9305 Diag(CurrentLocation, diag::note_member_synthesized_at)
9306 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9307 CopyConstructor->setInvalidDecl();
9309 Sema::CompoundScopeRAII CompoundScope(*this);
9310 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9311 CopyConstructor->getLocation(),
9313 /*isStmtExpr=*/false)
9315 CopyConstructor->setImplicitlyDefined(true);
9318 CopyConstructor->setUsed();
9319 if (ASTMutationListener *L = getASTMutationListener()) {
9320 L->CompletedImplicitDefinition(CopyConstructor);
9324 Sema::ImplicitExceptionSpecification
9325 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9326 CXXRecordDecl *ClassDecl = MD->getParent();
9328 // C++ [except.spec]p14:
9329 // An implicitly declared special member function (Clause 12) shall have an
9330 // exception-specification. [...]
9331 ImplicitExceptionSpecification ExceptSpec(*this);
9332 if (ClassDecl->isInvalidDecl())
9335 // Direct base-class constructors.
9336 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9337 BEnd = ClassDecl->bases_end();
9339 if (B->isVirtual()) // Handled below.
9342 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9343 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9344 CXXConstructorDecl *Constructor =
9345 LookupMovingConstructor(BaseClassDecl, 0);
9346 // If this is a deleted function, add it anyway. This might be conformant
9347 // with the standard. This might not. I'm not sure. It might not matter.
9349 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9353 // Virtual base-class constructors.
9354 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9355 BEnd = ClassDecl->vbases_end();
9357 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9358 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9359 CXXConstructorDecl *Constructor =
9360 LookupMovingConstructor(BaseClassDecl, 0);
9361 // If this is a deleted function, add it anyway. This might be conformant
9362 // with the standard. This might not. I'm not sure. It might not matter.
9364 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9368 // Field constructors.
9369 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9370 FEnd = ClassDecl->field_end();
9372 QualType FieldType = Context.getBaseElementType(F->getType());
9373 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9374 CXXConstructorDecl *Constructor =
9375 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9376 // If this is a deleted function, add it anyway. This might be conformant
9377 // with the standard. This might not. I'm not sure. It might not matter.
9378 // In particular, the problem is that this function never gets called. It
9379 // might just be ill-formed because this function attempts to refer to
9380 // a deleted function here.
9382 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9389 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9390 CXXRecordDecl *ClassDecl) {
9391 // C++11 [class.copy]p9:
9392 // If the definition of a class X does not explicitly declare a move
9393 // constructor, one will be implicitly declared as defaulted if and only if:
9395 // - [first 4 bullets]
9396 assert(ClassDecl->needsImplicitMoveConstructor());
9398 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9399 if (DSM.isAlreadyBeingDeclared())
9402 // [Checked after we build the declaration]
9403 // - the move assignment operator would not be implicitly defined as
9407 // - each of X's non-static data members and direct or virtual base classes
9408 // has a type that either has a move constructor or is trivially copyable.
9409 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9410 ClassDecl->setFailedImplicitMoveConstructor();
9414 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9415 QualType ArgType = Context.getRValueReferenceType(ClassType);
9417 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9421 DeclarationName Name
9422 = Context.DeclarationNames.getCXXConstructorName(
9423 Context.getCanonicalType(ClassType));
9424 SourceLocation ClassLoc = ClassDecl->getLocation();
9425 DeclarationNameInfo NameInfo(Name, ClassLoc);
9427 // C++0x [class.copy]p11:
9428 // An implicitly-declared copy/move constructor is an inline public
9429 // member of its class.
9430 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9431 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9432 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9434 MoveConstructor->setAccess(AS_public);
9435 MoveConstructor->setDefaulted();
9437 // Build an exception specification pointing back at this member.
9438 FunctionProtoType::ExtProtoInfo EPI;
9439 EPI.ExceptionSpecType = EST_Unevaluated;
9440 EPI.ExceptionSpecDecl = MoveConstructor;
9441 MoveConstructor->setType(
9442 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9444 // Add the parameter to the constructor.
9445 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9447 /*IdentifierInfo=*/0,
9448 ArgType, /*TInfo=*/0,
9450 MoveConstructor->setParams(FromParam);
9452 MoveConstructor->setTrivial(
9453 ClassDecl->needsOverloadResolutionForMoveConstructor()
9454 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9455 : ClassDecl->hasTrivialMoveConstructor());
9457 // C++0x [class.copy]p9:
9458 // If the definition of a class X does not explicitly declare a move
9459 // constructor, one will be implicitly declared as defaulted if and only if:
9461 // - the move constructor would not be implicitly defined as deleted.
9462 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9463 // Cache this result so that we don't try to generate this over and over
9464 // on every lookup, leaking memory and wasting time.
9465 ClassDecl->setFailedImplicitMoveConstructor();
9469 // Note that we have declared this constructor.
9470 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9472 if (Scope *S = getScopeForContext(ClassDecl))
9473 PushOnScopeChains(MoveConstructor, S, false);
9474 ClassDecl->addDecl(MoveConstructor);
9476 return MoveConstructor;
9479 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9480 CXXConstructorDecl *MoveConstructor) {
9481 assert((MoveConstructor->isDefaulted() &&
9482 MoveConstructor->isMoveConstructor() &&
9483 !MoveConstructor->doesThisDeclarationHaveABody() &&
9484 !MoveConstructor->isDeleted()) &&
9485 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9487 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9488 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9490 SynthesizedFunctionScope Scope(*this, MoveConstructor);
9491 DiagnosticErrorTrap Trap(Diags);
9493 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9494 Trap.hasErrorOccurred()) {
9495 Diag(CurrentLocation, diag::note_member_synthesized_at)
9496 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9497 MoveConstructor->setInvalidDecl();
9499 Sema::CompoundScopeRAII CompoundScope(*this);
9500 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9501 MoveConstructor->getLocation(),
9503 /*isStmtExpr=*/false)
9505 MoveConstructor->setImplicitlyDefined(true);
9508 MoveConstructor->setUsed();
9510 if (ASTMutationListener *L = getASTMutationListener()) {
9511 L->CompletedImplicitDefinition(MoveConstructor);
9515 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9516 return FD->isDeleted() &&
9517 (FD->isDefaulted() || FD->isImplicit()) &&
9518 isa<CXXMethodDecl>(FD);
9521 /// \brief Mark the call operator of the given lambda closure type as "used".
9522 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9523 CXXMethodDecl *CallOperator
9524 = cast<CXXMethodDecl>(
9526 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9527 CallOperator->setReferenced();
9528 CallOperator->setUsed();
9531 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9532 SourceLocation CurrentLocation,
9533 CXXConversionDecl *Conv)
9535 CXXRecordDecl *Lambda = Conv->getParent();
9537 // Make sure that the lambda call operator is marked used.
9538 markLambdaCallOperatorUsed(*this, Lambda);
9542 SynthesizedFunctionScope Scope(*this, Conv);
9543 DiagnosticErrorTrap Trap(Diags);
9545 // Return the address of the __invoke function.
9546 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9547 CXXMethodDecl *Invoke
9548 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9549 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9550 VK_LValue, Conv->getLocation()).take();
9551 assert(FunctionRef && "Can't refer to __invoke function?");
9552 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9553 Conv->setBody(new (Context) CompoundStmt(Context, Return,
9554 Conv->getLocation(),
9555 Conv->getLocation()));
9557 // Fill in the __invoke function with a dummy implementation. IR generation
9558 // will fill in the actual details.
9560 Invoke->setReferenced();
9561 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9563 if (ASTMutationListener *L = getASTMutationListener()) {
9564 L->CompletedImplicitDefinition(Conv);
9565 L->CompletedImplicitDefinition(Invoke);
9569 void Sema::DefineImplicitLambdaToBlockPointerConversion(
9570 SourceLocation CurrentLocation,
9571 CXXConversionDecl *Conv)
9575 SynthesizedFunctionScope Scope(*this, Conv);
9576 DiagnosticErrorTrap Trap(Diags);
9578 // Copy-initialize the lambda object as needed to capture it.
9579 Expr *This = ActOnCXXThis(CurrentLocation).take();
9580 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9582 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9583 Conv->getLocation(),
9586 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9587 // behavior. Note that only the general conversion function does this
9588 // (since it's unusable otherwise); in the case where we inline the
9589 // block literal, it has block literal lifetime semantics.
9590 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9591 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9592 CK_CopyAndAutoreleaseBlockObject,
9593 BuildBlock.get(), 0, VK_RValue);
9595 if (BuildBlock.isInvalid()) {
9596 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9597 Conv->setInvalidDecl();
9601 // Create the return statement that returns the block from the conversion
9603 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9604 if (Return.isInvalid()) {
9605 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9606 Conv->setInvalidDecl();
9610 // Set the body of the conversion function.
9611 Stmt *ReturnS = Return.take();
9612 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9613 Conv->getLocation(),
9614 Conv->getLocation()));
9616 // We're done; notify the mutation listener, if any.
9617 if (ASTMutationListener *L = getASTMutationListener()) {
9618 L->CompletedImplicitDefinition(Conv);
9622 /// \brief Determine whether the given list arguments contains exactly one
9623 /// "real" (non-default) argument.
9624 static bool hasOneRealArgument(MultiExprArg Args) {
9625 switch (Args.size()) {
9630 if (!Args[1]->isDefaultArgument())
9635 return !Args[0]->isDefaultArgument();
9642 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9643 CXXConstructorDecl *Constructor,
9644 MultiExprArg ExprArgs,
9645 bool HadMultipleCandidates,
9646 bool IsListInitialization,
9647 bool RequiresZeroInit,
9648 unsigned ConstructKind,
9649 SourceRange ParenRange) {
9650 bool Elidable = false;
9652 // C++0x [class.copy]p34:
9653 // When certain criteria are met, an implementation is allowed to
9654 // omit the copy/move construction of a class object, even if the
9655 // copy/move constructor and/or destructor for the object have
9656 // side effects. [...]
9657 // - when a temporary class object that has not been bound to a
9658 // reference (12.2) would be copied/moved to a class object
9659 // with the same cv-unqualified type, the copy/move operation
9660 // can be omitted by constructing the temporary object
9661 // directly into the target of the omitted copy/move
9662 if (ConstructKind == CXXConstructExpr::CK_Complete &&
9663 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9664 Expr *SubExpr = ExprArgs[0];
9665 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9668 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9669 Elidable, ExprArgs, HadMultipleCandidates,
9670 IsListInitialization, RequiresZeroInit,
9671 ConstructKind, ParenRange);
9674 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
9675 /// including handling of its default argument expressions.
9677 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9678 CXXConstructorDecl *Constructor, bool Elidable,
9679 MultiExprArg ExprArgs,
9680 bool HadMultipleCandidates,
9681 bool IsListInitialization,
9682 bool RequiresZeroInit,
9683 unsigned ConstructKind,
9684 SourceRange ParenRange) {
9685 MarkFunctionReferenced(ConstructLoc, Constructor);
9686 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9687 Constructor, Elidable, ExprArgs,
9688 HadMultipleCandidates,
9689 IsListInitialization, RequiresZeroInit,
9690 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9694 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9695 if (VD->isInvalidDecl()) return;
9697 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9698 if (ClassDecl->isInvalidDecl()) return;
9699 if (ClassDecl->hasIrrelevantDestructor()) return;
9700 if (ClassDecl->isDependentContext()) return;
9702 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9703 MarkFunctionReferenced(VD->getLocation(), Destructor);
9704 CheckDestructorAccess(VD->getLocation(), Destructor,
9705 PDiag(diag::err_access_dtor_var)
9706 << VD->getDeclName()
9708 DiagnoseUseOfDecl(Destructor, VD->getLocation());
9710 if (!VD->hasGlobalStorage()) return;
9712 // Emit warning for non-trivial dtor in global scope (a real global,
9713 // class-static, function-static).
9714 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9716 // TODO: this should be re-enabled for static locals by !CXAAtExit
9717 if (!VD->isStaticLocal())
9718 Diag(VD->getLocation(), diag::warn_global_destructor);
9721 /// \brief Given a constructor and the set of arguments provided for the
9722 /// constructor, convert the arguments and add any required default arguments
9723 /// to form a proper call to this constructor.
9725 /// \returns true if an error occurred, false otherwise.
9727 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9728 MultiExprArg ArgsPtr,
9730 SmallVectorImpl<Expr*> &ConvertedArgs,
9732 bool IsListInitialization) {
9733 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9734 unsigned NumArgs = ArgsPtr.size();
9735 Expr **Args = ArgsPtr.data();
9737 const FunctionProtoType *Proto
9738 = Constructor->getType()->getAs<FunctionProtoType>();
9739 assert(Proto && "Constructor without a prototype?");
9740 unsigned NumArgsInProto = Proto->getNumArgs();
9742 // If too few arguments are available, we'll fill in the rest with defaults.
9743 if (NumArgs < NumArgsInProto)
9744 ConvertedArgs.reserve(NumArgsInProto);
9746 ConvertedArgs.reserve(NumArgs);
9748 VariadicCallType CallType =
9749 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9750 SmallVector<Expr *, 8> AllArgs;
9751 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9752 Proto, 0, Args, NumArgs, AllArgs,
9753 CallType, AllowExplicit,
9754 IsListInitialization);
9755 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9757 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9759 CheckConstructorCall(Constructor,
9760 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9768 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9769 const FunctionDecl *FnDecl) {
9770 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9771 if (isa<NamespaceDecl>(DC)) {
9772 return SemaRef.Diag(FnDecl->getLocation(),
9773 diag::err_operator_new_delete_declared_in_namespace)
9774 << FnDecl->getDeclName();
9777 if (isa<TranslationUnitDecl>(DC) &&
9778 FnDecl->getStorageClass() == SC_Static) {
9779 return SemaRef.Diag(FnDecl->getLocation(),
9780 diag::err_operator_new_delete_declared_static)
9781 << FnDecl->getDeclName();
9788 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9789 CanQualType ExpectedResultType,
9790 CanQualType ExpectedFirstParamType,
9791 unsigned DependentParamTypeDiag,
9792 unsigned InvalidParamTypeDiag) {
9793 QualType ResultType =
9794 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9796 // Check that the result type is not dependent.
9797 if (ResultType->isDependentType())
9798 return SemaRef.Diag(FnDecl->getLocation(),
9799 diag::err_operator_new_delete_dependent_result_type)
9800 << FnDecl->getDeclName() << ExpectedResultType;
9802 // Check that the result type is what we expect.
9803 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9804 return SemaRef.Diag(FnDecl->getLocation(),
9805 diag::err_operator_new_delete_invalid_result_type)
9806 << FnDecl->getDeclName() << ExpectedResultType;
9808 // A function template must have at least 2 parameters.
9809 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9810 return SemaRef.Diag(FnDecl->getLocation(),
9811 diag::err_operator_new_delete_template_too_few_parameters)
9812 << FnDecl->getDeclName();
9814 // The function decl must have at least 1 parameter.
9815 if (FnDecl->getNumParams() == 0)
9816 return SemaRef.Diag(FnDecl->getLocation(),
9817 diag::err_operator_new_delete_too_few_parameters)
9818 << FnDecl->getDeclName();
9820 // Check the first parameter type is not dependent.
9821 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9822 if (FirstParamType->isDependentType())
9823 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9824 << FnDecl->getDeclName() << ExpectedFirstParamType;
9826 // Check that the first parameter type is what we expect.
9827 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9828 ExpectedFirstParamType)
9829 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9830 << FnDecl->getDeclName() << ExpectedFirstParamType;
9836 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9837 // C++ [basic.stc.dynamic.allocation]p1:
9838 // A program is ill-formed if an allocation function is declared in a
9839 // namespace scope other than global scope or declared static in global
9841 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9844 CanQualType SizeTy =
9845 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9847 // C++ [basic.stc.dynamic.allocation]p1:
9848 // The return type shall be void*. The first parameter shall have type
9850 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9852 diag::err_operator_new_dependent_param_type,
9853 diag::err_operator_new_param_type))
9856 // C++ [basic.stc.dynamic.allocation]p1:
9857 // The first parameter shall not have an associated default argument.
9858 if (FnDecl->getParamDecl(0)->hasDefaultArg())
9859 return SemaRef.Diag(FnDecl->getLocation(),
9860 diag::err_operator_new_default_arg)
9861 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9867 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
9868 // C++ [basic.stc.dynamic.deallocation]p1:
9869 // A program is ill-formed if deallocation functions are declared in a
9870 // namespace scope other than global scope or declared static in global
9872 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9875 // C++ [basic.stc.dynamic.deallocation]p2:
9876 // Each deallocation function shall return void and its first parameter
9878 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9879 SemaRef.Context.VoidPtrTy,
9880 diag::err_operator_delete_dependent_param_type,
9881 diag::err_operator_delete_param_type))
9887 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
9888 /// of this overloaded operator is well-formed. If so, returns false;
9889 /// otherwise, emits appropriate diagnostics and returns true.
9890 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9891 assert(FnDecl && FnDecl->isOverloadedOperator() &&
9892 "Expected an overloaded operator declaration");
9894 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9896 // C++ [over.oper]p5:
9897 // The allocation and deallocation functions, operator new,
9898 // operator new[], operator delete and operator delete[], are
9899 // described completely in 3.7.3. The attributes and restrictions
9900 // found in the rest of this subclause do not apply to them unless
9901 // explicitly stated in 3.7.3.
9902 if (Op == OO_Delete || Op == OO_Array_Delete)
9903 return CheckOperatorDeleteDeclaration(*this, FnDecl);
9905 if (Op == OO_New || Op == OO_Array_New)
9906 return CheckOperatorNewDeclaration(*this, FnDecl);
9908 // C++ [over.oper]p6:
9909 // An operator function shall either be a non-static member
9910 // function or be a non-member function and have at least one
9911 // parameter whose type is a class, a reference to a class, an
9912 // enumeration, or a reference to an enumeration.
9913 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9914 if (MethodDecl->isStatic())
9915 return Diag(FnDecl->getLocation(),
9916 diag::err_operator_overload_static) << FnDecl->getDeclName();
9918 bool ClassOrEnumParam = false;
9919 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9920 ParamEnd = FnDecl->param_end();
9921 Param != ParamEnd; ++Param) {
9922 QualType ParamType = (*Param)->getType().getNonReferenceType();
9923 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9924 ParamType->isEnumeralType()) {
9925 ClassOrEnumParam = true;
9930 if (!ClassOrEnumParam)
9931 return Diag(FnDecl->getLocation(),
9932 diag::err_operator_overload_needs_class_or_enum)
9933 << FnDecl->getDeclName();
9936 // C++ [over.oper]p8:
9937 // An operator function cannot have default arguments (8.3.6),
9938 // except where explicitly stated below.
9940 // Only the function-call operator allows default arguments
9941 // (C++ [over.call]p1).
9942 if (Op != OO_Call) {
9943 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9944 Param != FnDecl->param_end(); ++Param) {
9945 if ((*Param)->hasDefaultArg())
9946 return Diag((*Param)->getLocation(),
9947 diag::err_operator_overload_default_arg)
9948 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9952 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9953 { false, false, false }
9954 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9955 , { Unary, Binary, MemberOnly }
9956 #include "clang/Basic/OperatorKinds.def"
9959 bool CanBeUnaryOperator = OperatorUses[Op][0];
9960 bool CanBeBinaryOperator = OperatorUses[Op][1];
9961 bool MustBeMemberOperator = OperatorUses[Op][2];
9963 // C++ [over.oper]p8:
9964 // [...] Operator functions cannot have more or fewer parameters
9965 // than the number required for the corresponding operator, as
9966 // described in the rest of this subclause.
9967 unsigned NumParams = FnDecl->getNumParams()
9968 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9969 if (Op != OO_Call &&
9970 ((NumParams == 1 && !CanBeUnaryOperator) ||
9971 (NumParams == 2 && !CanBeBinaryOperator) ||
9972 (NumParams < 1) || (NumParams > 2))) {
9973 // We have the wrong number of parameters.
9975 if (CanBeUnaryOperator && CanBeBinaryOperator) {
9976 ErrorKind = 2; // 2 -> unary or binary.
9977 } else if (CanBeUnaryOperator) {
9978 ErrorKind = 0; // 0 -> unary
9980 assert(CanBeBinaryOperator &&
9981 "All non-call overloaded operators are unary or binary!");
9982 ErrorKind = 1; // 1 -> binary
9985 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9986 << FnDecl->getDeclName() << NumParams << ErrorKind;
9989 // Overloaded operators other than operator() cannot be variadic.
9990 if (Op != OO_Call &&
9991 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9992 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9993 << FnDecl->getDeclName();
9996 // Some operators must be non-static member functions.
9997 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9998 return Diag(FnDecl->getLocation(),
9999 diag::err_operator_overload_must_be_member)
10000 << FnDecl->getDeclName();
10003 // C++ [over.inc]p1:
10004 // The user-defined function called operator++ implements the
10005 // prefix and postfix ++ operator. If this function is a member
10006 // function with no parameters, or a non-member function with one
10007 // parameter of class or enumeration type, it defines the prefix
10008 // increment operator ++ for objects of that type. If the function
10009 // is a member function with one parameter (which shall be of type
10010 // int) or a non-member function with two parameters (the second
10011 // of which shall be of type int), it defines the postfix
10012 // increment operator ++ for objects of that type.
10013 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10014 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10015 bool ParamIsInt = false;
10016 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10017 ParamIsInt = BT->getKind() == BuiltinType::Int;
10020 return Diag(LastParam->getLocation(),
10021 diag::err_operator_overload_post_incdec_must_be_int)
10022 << LastParam->getType() << (Op == OO_MinusMinus);
10028 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10029 /// of this literal operator function is well-formed. If so, returns
10030 /// false; otherwise, emits appropriate diagnostics and returns true.
10031 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10032 if (isa<CXXMethodDecl>(FnDecl)) {
10033 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10034 << FnDecl->getDeclName();
10038 if (FnDecl->isExternC()) {
10039 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10043 bool Valid = false;
10045 // This might be the definition of a literal operator template.
10046 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10047 // This might be a specialization of a literal operator template.
10049 TpDecl = FnDecl->getPrimaryTemplate();
10051 // template <char...> type operator "" name() is the only valid template
10052 // signature, and the only valid signature with no parameters.
10054 if (FnDecl->param_size() == 0) {
10055 // Must have only one template parameter
10056 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10057 if (Params->size() == 1) {
10058 NonTypeTemplateParmDecl *PmDecl =
10059 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10061 // The template parameter must be a char parameter pack.
10062 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10063 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10067 } else if (FnDecl->param_size()) {
10068 // Check the first parameter
10069 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10071 QualType T = (*Param)->getType().getUnqualifiedType();
10073 // unsigned long long int, long double, and any character type are allowed
10074 // as the only parameters.
10075 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10076 Context.hasSameType(T, Context.LongDoubleTy) ||
10077 Context.hasSameType(T, Context.CharTy) ||
10078 Context.hasSameType(T, Context.WCharTy) ||
10079 Context.hasSameType(T, Context.Char16Ty) ||
10080 Context.hasSameType(T, Context.Char32Ty)) {
10081 if (++Param == FnDecl->param_end())
10083 goto FinishedParams;
10086 // Otherwise it must be a pointer to const; let's strip those qualifiers.
10087 const PointerType *PT = T->getAs<PointerType>();
10089 goto FinishedParams;
10090 T = PT->getPointeeType();
10091 if (!T.isConstQualified() || T.isVolatileQualified())
10092 goto FinishedParams;
10093 T = T.getUnqualifiedType();
10095 // Move on to the second parameter;
10098 // If there is no second parameter, the first must be a const char *
10099 if (Param == FnDecl->param_end()) {
10100 if (Context.hasSameType(T, Context.CharTy))
10102 goto FinishedParams;
10105 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10106 // are allowed as the first parameter to a two-parameter function
10107 if (!(Context.hasSameType(T, Context.CharTy) ||
10108 Context.hasSameType(T, Context.WCharTy) ||
10109 Context.hasSameType(T, Context.Char16Ty) ||
10110 Context.hasSameType(T, Context.Char32Ty)))
10111 goto FinishedParams;
10113 // The second and final parameter must be an std::size_t
10114 T = (*Param)->getType().getUnqualifiedType();
10115 if (Context.hasSameType(T, Context.getSizeType()) &&
10116 ++Param == FnDecl->param_end())
10120 // FIXME: This diagnostic is absolutely terrible.
10123 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10124 << FnDecl->getDeclName();
10128 // A parameter-declaration-clause containing a default argument is not
10129 // equivalent to any of the permitted forms.
10130 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10131 ParamEnd = FnDecl->param_end();
10132 Param != ParamEnd; ++Param) {
10133 if ((*Param)->hasDefaultArg()) {
10134 Diag((*Param)->getDefaultArgRange().getBegin(),
10135 diag::err_literal_operator_default_argument)
10136 << (*Param)->getDefaultArgRange();
10141 StringRef LiteralName
10142 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10143 if (LiteralName[0] != '_') {
10144 // C++11 [usrlit.suffix]p1:
10145 // Literal suffix identifiers that do not start with an underscore
10146 // are reserved for future standardization.
10147 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10153 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10154 /// linkage specification, including the language and (if present)
10155 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10156 /// the location of the language string literal, which is provided
10157 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10158 /// the '{' brace. Otherwise, this linkage specification does not
10159 /// have any braces.
10160 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10161 SourceLocation LangLoc,
10163 SourceLocation LBraceLoc) {
10164 LinkageSpecDecl::LanguageIDs Language;
10165 if (Lang == "\"C\"")
10166 Language = LinkageSpecDecl::lang_c;
10167 else if (Lang == "\"C++\"")
10168 Language = LinkageSpecDecl::lang_cxx;
10170 Diag(LangLoc, diag::err_bad_language);
10174 // FIXME: Add all the various semantics of linkage specifications
10176 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10177 ExternLoc, LangLoc, Language);
10178 CurContext->addDecl(D);
10179 PushDeclContext(S, D);
10183 /// ActOnFinishLinkageSpecification - Complete the definition of
10184 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
10185 /// valid, it's the position of the closing '}' brace in a linkage
10186 /// specification that uses braces.
10187 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10189 SourceLocation RBraceLoc) {
10191 if (RBraceLoc.isValid()) {
10192 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10193 LSDecl->setRBraceLoc(RBraceLoc);
10197 return LinkageSpec;
10200 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10201 AttributeList *AttrList,
10202 SourceLocation SemiLoc) {
10203 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10204 // Attribute declarations appertain to empty declaration so we handle
10207 ProcessDeclAttributeList(S, ED, AttrList);
10209 CurContext->addDecl(ED);
10213 /// \brief Perform semantic analysis for the variable declaration that
10214 /// occurs within a C++ catch clause, returning the newly-created
10216 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10217 TypeSourceInfo *TInfo,
10218 SourceLocation StartLoc,
10219 SourceLocation Loc,
10220 IdentifierInfo *Name) {
10221 bool Invalid = false;
10222 QualType ExDeclType = TInfo->getType();
10224 // Arrays and functions decay.
10225 if (ExDeclType->isArrayType())
10226 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10227 else if (ExDeclType->isFunctionType())
10228 ExDeclType = Context.getPointerType(ExDeclType);
10230 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10231 // The exception-declaration shall not denote a pointer or reference to an
10232 // incomplete type, other than [cv] void*.
10233 // N2844 forbids rvalue references.
10234 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10235 Diag(Loc, diag::err_catch_rvalue_ref);
10239 QualType BaseType = ExDeclType;
10240 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10241 unsigned DK = diag::err_catch_incomplete;
10242 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10243 BaseType = Ptr->getPointeeType();
10245 DK = diag::err_catch_incomplete_ptr;
10246 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10247 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10248 BaseType = Ref->getPointeeType();
10250 DK = diag::err_catch_incomplete_ref;
10252 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10253 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10256 if (!Invalid && !ExDeclType->isDependentType() &&
10257 RequireNonAbstractType(Loc, ExDeclType,
10258 diag::err_abstract_type_in_decl,
10259 AbstractVariableType))
10262 // Only the non-fragile NeXT runtime currently supports C++ catches
10263 // of ObjC types, and no runtime supports catching ObjC types by value.
10264 if (!Invalid && getLangOpts().ObjC1) {
10265 QualType T = ExDeclType;
10266 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10267 T = RT->getPointeeType();
10269 if (T->isObjCObjectType()) {
10270 Diag(Loc, diag::err_objc_object_catch);
10272 } else if (T->isObjCObjectPointerType()) {
10273 // FIXME: should this be a test for macosx-fragile specifically?
10274 if (getLangOpts().ObjCRuntime.isFragile())
10275 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10279 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10280 ExDeclType, TInfo, SC_None);
10281 ExDecl->setExceptionVariable(true);
10283 // In ARC, infer 'retaining' for variables of retainable type.
10284 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10287 if (!Invalid && !ExDeclType->isDependentType()) {
10288 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10289 // Insulate this from anything else we might currently be parsing.
10290 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10292 // C++ [except.handle]p16:
10293 // The object declared in an exception-declaration or, if the
10294 // exception-declaration does not specify a name, a temporary (12.2) is
10295 // copy-initialized (8.5) from the exception object. [...]
10296 // The object is destroyed when the handler exits, after the destruction
10297 // of any automatic objects initialized within the handler.
10299 // We just pretend to initialize the object with itself, then make sure
10300 // it can be destroyed later.
10301 QualType initType = ExDeclType;
10303 InitializedEntity entity =
10304 InitializedEntity::InitializeVariable(ExDecl);
10305 InitializationKind initKind =
10306 InitializationKind::CreateCopy(Loc, SourceLocation());
10308 Expr *opaqueValue =
10309 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10310 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10311 ExprResult result = sequence.Perform(*this, entity, initKind,
10312 MultiExprArg(&opaqueValue, 1));
10313 if (result.isInvalid())
10316 // If the constructor used was non-trivial, set this as the
10318 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10319 if (!construct->getConstructor()->isTrivial()) {
10320 Expr *init = MaybeCreateExprWithCleanups(construct);
10321 ExDecl->setInit(init);
10324 // And make sure it's destructable.
10325 FinalizeVarWithDestructor(ExDecl, recordType);
10331 ExDecl->setInvalidDecl();
10336 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10338 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10339 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10340 bool Invalid = D.isInvalidType();
10342 // Check for unexpanded parameter packs.
10343 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10344 UPPC_ExceptionType)) {
10345 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10346 D.getIdentifierLoc());
10350 IdentifierInfo *II = D.getIdentifier();
10351 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10352 LookupOrdinaryName,
10353 ForRedeclaration)) {
10354 // The scope should be freshly made just for us. There is just no way
10355 // it contains any previous declaration.
10356 assert(!S->isDeclScope(PrevDecl));
10357 if (PrevDecl->isTemplateParameter()) {
10358 // Maybe we will complain about the shadowed template parameter.
10359 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10364 if (D.getCXXScopeSpec().isSet() && !Invalid) {
10365 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10366 << D.getCXXScopeSpec().getRange();
10370 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10372 D.getIdentifierLoc(),
10373 D.getIdentifier());
10375 ExDecl->setInvalidDecl();
10377 // Add the exception declaration into this scope.
10379 PushOnScopeChains(ExDecl, S);
10381 CurContext->addDecl(ExDecl);
10383 ProcessDeclAttributes(S, ExDecl, D);
10387 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10389 Expr *AssertMessageExpr,
10390 SourceLocation RParenLoc) {
10391 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10393 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10396 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10397 AssertMessage, RParenLoc, false);
10400 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10402 StringLiteral *AssertMessage,
10403 SourceLocation RParenLoc,
10405 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10407 // In a static_assert-declaration, the constant-expression shall be a
10408 // constant expression that can be contextually converted to bool.
10409 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10410 if (Converted.isInvalid())
10414 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10415 diag::err_static_assert_expression_is_not_constant,
10416 /*AllowFold=*/false).isInvalid())
10419 if (!Failed && !Cond) {
10420 SmallString<256> MsgBuffer;
10421 llvm::raw_svector_ostream Msg(MsgBuffer);
10422 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10423 Diag(StaticAssertLoc, diag::err_static_assert_failed)
10424 << Msg.str() << AssertExpr->getSourceRange();
10429 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10430 AssertExpr, AssertMessage, RParenLoc,
10433 CurContext->addDecl(Decl);
10437 /// \brief Perform semantic analysis of the given friend type declaration.
10439 /// \returns A friend declaration that.
10440 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10441 SourceLocation FriendLoc,
10442 TypeSourceInfo *TSInfo) {
10443 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10445 QualType T = TSInfo->getType();
10446 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10448 // C++03 [class.friend]p2:
10449 // An elaborated-type-specifier shall be used in a friend declaration
10452 // * The class-key of the elaborated-type-specifier is required.
10453 if (!ActiveTemplateInstantiations.empty()) {
10454 // Do not complain about the form of friend template types during
10455 // template instantiation; we will already have complained when the
10456 // template was declared.
10458 if (!T->isElaboratedTypeSpecifier()) {
10459 // If we evaluated the type to a record type, suggest putting
10461 if (const RecordType *RT = T->getAs<RecordType>()) {
10462 RecordDecl *RD = RT->getDecl();
10464 std::string InsertionText = std::string(" ") + RD->getKindName();
10466 Diag(TypeRange.getBegin(),
10467 getLangOpts().CPlusPlus11 ?
10468 diag::warn_cxx98_compat_unelaborated_friend_type :
10469 diag::ext_unelaborated_friend_type)
10470 << (unsigned) RD->getTagKind()
10472 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10476 getLangOpts().CPlusPlus11 ?
10477 diag::warn_cxx98_compat_nonclass_type_friend :
10478 diag::ext_nonclass_type_friend)
10482 } else if (T->getAs<EnumType>()) {
10484 getLangOpts().CPlusPlus11 ?
10485 diag::warn_cxx98_compat_enum_friend :
10486 diag::ext_enum_friend)
10491 // C++11 [class.friend]p3:
10492 // A friend declaration that does not declare a function shall have one
10493 // of the following forms:
10494 // friend elaborated-type-specifier ;
10495 // friend simple-type-specifier ;
10496 // friend typename-specifier ;
10497 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10498 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10501 // If the type specifier in a friend declaration designates a (possibly
10502 // cv-qualified) class type, that class is declared as a friend; otherwise,
10503 // the friend declaration is ignored.
10504 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10507 /// Handle a friend tag declaration where the scope specifier was
10509 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10510 unsigned TagSpec, SourceLocation TagLoc,
10512 IdentifierInfo *Name,
10513 SourceLocation NameLoc,
10514 AttributeList *Attr,
10515 MultiTemplateParamsArg TempParamLists) {
10516 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10518 bool isExplicitSpecialization = false;
10519 bool Invalid = false;
10521 if (TemplateParameterList *TemplateParams
10522 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10523 TempParamLists.data(),
10524 TempParamLists.size(),
10526 isExplicitSpecialization,
10528 if (TemplateParams->size() > 0) {
10529 // This is a declaration of a class template.
10533 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10534 SS, Name, NameLoc, Attr,
10535 TemplateParams, AS_public,
10536 /*ModulePrivateLoc=*/SourceLocation(),
10537 TempParamLists.size() - 1,
10538 TempParamLists.data()).take();
10540 // The "template<>" header is extraneous.
10541 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10542 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10543 isExplicitSpecialization = true;
10547 if (Invalid) return 0;
10549 bool isAllExplicitSpecializations = true;
10550 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10551 if (TempParamLists[I]->size()) {
10552 isAllExplicitSpecializations = false;
10557 // FIXME: don't ignore attributes.
10559 // If it's explicit specializations all the way down, just forget
10560 // about the template header and build an appropriate non-templated
10561 // friend. TODO: for source fidelity, remember the headers.
10562 if (isAllExplicitSpecializations) {
10563 if (SS.isEmpty()) {
10564 bool Owned = false;
10565 bool IsDependent = false;
10566 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10568 /*ModulePrivateLoc=*/SourceLocation(),
10569 MultiTemplateParamsArg(), Owned, IsDependent,
10570 /*ScopedEnumKWLoc=*/SourceLocation(),
10571 /*ScopedEnumUsesClassTag=*/false,
10572 /*UnderlyingType=*/TypeResult());
10575 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10576 ElaboratedTypeKeyword Keyword
10577 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10578 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10583 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10584 if (isa<DependentNameType>(T)) {
10585 DependentNameTypeLoc TL =
10586 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10587 TL.setElaboratedKeywordLoc(TagLoc);
10588 TL.setQualifierLoc(QualifierLoc);
10589 TL.setNameLoc(NameLoc);
10591 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10592 TL.setElaboratedKeywordLoc(TagLoc);
10593 TL.setQualifierLoc(QualifierLoc);
10594 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10597 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10598 TSI, FriendLoc, TempParamLists);
10599 Friend->setAccess(AS_public);
10600 CurContext->addDecl(Friend);
10604 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10608 // Handle the case of a templated-scope friend class. e.g.
10609 // template <class T> class A<T>::B;
10610 // FIXME: we don't support these right now.
10611 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10612 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10613 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10614 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10615 TL.setElaboratedKeywordLoc(TagLoc);
10616 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10617 TL.setNameLoc(NameLoc);
10619 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10620 TSI, FriendLoc, TempParamLists);
10621 Friend->setAccess(AS_public);
10622 Friend->setUnsupportedFriend(true);
10623 CurContext->addDecl(Friend);
10628 /// Handle a friend type declaration. This works in tandem with
10631 /// Notes on friend class templates:
10633 /// We generally treat friend class declarations as if they were
10634 /// declaring a class. So, for example, the elaborated type specifier
10635 /// in a friend declaration is required to obey the restrictions of a
10636 /// class-head (i.e. no typedefs in the scope chain), template
10637 /// parameters are required to match up with simple template-ids, &c.
10638 /// However, unlike when declaring a template specialization, it's
10639 /// okay to refer to a template specialization without an empty
10640 /// template parameter declaration, e.g.
10641 /// friend class A<T>::B<unsigned>;
10642 /// We permit this as a special case; if there are any template
10643 /// parameters present at all, require proper matching, i.e.
10644 /// template <> template \<class T> friend class A<int>::B;
10645 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10646 MultiTemplateParamsArg TempParams) {
10647 SourceLocation Loc = DS.getLocStart();
10649 assert(DS.isFriendSpecified());
10650 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10652 // Try to convert the decl specifier to a type. This works for
10653 // friend templates because ActOnTag never produces a ClassTemplateDecl
10654 // for a TUK_Friend.
10655 Declarator TheDeclarator(DS, Declarator::MemberContext);
10656 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10657 QualType T = TSI->getType();
10658 if (TheDeclarator.isInvalidType())
10661 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10664 // This is definitely an error in C++98. It's probably meant to
10665 // be forbidden in C++0x, too, but the specification is just
10668 // The problem is with declarations like the following:
10669 // template <T> friend A<T>::foo;
10670 // where deciding whether a class C is a friend or not now hinges
10671 // on whether there exists an instantiation of A that causes
10672 // 'foo' to equal C. There are restrictions on class-heads
10673 // (which we declare (by fiat) elaborated friend declarations to
10674 // be) that makes this tractable.
10676 // FIXME: handle "template <> friend class A<T>;", which
10677 // is possibly well-formed? Who even knows?
10678 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10679 Diag(Loc, diag::err_tagless_friend_type_template)
10680 << DS.getSourceRange();
10684 // C++98 [class.friend]p1: A friend of a class is a function
10685 // or class that is not a member of the class . . .
10686 // This is fixed in DR77, which just barely didn't make the C++03
10687 // deadline. It's also a very silly restriction that seriously
10688 // affects inner classes and which nobody else seems to implement;
10689 // thus we never diagnose it, not even in -pedantic.
10691 // But note that we could warn about it: it's always useless to
10692 // friend one of your own members (it's not, however, worthless to
10693 // friend a member of an arbitrary specialization of your template).
10696 if (unsigned NumTempParamLists = TempParams.size())
10697 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10701 DS.getFriendSpecLoc());
10703 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10708 D->setAccess(AS_public);
10709 CurContext->addDecl(D);
10714 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10715 MultiTemplateParamsArg TemplateParams) {
10716 const DeclSpec &DS = D.getDeclSpec();
10718 assert(DS.isFriendSpecified());
10719 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10721 SourceLocation Loc = D.getIdentifierLoc();
10722 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10724 // C++ [class.friend]p1
10725 // A friend of a class is a function or class....
10726 // Note that this sees through typedefs, which is intended.
10727 // It *doesn't* see through dependent types, which is correct
10728 // according to [temp.arg.type]p3:
10729 // If a declaration acquires a function type through a
10730 // type dependent on a template-parameter and this causes
10731 // a declaration that does not use the syntactic form of a
10732 // function declarator to have a function type, the program
10734 if (!TInfo->getType()->isFunctionType()) {
10735 Diag(Loc, diag::err_unexpected_friend);
10737 // It might be worthwhile to try to recover by creating an
10738 // appropriate declaration.
10742 // C++ [namespace.memdef]p3
10743 // - If a friend declaration in a non-local class first declares a
10744 // class or function, the friend class or function is a member
10745 // of the innermost enclosing namespace.
10746 // - The name of the friend is not found by simple name lookup
10747 // until a matching declaration is provided in that namespace
10748 // scope (either before or after the class declaration granting
10750 // - If a friend function is called, its name may be found by the
10751 // name lookup that considers functions from namespaces and
10752 // classes associated with the types of the function arguments.
10753 // - When looking for a prior declaration of a class or a function
10754 // declared as a friend, scopes outside the innermost enclosing
10755 // namespace scope are not considered.
10757 CXXScopeSpec &SS = D.getCXXScopeSpec();
10758 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10759 DeclarationName Name = NameInfo.getName();
10762 // Check for unexpanded parameter packs.
10763 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10764 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10765 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10768 // The context we found the declaration in, or in which we should
10769 // create the declaration.
10771 Scope *DCScope = S;
10772 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10775 // FIXME: there are different rules in local classes
10777 // There are four cases here.
10778 // - There's no scope specifier, in which case we just go to the
10779 // appropriate scope and look for a function or function template
10780 // there as appropriate.
10781 // Recover from invalid scope qualifiers as if they just weren't there.
10782 if (SS.isInvalid() || !SS.isSet()) {
10783 // C++0x [namespace.memdef]p3:
10784 // If the name in a friend declaration is neither qualified nor
10785 // a template-id and the declaration is a function or an
10786 // elaborated-type-specifier, the lookup to determine whether
10787 // the entity has been previously declared shall not consider
10788 // any scopes outside the innermost enclosing namespace.
10789 // C++0x [class.friend]p11:
10790 // If a friend declaration appears in a local class and the name
10791 // specified is an unqualified name, a prior declaration is
10792 // looked up without considering scopes that are outside the
10793 // innermost enclosing non-class scope. For a friend function
10794 // declaration, if there is no prior declaration, the program is
10796 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10797 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10799 // Find the appropriate context according to the above.
10802 // Skip class contexts. If someone can cite chapter and verse
10803 // for this behavior, that would be nice --- it's what GCC and
10804 // EDG do, and it seems like a reasonable intent, but the spec
10805 // really only says that checks for unqualified existing
10806 // declarations should stop at the nearest enclosing namespace,
10807 // not that they should only consider the nearest enclosing
10809 while (DC->isRecord() || DC->isTransparentContext())
10810 DC = DC->getParent();
10812 LookupQualifiedName(Previous, DC);
10814 // TODO: decide what we think about using declarations.
10815 if (isLocal || !Previous.empty())
10818 if (isTemplateId) {
10819 if (isa<TranslationUnitDecl>(DC)) break;
10821 if (DC->isFileContext()) break;
10823 DC = DC->getParent();
10826 DCScope = getScopeForDeclContext(S, DC);
10828 // C++ [class.friend]p6:
10829 // A function can be defined in a friend declaration of a class if and
10830 // only if the class is a non-local class (9.8), the function name is
10831 // unqualified, and the function has namespace scope.
10832 if (isLocal && D.isFunctionDefinition()) {
10833 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10836 // - There's a non-dependent scope specifier, in which case we
10837 // compute it and do a previous lookup there for a function
10838 // or function template.
10839 } else if (!SS.getScopeRep()->isDependent()) {
10840 DC = computeDeclContext(SS);
10843 if (RequireCompleteDeclContext(SS, DC)) return 0;
10845 LookupQualifiedName(Previous, DC);
10847 // Ignore things found implicitly in the wrong scope.
10848 // TODO: better diagnostics for this case. Suggesting the right
10849 // qualified scope would be nice...
10850 LookupResult::Filter F = Previous.makeFilter();
10851 while (F.hasNext()) {
10852 NamedDecl *D = F.next();
10853 if (!DC->InEnclosingNamespaceSetOf(
10854 D->getDeclContext()->getRedeclContext()))
10859 if (Previous.empty()) {
10860 D.setInvalidType();
10861 Diag(Loc, diag::err_qualified_friend_not_found)
10862 << Name << TInfo->getType();
10866 // C++ [class.friend]p1: A friend of a class is a function or
10867 // class that is not a member of the class . . .
10868 if (DC->Equals(CurContext))
10869 Diag(DS.getFriendSpecLoc(),
10870 getLangOpts().CPlusPlus11 ?
10871 diag::warn_cxx98_compat_friend_is_member :
10872 diag::err_friend_is_member);
10874 if (D.isFunctionDefinition()) {
10875 // C++ [class.friend]p6:
10876 // A function can be defined in a friend declaration of a class if and
10877 // only if the class is a non-local class (9.8), the function name is
10878 // unqualified, and the function has namespace scope.
10879 SemaDiagnosticBuilder DB
10880 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10882 DB << SS.getScopeRep();
10883 if (DC->isFileContext())
10884 DB << FixItHint::CreateRemoval(SS.getRange());
10888 // - There's a scope specifier that does not match any template
10889 // parameter lists, in which case we use some arbitrary context,
10890 // create a method or method template, and wait for instantiation.
10891 // - There's a scope specifier that does match some template
10892 // parameter lists, which we don't handle right now.
10894 if (D.isFunctionDefinition()) {
10895 // C++ [class.friend]p6:
10896 // A function can be defined in a friend declaration of a class if and
10897 // only if the class is a non-local class (9.8), the function name is
10898 // unqualified, and the function has namespace scope.
10899 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10900 << SS.getScopeRep();
10904 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10907 if (!DC->isRecord()) {
10908 // This implies that it has to be an operator or function.
10909 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10910 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10911 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10912 Diag(Loc, diag::err_introducing_special_friend) <<
10913 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10914 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10919 // FIXME: This is an egregious hack to cope with cases where the scope stack
10920 // does not contain the declaration context, i.e., in an out-of-line
10921 // definition of a class.
10922 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10924 FakeDCScope.setEntity(DC);
10925 DCScope = &FakeDCScope;
10928 bool AddToScope = true;
10929 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10930 TemplateParams, AddToScope);
10933 assert(ND->getDeclContext() == DC);
10934 assert(ND->getLexicalDeclContext() == CurContext);
10936 // Add the function declaration to the appropriate lookup tables,
10937 // adjusting the redeclarations list as necessary. We don't
10938 // want to do this yet if the friending class is dependent.
10940 // Also update the scope-based lookup if the target context's
10941 // lookup context is in lexical scope.
10942 if (!CurContext->isDependentContext()) {
10943 DC = DC->getRedeclContext();
10944 DC->makeDeclVisibleInContext(ND);
10945 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10946 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10949 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10950 D.getIdentifierLoc(), ND,
10951 DS.getFriendSpecLoc());
10952 FrD->setAccess(AS_public);
10953 CurContext->addDecl(FrD);
10955 if (ND->isInvalidDecl()) {
10956 FrD->setInvalidDecl();
10958 if (DC->isRecord()) CheckFriendAccess(ND);
10961 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10962 FD = FTD->getTemplatedDecl();
10964 FD = cast<FunctionDecl>(ND);
10966 // Mark templated-scope function declarations as unsupported.
10967 if (FD->getNumTemplateParameterLists())
10968 FrD->setUnsupportedFriend(true);
10974 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10975 AdjustDeclIfTemplate(Dcl);
10977 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
10979 Diag(DelLoc, diag::err_deleted_non_function);
10983 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10984 // Don't consider the implicit declaration we generate for explicit
10985 // specializations. FIXME: Do not generate these implicit declarations.
10986 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10987 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10988 Diag(DelLoc, diag::err_deleted_decl_not_first);
10989 Diag(Prev->getLocation(), diag::note_previous_declaration);
10991 // If the declaration wasn't the first, we delete the function anyway for
10993 Fn = Fn->getCanonicalDecl();
10996 if (Fn->isDeleted())
10999 // See if we're deleting a function which is already known to override a
11000 // non-deleted virtual function.
11001 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11002 bool IssuedDiagnostic = false;
11003 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11004 E = MD->end_overridden_methods();
11006 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11007 if (!IssuedDiagnostic) {
11008 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11009 IssuedDiagnostic = true;
11011 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11016 Fn->setDeletedAsWritten();
11019 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11020 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11023 if (MD->getParent()->isDependentType()) {
11024 MD->setDefaulted();
11025 MD->setExplicitlyDefaulted();
11029 CXXSpecialMember Member = getSpecialMember(MD);
11030 if (Member == CXXInvalid) {
11031 Diag(DefaultLoc, diag::err_default_special_members);
11035 MD->setDefaulted();
11036 MD->setExplicitlyDefaulted();
11038 // If this definition appears within the record, do the checking when
11039 // the record is complete.
11040 const FunctionDecl *Primary = MD;
11041 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11042 // Find the uninstantiated declaration that actually had the '= default'
11044 Pattern->isDefined(Primary);
11046 // If the method was defaulted on its first declaration, we will have
11047 // already performed the checking in CheckCompletedCXXClass. Such a
11048 // declaration doesn't trigger an implicit definition.
11049 if (Primary == Primary->getCanonicalDecl())
11052 CheckExplicitlyDefaultedSpecialMember(MD);
11054 // The exception specification is needed because we are defining the
11056 ResolveExceptionSpec(DefaultLoc,
11057 MD->getType()->castAs<FunctionProtoType>());
11060 case CXXDefaultConstructor: {
11061 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11062 if (!CD->isInvalidDecl())
11063 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11067 case CXXCopyConstructor: {
11068 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11069 if (!CD->isInvalidDecl())
11070 DefineImplicitCopyConstructor(DefaultLoc, CD);
11074 case CXXCopyAssignment: {
11075 if (!MD->isInvalidDecl())
11076 DefineImplicitCopyAssignment(DefaultLoc, MD);
11080 case CXXDestructor: {
11081 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11082 if (!DD->isInvalidDecl())
11083 DefineImplicitDestructor(DefaultLoc, DD);
11087 case CXXMoveConstructor: {
11088 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11089 if (!CD->isInvalidDecl())
11090 DefineImplicitMoveConstructor(DefaultLoc, CD);
11094 case CXXMoveAssignment: {
11095 if (!MD->isInvalidDecl())
11096 DefineImplicitMoveAssignment(DefaultLoc, MD);
11101 llvm_unreachable("Invalid special member.");
11104 Diag(DefaultLoc, diag::err_default_special_members);
11108 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11109 for (Stmt::child_range CI = S->children(); CI; ++CI) {
11110 Stmt *SubStmt = *CI;
11113 if (isa<ReturnStmt>(SubStmt))
11114 Self.Diag(SubStmt->getLocStart(),
11115 diag::err_return_in_constructor_handler);
11116 if (!isa<Expr>(SubStmt))
11117 SearchForReturnInStmt(Self, SubStmt);
11121 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11122 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11123 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11124 SearchForReturnInStmt(*this, Handler);
11128 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11129 const CXXMethodDecl *Old) {
11130 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11131 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11133 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11135 // If the calling conventions match, everything is fine
11136 if (NewCC == OldCC)
11139 // If either of the calling conventions are set to "default", we need to pick
11140 // something more sensible based on the target. This supports code where the
11141 // one method explicitly sets thiscall, and another has no explicit calling
11143 CallingConv Default =
11144 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11145 if (NewCC == CC_Default)
11147 if (OldCC == CC_Default)
11150 // If the calling conventions still don't match, then report the error
11151 if (NewCC != OldCC) {
11152 Diag(New->getLocation(),
11153 diag::err_conflicting_overriding_cc_attributes)
11154 << New->getDeclName() << New->getType() << Old->getType();
11155 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11162 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11163 const CXXMethodDecl *Old) {
11164 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11165 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11167 if (Context.hasSameType(NewTy, OldTy) ||
11168 NewTy->isDependentType() || OldTy->isDependentType())
11171 // Check if the return types are covariant
11172 QualType NewClassTy, OldClassTy;
11174 /// Both types must be pointers or references to classes.
11175 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11176 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11177 NewClassTy = NewPT->getPointeeType();
11178 OldClassTy = OldPT->getPointeeType();
11180 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11181 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11182 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11183 NewClassTy = NewRT->getPointeeType();
11184 OldClassTy = OldRT->getPointeeType();
11189 // The return types aren't either both pointers or references to a class type.
11190 if (NewClassTy.isNull()) {
11191 Diag(New->getLocation(),
11192 diag::err_different_return_type_for_overriding_virtual_function)
11193 << New->getDeclName() << NewTy << OldTy;
11194 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11199 // C++ [class.virtual]p6:
11200 // If the return type of D::f differs from the return type of B::f, the
11201 // class type in the return type of D::f shall be complete at the point of
11202 // declaration of D::f or shall be the class type D.
11203 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11204 if (!RT->isBeingDefined() &&
11205 RequireCompleteType(New->getLocation(), NewClassTy,
11206 diag::err_covariant_return_incomplete,
11207 New->getDeclName()))
11211 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11212 // Check if the new class derives from the old class.
11213 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11214 Diag(New->getLocation(),
11215 diag::err_covariant_return_not_derived)
11216 << New->getDeclName() << NewTy << OldTy;
11217 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11221 // Check if we the conversion from derived to base is valid.
11222 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11223 diag::err_covariant_return_inaccessible_base,
11224 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11225 // FIXME: Should this point to the return type?
11226 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11227 // FIXME: this note won't trigger for delayed access control
11228 // diagnostics, and it's impossible to get an undelayed error
11229 // here from access control during the original parse because
11230 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11231 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11236 // The qualifiers of the return types must be the same.
11237 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11238 Diag(New->getLocation(),
11239 diag::err_covariant_return_type_different_qualifications)
11240 << New->getDeclName() << NewTy << OldTy;
11241 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11246 // The new class type must have the same or less qualifiers as the old type.
11247 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11248 Diag(New->getLocation(),
11249 diag::err_covariant_return_type_class_type_more_qualified)
11250 << New->getDeclName() << NewTy << OldTy;
11251 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11258 /// \brief Mark the given method pure.
11260 /// \param Method the method to be marked pure.
11262 /// \param InitRange the source range that covers the "0" initializer.
11263 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11264 SourceLocation EndLoc = InitRange.getEnd();
11265 if (EndLoc.isValid())
11266 Method->setRangeEnd(EndLoc);
11268 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11273 if (!Method->isInvalidDecl())
11274 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11275 << Method->getDeclName() << InitRange;
11279 /// \brief Determine whether the given declaration is a static data member.
11280 static bool isStaticDataMember(Decl *D) {
11281 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11285 return Var->isStaticDataMember();
11287 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11288 /// an initializer for the out-of-line declaration 'Dcl'. The scope
11289 /// is a fresh scope pushed for just this purpose.
11291 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11292 /// static data member of class X, names should be looked up in the scope of
11294 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11295 // If there is no declaration, there was an error parsing it.
11296 if (D == 0 || D->isInvalidDecl()) return;
11298 // We should only get called for declarations with scope specifiers, like:
11300 assert(D->isOutOfLine());
11301 EnterDeclaratorContext(S, D->getDeclContext());
11303 // If we are parsing the initializer for a static data member, push a
11304 // new expression evaluation context that is associated with this static
11306 if (isStaticDataMember(D))
11307 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11310 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11311 /// initializer for the out-of-line declaration 'D'.
11312 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11313 // If there is no declaration, there was an error parsing it.
11314 if (D == 0 || D->isInvalidDecl()) return;
11316 if (isStaticDataMember(D))
11317 PopExpressionEvaluationContext();
11319 assert(D->isOutOfLine());
11320 ExitDeclaratorContext(S);
11323 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11324 /// C++ if/switch/while/for statement.
11325 /// e.g: "if (int x = f()) {...}"
11326 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11328 // The declarator shall not specify a function or an array.
11329 // The type-specifier-seq shall not contain typedef and shall not declare a
11330 // new class or enumeration.
11331 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11332 "Parser allowed 'typedef' as storage class of condition decl.");
11334 Decl *Dcl = ActOnDeclarator(S, D);
11338 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11339 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11340 << D.getSourceRange();
11347 void Sema::LoadExternalVTableUses() {
11348 if (!ExternalSource)
11351 SmallVector<ExternalVTableUse, 4> VTables;
11352 ExternalSource->ReadUsedVTables(VTables);
11353 SmallVector<VTableUse, 4> NewUses;
11354 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11355 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11356 = VTablesUsed.find(VTables[I].Record);
11357 // Even if a definition wasn't required before, it may be required now.
11358 if (Pos != VTablesUsed.end()) {
11359 if (!Pos->second && VTables[I].DefinitionRequired)
11360 Pos->second = true;
11364 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11365 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11368 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11371 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11372 bool DefinitionRequired) {
11373 // Ignore any vtable uses in unevaluated operands or for classes that do
11374 // not have a vtable.
11375 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11376 CurContext->isDependentContext() ||
11377 ExprEvalContexts.back().Context == Unevaluated)
11380 // Try to insert this class into the map.
11381 LoadExternalVTableUses();
11382 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11383 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11384 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11386 // If we already had an entry, check to see if we are promoting this vtable
11387 // to required a definition. If so, we need to reappend to the VTableUses
11388 // list, since we may have already processed the first entry.
11389 if (DefinitionRequired && !Pos.first->second) {
11390 Pos.first->second = true;
11392 // Otherwise, we can early exit.
11397 // Local classes need to have their virtual members marked
11398 // immediately. For all other classes, we mark their virtual members
11399 // at the end of the translation unit.
11400 if (Class->isLocalClass())
11401 MarkVirtualMembersReferenced(Loc, Class);
11403 VTableUses.push_back(std::make_pair(Class, Loc));
11406 bool Sema::DefineUsedVTables() {
11407 LoadExternalVTableUses();
11408 if (VTableUses.empty())
11411 // Note: The VTableUses vector could grow as a result of marking
11412 // the members of a class as "used", so we check the size each
11413 // time through the loop and prefer indices (which are stable) to
11414 // iterators (which are not).
11415 bool DefinedAnything = false;
11416 for (unsigned I = 0; I != VTableUses.size(); ++I) {
11417 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11421 SourceLocation Loc = VTableUses[I].second;
11423 bool DefineVTable = true;
11425 // If this class has a key function, but that key function is
11426 // defined in another translation unit, we don't need to emit the
11427 // vtable even though we're using it.
11428 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11429 if (KeyFunction && !KeyFunction->hasBody()) {
11430 switch (KeyFunction->getTemplateSpecializationKind()) {
11431 case TSK_Undeclared:
11432 case TSK_ExplicitSpecialization:
11433 case TSK_ExplicitInstantiationDeclaration:
11434 // The key function is in another translation unit.
11435 DefineVTable = false;
11438 case TSK_ExplicitInstantiationDefinition:
11439 case TSK_ImplicitInstantiation:
11440 // We will be instantiating the key function.
11443 } else if (!KeyFunction) {
11444 // If we have a class with no key function that is the subject
11445 // of an explicit instantiation declaration, suppress the
11446 // vtable; it will live with the explicit instantiation
11448 bool IsExplicitInstantiationDeclaration
11449 = Class->getTemplateSpecializationKind()
11450 == TSK_ExplicitInstantiationDeclaration;
11451 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11452 REnd = Class->redecls_end();
11454 TemplateSpecializationKind TSK
11455 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11456 if (TSK == TSK_ExplicitInstantiationDeclaration)
11457 IsExplicitInstantiationDeclaration = true;
11458 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11459 IsExplicitInstantiationDeclaration = false;
11464 if (IsExplicitInstantiationDeclaration)
11465 DefineVTable = false;
11468 // The exception specifications for all virtual members may be needed even
11469 // if we are not providing an authoritative form of the vtable in this TU.
11470 // We may choose to emit it available_externally anyway.
11471 if (!DefineVTable) {
11472 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11476 // Mark all of the virtual members of this class as referenced, so
11477 // that we can build a vtable. Then, tell the AST consumer that a
11478 // vtable for this class is required.
11479 DefinedAnything = true;
11480 MarkVirtualMembersReferenced(Loc, Class);
11481 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11482 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11484 // Optionally warn if we're emitting a weak vtable.
11485 if (Class->hasExternalLinkage() &&
11486 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11487 const FunctionDecl *KeyFunctionDef = 0;
11488 if (!KeyFunction ||
11489 (KeyFunction->hasBody(KeyFunctionDef) &&
11490 KeyFunctionDef->isInlined()))
11491 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11492 TSK_ExplicitInstantiationDefinition
11493 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11497 VTableUses.clear();
11499 return DefinedAnything;
11502 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11503 const CXXRecordDecl *RD) {
11504 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11505 E = RD->method_end(); I != E; ++I)
11506 if ((*I)->isVirtual() && !(*I)->isPure())
11507 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11510 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11511 const CXXRecordDecl *RD) {
11512 // Mark all functions which will appear in RD's vtable as used.
11513 CXXFinalOverriderMap FinalOverriders;
11514 RD->getFinalOverriders(FinalOverriders);
11515 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11516 E = FinalOverriders.end();
11518 for (OverridingMethods::const_iterator OI = I->second.begin(),
11519 OE = I->second.end();
11521 assert(OI->second.size() > 0 && "no final overrider");
11522 CXXMethodDecl *Overrider = OI->second.front().Method;
11524 // C++ [basic.def.odr]p2:
11525 // [...] A virtual member function is used if it is not pure. [...]
11526 if (!Overrider->isPure())
11527 MarkFunctionReferenced(Loc, Overrider);
11531 // Only classes that have virtual bases need a VTT.
11532 if (RD->getNumVBases() == 0)
11535 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11536 e = RD->bases_end(); i != e; ++i) {
11537 const CXXRecordDecl *Base =
11538 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11539 if (Base->getNumVBases() == 0)
11541 MarkVirtualMembersReferenced(Loc, Base);
11545 /// SetIvarInitializers - This routine builds initialization ASTs for the
11546 /// Objective-C implementation whose ivars need be initialized.
11547 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11548 if (!getLangOpts().CPlusPlus)
11550 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11551 SmallVector<ObjCIvarDecl*, 8> ivars;
11552 CollectIvarsToConstructOrDestruct(OID, ivars);
11555 SmallVector<CXXCtorInitializer*, 32> AllToInit;
11556 for (unsigned i = 0; i < ivars.size(); i++) {
11557 FieldDecl *Field = ivars[i];
11558 if (Field->isInvalidDecl())
11561 CXXCtorInitializer *Member;
11562 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11563 InitializationKind InitKind =
11564 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11566 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11567 ExprResult MemberInit =
11568 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11569 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11570 // Note, MemberInit could actually come back empty if no initialization
11571 // is required (e.g., because it would call a trivial default constructor)
11572 if (!MemberInit.get() || MemberInit.isInvalid())
11576 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11578 MemberInit.takeAs<Expr>(),
11580 AllToInit.push_back(Member);
11582 // Be sure that the destructor is accessible and is marked as referenced.
11583 if (const RecordType *RecordTy
11584 = Context.getBaseElementType(Field->getType())
11585 ->getAs<RecordType>()) {
11586 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11587 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11588 MarkFunctionReferenced(Field->getLocation(), Destructor);
11589 CheckDestructorAccess(Field->getLocation(), Destructor,
11590 PDiag(diag::err_access_dtor_ivar)
11591 << Context.getBaseElementType(Field->getType()));
11595 ObjCImplementation->setIvarInitializers(Context,
11596 AllToInit.data(), AllToInit.size());
11601 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11602 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11603 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11604 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11606 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11607 CE = Current.end();
11608 if (Ctor->isInvalidDecl())
11611 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11613 // Target may not be determinable yet, for instance if this is a dependent
11614 // call in an uninstantiated template.
11616 const FunctionDecl *FNTarget = 0;
11617 (void)Target->hasBody(FNTarget);
11618 Target = const_cast<CXXConstructorDecl*>(
11619 cast_or_null<CXXConstructorDecl>(FNTarget));
11622 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11623 // Avoid dereferencing a null pointer here.
11624 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11626 if (!Current.insert(Canonical))
11629 // We know that beyond here, we aren't chaining into a cycle.
11630 if (!Target || !Target->isDelegatingConstructor() ||
11631 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11632 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11635 // We've hit a cycle.
11636 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11637 Current.count(TCanonical)) {
11638 // If we haven't diagnosed this cycle yet, do so now.
11639 if (!Invalid.count(TCanonical)) {
11640 S.Diag((*Ctor->init_begin())->getSourceLocation(),
11641 diag::warn_delegating_ctor_cycle)
11644 // Don't add a note for a function delegating directly to itself.
11645 if (TCanonical != Canonical)
11646 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11648 CXXConstructorDecl *C = Target;
11649 while (C->getCanonicalDecl() != Canonical) {
11650 const FunctionDecl *FNTarget = 0;
11651 (void)C->getTargetConstructor()->hasBody(FNTarget);
11652 assert(FNTarget && "Ctor cycle through bodiless function");
11654 C = const_cast<CXXConstructorDecl*>(
11655 cast<CXXConstructorDecl>(FNTarget));
11656 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11660 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11661 Invalid.insert(*CI);
11664 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11669 void Sema::CheckDelegatingCtorCycles() {
11670 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11672 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11673 CE = Current.end();
11675 for (DelegatingCtorDeclsType::iterator
11676 I = DelegatingCtorDecls.begin(ExternalSource),
11677 E = DelegatingCtorDecls.end();
11679 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11681 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11682 (*CI)->setInvalidDecl();
11686 /// \brief AST visitor that finds references to the 'this' expression.
11687 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11691 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11693 bool VisitCXXThisExpr(CXXThisExpr *E) {
11694 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11695 << E->isImplicit();
11701 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11702 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11706 TypeLoc TL = TSInfo->getTypeLoc();
11707 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11711 // C++11 [expr.prim.general]p3:
11712 // [The expression this] shall not appear before the optional
11713 // cv-qualifier-seq and it shall not appear within the declaration of a
11714 // static member function (although its type and value category are defined
11715 // within a static member function as they are within a non-static member
11716 // function). [ Note: this is because declaration matching does not occur
11717 // until the complete declarator is known. - end note ]
11718 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11719 FindCXXThisExpr Finder(*this);
11721 // If the return type came after the cv-qualifier-seq, check it now.
11722 if (Proto->hasTrailingReturn() &&
11723 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
11726 // Check the exception specification.
11727 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11730 return checkThisInStaticMemberFunctionAttributes(Method);
11733 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11734 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11738 TypeLoc TL = TSInfo->getTypeLoc();
11739 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11743 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11744 FindCXXThisExpr Finder(*this);
11746 switch (Proto->getExceptionSpecType()) {
11747 case EST_Uninstantiated:
11748 case EST_Unevaluated:
11749 case EST_BasicNoexcept:
11750 case EST_DynamicNone:
11755 case EST_ComputedNoexcept:
11756 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11760 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11761 EEnd = Proto->exception_end();
11763 if (!Finder.TraverseType(*E))
11772 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11773 FindCXXThisExpr Finder(*this);
11775 // Check attributes.
11776 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11778 // FIXME: This should be emitted by tblgen.
11780 ArrayRef<Expr *> Args;
11781 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11783 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11785 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11786 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11787 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11788 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11789 else if (ExclusiveLockFunctionAttr *ELF
11790 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11791 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11792 else if (SharedLockFunctionAttr *SLF
11793 = dyn_cast<SharedLockFunctionAttr>(*A))
11794 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11795 else if (ExclusiveTrylockFunctionAttr *ETLF
11796 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11797 Arg = ETLF->getSuccessValue();
11798 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11799 } else if (SharedTrylockFunctionAttr *STLF
11800 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11801 Arg = STLF->getSuccessValue();
11802 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11803 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11804 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11805 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11806 Arg = LR->getArg();
11807 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11808 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11809 else if (ExclusiveLocksRequiredAttr *ELR
11810 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11811 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11812 else if (SharedLocksRequiredAttr *SLR
11813 = dyn_cast<SharedLocksRequiredAttr>(*A))
11814 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11816 if (Arg && !Finder.TraverseStmt(Arg))
11819 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11820 if (!Finder.TraverseStmt(Args[I]))
11829 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11830 ArrayRef<ParsedType> DynamicExceptions,
11831 ArrayRef<SourceRange> DynamicExceptionRanges,
11832 Expr *NoexceptExpr,
11833 SmallVectorImpl<QualType> &Exceptions,
11834 FunctionProtoType::ExtProtoInfo &EPI) {
11835 Exceptions.clear();
11836 EPI.ExceptionSpecType = EST;
11837 if (EST == EST_Dynamic) {
11838 Exceptions.reserve(DynamicExceptions.size());
11839 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11840 // FIXME: Preserve type source info.
11841 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11843 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11844 collectUnexpandedParameterPacks(ET, Unexpanded);
11845 if (!Unexpanded.empty()) {
11846 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11847 UPPC_ExceptionType,
11852 // Check that the type is valid for an exception spec, and
11854 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11855 Exceptions.push_back(ET);
11857 EPI.NumExceptions = Exceptions.size();
11858 EPI.Exceptions = Exceptions.data();
11862 if (EST == EST_ComputedNoexcept) {
11863 // If an error occurred, there's no expression here.
11864 if (NoexceptExpr) {
11865 assert((NoexceptExpr->isTypeDependent() ||
11866 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11868 "Parser should have made sure that the expression is boolean");
11869 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11870 EPI.ExceptionSpecType = EST_BasicNoexcept;
11874 if (!NoexceptExpr->isValueDependent())
11875 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11876 diag::err_noexcept_needs_constant_expression,
11877 /*AllowFold*/ false).take();
11878 EPI.NoexceptExpr = NoexceptExpr;
11884 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11885 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11886 // Implicitly declared functions (e.g. copy constructors) are
11887 // __host__ __device__
11888 if (D->isImplicit())
11889 return CFT_HostDevice;
11891 if (D->hasAttr<CUDAGlobalAttr>())
11894 if (D->hasAttr<CUDADeviceAttr>()) {
11895 if (D->hasAttr<CUDAHostAttr>())
11896 return CFT_HostDevice;
11904 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11905 CUDAFunctionTarget CalleeTarget) {
11906 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11907 // Callable from the device only."
11908 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11911 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11912 // Callable from the host only."
11913 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11914 // Callable from the host only."
11915 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11916 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11919 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)