1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
45 using namespace clang;
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
57 class CheckDefaultArgumentVisitor
58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64 : DefaultArg(defarg), S(s) {}
66 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
68 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69 bool VisitLambdaExpr(LambdaExpr *Lambda);
70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
76 for (Stmt *SubStmt : Node->children())
77 IsInvalid |= Visit(SubStmt);
81 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85 NamedDecl *Decl = DRE->getDecl();
86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
95 return S->Diag(DRE->getLocStart(),
96 diag::err_param_default_argument_references_param)
97 << Param->getDeclName() << DefaultArg->getSourceRange();
98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
102 if (VDecl->isLocalVarDecl())
103 return S->Diag(DRE->getLocStart(),
104 diag::err_param_default_argument_references_local)
105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
116 return S->Diag(ThisE->getLocStart(),
117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 // If we have a throw-all spec at this point, ignore the function.
166 if (ComputedEST == EST_None)
170 // If this function can throw any exceptions, make a note of that.
176 // FIXME: If the call to this decl is using any of its default arguments, we
177 // need to search them for potentially-throwing calls.
178 // If this function has a basic noexcept, it doesn't affect the outcome.
179 case EST_BasicNoexcept:
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 case EST_DynamicNone:
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
187 // Check out noexcept specs.
188 case EST_ComputedNoexcept:
190 FunctionProtoType::NoexceptResult NR =
191 Proto->getNoexceptSpec(Self->Context);
192 assert(NR != FunctionProtoType::NR_NoNoexcept &&
193 "Must have noexcept result for EST_ComputedNoexcept.");
194 assert(NR != FunctionProtoType::NR_Dependent &&
195 "Should not generate implicit declarations for dependent cases, "
196 "and don't know how to handle them anyway.");
197 // noexcept(false) -> no spec on the new function
198 if (NR == FunctionProtoType::NR_Throw) {
200 ComputedEST = EST_None;
202 // noexcept(true) won't change anything either.
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (const auto &E : Proto->exceptions())
214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215 Exceptions.push_back(E);
218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219 if (!E || ComputedEST == EST_MSAny)
224 // C++0x [except.spec]p14:
225 // [An] implicit exception-specification specifies the type-id T if and
226 // only if T is allowed by the exception-specification of a function directly
227 // invoked by f's implicit definition; f shall allow all exceptions if any
228 // function it directly invokes allows all exceptions, and f shall allow no
229 // exceptions if every function it directly invokes allows no exceptions.
231 // Note in particular that if an implicit exception-specification is generated
232 // for a function containing a throw-expression, that specification can still
233 // be noexcept(true).
235 // Note also that 'directly invoked' is not defined in the standard, and there
236 // is no indication that we should only consider potentially-evaluated calls.
238 // Ultimately we should implement the intent of the standard: the exception
239 // specification should be the set of exceptions which can be thrown by the
240 // implicit definition. For now, we assume that any non-nothrow expression can
241 // throw any exception.
243 if (Self->canThrow(E))
244 ComputedEST = EST_None;
248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249 SourceLocation EqualLoc) {
250 if (RequireCompleteType(Param->getLocation(), Param->getType(),
251 diag::err_typecheck_decl_incomplete_type)) {
252 Param->setInvalidDecl();
256 // C++ [dcl.fct.default]p5
257 // A default argument expression is implicitly converted (clause
258 // 4) to the parameter type. The default argument expression has
259 // the same semantic constraints as the initializer expression in
260 // a declaration of a variable of the parameter type, using the
261 // copy-initialization semantics (8.5).
262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268 if (Result.isInvalid())
270 Arg = Result.getAs<Expr>();
272 CheckCompletedExpr(Arg, EqualLoc);
273 Arg = MaybeCreateExprWithCleanups(Arg);
275 // Okay: add the default argument to the parameter
276 Param->setDefaultArg(Arg);
278 // We have already instantiated this parameter; provide each of the
279 // instantiations with the uninstantiated default argument.
280 UnparsedDefaultArgInstantiationsMap::iterator InstPos
281 = UnparsedDefaultArgInstantiations.find(Param);
282 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 // We're done tracking this parameter's instantiations.
287 UnparsedDefaultArgInstantiations.erase(InstPos);
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299 if (!param || !DefaultArg)
302 ParmVarDecl *Param = cast<ParmVarDecl>(param);
303 UnparsedDefaultArgLocs.erase(Param);
305 // Default arguments are only permitted in C++
306 if (!getLangOpts().CPlusPlus) {
307 Diag(EqualLoc, diag::err_param_default_argument)
308 << DefaultArg->getSourceRange();
309 Param->setInvalidDecl();
313 // Check for unexpanded parameter packs.
314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315 Param->setInvalidDecl();
319 // C++11 [dcl.fct.default]p3
320 // A default argument expression [...] shall not be specified for a
322 if (Param->isParameterPack()) {
323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324 << DefaultArg->getSourceRange();
328 // Check that the default argument is well-formed
329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330 if (DefaultArgChecker.Visit(DefaultArg)) {
331 Param->setInvalidDecl();
335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343 SourceLocation EqualLoc,
344 SourceLocation ArgLoc) {
348 ParmVarDecl *Param = cast<ParmVarDecl>(param);
349 Param->setUnparsedDefaultArg();
350 UnparsedDefaultArgLocs[Param] = ArgLoc;
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
356 SourceLocation EqualLoc) {
360 ParmVarDecl *Param = cast<ParmVarDecl>(param);
361 Param->setInvalidDecl();
362 UnparsedDefaultArgLocs.erase(Param);
363 Param->setDefaultArg(new(Context)
364 OpaqueValueExpr(EqualLoc,
365 Param->getType().getNonReferenceType(),
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375 // C++ [dcl.fct.default]p3
376 // A default argument expression shall be specified only in the
377 // parameter-declaration-clause of a function declaration or in a
378 // template-parameter (14.1). It shall not be specified for a
379 // parameter pack. If it is specified in a
380 // parameter-declaration-clause, it shall not occur within a
381 // declarator or abstract-declarator of a parameter-declaration.
382 bool MightBeFunction = D.isFunctionDeclarationContext();
383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384 DeclaratorChunk &chunk = D.getTypeObject(i);
385 if (chunk.Kind == DeclaratorChunk::Function) {
386 if (MightBeFunction) {
387 // This is a function declaration. It can have default arguments, but
388 // keep looking in case its return type is a function type with default
390 MightBeFunction = false;
393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396 if (Param->hasUnparsedDefaultArg()) {
397 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
399 if (Toks->size() > 1)
400 SR = SourceRange((*Toks)[1].getLocation(),
401 Toks->back().getLocation());
403 SR = UnparsedDefaultArgLocs[Param];
404 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
411 Param->setDefaultArg(nullptr);
414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
425 if (!PVD->hasInheritedDefaultArg())
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437 bool Invalid = false;
439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficent, and if neither is local, then they are in the same scope.)
478 // C++ [dcl.fct.default]p4:
479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
491 // C++ [dcl.fct.default]p6:
492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
495 // member function declaration in the class definition.
496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501 ParmVarDecl *NewParam = New->getParamDecl(p);
503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504 bool NewParamHasDfl = NewParam->hasDefaultArg();
506 if (OldParamHasDfl && NewParamHasDfl) {
507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
513 if (getLangOpts().MicrosoftExt) {
514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
522 NewParam->setDefaultArg(OldParam->getInit());
523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
536 Diag(NewParam->getLocation(), DiagDefaultParamID)
537 << NewParam->getDefaultArgRange();
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
543 Older = Older->getPreviousDecl();
544 OldParam = Older->getParamDecl(p);
547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
549 } else if (OldParamHasDfl) {
550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
552 // strips off any top-level ExprWithCleanups.
553 NewParam->setHasInheritedDefaultArg();
554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
560 NewParam->setDefaultArg(OldParam->getInit());
561 } else if (NewParamHasDfl) {
562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
610 << NewParam->getDefaultArgRange();
615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg());
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
631 const FunctionDecl *Def;
632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633 // template has a constexpr specifier then all its declarations shall
634 // contain the constexpr specifier.
635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
651 // argument expression, that declaration shall be a definition and shall be
652 // the only declaration of the function or function template in the
654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655 functionDeclHasDefaultArgument(Old)) {
656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657 Diag(Old->getLocation(), diag::note_previous_declaration);
661 if (CheckEquivalentExceptionSpec(Old, New))
667 /// \brief Merge the exception specifications of two variable declarations.
669 /// This is called when there's a redeclaration of a VarDecl. The function
670 /// checks if the redeclaration might have an exception specification and
671 /// validates compatibility and merges the specs if necessary.
672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
673 // Shortcut if exceptions are disabled.
674 if (!getLangOpts().CXXExceptions)
677 assert(Context.hasSameType(New->getType(), Old->getType()) &&
678 "Should only be called if types are otherwise the same.");
680 QualType NewType = New->getType();
681 QualType OldType = Old->getType();
683 // We're only interested in pointers and references to functions, as well
684 // as pointers to member functions.
685 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686 NewType = R->getPointeeType();
687 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689 NewType = P->getPointeeType();
690 OldType = OldType->getAs<PointerType>()->getPointeeType();
691 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692 NewType = M->getPointeeType();
693 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
696 if (!NewType->isFunctionProtoType())
699 // There's lots of special cases for functions. For function pointers, system
700 // libraries are hopefully not as broken so that we don't need these
702 if (CheckEquivalentExceptionSpec(
703 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705 New->setInvalidDecl();
709 /// CheckCXXDefaultArguments - Verify that the default arguments for a
710 /// function declaration are well-formed according to C++
711 /// [dcl.fct.default].
712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
713 unsigned NumParams = FD->getNumParams();
716 // Find first parameter with a default argument
717 for (p = 0; p < NumParams; ++p) {
718 ParmVarDecl *Param = FD->getParamDecl(p);
719 if (Param->hasDefaultArg())
723 // C++11 [dcl.fct.default]p4:
724 // In a given function declaration, each parameter subsequent to a parameter
725 // with a default argument shall have a default argument supplied in this or
726 // a previous declaration or shall be a function parameter pack. A default
727 // argument shall not be redefined by a later declaration (not even to the
729 unsigned LastMissingDefaultArg = 0;
730 for (; p < NumParams; ++p) {
731 ParmVarDecl *Param = FD->getParamDecl(p);
732 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
733 if (Param->isInvalidDecl())
734 /* We already complained about this parameter. */;
735 else if (Param->getIdentifier())
736 Diag(Param->getLocation(),
737 diag::err_param_default_argument_missing_name)
738 << Param->getIdentifier();
740 Diag(Param->getLocation(),
741 diag::err_param_default_argument_missing);
743 LastMissingDefaultArg = p;
747 if (LastMissingDefaultArg > 0) {
748 // Some default arguments were missing. Clear out all of the
749 // default arguments up to (and including) the last missing
750 // default argument, so that we leave the function parameters
751 // in a semantically valid state.
752 for (p = 0; p <= LastMissingDefaultArg; ++p) {
753 ParmVarDecl *Param = FD->getParamDecl(p);
754 if (Param->hasDefaultArg()) {
755 Param->setDefaultArg(nullptr);
761 // CheckConstexprParameterTypes - Check whether a function's parameter types
762 // are all literal types. If so, return true. If not, produce a suitable
763 // diagnostic and return false.
764 static bool CheckConstexprParameterTypes(Sema &SemaRef,
765 const FunctionDecl *FD) {
766 unsigned ArgIndex = 0;
767 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
768 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
769 e = FT->param_type_end();
770 i != e; ++i, ++ArgIndex) {
771 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772 SourceLocation ParamLoc = PD->getLocation();
773 if (!(*i)->isDependentType() &&
774 SemaRef.RequireLiteralType(ParamLoc, *i,
775 diag::err_constexpr_non_literal_param,
776 ArgIndex+1, PD->getSourceRange(),
777 isa<CXXConstructorDecl>(FD)))
783 /// \brief Get diagnostic %select index for tag kind for
784 /// record diagnostic message.
785 /// WARNING: Indexes apply to particular diagnostics only!
787 /// \returns diagnostic %select index.
788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
790 case TTK_Struct: return 0;
791 case TTK_Interface: return 1;
792 case TTK_Class: return 2;
793 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798 // the requirements of a constexpr function definition or a constexpr
799 // constructor definition. If so, return true. If not, produce appropriate
800 // diagnostics and return false.
802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805 if (MD && MD->isInstance()) {
806 // C++11 [dcl.constexpr]p4:
807 // The definition of a constexpr constructor shall satisfy the following
809 // - the class shall not have any virtual base classes;
810 const CXXRecordDecl *RD = MD->getParent();
811 if (RD->getNumVBases()) {
812 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813 << isa<CXXConstructorDecl>(NewFD)
814 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
815 for (const auto &I : RD->vbases())
816 Diag(I.getLocStart(),
817 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
822 if (!isa<CXXConstructorDecl>(NewFD)) {
823 // C++11 [dcl.constexpr]p3:
824 // The definition of a constexpr function shall satisfy the following
826 // - it shall not be virtual;
827 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828 if (Method && Method->isVirtual()) {
829 Method = Method->getCanonicalDecl();
830 Diag(Method->getLocation(), diag::err_constexpr_virtual);
832 // If it's not obvious why this function is virtual, find an overridden
833 // function which uses the 'virtual' keyword.
834 const CXXMethodDecl *WrittenVirtual = Method;
835 while (!WrittenVirtual->isVirtualAsWritten())
836 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837 if (WrittenVirtual != Method)
838 Diag(WrittenVirtual->getLocation(),
839 diag::note_overridden_virtual_function);
843 // - its return type shall be a literal type;
844 QualType RT = NewFD->getReturnType();
845 if (!RT->isDependentType() &&
846 RequireLiteralType(NewFD->getLocation(), RT,
847 diag::err_constexpr_non_literal_return))
851 // - each of its parameter types shall be a literal type;
852 if (!CheckConstexprParameterTypes(*this, NewFD))
858 /// Check the given declaration statement is legal within a constexpr function
859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
861 /// \return true if the body is OK (maybe only as an extension), false if we
862 /// have diagnosed a problem.
863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
864 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865 // C++11 [dcl.constexpr]p3 and p4:
866 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
868 for (const auto *DclIt : DS->decls()) {
869 switch (DclIt->getKind()) {
870 case Decl::StaticAssert:
872 case Decl::UsingShadow:
873 case Decl::UsingDirective:
874 case Decl::UnresolvedUsingTypename:
875 case Decl::UnresolvedUsingValue:
876 // - static_assert-declarations
877 // - using-declarations,
878 // - using-directives,
882 case Decl::TypeAlias: {
883 // - typedef declarations and alias-declarations that do not define
884 // classes or enumerations,
885 const auto *TN = cast<TypedefNameDecl>(DclIt);
886 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887 // Don't allow variably-modified types in constexpr functions.
888 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890 << TL.getSourceRange() << TL.getType()
891 << isa<CXXConstructorDecl>(Dcl);
898 case Decl::CXXRecord:
899 // C++1y allows types to be defined, not just declared.
900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
901 SemaRef.Diag(DS->getLocStart(),
902 SemaRef.getLangOpts().CPlusPlus14
903 ? diag::warn_cxx11_compat_constexpr_type_definition
904 : diag::ext_constexpr_type_definition)
905 << isa<CXXConstructorDecl>(Dcl);
908 case Decl::EnumConstant:
909 case Decl::IndirectField:
911 // These can only appear with other declarations which are banned in
912 // C++11 and permitted in C++1y, so ignore them.
916 // C++1y [dcl.constexpr]p3 allows anything except:
917 // a definition of a variable of non-literal type or of static or
918 // thread storage duration or for which no initialization is performed.
919 const auto *VD = cast<VarDecl>(DclIt);
920 if (VD->isThisDeclarationADefinition()) {
921 if (VD->isStaticLocal()) {
922 SemaRef.Diag(VD->getLocation(),
923 diag::err_constexpr_local_var_static)
924 << isa<CXXConstructorDecl>(Dcl)
925 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
928 if (!VD->getType()->isDependentType() &&
929 SemaRef.RequireLiteralType(
930 VD->getLocation(), VD->getType(),
931 diag::err_constexpr_local_var_non_literal_type,
932 isa<CXXConstructorDecl>(Dcl)))
934 if (!VD->getType()->isDependentType() &&
935 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
936 SemaRef.Diag(VD->getLocation(),
937 diag::err_constexpr_local_var_no_init)
938 << isa<CXXConstructorDecl>(Dcl);
942 SemaRef.Diag(VD->getLocation(),
943 SemaRef.getLangOpts().CPlusPlus14
944 ? diag::warn_cxx11_compat_constexpr_local_var
945 : diag::ext_constexpr_local_var)
946 << isa<CXXConstructorDecl>(Dcl);
950 case Decl::NamespaceAlias:
952 // These are disallowed in C++11 and permitted in C++1y. Allow them
953 // everywhere as an extension.
954 if (!Cxx1yLoc.isValid())
955 Cxx1yLoc = DS->getLocStart();
959 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960 << isa<CXXConstructorDecl>(Dcl);
968 /// Check that the given field is initialized within a constexpr constructor.
970 /// \param Dcl The constexpr constructor being checked.
971 /// \param Field The field being checked. This may be a member of an anonymous
972 /// struct or union nested within the class being checked.
973 /// \param Inits All declarations, including anonymous struct/union members and
974 /// indirect members, for which any initialization was provided.
975 /// \param Diagnosed Set to true if an error is produced.
976 static void CheckConstexprCtorInitializer(Sema &SemaRef,
977 const FunctionDecl *Dcl,
979 llvm::SmallSet<Decl*, 16> &Inits,
981 if (Field->isInvalidDecl())
984 if (Field->isUnnamedBitfield())
987 // Anonymous unions with no variant members and empty anonymous structs do not
988 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989 // indirect fields don't need initializing.
990 if (Field->isAnonymousStructOrUnion() &&
991 (Field->getType()->isUnionType()
992 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
993 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
996 if (!Inits.count(Field)) {
998 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1001 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002 } else if (Field->isAnonymousStructOrUnion()) {
1003 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1004 for (auto *I : RD->fields())
1005 // If an anonymous union contains an anonymous struct of which any member
1006 // is initialized, all members must be initialized.
1007 if (!RD->isUnion() || Inits.count(I))
1008 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1012 /// Check the provided statement is allowed in a constexpr function
1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1016 SmallVectorImpl<SourceLocation> &ReturnStmts,
1017 SourceLocation &Cxx1yLoc) {
1018 // - its function-body shall be [...] a compound-statement that contains only
1019 switch (S->getStmtClass()) {
1020 case Stmt::NullStmtClass:
1021 // - null statements,
1024 case Stmt::DeclStmtClass:
1025 // - static_assert-declarations
1026 // - using-declarations,
1027 // - using-directives,
1028 // - typedef declarations and alias-declarations that do not define
1029 // classes or enumerations,
1030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1034 case Stmt::ReturnStmtClass:
1035 // - and exactly one return statement;
1036 if (isa<CXXConstructorDecl>(Dcl)) {
1037 // C++1y allows return statements in constexpr constructors.
1038 if (!Cxx1yLoc.isValid())
1039 Cxx1yLoc = S->getLocStart();
1043 ReturnStmts.push_back(S->getLocStart());
1046 case Stmt::CompoundStmtClass: {
1047 // C++1y allows compound-statements.
1048 if (!Cxx1yLoc.isValid())
1049 Cxx1yLoc = S->getLocStart();
1051 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1052 for (auto *BodyIt : CompStmt->body()) {
1053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1060 case Stmt::AttributedStmtClass:
1061 if (!Cxx1yLoc.isValid())
1062 Cxx1yLoc = S->getLocStart();
1065 case Stmt::IfStmtClass: {
1066 // C++1y allows if-statements.
1067 if (!Cxx1yLoc.isValid())
1068 Cxx1yLoc = S->getLocStart();
1070 IfStmt *If = cast<IfStmt>(S);
1071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1074 if (If->getElse() &&
1075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1081 case Stmt::WhileStmtClass:
1082 case Stmt::DoStmtClass:
1083 case Stmt::ForStmtClass:
1084 case Stmt::CXXForRangeStmtClass:
1085 case Stmt::ContinueStmtClass:
1086 // C++1y allows all of these. We don't allow them as extensions in C++11,
1087 // because they don't make sense without variable mutation.
1088 if (!SemaRef.getLangOpts().CPlusPlus14)
1090 if (!Cxx1yLoc.isValid())
1091 Cxx1yLoc = S->getLocStart();
1092 for (Stmt *SubStmt : S->children())
1094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1099 case Stmt::SwitchStmtClass:
1100 case Stmt::CaseStmtClass:
1101 case Stmt::DefaultStmtClass:
1102 case Stmt::BreakStmtClass:
1103 // C++1y allows switch-statements, and since they don't need variable
1104 // mutation, we can reasonably allow them in C++11 as an extension.
1105 if (!Cxx1yLoc.isValid())
1106 Cxx1yLoc = S->getLocStart();
1107 for (Stmt *SubStmt : S->children())
1109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1118 // C++1y allows expression-statements.
1119 if (!Cxx1yLoc.isValid())
1120 Cxx1yLoc = S->getLocStart();
1124 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125 << isa<CXXConstructorDecl>(Dcl);
1129 /// Check the body for the given constexpr function declaration only contains
1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1132 /// \return true if the body is OK, false if we have diagnosed a problem.
1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1134 if (isa<CXXTryStmt>(Body)) {
1135 // C++11 [dcl.constexpr]p3:
1136 // The definition of a constexpr function shall satisfy the following
1137 // constraints: [...]
1138 // - its function-body shall be = delete, = default, or a
1139 // compound-statement
1141 // C++11 [dcl.constexpr]p4:
1142 // In the definition of a constexpr constructor, [...]
1143 // - its function-body shall not be a function-try-block;
1144 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145 << isa<CXXConstructorDecl>(Dcl);
1149 SmallVector<SourceLocation, 4> ReturnStmts;
1151 // - its function-body shall be [...] a compound-statement that contains only
1152 // [... list of cases ...]
1153 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154 SourceLocation Cxx1yLoc;
1155 for (auto *BodyIt : CompBody->body()) {
1156 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1160 if (Cxx1yLoc.isValid())
1162 getLangOpts().CPlusPlus14
1163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164 : diag::ext_constexpr_body_invalid_stmt)
1165 << isa<CXXConstructorDecl>(Dcl);
1167 if (const CXXConstructorDecl *Constructor
1168 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169 const CXXRecordDecl *RD = Constructor->getParent();
1171 // - every non-variant non-static data member and base class sub-object
1172 // shall be initialized;
1174 // - if the class is a union having variant members, exactly one of them
1175 // shall be initialized;
1176 if (RD->isUnion()) {
1177 if (Constructor->getNumCtorInitializers() == 0 &&
1178 RD->hasVariantMembers()) {
1179 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1182 } else if (!Constructor->isDependentContext() &&
1183 !Constructor->isDelegatingConstructor()) {
1184 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1186 // Skip detailed checking if we have enough initializers, and we would
1187 // allow at most one initializer per member.
1188 bool AnyAnonStructUnionMembers = false;
1189 unsigned Fields = 0;
1190 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1191 E = RD->field_end(); I != E; ++I, ++Fields) {
1192 if (I->isAnonymousStructOrUnion()) {
1193 AnyAnonStructUnionMembers = true;
1198 // - if the class is a union-like class, but is not a union, for each of
1199 // its anonymous union members having variant members, exactly one of
1200 // them shall be initialized;
1201 if (AnyAnonStructUnionMembers ||
1202 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203 // Check initialization of non-static data members. Base classes are
1204 // always initialized so do not need to be checked. Dependent bases
1205 // might not have initializers in the member initializer list.
1206 llvm::SmallSet<Decl*, 16> Inits;
1207 for (const auto *I: Constructor->inits()) {
1208 if (FieldDecl *FD = I->getMember())
1210 else if (IndirectFieldDecl *ID = I->getIndirectMember())
1211 Inits.insert(ID->chain_begin(), ID->chain_end());
1214 bool Diagnosed = false;
1215 for (auto *I : RD->fields())
1216 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1222 if (ReturnStmts.empty()) {
1223 // C++1y doesn't require constexpr functions to contain a 'return'
1224 // statement. We still do, unless the return type might be void, because
1225 // otherwise if there's no return statement, the function cannot
1226 // be used in a core constant expression.
1227 bool OK = getLangOpts().CPlusPlus14 &&
1228 (Dcl->getReturnType()->isVoidType() ||
1229 Dcl->getReturnType()->isDependentType());
1230 Diag(Dcl->getLocation(),
1231 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232 : diag::err_constexpr_body_no_return);
1235 } else if (ReturnStmts.size() > 1) {
1236 Diag(ReturnStmts.back(),
1237 getLangOpts().CPlusPlus14
1238 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239 : diag::ext_constexpr_body_multiple_return);
1240 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1245 // C++11 [dcl.constexpr]p5:
1246 // if no function argument values exist such that the function invocation
1247 // substitution would produce a constant expression, the program is
1248 // ill-formed; no diagnostic required.
1249 // C++11 [dcl.constexpr]p3:
1250 // - every constructor call and implicit conversion used in initializing the
1251 // return value shall be one of those allowed in a constant expression.
1252 // C++11 [dcl.constexpr]p4:
1253 // - every constructor involved in initializing non-static data members and
1254 // base class sub-objects shall be a constexpr constructor.
1255 SmallVector<PartialDiagnosticAt, 8> Diags;
1256 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1257 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1258 << isa<CXXConstructorDecl>(Dcl);
1259 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260 Diag(Diags[I].first, Diags[I].second);
1261 // Don't return false here: we allow this for compatibility in
1268 /// isCurrentClassName - Determine whether the identifier II is the
1269 /// name of the class type currently being defined. In the case of
1270 /// nested classes, this will only return true if II is the name of
1271 /// the innermost class.
1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1273 const CXXScopeSpec *SS) {
1274 assert(getLangOpts().CPlusPlus && "No class names in C!");
1276 CXXRecordDecl *CurDecl;
1277 if (SS && SS->isSet() && !SS->isInvalid()) {
1278 DeclContext *DC = computeDeclContext(*SS, true);
1279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1283 if (CurDecl && CurDecl->getIdentifier())
1284 return &II == CurDecl->getIdentifier();
1288 /// \brief Determine whether the identifier II is a typo for the name of
1289 /// the class type currently being defined. If so, update it to the identifier
1290 /// that should have been used.
1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1292 assert(getLangOpts().CPlusPlus && "No class names in C!");
1294 if (!getLangOpts().SpellChecking)
1297 CXXRecordDecl *CurDecl;
1298 if (SS && SS->isSet() && !SS->isInvalid()) {
1299 DeclContext *DC = computeDeclContext(*SS, true);
1300 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1304 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306 < II->getLength()) {
1307 II = CurDecl->getIdentifier();
1314 /// \brief Determine whether the given class is a base class of the given
1315 /// class, including looking at dependent bases.
1316 static bool findCircularInheritance(const CXXRecordDecl *Class,
1317 const CXXRecordDecl *Current) {
1318 SmallVector<const CXXRecordDecl*, 8> Queue;
1320 Class = Class->getCanonicalDecl();
1322 for (const auto &I : Current->bases()) {
1323 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1327 Base = Base->getDefinition();
1331 if (Base->getCanonicalDecl() == Class)
1334 Queue.push_back(Base);
1340 Current = Queue.pop_back_val();
1346 /// \brief Check the validity of a C++ base class specifier.
1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349 /// and returns NULL otherwise.
1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1352 SourceRange SpecifierRange,
1353 bool Virtual, AccessSpecifier Access,
1354 TypeSourceInfo *TInfo,
1355 SourceLocation EllipsisLoc) {
1356 QualType BaseType = TInfo->getType();
1358 // C++ [class.union]p1:
1359 // A union shall not have base classes.
1360 if (Class->isUnion()) {
1361 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1366 if (EllipsisLoc.isValid() &&
1367 !TInfo->getType()->containsUnexpandedParameterPack()) {
1368 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369 << TInfo->getTypeLoc().getSourceRange();
1370 EllipsisLoc = SourceLocation();
1373 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1375 if (BaseType->isDependentType()) {
1376 // Make sure that we don't have circular inheritance among our dependent
1377 // bases. For non-dependent bases, the check for completeness below handles
1379 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381 ((BaseDecl = BaseDecl->getDefinition()) &&
1382 findCircularInheritance(Class, BaseDecl))) {
1383 Diag(BaseLoc, diag::err_circular_inheritance)
1384 << BaseType << Context.getTypeDeclType(Class);
1386 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1394 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1395 Class->getTagKind() == TTK_Class,
1396 Access, TInfo, EllipsisLoc);
1399 // Base specifiers must be record types.
1400 if (!BaseType->isRecordType()) {
1401 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1405 // C++ [class.union]p1:
1406 // A union shall not be used as a base class.
1407 if (BaseType->isUnionType()) {
1408 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1412 // For the MS ABI, propagate DLL attributes to base class templates.
1413 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1414 if (Attr *ClassAttr = getDLLAttr(Class)) {
1415 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416 BaseType->getAsCXXRecordDecl())) {
1417 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1423 // C++ [class.derived]p2:
1424 // The class-name in a base-specifier shall not be an incompletely
1426 if (RequireCompleteType(BaseLoc, BaseType,
1427 diag::err_incomplete_base_class, SpecifierRange)) {
1428 Class->setInvalidDecl();
1432 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1433 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1434 assert(BaseDecl && "Record type has no declaration");
1435 BaseDecl = BaseDecl->getDefinition();
1436 assert(BaseDecl && "Base type is not incomplete, but has no definition");
1437 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1438 assert(CXXBaseDecl && "Base type is not a C++ type");
1440 // A class which contains a flexible array member is not suitable for use as a
1442 // - If the layout determines that a base comes before another base,
1443 // the flexible array member would index into the subsequent base.
1444 // - If the layout determines that base comes before the derived class,
1445 // the flexible array member would index into the derived class.
1446 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448 << CXXBaseDecl->getDeclName();
1453 // If a class is marked final and it appears as a base-type-specifier in
1454 // base-clause, the program is ill-formed.
1455 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1456 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1457 << CXXBaseDecl->getDeclName()
1458 << FA->isSpelledAsSealed();
1459 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460 << CXXBaseDecl->getDeclName() << FA->getRange();
1464 if (BaseDecl->isInvalidDecl())
1465 Class->setInvalidDecl();
1467 // Create the base specifier.
1468 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1469 Class->getTagKind() == TTK_Class,
1470 Access, TInfo, EllipsisLoc);
1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474 /// one entry in the base class list of a class specifier, for
1476 /// class foo : public bar, virtual private baz {
1477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1480 ParsedAttributes &Attributes,
1481 bool Virtual, AccessSpecifier Access,
1482 ParsedType basetype, SourceLocation BaseLoc,
1483 SourceLocation EllipsisLoc) {
1487 AdjustDeclIfTemplate(classdecl);
1488 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1492 // We haven't yet attached the base specifiers.
1493 Class->setIsParsingBaseSpecifiers();
1495 // We do not support any C++11 attributes on base-specifiers yet.
1496 // Diagnose any attributes we see.
1497 if (!Attributes.empty()) {
1498 for (AttributeList *Attr = Attributes.getList(); Attr;
1499 Attr = Attr->getNext()) {
1500 if (Attr->isInvalid() ||
1501 Attr->getKind() == AttributeList::IgnoredAttribute)
1503 Diag(Attr->getLoc(),
1504 Attr->getKind() == AttributeList::UnknownAttribute
1505 ? diag::warn_unknown_attribute_ignored
1506 : diag::err_base_specifier_attribute)
1511 TypeSourceInfo *TInfo = nullptr;
1512 GetTypeFromParser(basetype, &TInfo);
1514 if (EllipsisLoc.isInvalid() &&
1515 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1519 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1520 Virtual, Access, TInfo,
1524 Class->setInvalidDecl();
1529 /// Use small set to collect indirect bases. As this is only used
1530 /// locally, there's no need to abstract the small size parameter.
1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1533 /// \brief Recursively add the bases of Type. Don't add Type itself.
1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1536 const QualType &Type)
1538 // Even though the incoming type is a base, it might not be
1539 // a class -- it could be a template parm, for instance.
1540 if (auto Rec = Type->getAs<RecordType>()) {
1541 auto Decl = Rec->getAsCXXRecordDecl();
1543 // Iterate over its bases.
1544 for (const auto &BaseSpec : Decl->bases()) {
1545 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546 .getUnqualifiedType();
1547 if (Set.insert(Base).second)
1548 // If we've not already seen it, recurse.
1549 NoteIndirectBases(Context, Set, Base);
1554 /// \brief Performs the actual work of attaching the given base class
1555 /// specifiers to a C++ class.
1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
1557 MutableArrayRef<CXXBaseSpecifier *> Bases) {
1561 // Used to keep track of which base types we have already seen, so
1562 // that we can properly diagnose redundant direct base types. Note
1563 // that the key is always the unqualified canonical type of the base
1565 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1567 // Used to track indirect bases so we can see if a direct base is
1569 IndirectBaseSet IndirectBaseTypes;
1571 // Copy non-redundant base specifiers into permanent storage.
1572 unsigned NumGoodBases = 0;
1573 bool Invalid = false;
1574 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
1575 QualType NewBaseType
1576 = Context.getCanonicalType(Bases[idx]->getType());
1577 NewBaseType = NewBaseType.getLocalUnqualifiedType();
1579 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1581 // C++ [class.mi]p3:
1582 // A class shall not be specified as a direct base class of a
1583 // derived class more than once.
1584 Diag(Bases[idx]->getLocStart(),
1585 diag::err_duplicate_base_class)
1586 << KnownBase->getType()
1587 << Bases[idx]->getSourceRange();
1589 // Delete the duplicate base class specifier; we're going to
1590 // overwrite its pointer later.
1591 Context.Deallocate(Bases[idx]);
1595 // Okay, add this new base class.
1596 KnownBase = Bases[idx];
1597 Bases[NumGoodBases++] = Bases[idx];
1599 // Note this base's direct & indirect bases, if there could be ambiguity.
1600 if (Bases.size() > 1)
1601 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1603 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605 if (Class->isInterface() &&
1606 (!RD->isInterface() ||
1607 KnownBase->getAccessSpecifier() != AS_public)) {
1608 // The Microsoft extension __interface does not permit bases that
1609 // are not themselves public interfaces.
1610 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612 << RD->getSourceRange();
1615 if (RD->hasAttr<WeakAttr>())
1616 Class->addAttr(WeakAttr::CreateImplicit(Context));
1621 // Attach the remaining base class specifiers to the derived class.
1622 Class->setBases(Bases.data(), NumGoodBases);
1624 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625 // Check whether this direct base is inaccessible due to ambiguity.
1626 QualType BaseType = Bases[idx]->getType();
1627 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628 .getUnqualifiedType();
1630 if (IndirectBaseTypes.count(CanonicalBase)) {
1631 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632 /*DetectVirtual=*/true);
1634 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1638 if (Paths.isAmbiguous(CanonicalBase))
1639 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640 << BaseType << getAmbiguousPathsDisplayString(Paths)
1641 << Bases[idx]->getSourceRange();
1643 assert(Bases[idx]->isVirtual());
1646 // Delete the base class specifier, since its data has been copied
1647 // into the CXXRecordDecl.
1648 Context.Deallocate(Bases[idx]);
1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655 /// class, after checking whether there are any duplicate base
1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
1658 MutableArrayRef<CXXBaseSpecifier *> Bases) {
1659 if (!ClassDecl || Bases.empty())
1662 AdjustDeclIfTemplate(ClassDecl);
1663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
1666 /// \brief Determine whether the type \p Derived is a C++ class that is
1667 /// derived from the type \p Base.
1668 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
1669 if (!getLangOpts().CPlusPlus)
1672 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1676 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1680 // If either the base or the derived type is invalid, don't try to
1681 // check whether one is derived from the other.
1682 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1685 // FIXME: In a modules build, do we need the entire path to be visible for us
1686 // to be able to use the inheritance relationship?
1687 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1690 return DerivedRD->isDerivedFrom(BaseRD);
1693 /// \brief Determine whether the type \p Derived is a C++ class that is
1694 /// derived from the type \p Base.
1695 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
1696 CXXBasePaths &Paths) {
1697 if (!getLangOpts().CPlusPlus)
1700 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1704 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1708 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1711 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1714 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1715 CXXCastPath &BasePathArray) {
1716 assert(BasePathArray.empty() && "Base path array must be empty!");
1717 assert(Paths.isRecordingPaths() && "Must record paths!");
1719 const CXXBasePath &Path = Paths.front();
1721 // We first go backward and check if we have a virtual base.
1722 // FIXME: It would be better if CXXBasePath had the base specifier for
1723 // the nearest virtual base.
1725 for (unsigned I = Path.size(); I != 0; --I) {
1726 if (Path[I - 1].Base->isVirtual()) {
1732 // Now add all bases.
1733 for (unsigned I = Start, E = Path.size(); I != E; ++I)
1734 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1737 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1738 /// conversion (where Derived and Base are class types) is
1739 /// well-formed, meaning that the conversion is unambiguous (and
1740 /// that all of the base classes are accessible). Returns true
1741 /// and emits a diagnostic if the code is ill-formed, returns false
1742 /// otherwise. Loc is the location where this routine should point to
1743 /// if there is an error, and Range is the source range to highlight
1744 /// if there is an error.
1746 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1747 unsigned InaccessibleBaseID,
1748 unsigned AmbigiousBaseConvID,
1749 SourceLocation Loc, SourceRange Range,
1750 DeclarationName Name,
1751 CXXCastPath *BasePath) {
1752 // First, determine whether the path from Derived to Base is
1753 // ambiguous. This is slightly more expensive than checking whether
1754 // the Derived to Base conversion exists, because here we need to
1755 // explore multiple paths to determine if there is an ambiguity.
1756 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1757 /*DetectVirtual=*/false);
1758 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1759 assert(DerivationOkay &&
1760 "Can only be used with a derived-to-base conversion");
1761 (void)DerivationOkay;
1763 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1764 if (InaccessibleBaseID) {
1765 // Check that the base class can be accessed.
1766 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1767 InaccessibleBaseID)) {
1768 case AR_inaccessible:
1777 // Build a base path if necessary.
1779 BuildBasePathArray(Paths, *BasePath);
1783 if (AmbigiousBaseConvID) {
1784 // We know that the derived-to-base conversion is ambiguous, and
1785 // we're going to produce a diagnostic. Perform the derived-to-base
1786 // search just one more time to compute all of the possible paths so
1787 // that we can print them out. This is more expensive than any of
1788 // the previous derived-to-base checks we've done, but at this point
1789 // performance isn't as much of an issue.
1791 Paths.setRecordingPaths(true);
1792 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1793 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1796 // Build up a textual representation of the ambiguous paths, e.g.,
1797 // D -> B -> A, that will be used to illustrate the ambiguous
1798 // conversions in the diagnostic. We only print one of the paths
1799 // to each base class subobject.
1800 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1802 Diag(Loc, AmbigiousBaseConvID)
1803 << Derived << Base << PathDisplayStr << Range << Name;
1809 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1810 SourceLocation Loc, SourceRange Range,
1811 CXXCastPath *BasePath,
1812 bool IgnoreAccess) {
1813 return CheckDerivedToBaseConversion(Derived, Base,
1815 : diag::err_upcast_to_inaccessible_base,
1816 diag::err_ambiguous_derived_to_base_conv,
1817 Loc, Range, DeclarationName(),
1822 /// @brief Builds a string representing ambiguous paths from a
1823 /// specific derived class to different subobjects of the same base
1826 /// This function builds a string that can be used in error messages
1827 /// to show the different paths that one can take through the
1828 /// inheritance hierarchy to go from the derived class to different
1829 /// subobjects of a base class. The result looks something like this:
1831 /// struct D -> struct B -> struct A
1832 /// struct D -> struct C -> struct A
1834 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1835 std::string PathDisplayStr;
1836 std::set<unsigned> DisplayedPaths;
1837 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1838 Path != Paths.end(); ++Path) {
1839 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1840 // We haven't displayed a path to this particular base
1841 // class subobject yet.
1842 PathDisplayStr += "\n ";
1843 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1844 for (CXXBasePath::const_iterator Element = Path->begin();
1845 Element != Path->end(); ++Element)
1846 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1850 return PathDisplayStr;
1853 //===----------------------------------------------------------------------===//
1854 // C++ class member Handling
1855 //===----------------------------------------------------------------------===//
1857 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1858 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1859 SourceLocation ASLoc,
1860 SourceLocation ColonLoc,
1861 AttributeList *Attrs) {
1862 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1863 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1865 CurContext->addHiddenDecl(ASDecl);
1866 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1869 /// CheckOverrideControl - Check C++11 override control semantics.
1870 void Sema::CheckOverrideControl(NamedDecl *D) {
1871 if (D->isInvalidDecl())
1874 // We only care about "override" and "final" declarations.
1875 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1878 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1880 // We can't check dependent instance methods.
1881 if (MD && MD->isInstance() &&
1882 (MD->getParent()->hasAnyDependentBases() ||
1883 MD->getType()->isDependentType()))
1886 if (MD && !MD->isVirtual()) {
1887 // If we have a non-virtual method, check if if hides a virtual method.
1888 // (In that case, it's most likely the method has the wrong type.)
1889 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1890 FindHiddenVirtualMethods(MD, OverloadedMethods);
1892 if (!OverloadedMethods.empty()) {
1893 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1894 Diag(OA->getLocation(),
1895 diag::override_keyword_hides_virtual_member_function)
1896 << "override" << (OverloadedMethods.size() > 1);
1897 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1898 Diag(FA->getLocation(),
1899 diag::override_keyword_hides_virtual_member_function)
1900 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1901 << (OverloadedMethods.size() > 1);
1903 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1904 MD->setInvalidDecl();
1907 // Fall through into the general case diagnostic.
1908 // FIXME: We might want to attempt typo correction here.
1911 if (!MD || !MD->isVirtual()) {
1912 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1913 Diag(OA->getLocation(),
1914 diag::override_keyword_only_allowed_on_virtual_member_functions)
1915 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1916 D->dropAttr<OverrideAttr>();
1918 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1919 Diag(FA->getLocation(),
1920 diag::override_keyword_only_allowed_on_virtual_member_functions)
1921 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1922 << FixItHint::CreateRemoval(FA->getLocation());
1923 D->dropAttr<FinalAttr>();
1928 // C++11 [class.virtual]p5:
1929 // If a function is marked with the virt-specifier override and
1930 // does not override a member function of a base class, the program is
1932 bool HasOverriddenMethods =
1933 MD->begin_overridden_methods() != MD->end_overridden_methods();
1934 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1935 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1936 << MD->getDeclName();
1939 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1940 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1942 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1943 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1944 isa<CXXDestructorDecl>(MD))
1947 SourceLocation Loc = MD->getLocation();
1948 SourceLocation SpellingLoc = Loc;
1949 if (getSourceManager().isMacroArgExpansion(Loc))
1950 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1951 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1952 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1955 if (MD->size_overridden_methods() > 0) {
1956 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1957 << MD->getDeclName();
1958 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1959 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1963 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1964 /// function overrides a virtual member function marked 'final', according to
1965 /// C++11 [class.virtual]p4.
1966 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1967 const CXXMethodDecl *Old) {
1968 FinalAttr *FA = Old->getAttr<FinalAttr>();
1972 Diag(New->getLocation(), diag::err_final_function_overridden)
1973 << New->getDeclName()
1974 << FA->isSpelledAsSealed();
1975 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1979 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1980 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1981 // FIXME: Destruction of ObjC lifetime types has side-effects.
1982 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1983 return !RD->isCompleteDefinition() ||
1984 !RD->hasTrivialDefaultConstructor() ||
1985 !RD->hasTrivialDestructor();
1989 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1990 for (AttributeList *it = list; it != nullptr; it = it->getNext())
1991 if (it->isDeclspecPropertyAttribute())
1996 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1997 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1998 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1999 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2000 /// present (but parsing it has been deferred).
2002 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2003 MultiTemplateParamsArg TemplateParameterLists,
2004 Expr *BW, const VirtSpecifiers &VS,
2005 InClassInitStyle InitStyle) {
2006 const DeclSpec &DS = D.getDeclSpec();
2007 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2008 DeclarationName Name = NameInfo.getName();
2009 SourceLocation Loc = NameInfo.getLoc();
2011 // For anonymous bitfields, the location should point to the type.
2012 if (Loc.isInvalid())
2013 Loc = D.getLocStart();
2015 Expr *BitWidth = static_cast<Expr*>(BW);
2017 assert(isa<CXXRecordDecl>(CurContext));
2018 assert(!DS.isFriendSpecified());
2020 bool isFunc = D.isDeclarationOfFunction();
2022 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2023 // The Microsoft extension __interface only permits public member functions
2024 // and prohibits constructors, destructors, operators, non-public member
2025 // functions, static methods and data members.
2026 unsigned InvalidDecl;
2027 bool ShowDeclName = true;
2029 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2030 else if (AS != AS_public)
2032 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2034 else switch (Name.getNameKind()) {
2035 case DeclarationName::CXXConstructorName:
2037 ShowDeclName = false;
2040 case DeclarationName::CXXDestructorName:
2042 ShowDeclName = false;
2045 case DeclarationName::CXXOperatorName:
2046 case DeclarationName::CXXConversionFunctionName:
2057 Diag(Loc, diag::err_invalid_member_in_interface)
2058 << (InvalidDecl-1) << Name;
2060 Diag(Loc, diag::err_invalid_member_in_interface)
2061 << (InvalidDecl-1) << "";
2066 // C++ 9.2p6: A member shall not be declared to have automatic storage
2067 // duration (auto, register) or with the extern storage-class-specifier.
2068 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2069 // data members and cannot be applied to names declared const or static,
2070 // and cannot be applied to reference members.
2071 switch (DS.getStorageClassSpec()) {
2072 case DeclSpec::SCS_unspecified:
2073 case DeclSpec::SCS_typedef:
2074 case DeclSpec::SCS_static:
2076 case DeclSpec::SCS_mutable:
2078 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2080 // FIXME: It would be nicer if the keyword was ignored only for this
2081 // declarator. Otherwise we could get follow-up errors.
2082 D.getMutableDeclSpec().ClearStorageClassSpecs();
2086 Diag(DS.getStorageClassSpecLoc(),
2087 diag::err_storageclass_invalid_for_member);
2088 D.getMutableDeclSpec().ClearStorageClassSpecs();
2092 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2093 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2096 if (DS.isConstexprSpecified() && isInstField) {
2097 SemaDiagnosticBuilder B =
2098 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2099 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2100 if (InitStyle == ICIS_NoInit) {
2102 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2103 B << FixItHint::CreateRemoval(ConstexprLoc);
2105 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2106 D.getMutableDeclSpec().ClearConstexprSpec();
2107 const char *PrevSpec;
2109 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2110 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2112 assert(!Failed && "Making a constexpr member const shouldn't fail");
2116 const char *PrevSpec;
2118 if (D.getMutableDeclSpec().SetStorageClassSpec(
2119 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2120 Context.getPrintingPolicy())) {
2121 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2122 "This is the only DeclSpec that should fail to be applied");
2125 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2126 isInstField = false;
2133 CXXScopeSpec &SS = D.getCXXScopeSpec();
2135 // Data members must have identifiers for names.
2136 if (!Name.isIdentifier()) {
2137 Diag(Loc, diag::err_bad_variable_name)
2142 IdentifierInfo *II = Name.getAsIdentifierInfo();
2144 // Member field could not be with "template" keyword.
2145 // So TemplateParameterLists should be empty in this case.
2146 if (TemplateParameterLists.size()) {
2147 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2148 if (TemplateParams->size()) {
2149 // There is no such thing as a member field template.
2150 Diag(D.getIdentifierLoc(), diag::err_template_member)
2152 << SourceRange(TemplateParams->getTemplateLoc(),
2153 TemplateParams->getRAngleLoc());
2155 // There is an extraneous 'template<>' for this member.
2156 Diag(TemplateParams->getTemplateLoc(),
2157 diag::err_template_member_noparams)
2159 << SourceRange(TemplateParams->getTemplateLoc(),
2160 TemplateParams->getRAngleLoc());
2165 if (SS.isSet() && !SS.isInvalid()) {
2166 // The user provided a superfluous scope specifier inside a class
2172 if (DeclContext *DC = computeDeclContext(SS, false))
2173 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2175 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2176 << Name << SS.getRange();
2181 AttributeList *MSPropertyAttr =
2182 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2183 if (MSPropertyAttr) {
2184 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2185 BitWidth, InitStyle, AS, MSPropertyAttr);
2188 isInstField = false;
2190 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2191 BitWidth, InitStyle, AS);
2192 assert(Member && "HandleField never returns null");
2195 Member = HandleDeclarator(S, D, TemplateParameterLists);
2199 // Non-instance-fields can't have a bitfield.
2201 if (Member->isInvalidDecl()) {
2202 // don't emit another diagnostic.
2203 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2204 // C++ 9.6p3: A bit-field shall not be a static member.
2205 // "static member 'A' cannot be a bit-field"
2206 Diag(Loc, diag::err_static_not_bitfield)
2207 << Name << BitWidth->getSourceRange();
2208 } else if (isa<TypedefDecl>(Member)) {
2209 // "typedef member 'x' cannot be a bit-field"
2210 Diag(Loc, diag::err_typedef_not_bitfield)
2211 << Name << BitWidth->getSourceRange();
2213 // A function typedef ("typedef int f(); f a;").
2214 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2215 Diag(Loc, diag::err_not_integral_type_bitfield)
2216 << Name << cast<ValueDecl>(Member)->getType()
2217 << BitWidth->getSourceRange();
2221 Member->setInvalidDecl();
2224 Member->setAccess(AS);
2226 // If we have declared a member function template or static data member
2227 // template, set the access of the templated declaration as well.
2228 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2229 FunTmpl->getTemplatedDecl()->setAccess(AS);
2230 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2231 VarTmpl->getTemplatedDecl()->setAccess(AS);
2234 if (VS.isOverrideSpecified())
2235 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2236 if (VS.isFinalSpecified())
2237 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2238 VS.isFinalSpelledSealed()));
2240 if (VS.getLastLocation().isValid()) {
2241 // Update the end location of a method that has a virt-specifiers.
2242 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2243 MD->setRangeEnd(VS.getLastLocation());
2246 CheckOverrideControl(Member);
2248 assert((Name || isInstField) && "No identifier for non-field ?");
2251 FieldDecl *FD = cast<FieldDecl>(Member);
2252 FieldCollector->Add(FD);
2254 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2255 // Remember all explicit private FieldDecls that have a name, no side
2256 // effects and are not part of a dependent type declaration.
2257 if (!FD->isImplicit() && FD->getDeclName() &&
2258 FD->getAccess() == AS_private &&
2259 !FD->hasAttr<UnusedAttr>() &&
2260 !FD->getParent()->isDependentContext() &&
2261 !InitializationHasSideEffects(*FD))
2262 UnusedPrivateFields.insert(FD);
2270 class UninitializedFieldVisitor
2271 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2273 // List of Decls to generate a warning on. Also remove Decls that become
2275 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2276 // List of base classes of the record. Classes are removed after their
2278 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2279 // Vector of decls to be removed from the Decl set prior to visiting the
2280 // nodes. These Decls may have been initialized in the prior initializer.
2281 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2282 // If non-null, add a note to the warning pointing back to the constructor.
2283 const CXXConstructorDecl *Constructor;
2284 // Variables to hold state when processing an initializer list. When
2285 // InitList is true, special case initialization of FieldDecls matching
2286 // InitListFieldDecl.
2288 FieldDecl *InitListFieldDecl;
2289 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2292 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2293 UninitializedFieldVisitor(Sema &S,
2294 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2295 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2296 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2297 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2299 // Returns true if the use of ME is not an uninitialized use.
2300 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2301 bool CheckReferenceOnly) {
2302 llvm::SmallVector<FieldDecl*, 4> Fields;
2303 bool ReferenceField = false;
2305 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2308 Fields.push_back(FD);
2309 if (FD->getType()->isReferenceType())
2310 ReferenceField = true;
2311 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2314 // Binding a reference to an unintialized field is not an
2315 // uninitialized use.
2316 if (CheckReferenceOnly && !ReferenceField)
2319 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2320 // Discard the first field since it is the field decl that is being
2322 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2323 UsedFieldIndex.push_back((*I)->getFieldIndex());
2326 for (auto UsedIter = UsedFieldIndex.begin(),
2327 UsedEnd = UsedFieldIndex.end(),
2328 OrigIter = InitFieldIndex.begin(),
2329 OrigEnd = InitFieldIndex.end();
2330 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2331 if (*UsedIter < *OrigIter)
2333 if (*UsedIter > *OrigIter)
2340 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2342 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2345 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2347 MemberExpr *FieldME = ME;
2349 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2352 while (MemberExpr *SubME =
2353 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2355 if (isa<VarDecl>(SubME->getMemberDecl()))
2358 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2359 if (!FD->isAnonymousStructOrUnion())
2362 if (!FieldME->getType().isPODType(S.Context))
2363 AllPODFields = false;
2365 Base = SubME->getBase();
2368 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2371 if (AddressOf && AllPODFields)
2374 ValueDecl* FoundVD = FieldME->getMemberDecl();
2376 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2377 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2378 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2381 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2382 QualType T = BaseCast->getType();
2383 if (T->isPointerType() &&
2384 BaseClasses.count(T->getPointeeType())) {
2385 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2386 << T->getPointeeType() << FoundVD;
2391 if (!Decls.count(FoundVD))
2394 const bool IsReference = FoundVD->getType()->isReferenceType();
2396 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2397 // Special checking for initializer lists.
2398 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2402 // Prevent double warnings on use of unbounded references.
2403 if (CheckReferenceOnly && !IsReference)
2407 unsigned diag = IsReference
2408 ? diag::warn_reference_field_is_uninit
2409 : diag::warn_field_is_uninit;
2410 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2412 S.Diag(Constructor->getLocation(),
2413 diag::note_uninit_in_this_constructor)
2414 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2418 void HandleValue(Expr *E, bool AddressOf) {
2419 E = E->IgnoreParens();
2421 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2422 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2423 AddressOf /*AddressOf*/);
2427 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2428 Visit(CO->getCond());
2429 HandleValue(CO->getTrueExpr(), AddressOf);
2430 HandleValue(CO->getFalseExpr(), AddressOf);
2434 if (BinaryConditionalOperator *BCO =
2435 dyn_cast<BinaryConditionalOperator>(E)) {
2436 Visit(BCO->getCond());
2437 HandleValue(BCO->getFalseExpr(), AddressOf);
2441 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2442 HandleValue(OVE->getSourceExpr(), AddressOf);
2446 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2447 switch (BO->getOpcode()) {
2452 HandleValue(BO->getLHS(), AddressOf);
2453 Visit(BO->getRHS());
2456 Visit(BO->getLHS());
2457 HandleValue(BO->getRHS(), AddressOf);
2465 void CheckInitListExpr(InitListExpr *ILE) {
2466 InitFieldIndex.push_back(0);
2467 for (auto Child : ILE->children()) {
2468 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2469 CheckInitListExpr(SubList);
2473 ++InitFieldIndex.back();
2475 InitFieldIndex.pop_back();
2478 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2479 FieldDecl *Field, const Type *BaseClass) {
2480 // Remove Decls that may have been initialized in the previous
2482 for (ValueDecl* VD : DeclsToRemove)
2484 DeclsToRemove.clear();
2486 Constructor = FieldConstructor;
2487 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2491 InitListFieldDecl = Field;
2492 InitFieldIndex.clear();
2493 CheckInitListExpr(ILE);
2502 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2505 void VisitMemberExpr(MemberExpr *ME) {
2506 // All uses of unbounded reference fields will warn.
2507 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2510 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2511 if (E->getCastKind() == CK_LValueToRValue) {
2512 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2516 Inherited::VisitImplicitCastExpr(E);
2519 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2520 if (E->getConstructor()->isCopyConstructor()) {
2521 Expr *ArgExpr = E->getArg(0);
2522 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2523 if (ILE->getNumInits() == 1)
2524 ArgExpr = ILE->getInit(0);
2525 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2526 if (ICE->getCastKind() == CK_NoOp)
2527 ArgExpr = ICE->getSubExpr();
2528 HandleValue(ArgExpr, false /*AddressOf*/);
2531 Inherited::VisitCXXConstructExpr(E);
2534 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2535 Expr *Callee = E->getCallee();
2536 if (isa<MemberExpr>(Callee)) {
2537 HandleValue(Callee, false /*AddressOf*/);
2538 for (auto Arg : E->arguments())
2543 Inherited::VisitCXXMemberCallExpr(E);
2546 void VisitCallExpr(CallExpr *E) {
2547 // Treat std::move as a use.
2548 if (E->getNumArgs() == 1) {
2549 if (FunctionDecl *FD = E->getDirectCallee()) {
2550 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2551 FD->getIdentifier()->isStr("move")) {
2552 HandleValue(E->getArg(0), false /*AddressOf*/);
2558 Inherited::VisitCallExpr(E);
2561 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2562 Expr *Callee = E->getCallee();
2564 if (isa<UnresolvedLookupExpr>(Callee))
2565 return Inherited::VisitCXXOperatorCallExpr(E);
2568 for (auto Arg : E->arguments())
2569 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2572 void VisitBinaryOperator(BinaryOperator *E) {
2573 // If a field assignment is detected, remove the field from the
2574 // uninitiailized field set.
2575 if (E->getOpcode() == BO_Assign)
2576 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2577 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2578 if (!FD->getType()->isReferenceType())
2579 DeclsToRemove.push_back(FD);
2581 if (E->isCompoundAssignmentOp()) {
2582 HandleValue(E->getLHS(), false /*AddressOf*/);
2587 Inherited::VisitBinaryOperator(E);
2590 void VisitUnaryOperator(UnaryOperator *E) {
2591 if (E->isIncrementDecrementOp()) {
2592 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2595 if (E->getOpcode() == UO_AddrOf) {
2596 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2597 HandleValue(ME->getBase(), true /*AddressOf*/);
2602 Inherited::VisitUnaryOperator(E);
2606 // Diagnose value-uses of fields to initialize themselves, e.g.
2608 // where foo is not also a parameter to the constructor.
2609 // Also diagnose across field uninitialized use such as
2611 // TODO: implement -Wuninitialized and fold this into that framework.
2612 static void DiagnoseUninitializedFields(
2613 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2615 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2616 Constructor->getLocation())) {
2620 if (Constructor->isInvalidDecl())
2623 const CXXRecordDecl *RD = Constructor->getParent();
2625 if (RD->getDescribedClassTemplate())
2628 // Holds fields that are uninitialized.
2629 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2631 // At the beginning, all fields are uninitialized.
2632 for (auto *I : RD->decls()) {
2633 if (auto *FD = dyn_cast<FieldDecl>(I)) {
2634 UninitializedFields.insert(FD);
2635 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2636 UninitializedFields.insert(IFD->getAnonField());
2640 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2641 for (auto I : RD->bases())
2642 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2644 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2647 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2648 UninitializedFields,
2649 UninitializedBaseClasses);
2651 for (const auto *FieldInit : Constructor->inits()) {
2652 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2655 Expr *InitExpr = FieldInit->getInit();
2659 if (CXXDefaultInitExpr *Default =
2660 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2661 InitExpr = Default->getExpr();
2664 // In class initializers will point to the constructor.
2665 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2666 FieldInit->getAnyMember(),
2667 FieldInit->getBaseClass());
2669 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2670 FieldInit->getAnyMember(),
2671 FieldInit->getBaseClass());
2677 /// \brief Enter a new C++ default initializer scope. After calling this, the
2678 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2679 /// parsing or instantiating the initializer failed.
2680 void Sema::ActOnStartCXXInClassMemberInitializer() {
2681 // Create a synthetic function scope to represent the call to the constructor
2682 // that notionally surrounds a use of this initializer.
2683 PushFunctionScope();
2686 /// \brief This is invoked after parsing an in-class initializer for a
2687 /// non-static C++ class member, and after instantiating an in-class initializer
2688 /// in a class template. Such actions are deferred until the class is complete.
2689 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2690 SourceLocation InitLoc,
2692 // Pop the notional constructor scope we created earlier.
2693 PopFunctionScopeInfo(nullptr, D);
2695 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2696 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2697 "must set init style when field is created");
2700 D->setInvalidDecl();
2702 FD->removeInClassInitializer();
2706 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2707 FD->setInvalidDecl();
2708 FD->removeInClassInitializer();
2712 ExprResult Init = InitExpr;
2713 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2714 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2715 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2716 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2717 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2718 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2719 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2720 if (Init.isInvalid()) {
2721 FD->setInvalidDecl();
2726 // C++11 [class.base.init]p7:
2727 // The initialization of each base and member constitutes a
2729 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2730 if (Init.isInvalid()) {
2731 FD->setInvalidDecl();
2735 InitExpr = Init.get();
2737 FD->setInClassInitializer(InitExpr);
2740 /// \brief Find the direct and/or virtual base specifiers that
2741 /// correspond to the given base type, for use in base initialization
2742 /// within a constructor.
2743 static bool FindBaseInitializer(Sema &SemaRef,
2744 CXXRecordDecl *ClassDecl,
2746 const CXXBaseSpecifier *&DirectBaseSpec,
2747 const CXXBaseSpecifier *&VirtualBaseSpec) {
2748 // First, check for a direct base class.
2749 DirectBaseSpec = nullptr;
2750 for (const auto &Base : ClassDecl->bases()) {
2751 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2752 // We found a direct base of this type. That's what we're
2754 DirectBaseSpec = &Base;
2759 // Check for a virtual base class.
2760 // FIXME: We might be able to short-circuit this if we know in advance that
2761 // there are no virtual bases.
2762 VirtualBaseSpec = nullptr;
2763 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2764 // We haven't found a base yet; search the class hierarchy for a
2765 // virtual base class.
2766 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2767 /*DetectVirtual=*/false);
2768 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2769 SemaRef.Context.getTypeDeclType(ClassDecl),
2771 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2772 Path != Paths.end(); ++Path) {
2773 if (Path->back().Base->isVirtual()) {
2774 VirtualBaseSpec = Path->back().Base;
2781 return DirectBaseSpec || VirtualBaseSpec;
2784 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2786 Sema::ActOnMemInitializer(Decl *ConstructorD,
2789 IdentifierInfo *MemberOrBase,
2790 ParsedType TemplateTypeTy,
2792 SourceLocation IdLoc,
2794 SourceLocation EllipsisLoc) {
2795 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2796 DS, IdLoc, InitList,
2800 /// \brief Handle a C++ member initializer using parentheses syntax.
2802 Sema::ActOnMemInitializer(Decl *ConstructorD,
2805 IdentifierInfo *MemberOrBase,
2806 ParsedType TemplateTypeTy,
2808 SourceLocation IdLoc,
2809 SourceLocation LParenLoc,
2810 ArrayRef<Expr *> Args,
2811 SourceLocation RParenLoc,
2812 SourceLocation EllipsisLoc) {
2813 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2815 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2816 DS, IdLoc, List, EllipsisLoc);
2821 // Callback to only accept typo corrections that can be a valid C++ member
2822 // intializer: either a non-static field member or a base class.
2823 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2825 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2826 : ClassDecl(ClassDecl) {}
2828 bool ValidateCandidate(const TypoCorrection &candidate) override {
2829 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2830 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2831 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2832 return isa<TypeDecl>(ND);
2838 CXXRecordDecl *ClassDecl;
2843 /// \brief Handle a C++ member initializer.
2845 Sema::BuildMemInitializer(Decl *ConstructorD,
2848 IdentifierInfo *MemberOrBase,
2849 ParsedType TemplateTypeTy,
2851 SourceLocation IdLoc,
2853 SourceLocation EllipsisLoc) {
2854 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2855 if (!Res.isUsable())
2862 AdjustDeclIfTemplate(ConstructorD);
2864 CXXConstructorDecl *Constructor
2865 = dyn_cast<CXXConstructorDecl>(ConstructorD);
2867 // The user wrote a constructor initializer on a function that is
2868 // not a C++ constructor. Ignore the error for now, because we may
2869 // have more member initializers coming; we'll diagnose it just
2870 // once in ActOnMemInitializers.
2874 CXXRecordDecl *ClassDecl = Constructor->getParent();
2876 // C++ [class.base.init]p2:
2877 // Names in a mem-initializer-id are looked up in the scope of the
2878 // constructor's class and, if not found in that scope, are looked
2879 // up in the scope containing the constructor's definition.
2880 // [Note: if the constructor's class contains a member with the
2881 // same name as a direct or virtual base class of the class, a
2882 // mem-initializer-id naming the member or base class and composed
2883 // of a single identifier refers to the class member. A
2884 // mem-initializer-id for the hidden base class may be specified
2885 // using a qualified name. ]
2886 if (!SS.getScopeRep() && !TemplateTypeTy) {
2887 // Look for a member, first.
2888 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2889 if (!Result.empty()) {
2891 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2892 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2893 if (EllipsisLoc.isValid())
2894 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2896 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2898 return BuildMemberInitializer(Member, Init, IdLoc);
2902 // It didn't name a member, so see if it names a class.
2904 TypeSourceInfo *TInfo = nullptr;
2906 if (TemplateTypeTy) {
2907 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2908 } else if (DS.getTypeSpecType() == TST_decltype) {
2909 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2911 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2912 LookupParsedName(R, S, &SS);
2914 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2916 if (R.isAmbiguous()) return true;
2918 // We don't want access-control diagnostics here.
2919 R.suppressDiagnostics();
2921 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2922 bool NotUnknownSpecialization = false;
2923 DeclContext *DC = computeDeclContext(SS, false);
2924 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2925 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2927 if (!NotUnknownSpecialization) {
2928 // When the scope specifier can refer to a member of an unknown
2929 // specialization, we take it as a type name.
2930 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2931 SS.getWithLocInContext(Context),
2932 *MemberOrBase, IdLoc);
2933 if (BaseType.isNull())
2937 R.setLookupName(MemberOrBase);
2941 // If no results were found, try to correct typos.
2942 TypoCorrection Corr;
2943 if (R.empty() && BaseType.isNull() &&
2944 (Corr = CorrectTypo(
2945 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2946 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2947 CTK_ErrorRecovery, ClassDecl))) {
2948 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2949 // We have found a non-static data member with a similar
2950 // name to what was typed; complain and initialize that
2953 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2954 << MemberOrBase << true);
2955 return BuildMemberInitializer(Member, Init, IdLoc);
2956 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2957 const CXXBaseSpecifier *DirectBaseSpec;
2958 const CXXBaseSpecifier *VirtualBaseSpec;
2959 if (FindBaseInitializer(*this, ClassDecl,
2960 Context.getTypeDeclType(Type),
2961 DirectBaseSpec, VirtualBaseSpec)) {
2962 // We have found a direct or virtual base class with a
2963 // similar name to what was typed; complain and initialize
2966 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2967 << MemberOrBase << false,
2968 PDiag() /*Suppress note, we provide our own.*/);
2970 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2972 Diag(BaseSpec->getLocStart(),
2973 diag::note_base_class_specified_here)
2974 << BaseSpec->getType()
2975 << BaseSpec->getSourceRange();
2982 if (!TyD && BaseType.isNull()) {
2983 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2984 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2989 if (BaseType.isNull()) {
2990 BaseType = Context.getTypeDeclType(TyD);
2991 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2993 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2995 TInfo = Context.CreateTypeSourceInfo(BaseType);
2996 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
2997 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
2998 TL.setElaboratedKeywordLoc(SourceLocation());
2999 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3005 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3007 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3010 /// Checks a member initializer expression for cases where reference (or
3011 /// pointer) members are bound to by-value parameters (or their addresses).
3012 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3014 SourceLocation IdLoc) {
3015 QualType MemberTy = Member->getType();
3017 // We only handle pointers and references currently.
3018 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3019 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3022 const bool IsPointer = MemberTy->isPointerType();
3024 if (const UnaryOperator *Op
3025 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3026 // The only case we're worried about with pointers requires taking the
3028 if (Op->getOpcode() != UO_AddrOf)
3031 Init = Op->getSubExpr();
3033 // We only handle address-of expression initializers for pointers.
3038 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3039 // We only warn when referring to a non-reference parameter declaration.
3040 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3041 if (!Parameter || Parameter->getType()->isReferenceType())
3044 S.Diag(Init->getExprLoc(),
3045 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3046 : diag::warn_bind_ref_member_to_parameter)
3047 << Member << Parameter << Init->getSourceRange();
3049 // Other initializers are fine.
3053 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3054 << (unsigned)IsPointer;
3058 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3059 SourceLocation IdLoc) {
3060 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3061 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3062 assert((DirectMember || IndirectMember) &&
3063 "Member must be a FieldDecl or IndirectFieldDecl");
3065 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3068 if (Member->isInvalidDecl())
3072 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3073 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3074 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3075 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3077 // Template instantiation doesn't reconstruct ParenListExprs for us.
3081 SourceRange InitRange = Init->getSourceRange();
3083 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3084 // Can't check initialization for a member of dependent type or when
3085 // any of the arguments are type-dependent expressions.
3086 DiscardCleanupsInEvaluationContext();
3088 bool InitList = false;
3089 if (isa<InitListExpr>(Init)) {
3094 // Initialize the member.
3095 InitializedEntity MemberEntity =
3096 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3097 : InitializedEntity::InitializeMember(IndirectMember,
3099 InitializationKind Kind =
3100 InitList ? InitializationKind::CreateDirectList(IdLoc)
3101 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3102 InitRange.getEnd());
3104 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3105 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3107 if (MemberInit.isInvalid())
3110 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3112 // C++11 [class.base.init]p7:
3113 // The initialization of each base and member constitutes a
3115 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3116 if (MemberInit.isInvalid())
3119 Init = MemberInit.get();
3123 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3124 InitRange.getBegin(), Init,
3125 InitRange.getEnd());
3127 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3128 InitRange.getBegin(), Init,
3129 InitRange.getEnd());
3134 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3135 CXXRecordDecl *ClassDecl) {
3136 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3137 if (!LangOpts.CPlusPlus11)
3138 return Diag(NameLoc, diag::err_delegating_ctor)
3139 << TInfo->getTypeLoc().getLocalSourceRange();
3140 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3142 bool InitList = true;
3143 MultiExprArg Args = Init;
3144 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3146 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3149 SourceRange InitRange = Init->getSourceRange();
3150 // Initialize the object.
3151 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3152 QualType(ClassDecl->getTypeForDecl(), 0));
3153 InitializationKind Kind =
3154 InitList ? InitializationKind::CreateDirectList(NameLoc)
3155 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3156 InitRange.getEnd());
3157 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3158 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3160 if (DelegationInit.isInvalid())
3163 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3164 "Delegating constructor with no target?");
3166 // C++11 [class.base.init]p7:
3167 // The initialization of each base and member constitutes a
3169 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3170 InitRange.getBegin());
3171 if (DelegationInit.isInvalid())
3174 // If we are in a dependent context, template instantiation will
3175 // perform this type-checking again. Just save the arguments that we
3176 // received in a ParenListExpr.
3177 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3178 // of the information that we have about the base
3179 // initializer. However, deconstructing the ASTs is a dicey process,
3180 // and this approach is far more likely to get the corner cases right.
3181 if (CurContext->isDependentContext())
3182 DelegationInit = Init;
3184 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3185 DelegationInit.getAs<Expr>(),
3186 InitRange.getEnd());
3190 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3191 Expr *Init, CXXRecordDecl *ClassDecl,
3192 SourceLocation EllipsisLoc) {
3193 SourceLocation BaseLoc
3194 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3196 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3197 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3198 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3200 // C++ [class.base.init]p2:
3201 // [...] Unless the mem-initializer-id names a nonstatic data
3202 // member of the constructor's class or a direct or virtual base
3203 // of that class, the mem-initializer is ill-formed. A
3204 // mem-initializer-list can initialize a base class using any
3205 // name that denotes that base class type.
3206 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3208 SourceRange InitRange = Init->getSourceRange();
3209 if (EllipsisLoc.isValid()) {
3210 // This is a pack expansion.
3211 if (!BaseType->containsUnexpandedParameterPack()) {
3212 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3213 << SourceRange(BaseLoc, InitRange.getEnd());
3215 EllipsisLoc = SourceLocation();
3218 // Check for any unexpanded parameter packs.
3219 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3222 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3226 // Check for direct and virtual base classes.
3227 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3228 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3230 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3232 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3234 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3237 // C++ [base.class.init]p2:
3238 // Unless the mem-initializer-id names a nonstatic data member of the
3239 // constructor's class or a direct or virtual base of that class, the
3240 // mem-initializer is ill-formed.
3241 if (!DirectBaseSpec && !VirtualBaseSpec) {
3242 // If the class has any dependent bases, then it's possible that
3243 // one of those types will resolve to the same type as
3244 // BaseType. Therefore, just treat this as a dependent base
3245 // class initialization. FIXME: Should we try to check the
3246 // initialization anyway? It seems odd.
3247 if (ClassDecl->hasAnyDependentBases())
3250 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3251 << BaseType << Context.getTypeDeclType(ClassDecl)
3252 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3257 DiscardCleanupsInEvaluationContext();
3259 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3260 /*IsVirtual=*/false,
3261 InitRange.getBegin(), Init,
3262 InitRange.getEnd(), EllipsisLoc);
3265 // C++ [base.class.init]p2:
3266 // If a mem-initializer-id is ambiguous because it designates both
3267 // a direct non-virtual base class and an inherited virtual base
3268 // class, the mem-initializer is ill-formed.
3269 if (DirectBaseSpec && VirtualBaseSpec)
3270 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3271 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3275 BaseSpec = VirtualBaseSpec;
3277 // Initialize the base.
3278 bool InitList = true;
3279 MultiExprArg Args = Init;
3280 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3282 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3285 InitializedEntity BaseEntity =
3286 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3287 InitializationKind Kind =
3288 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3289 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3290 InitRange.getEnd());
3291 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3292 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3293 if (BaseInit.isInvalid())
3296 // C++11 [class.base.init]p7:
3297 // The initialization of each base and member constitutes a
3299 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3300 if (BaseInit.isInvalid())
3303 // If we are in a dependent context, template instantiation will
3304 // perform this type-checking again. Just save the arguments that we
3305 // received in a ParenListExpr.
3306 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3307 // of the information that we have about the base
3308 // initializer. However, deconstructing the ASTs is a dicey process,
3309 // and this approach is far more likely to get the corner cases right.
3310 if (CurContext->isDependentContext())
3313 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3314 BaseSpec->isVirtual(),
3315 InitRange.getBegin(),
3316 BaseInit.getAs<Expr>(),
3317 InitRange.getEnd(), EllipsisLoc);
3320 // Create a static_cast\<T&&>(expr).
3321 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3322 if (T.isNull()) T = E->getType();
3323 QualType TargetType = SemaRef.BuildReferenceType(
3324 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3325 SourceLocation ExprLoc = E->getLocStart();
3326 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3327 TargetType, ExprLoc);
3329 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3330 SourceRange(ExprLoc, ExprLoc),
3331 E->getSourceRange()).get();
3334 /// ImplicitInitializerKind - How an implicit base or member initializer should
3335 /// initialize its base or member.
3336 enum ImplicitInitializerKind {
3344 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3345 ImplicitInitializerKind ImplicitInitKind,
3346 CXXBaseSpecifier *BaseSpec,
3347 bool IsInheritedVirtualBase,
3348 CXXCtorInitializer *&CXXBaseInit) {
3349 InitializedEntity InitEntity
3350 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3351 IsInheritedVirtualBase);
3353 ExprResult BaseInit;
3355 switch (ImplicitInitKind) {
3357 const CXXRecordDecl *Inherited =
3358 Constructor->getInheritedConstructor()->getParent();
3359 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3360 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3361 // C++11 [class.inhctor]p8:
3362 // Each expression in the expression-list is of the form
3363 // static_cast<T&&>(p), where p is the name of the corresponding
3364 // constructor parameter and T is the declared type of p.
3365 SmallVector<Expr*, 16> Args;
3366 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3367 ParmVarDecl *PD = Constructor->getParamDecl(I);
3368 ExprResult ArgExpr =
3369 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3370 VK_LValue, SourceLocation());
3371 if (ArgExpr.isInvalid())
3373 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3376 InitializationKind InitKind = InitializationKind::CreateDirect(
3377 Constructor->getLocation(), SourceLocation(), SourceLocation());
3378 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3379 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3385 InitializationKind InitKind
3386 = InitializationKind::CreateDefault(Constructor->getLocation());
3387 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3388 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3394 bool Moving = ImplicitInitKind == IIK_Move;
3395 ParmVarDecl *Param = Constructor->getParamDecl(0);
3396 QualType ParamType = Param->getType().getNonReferenceType();
3399 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3400 SourceLocation(), Param, false,
3401 Constructor->getLocation(), ParamType,
3402 VK_LValue, nullptr);
3404 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3406 // Cast to the base class to avoid ambiguities.
3408 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3409 ParamType.getQualifiers());
3412 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3415 CXXCastPath BasePath;
3416 BasePath.push_back(BaseSpec);
3417 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3418 CK_UncheckedDerivedToBase,
3419 Moving ? VK_XValue : VK_LValue,
3422 InitializationKind InitKind
3423 = InitializationKind::CreateDirect(Constructor->getLocation(),
3424 SourceLocation(), SourceLocation());
3425 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3426 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3431 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3432 if (BaseInit.isInvalid())
3436 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3437 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3439 BaseSpec->isVirtual(),
3441 BaseInit.getAs<Expr>(),
3448 static bool RefersToRValueRef(Expr *MemRef) {
3449 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3450 return Referenced->getType()->isRValueReferenceType();
3454 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3455 ImplicitInitializerKind ImplicitInitKind,
3456 FieldDecl *Field, IndirectFieldDecl *Indirect,
3457 CXXCtorInitializer *&CXXMemberInit) {
3458 if (Field->isInvalidDecl())
3461 SourceLocation Loc = Constructor->getLocation();
3463 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3464 bool Moving = ImplicitInitKind == IIK_Move;
3465 ParmVarDecl *Param = Constructor->getParamDecl(0);
3466 QualType ParamType = Param->getType().getNonReferenceType();
3468 // Suppress copying zero-width bitfields.
3469 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3472 Expr *MemberExprBase =
3473 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3474 SourceLocation(), Param, false,
3475 Loc, ParamType, VK_LValue, nullptr);
3477 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3480 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3483 // Build a reference to this field within the parameter.
3485 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3486 Sema::LookupMemberName);
3487 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3488 : cast<ValueDecl>(Field), AS_public);
3489 MemberLookup.resolveKind();
3491 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3495 /*TemplateKWLoc=*/SourceLocation(),
3496 /*FirstQualifierInScope=*/nullptr,
3498 /*TemplateArgs=*/nullptr,
3500 if (CtorArg.isInvalid())
3503 // C++11 [class.copy]p15:
3504 // - if a member m has rvalue reference type T&&, it is direct-initialized
3505 // with static_cast<T&&>(x.m);
3506 if (RefersToRValueRef(CtorArg.get())) {
3507 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3510 // When the field we are copying is an array, create index variables for
3511 // each dimension of the array. We use these index variables to subscript
3512 // the source array, and other clients (e.g., CodeGen) will perform the
3513 // necessary iteration with these index variables.
3514 SmallVector<VarDecl *, 4> IndexVariables;
3515 QualType BaseType = Field->getType();
3516 QualType SizeType = SemaRef.Context.getSizeType();
3517 bool InitializingArray = false;
3518 while (const ConstantArrayType *Array
3519 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3520 InitializingArray = true;
3521 // Create the iteration variable for this array index.
3522 IdentifierInfo *IterationVarName = nullptr;
3525 llvm::raw_svector_ostream OS(Str);
3526 OS << "__i" << IndexVariables.size();
3527 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3529 VarDecl *IterationVar
3530 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3531 IterationVarName, SizeType,
3532 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3534 IndexVariables.push_back(IterationVar);
3536 // Create a reference to the iteration variable.
3537 ExprResult IterationVarRef
3538 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3539 assert(!IterationVarRef.isInvalid() &&
3540 "Reference to invented variable cannot fail!");
3541 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3542 assert(!IterationVarRef.isInvalid() &&
3543 "Conversion of invented variable cannot fail!");
3545 // Subscript the array with this iteration variable.
3546 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3547 IterationVarRef.get(),
3549 if (CtorArg.isInvalid())
3552 BaseType = Array->getElementType();
3555 // The array subscript expression is an lvalue, which is wrong for moving.
3556 if (Moving && InitializingArray)
3557 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3559 // Construct the entity that we will be initializing. For an array, this
3560 // will be first element in the array, which may require several levels
3561 // of array-subscript entities.
3562 SmallVector<InitializedEntity, 4> Entities;
3563 Entities.reserve(1 + IndexVariables.size());
3565 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3567 Entities.push_back(InitializedEntity::InitializeMember(Field));
3568 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3569 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3573 // Direct-initialize to use the copy constructor.
3574 InitializationKind InitKind =
3575 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3577 Expr *CtorArgE = CtorArg.getAs<Expr>();
3578 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3581 ExprResult MemberInit
3582 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3583 MultiExprArg(&CtorArgE, 1));
3584 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3585 if (MemberInit.isInvalid())
3589 assert(IndexVariables.size() == 0 &&
3590 "Indirect field improperly initialized");
3592 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3594 MemberInit.getAs<Expr>(),
3597 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3598 Loc, MemberInit.getAs<Expr>(),
3600 IndexVariables.data(),
3601 IndexVariables.size());
3605 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3606 "Unhandled implicit init kind!");
3608 QualType FieldBaseElementType =
3609 SemaRef.Context.getBaseElementType(Field->getType());
3611 if (FieldBaseElementType->isRecordType()) {
3612 InitializedEntity InitEntity
3613 = Indirect? InitializedEntity::InitializeMember(Indirect)
3614 : InitializedEntity::InitializeMember(Field);
3615 InitializationKind InitKind =
3616 InitializationKind::CreateDefault(Loc);
3618 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3619 ExprResult MemberInit =
3620 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3622 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3623 if (MemberInit.isInvalid())
3627 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3633 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3640 if (!Field->getParent()->isUnion()) {
3641 if (FieldBaseElementType->isReferenceType()) {
3642 SemaRef.Diag(Constructor->getLocation(),
3643 diag::err_uninitialized_member_in_ctor)
3644 << (int)Constructor->isImplicit()
3645 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3646 << 0 << Field->getDeclName();
3647 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3651 if (FieldBaseElementType.isConstQualified()) {
3652 SemaRef.Diag(Constructor->getLocation(),
3653 diag::err_uninitialized_member_in_ctor)
3654 << (int)Constructor->isImplicit()
3655 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3656 << 1 << Field->getDeclName();
3657 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3662 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3663 FieldBaseElementType->isObjCRetainableType() &&
3664 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3665 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3667 // Default-initialize Objective-C pointers to NULL.
3669 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3671 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3676 // Nothing to initialize.
3677 CXXMemberInit = nullptr;
3682 struct BaseAndFieldInfo {
3684 CXXConstructorDecl *Ctor;
3685 bool AnyErrorsInInits;
3686 ImplicitInitializerKind IIK;
3687 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3688 SmallVector<CXXCtorInitializer*, 8> AllToInit;
3689 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3691 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3692 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3693 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3694 if (Generated && Ctor->isCopyConstructor())
3696 else if (Generated && Ctor->isMoveConstructor())
3698 else if (Ctor->getInheritedConstructor())
3704 bool isImplicitCopyOrMove() const {
3715 llvm_unreachable("Invalid ImplicitInitializerKind!");
3718 bool addFieldInitializer(CXXCtorInitializer *Init) {
3719 AllToInit.push_back(Init);
3721 // Check whether this initializer makes the field "used".
3722 if (Init->getInit()->HasSideEffects(S.Context))
3723 S.UnusedPrivateFields.remove(Init->getAnyMember());
3728 bool isInactiveUnionMember(FieldDecl *Field) {
3729 RecordDecl *Record = Field->getParent();
3730 if (!Record->isUnion())
3733 if (FieldDecl *Active =
3734 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3735 return Active != Field->getCanonicalDecl();
3737 // In an implicit copy or move constructor, ignore any in-class initializer.
3738 if (isImplicitCopyOrMove())
3741 // If there's no explicit initialization, the field is active only if it
3742 // has an in-class initializer...
3743 if (Field->hasInClassInitializer())
3745 // ... or it's an anonymous struct or union whose class has an in-class
3747 if (!Field->isAnonymousStructOrUnion())
3749 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3750 return !FieldRD->hasInClassInitializer();
3753 /// \brief Determine whether the given field is, or is within, a union member
3754 /// that is inactive (because there was an initializer given for a different
3755 /// member of the union, or because the union was not initialized at all).
3756 bool isWithinInactiveUnionMember(FieldDecl *Field,
3757 IndirectFieldDecl *Indirect) {
3759 return isInactiveUnionMember(Field);
3761 for (auto *C : Indirect->chain()) {
3762 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3763 if (Field && isInactiveUnionMember(Field))
3771 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3773 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3774 if (T->isIncompleteArrayType())
3777 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3778 if (!ArrayT->getSize())
3781 T = ArrayT->getElementType();
3787 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3789 IndirectFieldDecl *Indirect = nullptr) {
3790 if (Field->isInvalidDecl())
3793 // Overwhelmingly common case: we have a direct initializer for this field.
3794 if (CXXCtorInitializer *Init =
3795 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3796 return Info.addFieldInitializer(Init);
3798 // C++11 [class.base.init]p8:
3799 // if the entity is a non-static data member that has a
3800 // brace-or-equal-initializer and either
3801 // -- the constructor's class is a union and no other variant member of that
3802 // union is designated by a mem-initializer-id or
3803 // -- the constructor's class is not a union, and, if the entity is a member
3804 // of an anonymous union, no other member of that union is designated by
3805 // a mem-initializer-id,
3806 // the entity is initialized as specified in [dcl.init].
3808 // We also apply the same rules to handle anonymous structs within anonymous
3810 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3813 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3815 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3816 if (DIE.isInvalid())
3818 CXXCtorInitializer *Init;
3820 Init = new (SemaRef.Context)
3821 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3822 SourceLocation(), DIE.get(), SourceLocation());
3824 Init = new (SemaRef.Context)
3825 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3826 SourceLocation(), DIE.get(), SourceLocation());
3827 return Info.addFieldInitializer(Init);
3830 // Don't initialize incomplete or zero-length arrays.
3831 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3834 // Don't try to build an implicit initializer if there were semantic
3835 // errors in any of the initializers (and therefore we might be
3836 // missing some that the user actually wrote).
3837 if (Info.AnyErrorsInInits)
3840 CXXCtorInitializer *Init = nullptr;
3841 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3848 return Info.addFieldInitializer(Init);
3852 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3853 CXXCtorInitializer *Initializer) {
3854 assert(Initializer->isDelegatingInitializer());
3855 Constructor->setNumCtorInitializers(1);
3856 CXXCtorInitializer **initializer =
3857 new (Context) CXXCtorInitializer*[1];
3858 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3859 Constructor->setCtorInitializers(initializer);
3861 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3862 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3863 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3866 DelegatingCtorDecls.push_back(Constructor);
3868 DiagnoseUninitializedFields(*this, Constructor);
3873 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3874 ArrayRef<CXXCtorInitializer *> Initializers) {
3875 if (Constructor->isDependentContext()) {
3876 // Just store the initializers as written, they will be checked during
3878 if (!Initializers.empty()) {
3879 Constructor->setNumCtorInitializers(Initializers.size());
3880 CXXCtorInitializer **baseOrMemberInitializers =
3881 new (Context) CXXCtorInitializer*[Initializers.size()];
3882 memcpy(baseOrMemberInitializers, Initializers.data(),
3883 Initializers.size() * sizeof(CXXCtorInitializer*));
3884 Constructor->setCtorInitializers(baseOrMemberInitializers);
3887 // Let template instantiation know whether we had errors.
3889 Constructor->setInvalidDecl();
3894 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3896 // We need to build the initializer AST according to order of construction
3897 // and not what user specified in the Initializers list.
3898 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3902 bool HadError = false;
3904 for (unsigned i = 0; i < Initializers.size(); i++) {
3905 CXXCtorInitializer *Member = Initializers[i];
3907 if (Member->isBaseInitializer())
3908 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3910 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3912 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3913 for (auto *C : F->chain()) {
3914 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3915 if (FD && FD->getParent()->isUnion())
3916 Info.ActiveUnionMember.insert(std::make_pair(
3917 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3919 } else if (FieldDecl *FD = Member->getMember()) {
3920 if (FD->getParent()->isUnion())
3921 Info.ActiveUnionMember.insert(std::make_pair(
3922 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3927 // Keep track of the direct virtual bases.
3928 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3929 for (auto &I : ClassDecl->bases()) {
3931 DirectVBases.insert(&I);
3934 // Push virtual bases before others.
3935 for (auto &VBase : ClassDecl->vbases()) {
3936 if (CXXCtorInitializer *Value
3937 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3938 // [class.base.init]p7, per DR257:
3939 // A mem-initializer where the mem-initializer-id names a virtual base
3940 // class is ignored during execution of a constructor of any class that
3941 // is not the most derived class.
3942 if (ClassDecl->isAbstract()) {
3943 // FIXME: Provide a fixit to remove the base specifier. This requires
3944 // tracking the location of the associated comma for a base specifier.
3945 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3946 << VBase.getType() << ClassDecl;
3947 DiagnoseAbstractType(ClassDecl);
3950 Info.AllToInit.push_back(Value);
3951 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3952 // [class.base.init]p8, per DR257:
3953 // If a given [...] base class is not named by a mem-initializer-id
3954 // [...] and the entity is not a virtual base class of an abstract
3955 // class, then [...] the entity is default-initialized.
3956 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3957 CXXCtorInitializer *CXXBaseInit;
3958 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3959 &VBase, IsInheritedVirtualBase,
3965 Info.AllToInit.push_back(CXXBaseInit);
3969 // Non-virtual bases.
3970 for (auto &Base : ClassDecl->bases()) {
3971 // Virtuals are in the virtual base list and already constructed.
3972 if (Base.isVirtual())
3975 if (CXXCtorInitializer *Value
3976 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3977 Info.AllToInit.push_back(Value);
3978 } else if (!AnyErrors) {
3979 CXXCtorInitializer *CXXBaseInit;
3980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3981 &Base, /*IsInheritedVirtualBase=*/false,
3987 Info.AllToInit.push_back(CXXBaseInit);
3992 for (auto *Mem : ClassDecl->decls()) {
3993 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3994 // C++ [class.bit]p2:
3995 // A declaration for a bit-field that omits the identifier declares an
3996 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3998 if (F->isUnnamedBitfield())
4001 // If we're not generating the implicit copy/move constructor, then we'll
4002 // handle anonymous struct/union fields based on their individual
4004 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4007 if (CollectFieldInitializer(*this, Info, F))
4012 // Beyond this point, we only consider default initialization.
4013 if (Info.isImplicitCopyOrMove())
4016 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4017 if (F->getType()->isIncompleteArrayType()) {
4018 assert(ClassDecl->hasFlexibleArrayMember() &&
4019 "Incomplete array type is not valid");
4023 // Initialize each field of an anonymous struct individually.
4024 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4031 unsigned NumInitializers = Info.AllToInit.size();
4032 if (NumInitializers > 0) {
4033 Constructor->setNumCtorInitializers(NumInitializers);
4034 CXXCtorInitializer **baseOrMemberInitializers =
4035 new (Context) CXXCtorInitializer*[NumInitializers];
4036 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4037 NumInitializers * sizeof(CXXCtorInitializer*));
4038 Constructor->setCtorInitializers(baseOrMemberInitializers);
4040 // Constructors implicitly reference the base and member
4042 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4043 Constructor->getParent());
4049 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4050 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4051 const RecordDecl *RD = RT->getDecl();
4052 if (RD->isAnonymousStructOrUnion()) {
4053 for (auto *Field : RD->fields())
4054 PopulateKeysForFields(Field, IdealInits);
4058 IdealInits.push_back(Field->getCanonicalDecl());
4061 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4062 return Context.getCanonicalType(BaseType).getTypePtr();
4065 static const void *GetKeyForMember(ASTContext &Context,
4066 CXXCtorInitializer *Member) {
4067 if (!Member->isAnyMemberInitializer())
4068 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4070 return Member->getAnyMember()->getCanonicalDecl();
4073 static void DiagnoseBaseOrMemInitializerOrder(
4074 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4075 ArrayRef<CXXCtorInitializer *> Inits) {
4076 if (Constructor->getDeclContext()->isDependentContext())
4079 // Don't check initializers order unless the warning is enabled at the
4080 // location of at least one initializer.
4081 bool ShouldCheckOrder = false;
4082 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4083 CXXCtorInitializer *Init = Inits[InitIndex];
4084 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4085 Init->getSourceLocation())) {
4086 ShouldCheckOrder = true;
4090 if (!ShouldCheckOrder)
4093 // Build the list of bases and members in the order that they'll
4094 // actually be initialized. The explicit initializers should be in
4095 // this same order but may be missing things.
4096 SmallVector<const void*, 32> IdealInitKeys;
4098 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4100 // 1. Virtual bases.
4101 for (const auto &VBase : ClassDecl->vbases())
4102 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4104 // 2. Non-virtual bases.
4105 for (const auto &Base : ClassDecl->bases()) {
4106 if (Base.isVirtual())
4108 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4111 // 3. Direct fields.
4112 for (auto *Field : ClassDecl->fields()) {
4113 if (Field->isUnnamedBitfield())
4116 PopulateKeysForFields(Field, IdealInitKeys);
4119 unsigned NumIdealInits = IdealInitKeys.size();
4120 unsigned IdealIndex = 0;
4122 CXXCtorInitializer *PrevInit = nullptr;
4123 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4124 CXXCtorInitializer *Init = Inits[InitIndex];
4125 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4127 // Scan forward to try to find this initializer in the idealized
4128 // initializers list.
4129 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4130 if (InitKey == IdealInitKeys[IdealIndex])
4133 // If we didn't find this initializer, it must be because we
4134 // scanned past it on a previous iteration. That can only
4135 // happen if we're out of order; emit a warning.
4136 if (IdealIndex == NumIdealInits && PrevInit) {
4137 Sema::SemaDiagnosticBuilder D =
4138 SemaRef.Diag(PrevInit->getSourceLocation(),
4139 diag::warn_initializer_out_of_order);
4141 if (PrevInit->isAnyMemberInitializer())
4142 D << 0 << PrevInit->getAnyMember()->getDeclName();
4144 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4146 if (Init->isAnyMemberInitializer())
4147 D << 0 << Init->getAnyMember()->getDeclName();
4149 D << 1 << Init->getTypeSourceInfo()->getType();
4151 // Move back to the initializer's location in the ideal list.
4152 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4153 if (InitKey == IdealInitKeys[IdealIndex])
4156 assert(IdealIndex < NumIdealInits &&
4157 "initializer not found in initializer list");
4165 bool CheckRedundantInit(Sema &S,
4166 CXXCtorInitializer *Init,
4167 CXXCtorInitializer *&PrevInit) {
4173 if (FieldDecl *Field = Init->getAnyMember())
4174 S.Diag(Init->getSourceLocation(),
4175 diag::err_multiple_mem_initialization)
4176 << Field->getDeclName()
4177 << Init->getSourceRange();
4179 const Type *BaseClass = Init->getBaseClass();
4180 assert(BaseClass && "neither field nor base");
4181 S.Diag(Init->getSourceLocation(),
4182 diag::err_multiple_base_initialization)
4183 << QualType(BaseClass, 0)
4184 << Init->getSourceRange();
4186 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4187 << 0 << PrevInit->getSourceRange();
4192 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4193 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4195 bool CheckRedundantUnionInit(Sema &S,
4196 CXXCtorInitializer *Init,
4197 RedundantUnionMap &Unions) {
4198 FieldDecl *Field = Init->getAnyMember();
4199 RecordDecl *Parent = Field->getParent();
4200 NamedDecl *Child = Field;
4202 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4203 if (Parent->isUnion()) {
4204 UnionEntry &En = Unions[Parent];
4205 if (En.first && En.first != Child) {
4206 S.Diag(Init->getSourceLocation(),
4207 diag::err_multiple_mem_union_initialization)
4208 << Field->getDeclName()
4209 << Init->getSourceRange();
4210 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4211 << 0 << En.second->getSourceRange();
4218 if (!Parent->isAnonymousStructOrUnion())
4223 Parent = cast<RecordDecl>(Parent->getDeclContext());
4230 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4231 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4232 SourceLocation ColonLoc,
4233 ArrayRef<CXXCtorInitializer*> MemInits,
4235 if (!ConstructorDecl)
4238 AdjustDeclIfTemplate(ConstructorDecl);
4240 CXXConstructorDecl *Constructor
4241 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4244 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4248 // Mapping for the duplicate initializers check.
4249 // For member initializers, this is keyed with a FieldDecl*.
4250 // For base initializers, this is keyed with a Type*.
4251 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4253 // Mapping for the inconsistent anonymous-union initializers check.
4254 RedundantUnionMap MemberUnions;
4256 bool HadError = false;
4257 for (unsigned i = 0; i < MemInits.size(); i++) {
4258 CXXCtorInitializer *Init = MemInits[i];
4260 // Set the source order index.
4261 Init->setSourceOrder(i);
4263 if (Init->isAnyMemberInitializer()) {
4264 const void *Key = GetKeyForMember(Context, Init);
4265 if (CheckRedundantInit(*this, Init, Members[Key]) ||
4266 CheckRedundantUnionInit(*this, Init, MemberUnions))
4268 } else if (Init->isBaseInitializer()) {
4269 const void *Key = GetKeyForMember(Context, Init);
4270 if (CheckRedundantInit(*this, Init, Members[Key]))
4273 assert(Init->isDelegatingInitializer());
4274 // This must be the only initializer
4275 if (MemInits.size() != 1) {
4276 Diag(Init->getSourceLocation(),
4277 diag::err_delegating_initializer_alone)
4278 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4279 // We will treat this as being the only initializer.
4281 SetDelegatingInitializer(Constructor, MemInits[i]);
4282 // Return immediately as the initializer is set.
4290 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4292 SetCtorInitializers(Constructor, AnyErrors, MemInits);
4294 DiagnoseUninitializedFields(*this, Constructor);
4298 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4299 CXXRecordDecl *ClassDecl) {
4300 // Ignore dependent contexts. Also ignore unions, since their members never
4301 // have destructors implicitly called.
4302 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4305 // FIXME: all the access-control diagnostics are positioned on the
4306 // field/base declaration. That's probably good; that said, the
4307 // user might reasonably want to know why the destructor is being
4308 // emitted, and we currently don't say.
4310 // Non-static data members.
4311 for (auto *Field : ClassDecl->fields()) {
4312 if (Field->isInvalidDecl())
4315 // Don't destroy incomplete or zero-length arrays.
4316 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4319 QualType FieldType = Context.getBaseElementType(Field->getType());
4321 const RecordType* RT = FieldType->getAs<RecordType>();
4325 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4326 if (FieldClassDecl->isInvalidDecl())
4328 if (FieldClassDecl->hasIrrelevantDestructor())
4330 // The destructor for an implicit anonymous union member is never invoked.
4331 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4334 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4335 assert(Dtor && "No dtor found for FieldClassDecl!");
4336 CheckDestructorAccess(Field->getLocation(), Dtor,
4337 PDiag(diag::err_access_dtor_field)
4338 << Field->getDeclName()
4341 MarkFunctionReferenced(Location, Dtor);
4342 DiagnoseUseOfDecl(Dtor, Location);
4345 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4348 for (const auto &Base : ClassDecl->bases()) {
4349 // Bases are always records in a well-formed non-dependent class.
4350 const RecordType *RT = Base.getType()->getAs<RecordType>();
4352 // Remember direct virtual bases.
4353 if (Base.isVirtual())
4354 DirectVirtualBases.insert(RT);
4356 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4357 // If our base class is invalid, we probably can't get its dtor anyway.
4358 if (BaseClassDecl->isInvalidDecl())
4360 if (BaseClassDecl->hasIrrelevantDestructor())
4363 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4364 assert(Dtor && "No dtor found for BaseClassDecl!");
4366 // FIXME: caret should be on the start of the class name
4367 CheckDestructorAccess(Base.getLocStart(), Dtor,
4368 PDiag(diag::err_access_dtor_base)
4370 << Base.getSourceRange(),
4371 Context.getTypeDeclType(ClassDecl));
4373 MarkFunctionReferenced(Location, Dtor);
4374 DiagnoseUseOfDecl(Dtor, Location);
4378 for (const auto &VBase : ClassDecl->vbases()) {
4379 // Bases are always records in a well-formed non-dependent class.
4380 const RecordType *RT = VBase.getType()->castAs<RecordType>();
4382 // Ignore direct virtual bases.
4383 if (DirectVirtualBases.count(RT))
4386 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4387 // If our base class is invalid, we probably can't get its dtor anyway.
4388 if (BaseClassDecl->isInvalidDecl())
4390 if (BaseClassDecl->hasIrrelevantDestructor())
4393 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4394 assert(Dtor && "No dtor found for BaseClassDecl!");
4395 if (CheckDestructorAccess(
4396 ClassDecl->getLocation(), Dtor,
4397 PDiag(diag::err_access_dtor_vbase)
4398 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4399 Context.getTypeDeclType(ClassDecl)) ==
4401 CheckDerivedToBaseConversion(
4402 Context.getTypeDeclType(ClassDecl), VBase.getType(),
4403 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4404 SourceRange(), DeclarationName(), nullptr);
4407 MarkFunctionReferenced(Location, Dtor);
4408 DiagnoseUseOfDecl(Dtor, Location);
4412 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4416 if (CXXConstructorDecl *Constructor
4417 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4418 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4419 DiagnoseUninitializedFields(*this, Constructor);
4423 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
4424 if (!getLangOpts().CPlusPlus)
4427 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
4431 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
4432 // class template specialization here, but doing so breaks a lot of code.
4434 // We can't answer whether something is abstract until it has a
4435 // definition. If it's currently being defined, we'll walk back
4436 // over all the declarations when we have a full definition.
4437 const CXXRecordDecl *Def = RD->getDefinition();
4438 if (!Def || Def->isBeingDefined())
4441 return RD->isAbstract();
4444 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4445 TypeDiagnoser &Diagnoser) {
4446 if (!isAbstractType(Loc, T))
4449 T = Context.getBaseElementType(T);
4450 Diagnoser.diagnose(*this, Loc, T);
4451 DiagnoseAbstractType(T->getAsCXXRecordDecl());
4455 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4456 // Check if we've already emitted the list of pure virtual functions
4458 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4461 // If the diagnostic is suppressed, don't emit the notes. We're only
4462 // going to emit them once, so try to attach them to a diagnostic we're
4463 // actually going to show.
4464 if (Diags.isLastDiagnosticIgnored())
4467 CXXFinalOverriderMap FinalOverriders;
4468 RD->getFinalOverriders(FinalOverriders);
4470 // Keep a set of seen pure methods so we won't diagnose the same method
4472 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4474 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4475 MEnd = FinalOverriders.end();
4478 for (OverridingMethods::iterator SO = M->second.begin(),
4479 SOEnd = M->second.end();
4480 SO != SOEnd; ++SO) {
4481 // C++ [class.abstract]p4:
4482 // A class is abstract if it contains or inherits at least one
4483 // pure virtual function for which the final overrider is pure
4487 if (SO->second.size() != 1)
4490 if (!SO->second.front().Method->isPure())
4493 if (!SeenPureMethods.insert(SO->second.front().Method).second)
4496 Diag(SO->second.front().Method->getLocation(),
4497 diag::note_pure_virtual_function)
4498 << SO->second.front().Method->getDeclName() << RD->getDeclName();
4502 if (!PureVirtualClassDiagSet)
4503 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4504 PureVirtualClassDiagSet->insert(RD);
4508 struct AbstractUsageInfo {
4510 CXXRecordDecl *Record;
4511 CanQualType AbstractType;
4514 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4515 : S(S), Record(Record),
4516 AbstractType(S.Context.getCanonicalType(
4517 S.Context.getTypeDeclType(Record))),
4520 void DiagnoseAbstractType() {
4521 if (Invalid) return;
4522 S.DiagnoseAbstractType(Record);
4526 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4529 struct CheckAbstractUsage {
4530 AbstractUsageInfo &Info;
4531 const NamedDecl *Ctx;
4533 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4534 : Info(Info), Ctx(Ctx) {}
4536 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4537 switch (TL.getTypeLocClass()) {
4538 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4539 #define TYPELOC(CLASS, PARENT) \
4540 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4541 #include "clang/AST/TypeLocNodes.def"
4545 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4546 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4547 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4548 if (!TL.getParam(I))
4551 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4552 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4556 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4557 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4560 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4561 // Visit the type parameters from a permissive context.
4562 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4563 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4564 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4565 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4566 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4567 // TODO: other template argument types?
4571 // Visit pointee types from a permissive context.
4572 #define CheckPolymorphic(Type) \
4573 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4574 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4576 CheckPolymorphic(PointerTypeLoc)
4577 CheckPolymorphic(ReferenceTypeLoc)
4578 CheckPolymorphic(MemberPointerTypeLoc)
4579 CheckPolymorphic(BlockPointerTypeLoc)
4580 CheckPolymorphic(AtomicTypeLoc)
4582 /// Handle all the types we haven't given a more specific
4583 /// implementation for above.
4584 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4585 // Every other kind of type that we haven't called out already
4586 // that has an inner type is either (1) sugar or (2) contains that
4587 // inner type in some way as a subobject.
4588 if (TypeLoc Next = TL.getNextTypeLoc())
4589 return Visit(Next, Sel);
4591 // If there's no inner type and we're in a permissive context,
4593 if (Sel == Sema::AbstractNone) return;
4595 // Check whether the type matches the abstract type.
4596 QualType T = TL.getType();
4597 if (T->isArrayType()) {
4598 Sel = Sema::AbstractArrayType;
4599 T = Info.S.Context.getBaseElementType(T);
4601 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4602 if (CT != Info.AbstractType) return;
4604 // It matched; do some magic.
4605 if (Sel == Sema::AbstractArrayType) {
4606 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4607 << T << TL.getSourceRange();
4609 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4610 << Sel << T << TL.getSourceRange();
4612 Info.DiagnoseAbstractType();
4616 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4617 Sema::AbstractDiagSelID Sel) {
4618 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4623 /// Check for invalid uses of an abstract type in a method declaration.
4624 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4625 CXXMethodDecl *MD) {
4626 // No need to do the check on definitions, which require that
4627 // the return/param types be complete.
4628 if (MD->doesThisDeclarationHaveABody())
4631 // For safety's sake, just ignore it if we don't have type source
4632 // information. This should never happen for non-implicit methods,
4634 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4635 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4638 /// Check for invalid uses of an abstract type within a class definition.
4639 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4640 CXXRecordDecl *RD) {
4641 for (auto *D : RD->decls()) {
4642 if (D->isImplicit()) continue;
4644 // Methods and method templates.
4645 if (isa<CXXMethodDecl>(D)) {
4646 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4647 } else if (isa<FunctionTemplateDecl>(D)) {
4648 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4649 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4651 // Fields and static variables.
4652 } else if (isa<FieldDecl>(D)) {
4653 FieldDecl *FD = cast<FieldDecl>(D);
4654 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4655 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4656 } else if (isa<VarDecl>(D)) {
4657 VarDecl *VD = cast<VarDecl>(D);
4658 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4659 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4661 // Nested classes and class templates.
4662 } else if (isa<CXXRecordDecl>(D)) {
4663 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4664 } else if (isa<ClassTemplateDecl>(D)) {
4665 CheckAbstractClassUsage(Info,
4666 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4671 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4672 Attr *ClassAttr = getDLLAttr(Class);
4676 assert(ClassAttr->getKind() == attr::DLLExport);
4678 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4680 if (TSK == TSK_ExplicitInstantiationDeclaration)
4681 // Don't go any further if this is just an explicit instantiation
4685 for (Decl *Member : Class->decls()) {
4686 auto *MD = dyn_cast<CXXMethodDecl>(Member);
4690 if (Member->getAttr<DLLExportAttr>()) {
4691 if (MD->isUserProvided()) {
4692 // Instantiate non-default class member functions ...
4694 // .. except for certain kinds of template specializations.
4695 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4698 S.MarkFunctionReferenced(Class->getLocation(), MD);
4700 // The function will be passed to the consumer when its definition is
4702 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4703 MD->isCopyAssignmentOperator() ||
4704 MD->isMoveAssignmentOperator()) {
4705 // Synthesize and instantiate non-trivial implicit methods, explicitly
4706 // defaulted methods, and the copy and move assignment operators. The
4707 // latter are exported even if they are trivial, because the address of
4708 // an operator can be taken and should compare equal accross libraries.
4709 DiagnosticErrorTrap Trap(S.Diags);
4710 S.MarkFunctionReferenced(Class->getLocation(), MD);
4711 if (Trap.hasErrorOccurred()) {
4712 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4713 << Class->getName() << !S.getLangOpts().CPlusPlus11;
4717 // There is no later point when we will see the definition of this
4718 // function, so pass it to the consumer now.
4719 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4725 /// \brief Check class-level dllimport/dllexport attribute.
4726 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4727 Attr *ClassAttr = getDLLAttr(Class);
4729 // MSVC inherits DLL attributes to partial class template specializations.
4730 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4731 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4732 if (Attr *TemplateAttr =
4733 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4734 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4735 A->setInherited(true);
4744 if (!Class->isExternallyVisible()) {
4745 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4746 << Class << ClassAttr;
4750 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4751 !ClassAttr->isInherited()) {
4752 // Diagnose dll attributes on members of class with dll attribute.
4753 for (Decl *Member : Class->decls()) {
4754 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4756 InheritableAttr *MemberAttr = getDLLAttr(Member);
4757 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4760 Diag(MemberAttr->getLocation(),
4761 diag::err_attribute_dll_member_of_dll_class)
4762 << MemberAttr << ClassAttr;
4763 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4764 Member->setInvalidDecl();
4768 if (Class->getDescribedClassTemplate())
4769 // Don't inherit dll attribute until the template is instantiated.
4772 // The class is either imported or exported.
4773 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4774 const bool ClassImported = !ClassExported;
4776 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4778 // Ignore explicit dllexport on explicit class template instantiation declarations.
4779 if (ClassExported && !ClassAttr->isInherited() &&
4780 TSK == TSK_ExplicitInstantiationDeclaration) {
4781 Class->dropAttr<DLLExportAttr>();
4785 // Force declaration of implicit members so they can inherit the attribute.
4786 ForceDeclarationOfImplicitMembers(Class);
4788 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4789 // seem to be true in practice?
4791 for (Decl *Member : Class->decls()) {
4792 VarDecl *VD = dyn_cast<VarDecl>(Member);
4793 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4795 // Only methods and static fields inherit the attributes.
4800 // Don't process deleted methods.
4801 if (MD->isDeleted())
4804 if (MD->isInlined()) {
4805 // MinGW does not import or export inline methods.
4806 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4809 // MSVC versions before 2015 don't export the move assignment operators,
4810 // so don't attempt to import them if we have a definition.
4811 if (ClassImported && MD->isMoveAssignmentOperator() &&
4812 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4817 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4820 if (!getDLLAttr(Member)) {
4822 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4823 NewAttr->setInherited(true);
4824 Member->addAttr(NewAttr);
4829 DelayedDllExportClasses.push_back(Class);
4832 /// \brief Perform propagation of DLL attributes from a derived class to a
4833 /// templated base class for MS compatibility.
4834 void Sema::propagateDLLAttrToBaseClassTemplate(
4835 CXXRecordDecl *Class, Attr *ClassAttr,
4836 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4838 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4839 // If the base class template has a DLL attribute, don't try to change it.
4843 auto TSK = BaseTemplateSpec->getSpecializationKind();
4844 if (!getDLLAttr(BaseTemplateSpec) &&
4845 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4846 TSK == TSK_ImplicitInstantiation)) {
4847 // The template hasn't been instantiated yet (or it has, but only as an
4848 // explicit instantiation declaration or implicit instantiation, which means
4849 // we haven't codegenned any members yet), so propagate the attribute.
4850 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4851 NewAttr->setInherited(true);
4852 BaseTemplateSpec->addAttr(NewAttr);
4854 // If the template is already instantiated, checkDLLAttributeRedeclaration()
4855 // needs to be run again to work see the new attribute. Otherwise this will
4856 // get run whenever the template is instantiated.
4857 if (TSK != TSK_Undeclared)
4858 checkClassLevelDLLAttribute(BaseTemplateSpec);
4863 if (getDLLAttr(BaseTemplateSpec)) {
4864 // The template has already been specialized or instantiated with an
4865 // attribute, explicitly or through propagation. We should not try to change
4870 // The template was previously instantiated or explicitly specialized without
4871 // a dll attribute, It's too late for us to add an attribute, so warn that
4872 // this is unsupported.
4873 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4874 << BaseTemplateSpec->isExplicitSpecialization();
4875 Diag(ClassAttr->getLocation(), diag::note_attribute);
4876 if (BaseTemplateSpec->isExplicitSpecialization()) {
4877 Diag(BaseTemplateSpec->getLocation(),
4878 diag::note_template_class_explicit_specialization_was_here)
4879 << BaseTemplateSpec;
4881 Diag(BaseTemplateSpec->getPointOfInstantiation(),
4882 diag::note_template_class_instantiation_was_here)
4883 << BaseTemplateSpec;
4887 /// \brief Perform semantic checks on a class definition that has been
4888 /// completing, introducing implicitly-declared members, checking for
4889 /// abstract types, etc.
4890 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4894 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4895 AbstractUsageInfo Info(*this, Record);
4896 CheckAbstractClassUsage(Info, Record);
4899 // If this is not an aggregate type and has no user-declared constructor,
4900 // complain about any non-static data members of reference or const scalar
4901 // type, since they will never get initializers.
4902 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4903 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4904 !Record->isLambda()) {
4905 bool Complained = false;
4906 for (const auto *F : Record->fields()) {
4907 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4910 if (F->getType()->isReferenceType() ||
4911 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4913 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4914 << Record->getTagKind() << Record;
4918 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4919 << F->getType()->isReferenceType()
4920 << F->getDeclName();
4925 if (Record->getIdentifier()) {
4926 // C++ [class.mem]p13:
4927 // If T is the name of a class, then each of the following shall have a
4928 // name different from T:
4929 // - every member of every anonymous union that is a member of class T.
4931 // C++ [class.mem]p14:
4932 // In addition, if class T has a user-declared constructor (12.1), every
4933 // non-static data member of class T shall have a name different from T.
4934 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4935 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4938 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4939 isa<IndirectFieldDecl>(D)) {
4940 Diag(D->getLocation(), diag::err_member_name_of_class)
4941 << D->getDeclName();
4947 // Warn if the class has virtual methods but non-virtual public destructor.
4948 if (Record->isPolymorphic() && !Record->isDependentType()) {
4949 CXXDestructorDecl *dtor = Record->getDestructor();
4950 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4951 !Record->hasAttr<FinalAttr>())
4952 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4953 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4956 if (Record->isAbstract()) {
4957 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4958 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4959 << FA->isSpelledAsSealed();
4960 DiagnoseAbstractType(Record);
4964 bool HasMethodWithOverrideControl = false,
4965 HasOverridingMethodWithoutOverrideControl = false;
4966 if (!Record->isDependentType()) {
4967 for (auto *M : Record->methods()) {
4968 // See if a method overloads virtual methods in a base
4969 // class without overriding any.
4971 DiagnoseHiddenVirtualMethods(M);
4972 if (M->hasAttr<OverrideAttr>())
4973 HasMethodWithOverrideControl = true;
4974 else if (M->size_overridden_methods() > 0)
4975 HasOverridingMethodWithoutOverrideControl = true;
4976 // Check whether the explicitly-defaulted special members are valid.
4977 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4978 CheckExplicitlyDefaultedSpecialMember(M);
4980 // For an explicitly defaulted or deleted special member, we defer
4981 // determining triviality until the class is complete. That time is now!
4982 if (!M->isImplicit() && !M->isUserProvided()) {
4983 CXXSpecialMember CSM = getSpecialMember(M);
4984 if (CSM != CXXInvalid) {
4985 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4987 // Inform the class that we've finished declaring this member.
4988 Record->finishedDefaultedOrDeletedMember(M);
4994 if (HasMethodWithOverrideControl &&
4995 HasOverridingMethodWithoutOverrideControl) {
4996 // At least one method has the 'override' control declared.
4997 // Diagnose all other overridden methods which do not have 'override' specified on them.
4998 for (auto *M : Record->methods())
4999 DiagnoseAbsenceOfOverrideControl(M);
5002 // ms_struct is a request to use the same ABI rules as MSVC. Check
5003 // whether this class uses any C++ features that are implemented
5004 // completely differently in MSVC, and if so, emit a diagnostic.
5005 // That diagnostic defaults to an error, but we allow projects to
5006 // map it down to a warning (or ignore it). It's a fairly common
5007 // practice among users of the ms_struct pragma to mass-annotate
5008 // headers, sweeping up a bunch of types that the project doesn't
5009 // really rely on MSVC-compatible layout for. We must therefore
5010 // support "ms_struct except for C++ stuff" as a secondary ABI.
5011 if (Record->isMsStruct(Context) &&
5012 (Record->isPolymorphic() || Record->getNumBases())) {
5013 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5016 // Declare inheriting constructors. We do this eagerly here because:
5017 // - The standard requires an eager diagnostic for conflicting inheriting
5018 // constructors from different classes.
5019 // - The lazy declaration of the other implicit constructors is so as to not
5020 // waste space and performance on classes that are not meant to be
5021 // instantiated (e.g. meta-functions). This doesn't apply to classes that
5022 // have inheriting constructors.
5023 DeclareInheritingConstructors(Record);
5025 checkClassLevelDLLAttribute(Record);
5028 /// Look up the special member function that would be called by a special
5029 /// member function for a subobject of class type.
5031 /// \param Class The class type of the subobject.
5032 /// \param CSM The kind of special member function.
5033 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5034 /// \param ConstRHS True if this is a copy operation with a const object
5035 /// on its RHS, that is, if the argument to the outer special member
5036 /// function is 'const' and this is not a field marked 'mutable'.
5037 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5038 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5039 unsigned FieldQuals, bool ConstRHS) {
5040 unsigned LHSQuals = 0;
5041 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5042 LHSQuals = FieldQuals;
5044 unsigned RHSQuals = FieldQuals;
5045 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5048 RHSQuals |= Qualifiers::Const;
5050 return S.LookupSpecialMember(Class, CSM,
5051 RHSQuals & Qualifiers::Const,
5052 RHSQuals & Qualifiers::Volatile,
5054 LHSQuals & Qualifiers::Const,
5055 LHSQuals & Qualifiers::Volatile);
5058 /// Is the special member function which would be selected to perform the
5059 /// specified operation on the specified class type a constexpr constructor?
5060 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5061 Sema::CXXSpecialMember CSM,
5062 unsigned Quals, bool ConstRHS) {
5063 Sema::SpecialMemberOverloadResult *SMOR =
5064 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5065 if (!SMOR || !SMOR->getMethod())
5066 // A constructor we wouldn't select can't be "involved in initializing"
5069 return SMOR->getMethod()->isConstexpr();
5072 /// Determine whether the specified special member function would be constexpr
5073 /// if it were implicitly defined.
5074 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5075 Sema::CXXSpecialMember CSM,
5077 if (!S.getLangOpts().CPlusPlus11)
5080 // C++11 [dcl.constexpr]p4:
5081 // In the definition of a constexpr constructor [...]
5084 case Sema::CXXDefaultConstructor:
5085 // Since default constructor lookup is essentially trivial (and cannot
5086 // involve, for instance, template instantiation), we compute whether a
5087 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5089 // This is important for performance; we need to know whether the default
5090 // constructor is constexpr to determine whether the type is a literal type.
5091 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5093 case Sema::CXXCopyConstructor:
5094 case Sema::CXXMoveConstructor:
5095 // For copy or move constructors, we need to perform overload resolution.
5098 case Sema::CXXCopyAssignment:
5099 case Sema::CXXMoveAssignment:
5100 if (!S.getLangOpts().CPlusPlus14)
5102 // In C++1y, we need to perform overload resolution.
5106 case Sema::CXXDestructor:
5107 case Sema::CXXInvalid:
5111 // -- if the class is a non-empty union, or for each non-empty anonymous
5112 // union member of a non-union class, exactly one non-static data member
5113 // shall be initialized; [DR1359]
5115 // If we squint, this is guaranteed, since exactly one non-static data member
5116 // will be initialized (if the constructor isn't deleted), we just don't know
5118 if (Ctor && ClassDecl->isUnion())
5121 // -- the class shall not have any virtual base classes;
5122 if (Ctor && ClassDecl->getNumVBases())
5125 // C++1y [class.copy]p26:
5126 // -- [the class] is a literal type, and
5127 if (!Ctor && !ClassDecl->isLiteral())
5130 // -- every constructor involved in initializing [...] base class
5131 // sub-objects shall be a constexpr constructor;
5132 // -- the assignment operator selected to copy/move each direct base
5133 // class is a constexpr function, and
5134 for (const auto &B : ClassDecl->bases()) {
5135 const RecordType *BaseType = B.getType()->getAs<RecordType>();
5136 if (!BaseType) continue;
5138 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5139 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5143 // -- every constructor involved in initializing non-static data members
5144 // [...] shall be a constexpr constructor;
5145 // -- every non-static data member and base class sub-object shall be
5147 // -- for each non-static data member of X that is of class type (or array
5148 // thereof), the assignment operator selected to copy/move that member is
5149 // a constexpr function
5150 for (const auto *F : ClassDecl->fields()) {
5151 if (F->isInvalidDecl())
5153 QualType BaseType = S.Context.getBaseElementType(F->getType());
5154 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5155 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5156 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5157 BaseType.getCVRQualifiers(),
5158 ConstArg && !F->isMutable()))
5163 // All OK, it's constexpr!
5167 static Sema::ImplicitExceptionSpecification
5168 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5169 switch (S.getSpecialMember(MD)) {
5170 case Sema::CXXDefaultConstructor:
5171 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5172 case Sema::CXXCopyConstructor:
5173 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5174 case Sema::CXXCopyAssignment:
5175 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5176 case Sema::CXXMoveConstructor:
5177 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5178 case Sema::CXXMoveAssignment:
5179 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5180 case Sema::CXXDestructor:
5181 return S.ComputeDefaultedDtorExceptionSpec(MD);
5182 case Sema::CXXInvalid:
5185 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5186 "only special members have implicit exception specs");
5187 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5190 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5191 CXXMethodDecl *MD) {
5192 FunctionProtoType::ExtProtoInfo EPI;
5194 // Build an exception specification pointing back at this member.
5195 EPI.ExceptionSpec.Type = EST_Unevaluated;
5196 EPI.ExceptionSpec.SourceDecl = MD;
5198 // Set the calling convention to the default for C++ instance methods.
5199 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5200 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5201 /*IsCXXMethod=*/true));
5205 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5206 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5207 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5210 // Evaluate the exception specification.
5211 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5213 // Update the type of the special member to use it.
5214 UpdateExceptionSpec(MD, ESI);
5216 // A user-provided destructor can be defined outside the class. When that
5217 // happens, be sure to update the exception specification on both
5219 const FunctionProtoType *CanonicalFPT =
5220 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5221 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5222 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5225 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5226 CXXRecordDecl *RD = MD->getParent();
5227 CXXSpecialMember CSM = getSpecialMember(MD);
5229 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5230 "not an explicitly-defaulted special member");
5232 // Whether this was the first-declared instance of the constructor.
5233 // This affects whether we implicitly add an exception spec and constexpr.
5234 bool First = MD == MD->getCanonicalDecl();
5236 bool HadError = false;
5238 // C++11 [dcl.fct.def.default]p1:
5239 // A function that is explicitly defaulted shall
5240 // -- be a special member function (checked elsewhere),
5241 // -- have the same type (except for ref-qualifiers, and except that a
5242 // copy operation can take a non-const reference) as an implicit
5244 // -- not have default arguments.
5245 unsigned ExpectedParams = 1;
5246 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5248 if (MD->getNumParams() != ExpectedParams) {
5249 // This also checks for default arguments: a copy or move constructor with a
5250 // default argument is classified as a default constructor, and assignment
5251 // operations and destructors can't have default arguments.
5252 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5253 << CSM << MD->getSourceRange();
5255 } else if (MD->isVariadic()) {
5256 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5257 << CSM << MD->getSourceRange();
5261 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5263 bool CanHaveConstParam = false;
5264 if (CSM == CXXCopyConstructor)
5265 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5266 else if (CSM == CXXCopyAssignment)
5267 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5269 QualType ReturnType = Context.VoidTy;
5270 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5271 // Check for return type matching.
5272 ReturnType = Type->getReturnType();
5273 QualType ExpectedReturnType =
5274 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5275 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5276 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5277 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5281 // A defaulted special member cannot have cv-qualifiers.
5282 if (Type->getTypeQuals()) {
5283 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5284 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5289 // Check for parameter type matching.
5290 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5291 bool HasConstParam = false;
5292 if (ExpectedParams && ArgType->isReferenceType()) {
5293 // Argument must be reference to possibly-const T.
5294 QualType ReferentType = ArgType->getPointeeType();
5295 HasConstParam = ReferentType.isConstQualified();
5297 if (ReferentType.isVolatileQualified()) {
5298 Diag(MD->getLocation(),
5299 diag::err_defaulted_special_member_volatile_param) << CSM;
5303 if (HasConstParam && !CanHaveConstParam) {
5304 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5305 Diag(MD->getLocation(),
5306 diag::err_defaulted_special_member_copy_const_param)
5307 << (CSM == CXXCopyAssignment);
5308 // FIXME: Explain why this special member can't be const.
5310 Diag(MD->getLocation(),
5311 diag::err_defaulted_special_member_move_const_param)
5312 << (CSM == CXXMoveAssignment);
5316 } else if (ExpectedParams) {
5317 // A copy assignment operator can take its argument by value, but a
5318 // defaulted one cannot.
5319 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5320 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5324 // C++11 [dcl.fct.def.default]p2:
5325 // An explicitly-defaulted function may be declared constexpr only if it
5326 // would have been implicitly declared as constexpr,
5327 // Do not apply this rule to members of class templates, since core issue 1358
5328 // makes such functions always instantiate to constexpr functions. For
5329 // functions which cannot be constexpr (for non-constructors in C++11 and for
5330 // destructors in C++1y), this is checked elsewhere.
5331 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5333 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5334 : isa<CXXConstructorDecl>(MD)) &&
5335 MD->isConstexpr() && !Constexpr &&
5336 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5337 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5338 // FIXME: Explain why the special member can't be constexpr.
5342 // and may have an explicit exception-specification only if it is compatible
5343 // with the exception-specification on the implicit declaration.
5344 if (Type->hasExceptionSpec()) {
5345 // Delay the check if this is the first declaration of the special member,
5346 // since we may not have parsed some necessary in-class initializers yet.
5348 // If the exception specification needs to be instantiated, do so now,
5349 // before we clobber it with an EST_Unevaluated specification below.
5350 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5351 InstantiateExceptionSpec(MD->getLocStart(), MD);
5352 Type = MD->getType()->getAs<FunctionProtoType>();
5354 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5356 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5359 // If a function is explicitly defaulted on its first declaration,
5361 // -- it is implicitly considered to be constexpr if the implicit
5362 // definition would be,
5363 MD->setConstexpr(Constexpr);
5365 // -- it is implicitly considered to have the same exception-specification
5366 // as if it had been implicitly declared,
5367 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5368 EPI.ExceptionSpec.Type = EST_Unevaluated;
5369 EPI.ExceptionSpec.SourceDecl = MD;
5370 MD->setType(Context.getFunctionType(ReturnType,
5371 llvm::makeArrayRef(&ArgType,
5376 if (ShouldDeleteSpecialMember(MD, CSM)) {
5378 SetDeclDeleted(MD, MD->getLocation());
5380 // C++11 [dcl.fct.def.default]p4:
5381 // [For a] user-provided explicitly-defaulted function [...] if such a
5382 // function is implicitly defined as deleted, the program is ill-formed.
5383 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5384 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5390 MD->setInvalidDecl();
5393 /// Check whether the exception specification provided for an
5394 /// explicitly-defaulted special member matches the exception specification
5395 /// that would have been generated for an implicit special member, per
5396 /// C++11 [dcl.fct.def.default]p2.
5397 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5398 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5399 // If the exception specification was explicitly specified but hadn't been
5400 // parsed when the method was defaulted, grab it now.
5401 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5403 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5405 // Compute the implicit exception specification.
5406 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5407 /*IsCXXMethod=*/true);
5408 FunctionProtoType::ExtProtoInfo EPI(CC);
5409 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5410 .getExceptionSpec();
5411 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5412 Context.getFunctionType(Context.VoidTy, None, EPI));
5414 // Ensure that it matches.
5415 CheckEquivalentExceptionSpec(
5416 PDiag(diag::err_incorrect_defaulted_exception_spec)
5417 << getSpecialMember(MD), PDiag(),
5418 ImplicitType, SourceLocation(),
5419 SpecifiedType, MD->getLocation());
5422 void Sema::CheckDelayedMemberExceptionSpecs() {
5423 decltype(DelayedExceptionSpecChecks) Checks;
5424 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5426 std::swap(Checks, DelayedExceptionSpecChecks);
5427 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5429 // Perform any deferred checking of exception specifications for virtual
5431 for (auto &Check : Checks)
5432 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5434 // Check that any explicitly-defaulted methods have exception specifications
5435 // compatible with their implicit exception specifications.
5436 for (auto &Spec : Specs)
5437 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5441 struct SpecialMemberDeletionInfo {
5444 Sema::CXXSpecialMember CSM;
5447 // Properties of the special member, computed for convenience.
5448 bool IsConstructor, IsAssignment, IsMove, ConstArg;
5451 bool AllFieldsAreConst;
5453 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5454 Sema::CXXSpecialMember CSM, bool Diagnose)
5455 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5456 IsConstructor(false), IsAssignment(false), IsMove(false),
5457 ConstArg(false), Loc(MD->getLocation()),
5458 AllFieldsAreConst(true) {
5460 case Sema::CXXDefaultConstructor:
5461 case Sema::CXXCopyConstructor:
5462 IsConstructor = true;
5464 case Sema::CXXMoveConstructor:
5465 IsConstructor = true;
5468 case Sema::CXXCopyAssignment:
5469 IsAssignment = true;
5471 case Sema::CXXMoveAssignment:
5472 IsAssignment = true;
5475 case Sema::CXXDestructor:
5477 case Sema::CXXInvalid:
5478 llvm_unreachable("invalid special member kind");
5481 if (MD->getNumParams()) {
5482 if (const ReferenceType *RT =
5483 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5484 ConstArg = RT->getPointeeType().isConstQualified();
5488 bool inUnion() const { return MD->getParent()->isUnion(); }
5490 /// Look up the corresponding special member in the given class.
5491 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5492 unsigned Quals, bool IsMutable) {
5493 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5494 ConstArg && !IsMutable);
5497 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5499 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5500 bool shouldDeleteForField(FieldDecl *FD);
5501 bool shouldDeleteForAllConstMembers();
5503 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5505 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5506 Sema::SpecialMemberOverloadResult *SMOR,
5507 bool IsDtorCallInCtor);
5509 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5513 /// Is the given special member inaccessible when used on the given
5515 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5516 CXXMethodDecl *target) {
5517 /// If we're operating on a base class, the object type is the
5518 /// type of this special member.
5520 AccessSpecifier access = target->getAccess();
5521 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5522 objectTy = S.Context.getTypeDeclType(MD->getParent());
5523 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5525 // If we're operating on a field, the object type is the type of the field.
5527 objectTy = S.Context.getTypeDeclType(target->getParent());
5530 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5533 /// Check whether we should delete a special member due to the implicit
5534 /// definition containing a call to a special member of a subobject.
5535 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5536 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5537 bool IsDtorCallInCtor) {
5538 CXXMethodDecl *Decl = SMOR->getMethod();
5539 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5543 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5544 DiagKind = !Decl ? 0 : 1;
5545 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5547 else if (!isAccessible(Subobj, Decl))
5549 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5550 !Decl->isTrivial()) {
5551 // A member of a union must have a trivial corresponding special member.
5552 // As a weird special case, a destructor call from a union's constructor
5553 // must be accessible and non-deleted, but need not be trivial. Such a
5554 // destructor is never actually called, but is semantically checked as
5564 S.Diag(Field->getLocation(),
5565 diag::note_deleted_special_member_class_subobject)
5566 << CSM << MD->getParent() << /*IsField*/true
5567 << Field << DiagKind << IsDtorCallInCtor;
5569 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5570 S.Diag(Base->getLocStart(),
5571 diag::note_deleted_special_member_class_subobject)
5572 << CSM << MD->getParent() << /*IsField*/false
5573 << Base->getType() << DiagKind << IsDtorCallInCtor;
5577 S.NoteDeletedFunction(Decl);
5578 // FIXME: Explain inaccessibility if DiagKind == 3.
5584 /// Check whether we should delete a special member function due to having a
5585 /// direct or virtual base class or non-static data member of class type M.
5586 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5587 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5588 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5589 bool IsMutable = Field && Field->isMutable();
5591 // C++11 [class.ctor]p5:
5592 // -- any direct or virtual base class, or non-static data member with no
5593 // brace-or-equal-initializer, has class type M (or array thereof) and
5594 // either M has no default constructor or overload resolution as applied
5595 // to M's default constructor results in an ambiguity or in a function
5596 // that is deleted or inaccessible
5597 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5598 // -- a direct or virtual base class B that cannot be copied/moved because
5599 // overload resolution, as applied to B's corresponding special member,
5600 // results in an ambiguity or a function that is deleted or inaccessible
5601 // from the defaulted special member
5602 // C++11 [class.dtor]p5:
5603 // -- any direct or virtual base class [...] has a type with a destructor
5604 // that is deleted or inaccessible
5605 if (!(CSM == Sema::CXXDefaultConstructor &&
5606 Field && Field->hasInClassInitializer()) &&
5607 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5611 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5612 // -- any direct or virtual base class or non-static data member has a
5613 // type with a destructor that is deleted or inaccessible
5614 if (IsConstructor) {
5615 Sema::SpecialMemberOverloadResult *SMOR =
5616 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5617 false, false, false, false, false);
5618 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5625 /// Check whether we should delete a special member function due to the class
5626 /// having a particular direct or virtual base class.
5627 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5628 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5629 // If program is correct, BaseClass cannot be null, but if it is, the error
5630 // must be reported elsewhere.
5631 return BaseClass && shouldDeleteForClassSubobject(BaseClass, Base, 0);
5634 /// Check whether we should delete a special member function due to the class
5635 /// having a particular non-static data member.
5636 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5637 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5638 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5640 if (CSM == Sema::CXXDefaultConstructor) {
5641 // For a default constructor, all references must be initialized in-class
5642 // and, if a union, it must have a non-const member.
5643 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5645 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5646 << MD->getParent() << FD << FieldType << /*Reference*/0;
5649 // C++11 [class.ctor]p5: any non-variant non-static data member of
5650 // const-qualified type (or array thereof) with no
5651 // brace-or-equal-initializer does not have a user-provided default
5653 if (!inUnion() && FieldType.isConstQualified() &&
5654 !FD->hasInClassInitializer() &&
5655 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5657 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5658 << MD->getParent() << FD << FD->getType() << /*Const*/1;
5662 if (inUnion() && !FieldType.isConstQualified())
5663 AllFieldsAreConst = false;
5664 } else if (CSM == Sema::CXXCopyConstructor) {
5665 // For a copy constructor, data members must not be of rvalue reference
5667 if (FieldType->isRValueReferenceType()) {
5669 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5670 << MD->getParent() << FD << FieldType;
5673 } else if (IsAssignment) {
5674 // For an assignment operator, data members must not be of reference type.
5675 if (FieldType->isReferenceType()) {
5677 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5678 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5681 if (!FieldRecord && FieldType.isConstQualified()) {
5682 // C++11 [class.copy]p23:
5683 // -- a non-static data member of const non-class type (or array thereof)
5685 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5686 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5692 // Some additional restrictions exist on the variant members.
5693 if (!inUnion() && FieldRecord->isUnion() &&
5694 FieldRecord->isAnonymousStructOrUnion()) {
5695 bool AllVariantFieldsAreConst = true;
5697 // FIXME: Handle anonymous unions declared within anonymous unions.
5698 for (auto *UI : FieldRecord->fields()) {
5699 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5701 if (!UnionFieldType.isConstQualified())
5702 AllVariantFieldsAreConst = false;
5704 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5705 if (UnionFieldRecord &&
5706 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5707 UnionFieldType.getCVRQualifiers()))
5711 // At least one member in each anonymous union must be non-const
5712 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5713 !FieldRecord->field_empty()) {
5715 S.Diag(FieldRecord->getLocation(),
5716 diag::note_deleted_default_ctor_all_const)
5717 << MD->getParent() << /*anonymous union*/1;
5721 // Don't check the implicit member of the anonymous union type.
5722 // This is technically non-conformant, but sanity demands it.
5726 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5727 FieldType.getCVRQualifiers()))
5734 /// C++11 [class.ctor] p5:
5735 /// A defaulted default constructor for a class X is defined as deleted if
5736 /// X is a union and all of its variant members are of const-qualified type.
5737 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5738 // This is a silly definition, because it gives an empty union a deleted
5739 // default constructor. Don't do that.
5740 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5741 !MD->getParent()->field_empty()) {
5743 S.Diag(MD->getParent()->getLocation(),
5744 diag::note_deleted_default_ctor_all_const)
5745 << MD->getParent() << /*not anonymous union*/0;
5751 /// Determine whether a defaulted special member function should be defined as
5752 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5753 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5754 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5756 if (MD->isInvalidDecl())
5758 CXXRecordDecl *RD = MD->getParent();
5759 assert(!RD->isDependentType() && "do deletion after instantiation");
5760 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5763 // C++11 [expr.lambda.prim]p19:
5764 // The closure type associated with a lambda-expression has a
5765 // deleted (8.4.3) default constructor and a deleted copy
5766 // assignment operator.
5767 if (RD->isLambda() &&
5768 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5770 Diag(RD->getLocation(), diag::note_lambda_decl);
5774 // For an anonymous struct or union, the copy and assignment special members
5775 // will never be used, so skip the check. For an anonymous union declared at
5776 // namespace scope, the constructor and destructor are used.
5777 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5778 RD->isAnonymousStructOrUnion())
5781 // C++11 [class.copy]p7, p18:
5782 // If the class definition declares a move constructor or move assignment
5783 // operator, an implicitly declared copy constructor or copy assignment
5784 // operator is defined as deleted.
5785 if (MD->isImplicit() &&
5786 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5787 CXXMethodDecl *UserDeclaredMove = nullptr;
5789 // In Microsoft mode, a user-declared move only causes the deletion of the
5790 // corresponding copy operation, not both copy operations.
5791 if (RD->hasUserDeclaredMoveConstructor() &&
5792 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5793 if (!Diagnose) return true;
5795 // Find any user-declared move constructor.
5796 for (auto *I : RD->ctors()) {
5797 if (I->isMoveConstructor()) {
5798 UserDeclaredMove = I;
5802 assert(UserDeclaredMove);
5803 } else if (RD->hasUserDeclaredMoveAssignment() &&
5804 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5805 if (!Diagnose) return true;
5807 // Find any user-declared move assignment operator.
5808 for (auto *I : RD->methods()) {
5809 if (I->isMoveAssignmentOperator()) {
5810 UserDeclaredMove = I;
5814 assert(UserDeclaredMove);
5817 if (UserDeclaredMove) {
5818 Diag(UserDeclaredMove->getLocation(),
5819 diag::note_deleted_copy_user_declared_move)
5820 << (CSM == CXXCopyAssignment) << RD
5821 << UserDeclaredMove->isMoveAssignmentOperator();
5826 // Do access control from the special member function
5827 ContextRAII MethodContext(*this, MD);
5829 // C++11 [class.dtor]p5:
5830 // -- for a virtual destructor, lookup of the non-array deallocation function
5831 // results in an ambiguity or in a function that is deleted or inaccessible
5832 if (CSM == CXXDestructor && MD->isVirtual()) {
5833 FunctionDecl *OperatorDelete = nullptr;
5834 DeclarationName Name =
5835 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5836 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5837 OperatorDelete, false)) {
5839 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5844 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5846 for (auto &BI : RD->bases())
5847 if (!BI.isVirtual() &&
5848 SMI.shouldDeleteForBase(&BI))
5851 // Per DR1611, do not consider virtual bases of constructors of abstract
5852 // classes, since we are not going to construct them.
5853 if (!RD->isAbstract() || !SMI.IsConstructor) {
5854 for (auto &BI : RD->vbases())
5855 if (SMI.shouldDeleteForBase(&BI))
5859 for (auto *FI : RD->fields())
5860 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5861 SMI.shouldDeleteForField(FI))
5864 if (SMI.shouldDeleteForAllConstMembers())
5867 if (getLangOpts().CUDA) {
5868 // We should delete the special member in CUDA mode if target inference
5870 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5877 /// Perform lookup for a special member of the specified kind, and determine
5878 /// whether it is trivial. If the triviality can be determined without the
5879 /// lookup, skip it. This is intended for use when determining whether a
5880 /// special member of a containing object is trivial, and thus does not ever
5881 /// perform overload resolution for default constructors.
5883 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5884 /// member that was most likely to be intended to be trivial, if any.
5885 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5886 Sema::CXXSpecialMember CSM, unsigned Quals,
5887 bool ConstRHS, CXXMethodDecl **Selected) {
5889 *Selected = nullptr;
5892 case Sema::CXXInvalid:
5893 llvm_unreachable("not a special member");
5895 case Sema::CXXDefaultConstructor:
5896 // C++11 [class.ctor]p5:
5897 // A default constructor is trivial if:
5898 // - all the [direct subobjects] have trivial default constructors
5900 // Note, no overload resolution is performed in this case.
5901 if (RD->hasTrivialDefaultConstructor())
5905 // If there's a default constructor which could have been trivial, dig it
5906 // out. Otherwise, if there's any user-provided default constructor, point
5907 // to that as an example of why there's not a trivial one.
5908 CXXConstructorDecl *DefCtor = nullptr;
5909 if (RD->needsImplicitDefaultConstructor())
5910 S.DeclareImplicitDefaultConstructor(RD);
5911 for (auto *CI : RD->ctors()) {
5912 if (!CI->isDefaultConstructor())
5915 if (!DefCtor->isUserProvided())
5919 *Selected = DefCtor;
5924 case Sema::CXXDestructor:
5925 // C++11 [class.dtor]p5:
5926 // A destructor is trivial if:
5927 // - all the direct [subobjects] have trivial destructors
5928 if (RD->hasTrivialDestructor())
5932 if (RD->needsImplicitDestructor())
5933 S.DeclareImplicitDestructor(RD);
5934 *Selected = RD->getDestructor();
5939 case Sema::CXXCopyConstructor:
5940 // C++11 [class.copy]p12:
5941 // A copy constructor is trivial if:
5942 // - the constructor selected to copy each direct [subobject] is trivial
5943 if (RD->hasTrivialCopyConstructor()) {
5944 if (Quals == Qualifiers::Const)
5945 // We must either select the trivial copy constructor or reach an
5946 // ambiguity; no need to actually perform overload resolution.
5948 } else if (!Selected) {
5951 // In C++98, we are not supposed to perform overload resolution here, but we
5952 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5953 // cases like B as having a non-trivial copy constructor:
5954 // struct A { template<typename T> A(T&); };
5955 // struct B { mutable A a; };
5956 goto NeedOverloadResolution;
5958 case Sema::CXXCopyAssignment:
5959 // C++11 [class.copy]p25:
5960 // A copy assignment operator is trivial if:
5961 // - the assignment operator selected to copy each direct [subobject] is
5963 if (RD->hasTrivialCopyAssignment()) {
5964 if (Quals == Qualifiers::Const)
5966 } else if (!Selected) {
5969 // In C++98, we are not supposed to perform overload resolution here, but we
5970 // treat that as a language defect.
5971 goto NeedOverloadResolution;
5973 case Sema::CXXMoveConstructor:
5974 case Sema::CXXMoveAssignment:
5975 NeedOverloadResolution:
5976 Sema::SpecialMemberOverloadResult *SMOR =
5977 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5979 // The standard doesn't describe how to behave if the lookup is ambiguous.
5980 // We treat it as not making the member non-trivial, just like the standard
5981 // mandates for the default constructor. This should rarely matter, because
5982 // the member will also be deleted.
5983 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5986 if (!SMOR->getMethod()) {
5987 assert(SMOR->getKind() ==
5988 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5992 // We deliberately don't check if we found a deleted special member. We're
5995 *Selected = SMOR->getMethod();
5996 return SMOR->getMethod()->isTrivial();
5999 llvm_unreachable("unknown special method kind");
6002 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6003 for (auto *CI : RD->ctors())
6004 if (!CI->isImplicit())
6007 // Look for constructor templates.
6008 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6009 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6010 if (CXXConstructorDecl *CD =
6011 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6018 /// The kind of subobject we are checking for triviality. The values of this
6019 /// enumeration are used in diagnostics.
6020 enum TrivialSubobjectKind {
6021 /// The subobject is a base class.
6023 /// The subobject is a non-static data member.
6025 /// The object is actually the complete object.
6029 /// Check whether the special member selected for a given type would be trivial.
6030 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6031 QualType SubType, bool ConstRHS,
6032 Sema::CXXSpecialMember CSM,
6033 TrivialSubobjectKind Kind,
6035 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6039 CXXMethodDecl *Selected;
6040 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6041 ConstRHS, Diagnose ? &Selected : nullptr))
6048 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6049 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6050 << Kind << SubType.getUnqualifiedType();
6051 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6052 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6053 } else if (!Selected)
6054 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6055 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6056 else if (Selected->isUserProvided()) {
6057 if (Kind == TSK_CompleteObject)
6058 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6059 << Kind << SubType.getUnqualifiedType() << CSM;
6061 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6062 << Kind << SubType.getUnqualifiedType() << CSM;
6063 S.Diag(Selected->getLocation(), diag::note_declared_at);
6066 if (Kind != TSK_CompleteObject)
6067 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6068 << Kind << SubType.getUnqualifiedType() << CSM;
6070 // Explain why the defaulted or deleted special member isn't trivial.
6071 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6078 /// Check whether the members of a class type allow a special member to be
6080 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6081 Sema::CXXSpecialMember CSM,
6082 bool ConstArg, bool Diagnose) {
6083 for (const auto *FI : RD->fields()) {
6084 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6087 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6089 // Pretend anonymous struct or union members are members of this class.
6090 if (FI->isAnonymousStructOrUnion()) {
6091 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6092 CSM, ConstArg, Diagnose))
6097 // C++11 [class.ctor]p5:
6098 // A default constructor is trivial if [...]
6099 // -- no non-static data member of its class has a
6100 // brace-or-equal-initializer
6101 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6103 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6107 // Objective C ARC 4.3.5:
6108 // [...] nontrivally ownership-qualified types are [...] not trivially
6109 // default constructible, copy constructible, move constructible, copy
6110 // assignable, move assignable, or destructible [...]
6111 if (S.getLangOpts().ObjCAutoRefCount &&
6112 FieldType.hasNonTrivialObjCLifetime()) {
6114 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6115 << RD << FieldType.getObjCLifetime();
6119 bool ConstRHS = ConstArg && !FI->isMutable();
6120 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6121 CSM, TSK_Field, Diagnose))
6128 /// Diagnose why the specified class does not have a trivial special member of
6130 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6131 QualType Ty = Context.getRecordType(RD);
6133 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6134 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6135 TSK_CompleteObject, /*Diagnose*/true);
6138 /// Determine whether a defaulted or deleted special member function is trivial,
6139 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6140 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6141 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6143 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6145 CXXRecordDecl *RD = MD->getParent();
6147 bool ConstArg = false;
6149 // C++11 [class.copy]p12, p25: [DR1593]
6150 // A [special member] is trivial if [...] its parameter-type-list is
6151 // equivalent to the parameter-type-list of an implicit declaration [...]
6153 case CXXDefaultConstructor:
6155 // Trivial default constructors and destructors cannot have parameters.
6158 case CXXCopyConstructor:
6159 case CXXCopyAssignment: {
6160 // Trivial copy operations always have const, non-volatile parameter types.
6162 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6163 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6164 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6166 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6167 << Param0->getSourceRange() << Param0->getType()
6168 << Context.getLValueReferenceType(
6169 Context.getRecordType(RD).withConst());
6175 case CXXMoveConstructor:
6176 case CXXMoveAssignment: {
6177 // Trivial move operations always have non-cv-qualified parameters.
6178 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6179 const RValueReferenceType *RT =
6180 Param0->getType()->getAs<RValueReferenceType>();
6181 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6183 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6184 << Param0->getSourceRange() << Param0->getType()
6185 << Context.getRValueReferenceType(Context.getRecordType(RD));
6192 llvm_unreachable("not a special member");
6195 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6197 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6198 diag::note_nontrivial_default_arg)
6199 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6202 if (MD->isVariadic()) {
6204 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6208 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6209 // A copy/move [constructor or assignment operator] is trivial if
6210 // -- the [member] selected to copy/move each direct base class subobject
6213 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6214 // A [default constructor or destructor] is trivial if
6215 // -- all the direct base classes have trivial [default constructors or
6217 for (const auto &BI : RD->bases())
6218 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6219 ConstArg, CSM, TSK_BaseClass, Diagnose))
6222 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6223 // A copy/move [constructor or assignment operator] for a class X is
6225 // -- for each non-static data member of X that is of class type (or array
6226 // thereof), the constructor selected to copy/move that member is
6229 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6230 // A [default constructor or destructor] is trivial if
6231 // -- for all of the non-static data members of its class that are of class
6232 // type (or array thereof), each such class has a trivial [default
6233 // constructor or destructor]
6234 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6237 // C++11 [class.dtor]p5:
6238 // A destructor is trivial if [...]
6239 // -- the destructor is not virtual
6240 if (CSM == CXXDestructor && MD->isVirtual()) {
6242 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6246 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6247 // A [special member] for class X is trivial if [...]
6248 // -- class X has no virtual functions and no virtual base classes
6249 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6253 if (RD->getNumVBases()) {
6254 // Check for virtual bases. We already know that the corresponding
6255 // member in all bases is trivial, so vbases must all be direct.
6256 CXXBaseSpecifier &BS = *RD->vbases_begin();
6257 assert(BS.isVirtual());
6258 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6262 // Must have a virtual method.
6263 for (const auto *MI : RD->methods()) {
6264 if (MI->isVirtual()) {
6265 SourceLocation MLoc = MI->getLocStart();
6266 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6271 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6274 // Looks like it's trivial!
6279 struct FindHiddenVirtualMethod {
6281 CXXMethodDecl *Method;
6282 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6283 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6286 /// Check whether any most overriden method from MD in Methods
6287 static bool CheckMostOverridenMethods(
6288 const CXXMethodDecl *MD,
6289 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6290 if (MD->size_overridden_methods() == 0)
6291 return Methods.count(MD->getCanonicalDecl());
6292 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6293 E = MD->end_overridden_methods();
6295 if (CheckMostOverridenMethods(*I, Methods))
6301 /// Member lookup function that determines whether a given C++
6302 /// method overloads virtual methods in a base class without overriding any,
6303 /// to be used with CXXRecordDecl::lookupInBases().
6304 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6305 RecordDecl *BaseRecord =
6306 Specifier->getType()->getAs<RecordType>()->getDecl();
6308 DeclarationName Name = Method->getDeclName();
6309 assert(Name.getNameKind() == DeclarationName::Identifier);
6311 bool foundSameNameMethod = false;
6312 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6313 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6314 Path.Decls = Path.Decls.slice(1)) {
6315 NamedDecl *D = Path.Decls.front();
6316 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6317 MD = MD->getCanonicalDecl();
6318 foundSameNameMethod = true;
6319 // Interested only in hidden virtual methods.
6320 if (!MD->isVirtual())
6322 // If the method we are checking overrides a method from its base
6323 // don't warn about the other overloaded methods. Clang deviates from
6324 // GCC by only diagnosing overloads of inherited virtual functions that
6325 // do not override any other virtual functions in the base. GCC's
6326 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6327 // function from a base class. These cases may be better served by a
6328 // warning (not specific to virtual functions) on call sites when the
6329 // call would select a different function from the base class, were it
6331 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6332 if (!S->IsOverload(Method, MD, false))
6334 // Collect the overload only if its hidden.
6335 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6336 overloadedMethods.push_back(MD);
6340 if (foundSameNameMethod)
6341 OverloadedMethods.append(overloadedMethods.begin(),
6342 overloadedMethods.end());
6343 return foundSameNameMethod;
6346 } // end anonymous namespace
6348 /// \brief Add the most overriden methods from MD to Methods
6349 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6350 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6351 if (MD->size_overridden_methods() == 0)
6352 Methods.insert(MD->getCanonicalDecl());
6353 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6354 E = MD->end_overridden_methods();
6356 AddMostOverridenMethods(*I, Methods);
6359 /// \brief Check if a method overloads virtual methods in a base class without
6361 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6362 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6363 if (!MD->getDeclName().isIdentifier())
6366 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6367 /*bool RecordPaths=*/false,
6368 /*bool DetectVirtual=*/false);
6369 FindHiddenVirtualMethod FHVM;
6373 // Keep the base methods that were overriden or introduced in the subclass
6374 // by 'using' in a set. A base method not in this set is hidden.
6375 CXXRecordDecl *DC = MD->getParent();
6376 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6377 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6379 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6380 ND = shad->getTargetDecl();
6381 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6382 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
6385 if (DC->lookupInBases(FHVM, Paths))
6386 OverloadedMethods = FHVM.OverloadedMethods;
6389 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6390 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6391 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6392 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6393 PartialDiagnostic PD = PDiag(
6394 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6395 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6396 Diag(overloadedMD->getLocation(), PD);
6400 /// \brief Diagnose methods which overload virtual methods in a base class
6401 /// without overriding any.
6402 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6403 if (MD->isInvalidDecl())
6406 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6409 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6410 FindHiddenVirtualMethods(MD, OverloadedMethods);
6411 if (!OverloadedMethods.empty()) {
6412 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6413 << MD << (OverloadedMethods.size() > 1);
6415 NoteHiddenVirtualMethods(MD, OverloadedMethods);
6419 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6421 SourceLocation LBrac,
6422 SourceLocation RBrac,
6423 AttributeList *AttrList) {
6427 AdjustDeclIfTemplate(TagDecl);
6429 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6430 if (l->getKind() != AttributeList::AT_Visibility)
6433 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6437 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6438 // strict aliasing violation!
6439 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6440 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6442 CheckCompletedCXXClass(
6443 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6446 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6447 /// special functions, such as the default constructor, copy
6448 /// constructor, or destructor, to the given C++ class (C++
6449 /// [special]p1). This routine can only be executed just before the
6450 /// definition of the class is complete.
6451 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6452 if (!ClassDecl->hasUserDeclaredConstructor())
6453 ++ASTContext::NumImplicitDefaultConstructors;
6455 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6456 ++ASTContext::NumImplicitCopyConstructors;
6458 // If the properties or semantics of the copy constructor couldn't be
6459 // determined while the class was being declared, force a declaration
6461 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6462 DeclareImplicitCopyConstructor(ClassDecl);
6465 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6466 ++ASTContext::NumImplicitMoveConstructors;
6468 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6469 DeclareImplicitMoveConstructor(ClassDecl);
6472 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6473 ++ASTContext::NumImplicitCopyAssignmentOperators;
6475 // If we have a dynamic class, then the copy assignment operator may be
6476 // virtual, so we have to declare it immediately. This ensures that, e.g.,
6477 // it shows up in the right place in the vtable and that we diagnose
6478 // problems with the implicit exception specification.
6479 if (ClassDecl->isDynamicClass() ||
6480 ClassDecl->needsOverloadResolutionForCopyAssignment())
6481 DeclareImplicitCopyAssignment(ClassDecl);
6484 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6485 ++ASTContext::NumImplicitMoveAssignmentOperators;
6487 // Likewise for the move assignment operator.
6488 if (ClassDecl->isDynamicClass() ||
6489 ClassDecl->needsOverloadResolutionForMoveAssignment())
6490 DeclareImplicitMoveAssignment(ClassDecl);
6493 if (!ClassDecl->hasUserDeclaredDestructor()) {
6494 ++ASTContext::NumImplicitDestructors;
6496 // If we have a dynamic class, then the destructor may be virtual, so we
6497 // have to declare the destructor immediately. This ensures that, e.g., it
6498 // shows up in the right place in the vtable and that we diagnose problems
6499 // with the implicit exception specification.
6500 if (ClassDecl->isDynamicClass() ||
6501 ClassDecl->needsOverloadResolutionForDestructor())
6502 DeclareImplicitDestructor(ClassDecl);
6506 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6510 // The order of template parameters is not important here. All names
6511 // get added to the same scope.
6512 SmallVector<TemplateParameterList *, 4> ParameterLists;
6514 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6515 D = TD->getTemplatedDecl();
6517 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6518 ParameterLists.push_back(PSD->getTemplateParameters());
6520 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6521 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6522 ParameterLists.push_back(DD->getTemplateParameterList(i));
6524 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6525 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6526 ParameterLists.push_back(FTD->getTemplateParameters());
6530 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6531 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6532 ParameterLists.push_back(TD->getTemplateParameterList(i));
6534 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6535 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6536 ParameterLists.push_back(CTD->getTemplateParameters());
6541 for (TemplateParameterList *Params : ParameterLists) {
6542 if (Params->size() > 0)
6543 // Ignore explicit specializations; they don't contribute to the template
6546 for (NamedDecl *Param : *Params) {
6547 if (Param->getDeclName()) {
6549 IdResolver.AddDecl(Param);
6557 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6558 if (!RecordD) return;
6559 AdjustDeclIfTemplate(RecordD);
6560 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6561 PushDeclContext(S, Record);
6564 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6565 if (!RecordD) return;
6569 /// This is used to implement the constant expression evaluation part of the
6570 /// attribute enable_if extension. There is nothing in standard C++ which would
6571 /// require reentering parameters.
6572 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6577 if (Param->getDeclName())
6578 IdResolver.AddDecl(Param);
6581 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6582 /// parsing a top-level (non-nested) C++ class, and we are now
6583 /// parsing those parts of the given Method declaration that could
6584 /// not be parsed earlier (C++ [class.mem]p2), such as default
6585 /// arguments. This action should enter the scope of the given
6586 /// Method declaration as if we had just parsed the qualified method
6587 /// name. However, it should not bring the parameters into scope;
6588 /// that will be performed by ActOnDelayedCXXMethodParameter.
6589 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6592 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6593 /// C++ method declaration. We're (re-)introducing the given
6594 /// function parameter into scope for use in parsing later parts of
6595 /// the method declaration. For example, we could see an
6596 /// ActOnParamDefaultArgument event for this parameter.
6597 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6601 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6603 // If this parameter has an unparsed default argument, clear it out
6604 // to make way for the parsed default argument.
6605 if (Param->hasUnparsedDefaultArg())
6606 Param->setDefaultArg(nullptr);
6609 if (Param->getDeclName())
6610 IdResolver.AddDecl(Param);
6613 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6614 /// processing the delayed method declaration for Method. The method
6615 /// declaration is now considered finished. There may be a separate
6616 /// ActOnStartOfFunctionDef action later (not necessarily
6617 /// immediately!) for this method, if it was also defined inside the
6619 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6623 AdjustDeclIfTemplate(MethodD);
6625 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6627 // Now that we have our default arguments, check the constructor
6628 // again. It could produce additional diagnostics or affect whether
6629 // the class has implicitly-declared destructors, among other
6631 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6632 CheckConstructor(Constructor);
6634 // Check the default arguments, which we may have added.
6635 if (!Method->isInvalidDecl())
6636 CheckCXXDefaultArguments(Method);
6639 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6640 /// the well-formedness of the constructor declarator @p D with type @p
6641 /// R. If there are any errors in the declarator, this routine will
6642 /// emit diagnostics and set the invalid bit to true. In any case, the type
6643 /// will be updated to reflect a well-formed type for the constructor and
6645 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6647 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6649 // C++ [class.ctor]p3:
6650 // A constructor shall not be virtual (10.3) or static (9.4). A
6651 // constructor can be invoked for a const, volatile or const
6652 // volatile object. A constructor shall not be declared const,
6653 // volatile, or const volatile (9.3.2).
6655 if (!D.isInvalidType())
6656 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6657 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6658 << SourceRange(D.getIdentifierLoc());
6661 if (SC == SC_Static) {
6662 if (!D.isInvalidType())
6663 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6664 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6665 << SourceRange(D.getIdentifierLoc());
6670 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6671 diagnoseIgnoredQualifiers(
6672 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6673 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6674 D.getDeclSpec().getRestrictSpecLoc(),
6675 D.getDeclSpec().getAtomicSpecLoc());
6679 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6680 if (FTI.TypeQuals != 0) {
6681 if (FTI.TypeQuals & Qualifiers::Const)
6682 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6683 << "const" << SourceRange(D.getIdentifierLoc());
6684 if (FTI.TypeQuals & Qualifiers::Volatile)
6685 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6686 << "volatile" << SourceRange(D.getIdentifierLoc());
6687 if (FTI.TypeQuals & Qualifiers::Restrict)
6688 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6689 << "restrict" << SourceRange(D.getIdentifierLoc());
6693 // C++0x [class.ctor]p4:
6694 // A constructor shall not be declared with a ref-qualifier.
6695 if (FTI.hasRefQualifier()) {
6696 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6697 << FTI.RefQualifierIsLValueRef
6698 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6702 // Rebuild the function type "R" without any type qualifiers (in
6703 // case any of the errors above fired) and with "void" as the
6704 // return type, since constructors don't have return types.
6705 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6706 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6709 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6711 EPI.RefQualifier = RQ_None;
6713 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6716 /// CheckConstructor - Checks a fully-formed constructor for
6717 /// well-formedness, issuing any diagnostics required. Returns true if
6718 /// the constructor declarator is invalid.
6719 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6720 CXXRecordDecl *ClassDecl
6721 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6723 return Constructor->setInvalidDecl();
6725 // C++ [class.copy]p3:
6726 // A declaration of a constructor for a class X is ill-formed if
6727 // its first parameter is of type (optionally cv-qualified) X and
6728 // either there are no other parameters or else all other
6729 // parameters have default arguments.
6730 if (!Constructor->isInvalidDecl() &&
6731 ((Constructor->getNumParams() == 1) ||
6732 (Constructor->getNumParams() > 1 &&
6733 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6734 Constructor->getTemplateSpecializationKind()
6735 != TSK_ImplicitInstantiation) {
6736 QualType ParamType = Constructor->getParamDecl(0)->getType();
6737 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6738 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6739 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6740 const char *ConstRef
6741 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6743 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6744 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6746 // FIXME: Rather that making the constructor invalid, we should endeavor
6748 Constructor->setInvalidDecl();
6753 /// CheckDestructor - Checks a fully-formed destructor definition for
6754 /// well-formedness, issuing any diagnostics required. Returns true
6756 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6757 CXXRecordDecl *RD = Destructor->getParent();
6759 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6762 if (!Destructor->isImplicit())
6763 Loc = Destructor->getLocation();
6765 Loc = RD->getLocation();
6767 // If we have a virtual destructor, look up the deallocation function
6768 FunctionDecl *OperatorDelete = nullptr;
6769 DeclarationName Name =
6770 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6771 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6773 // If there's no class-specific operator delete, look up the global
6774 // non-array delete.
6775 if (!OperatorDelete)
6776 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6778 MarkFunctionReferenced(Loc, OperatorDelete);
6780 Destructor->setOperatorDelete(OperatorDelete);
6786 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6787 /// the well-formednes of the destructor declarator @p D with type @p
6788 /// R. If there are any errors in the declarator, this routine will
6789 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6790 /// will be updated to reflect a well-formed type for the destructor and
6792 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6794 // C++ [class.dtor]p1:
6795 // [...] A typedef-name that names a class is a class-name
6796 // (7.1.3); however, a typedef-name that names a class shall not
6797 // be used as the identifier in the declarator for a destructor
6799 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6800 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6801 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6802 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6803 else if (const TemplateSpecializationType *TST =
6804 DeclaratorType->getAs<TemplateSpecializationType>())
6805 if (TST->isTypeAlias())
6806 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6807 << DeclaratorType << 1;
6809 // C++ [class.dtor]p2:
6810 // A destructor is used to destroy objects of its class type. A
6811 // destructor takes no parameters, and no return type can be
6812 // specified for it (not even void). The address of a destructor
6813 // shall not be taken. A destructor shall not be static. A
6814 // destructor can be invoked for a const, volatile or const
6815 // volatile object. A destructor shall not be declared const,
6816 // volatile or const volatile (9.3.2).
6817 if (SC == SC_Static) {
6818 if (!D.isInvalidType())
6819 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6820 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6821 << SourceRange(D.getIdentifierLoc())
6822 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6826 if (!D.isInvalidType()) {
6827 // Destructors don't have return types, but the parser will
6828 // happily parse something like:
6834 // The return type will be eliminated later.
6835 if (D.getDeclSpec().hasTypeSpecifier())
6836 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6837 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6838 << SourceRange(D.getIdentifierLoc());
6839 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6840 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6842 D.getDeclSpec().getConstSpecLoc(),
6843 D.getDeclSpec().getVolatileSpecLoc(),
6844 D.getDeclSpec().getRestrictSpecLoc(),
6845 D.getDeclSpec().getAtomicSpecLoc());
6850 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6851 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6852 if (FTI.TypeQuals & Qualifiers::Const)
6853 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6854 << "const" << SourceRange(D.getIdentifierLoc());
6855 if (FTI.TypeQuals & Qualifiers::Volatile)
6856 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6857 << "volatile" << SourceRange(D.getIdentifierLoc());
6858 if (FTI.TypeQuals & Qualifiers::Restrict)
6859 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6860 << "restrict" << SourceRange(D.getIdentifierLoc());
6864 // C++0x [class.dtor]p2:
6865 // A destructor shall not be declared with a ref-qualifier.
6866 if (FTI.hasRefQualifier()) {
6867 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6868 << FTI.RefQualifierIsLValueRef
6869 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6873 // Make sure we don't have any parameters.
6874 if (FTIHasNonVoidParameters(FTI)) {
6875 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6877 // Delete the parameters.
6882 // Make sure the destructor isn't variadic.
6883 if (FTI.isVariadic) {
6884 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6888 // Rebuild the function type "R" without any type qualifiers or
6889 // parameters (in case any of the errors above fired) and with
6890 // "void" as the return type, since destructors don't have return
6892 if (!D.isInvalidType())
6895 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6896 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6897 EPI.Variadic = false;
6899 EPI.RefQualifier = RQ_None;
6900 return Context.getFunctionType(Context.VoidTy, None, EPI);
6903 static void extendLeft(SourceRange &R, SourceRange Before) {
6904 if (Before.isInvalid())
6906 R.setBegin(Before.getBegin());
6907 if (R.getEnd().isInvalid())
6908 R.setEnd(Before.getEnd());
6911 static void extendRight(SourceRange &R, SourceRange After) {
6912 if (After.isInvalid())
6914 if (R.getBegin().isInvalid())
6915 R.setBegin(After.getBegin());
6916 R.setEnd(After.getEnd());
6919 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6920 /// well-formednes of the conversion function declarator @p D with
6921 /// type @p R. If there are any errors in the declarator, this routine
6922 /// will emit diagnostics and return true. Otherwise, it will return
6923 /// false. Either way, the type @p R will be updated to reflect a
6924 /// well-formed type for the conversion operator.
6925 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6927 // C++ [class.conv.fct]p1:
6928 // Neither parameter types nor return type can be specified. The
6929 // type of a conversion function (8.3.5) is "function taking no
6930 // parameter returning conversion-type-id."
6931 if (SC == SC_Static) {
6932 if (!D.isInvalidType())
6933 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6934 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6935 << D.getName().getSourceRange();
6940 TypeSourceInfo *ConvTSI = nullptr;
6942 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6944 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6945 // Conversion functions don't have return types, but the parser will
6946 // happily parse something like:
6949 // float operator bool();
6952 // The return type will be changed later anyway.
6953 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6954 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6955 << SourceRange(D.getIdentifierLoc());
6959 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6961 // Make sure we don't have any parameters.
6962 if (Proto->getNumParams() > 0) {
6963 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6965 // Delete the parameters.
6966 D.getFunctionTypeInfo().freeParams();
6968 } else if (Proto->isVariadic()) {
6969 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6973 // Diagnose "&operator bool()" and other such nonsense. This
6974 // is actually a gcc extension which we don't support.
6975 if (Proto->getReturnType() != ConvType) {
6976 bool NeedsTypedef = false;
6977 SourceRange Before, After;
6979 // Walk the chunks and extract information on them for our diagnostic.
6980 bool PastFunctionChunk = false;
6981 for (auto &Chunk : D.type_objects()) {
6982 switch (Chunk.Kind) {
6983 case DeclaratorChunk::Function:
6984 if (!PastFunctionChunk) {
6985 if (Chunk.Fun.HasTrailingReturnType) {
6986 TypeSourceInfo *TRT = nullptr;
6987 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6988 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6990 PastFunctionChunk = true;
6994 case DeclaratorChunk::Array:
6995 NeedsTypedef = true;
6996 extendRight(After, Chunk.getSourceRange());
6999 case DeclaratorChunk::Pointer:
7000 case DeclaratorChunk::BlockPointer:
7001 case DeclaratorChunk::Reference:
7002 case DeclaratorChunk::MemberPointer:
7003 extendLeft(Before, Chunk.getSourceRange());
7006 case DeclaratorChunk::Paren:
7007 extendLeft(Before, Chunk.Loc);
7008 extendRight(After, Chunk.EndLoc);
7013 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7014 After.isValid() ? After.getBegin() :
7015 D.getIdentifierLoc();
7016 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7017 DB << Before << After;
7019 if (!NeedsTypedef) {
7020 DB << /*don't need a typedef*/0;
7022 // If we can provide a correct fix-it hint, do so.
7023 if (After.isInvalid() && ConvTSI) {
7024 SourceLocation InsertLoc =
7025 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7026 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7027 << FixItHint::CreateInsertionFromRange(
7028 InsertLoc, CharSourceRange::getTokenRange(Before))
7029 << FixItHint::CreateRemoval(Before);
7031 } else if (!Proto->getReturnType()->isDependentType()) {
7032 DB << /*typedef*/1 << Proto->getReturnType();
7033 } else if (getLangOpts().CPlusPlus11) {
7034 DB << /*alias template*/2 << Proto->getReturnType();
7036 DB << /*might not be fixable*/3;
7039 // Recover by incorporating the other type chunks into the result type.
7040 // Note, this does *not* change the name of the function. This is compatible
7041 // with the GCC extension:
7042 // struct S { &operator int(); } s;
7043 // int &r = s.operator int(); // ok in GCC
7044 // S::operator int&() {} // error in GCC, function name is 'operator int'.
7045 ConvType = Proto->getReturnType();
7048 // C++ [class.conv.fct]p4:
7049 // The conversion-type-id shall not represent a function type nor
7051 if (ConvType->isArrayType()) {
7052 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7053 ConvType = Context.getPointerType(ConvType);
7055 } else if (ConvType->isFunctionType()) {
7056 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7057 ConvType = Context.getPointerType(ConvType);
7061 // Rebuild the function type "R" without any parameters (in case any
7062 // of the errors above fired) and with the conversion type as the
7064 if (D.isInvalidType())
7065 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7067 // C++0x explicit conversion operators.
7068 if (D.getDeclSpec().isExplicitSpecified())
7069 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7070 getLangOpts().CPlusPlus11 ?
7071 diag::warn_cxx98_compat_explicit_conversion_functions :
7072 diag::ext_explicit_conversion_functions)
7073 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7076 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7077 /// the declaration of the given C++ conversion function. This routine
7078 /// is responsible for recording the conversion function in the C++
7079 /// class, if possible.
7080 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7081 assert(Conversion && "Expected to receive a conversion function declaration");
7083 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7085 // Make sure we aren't redeclaring the conversion function.
7086 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7088 // C++ [class.conv.fct]p1:
7089 // [...] A conversion function is never used to convert a
7090 // (possibly cv-qualified) object to the (possibly cv-qualified)
7091 // same object type (or a reference to it), to a (possibly
7092 // cv-qualified) base class of that type (or a reference to it),
7093 // or to (possibly cv-qualified) void.
7094 // FIXME: Suppress this warning if the conversion function ends up being a
7095 // virtual function that overrides a virtual function in a base class.
7097 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7098 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7099 ConvType = ConvTypeRef->getPointeeType();
7100 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7101 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7102 /* Suppress diagnostics for instantiations. */;
7103 else if (ConvType->isRecordType()) {
7104 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7105 if (ConvType == ClassType)
7106 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7108 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
7109 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7110 << ClassType << ConvType;
7111 } else if (ConvType->isVoidType()) {
7112 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7113 << ClassType << ConvType;
7116 if (FunctionTemplateDecl *ConversionTemplate
7117 = Conversion->getDescribedFunctionTemplate())
7118 return ConversionTemplate;
7123 //===----------------------------------------------------------------------===//
7124 // Namespace Handling
7125 //===----------------------------------------------------------------------===//
7127 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7129 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7131 IdentifierInfo *II, bool *IsInline,
7132 NamespaceDecl *PrevNS) {
7133 assert(*IsInline != PrevNS->isInline());
7135 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7136 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7137 // inline namespaces, with the intention of bringing names into namespace std.
7139 // We support this just well enough to get that case working; this is not
7140 // sufficient to support reopening namespaces as inline in general.
7141 if (*IsInline && II && II->getName().startswith("__atomic") &&
7142 S.getSourceManager().isInSystemHeader(Loc)) {
7143 // Mark all prior declarations of the namespace as inline.
7144 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7145 NS = NS->getPreviousDecl())
7146 NS->setInline(*IsInline);
7147 // Patch up the lookup table for the containing namespace. This isn't really
7148 // correct, but it's good enough for this particular case.
7149 for (auto *I : PrevNS->decls())
7150 if (auto *ND = dyn_cast<NamedDecl>(I))
7151 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7155 if (PrevNS->isInline())
7156 // The user probably just forgot the 'inline', so suggest that it
7158 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7159 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7161 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7163 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7164 *IsInline = PrevNS->isInline();
7167 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7169 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7170 SourceLocation InlineLoc,
7171 SourceLocation NamespaceLoc,
7172 SourceLocation IdentLoc,
7174 SourceLocation LBrace,
7175 AttributeList *AttrList,
7176 UsingDirectiveDecl *&UD) {
7177 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7178 // For anonymous namespace, take the location of the left brace.
7179 SourceLocation Loc = II ? IdentLoc : LBrace;
7180 bool IsInline = InlineLoc.isValid();
7181 bool IsInvalid = false;
7183 bool AddToKnown = false;
7184 Scope *DeclRegionScope = NamespcScope->getParent();
7186 NamespaceDecl *PrevNS = nullptr;
7188 // C++ [namespace.def]p2:
7189 // The identifier in an original-namespace-definition shall not
7190 // have been previously defined in the declarative region in
7191 // which the original-namespace-definition appears. The
7192 // identifier in an original-namespace-definition is the name of
7193 // the namespace. Subsequently in that declarative region, it is
7194 // treated as an original-namespace-name.
7196 // Since namespace names are unique in their scope, and we don't
7197 // look through using directives, just look for any ordinary names
7198 // as if by qualified name lookup.
7199 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7200 LookupQualifiedName(R, CurContext->getRedeclContext());
7201 NamedDecl *PrevDecl =
7202 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
7203 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7206 // This is an extended namespace definition.
7207 if (IsInline != PrevNS->isInline())
7208 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7210 } else if (PrevDecl) {
7211 // This is an invalid name redefinition.
7212 Diag(Loc, diag::err_redefinition_different_kind)
7214 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7216 // Continue on to push Namespc as current DeclContext and return it.
7217 } else if (II->isStr("std") &&
7218 CurContext->getRedeclContext()->isTranslationUnit()) {
7219 // This is the first "real" definition of the namespace "std", so update
7220 // our cache of the "std" namespace to point at this definition.
7221 PrevNS = getStdNamespace();
7223 AddToKnown = !IsInline;
7225 // We've seen this namespace for the first time.
7226 AddToKnown = !IsInline;
7229 // Anonymous namespaces.
7231 // Determine whether the parent already has an anonymous namespace.
7232 DeclContext *Parent = CurContext->getRedeclContext();
7233 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7234 PrevNS = TU->getAnonymousNamespace();
7236 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7237 PrevNS = ND->getAnonymousNamespace();
7240 if (PrevNS && IsInline != PrevNS->isInline())
7241 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7245 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7246 StartLoc, Loc, II, PrevNS);
7248 Namespc->setInvalidDecl();
7250 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7252 // FIXME: Should we be merging attributes?
7253 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7254 PushNamespaceVisibilityAttr(Attr, Loc);
7257 StdNamespace = Namespc;
7259 KnownNamespaces[Namespc] = false;
7262 PushOnScopeChains(Namespc, DeclRegionScope);
7264 // Link the anonymous namespace into its parent.
7265 DeclContext *Parent = CurContext->getRedeclContext();
7266 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7267 TU->setAnonymousNamespace(Namespc);
7269 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7272 CurContext->addDecl(Namespc);
7274 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7275 // behaves as if it were replaced by
7276 // namespace unique { /* empty body */ }
7277 // using namespace unique;
7278 // namespace unique { namespace-body }
7279 // where all occurrences of 'unique' in a translation unit are
7280 // replaced by the same identifier and this identifier differs
7281 // from all other identifiers in the entire program.
7283 // We just create the namespace with an empty name and then add an
7284 // implicit using declaration, just like the standard suggests.
7286 // CodeGen enforces the "universally unique" aspect by giving all
7287 // declarations semantically contained within an anonymous
7288 // namespace internal linkage.
7291 UD = UsingDirectiveDecl::Create(Context, Parent,
7292 /* 'using' */ LBrace,
7293 /* 'namespace' */ SourceLocation(),
7294 /* qualifier */ NestedNameSpecifierLoc(),
7295 /* identifier */ SourceLocation(),
7297 /* Ancestor */ Parent);
7299 Parent->addDecl(UD);
7303 ActOnDocumentableDecl(Namespc);
7305 // Although we could have an invalid decl (i.e. the namespace name is a
7306 // redefinition), push it as current DeclContext and try to continue parsing.
7307 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7308 // for the namespace has the declarations that showed up in that particular
7309 // namespace definition.
7310 PushDeclContext(NamespcScope, Namespc);
7314 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7315 /// is a namespace alias, returns the namespace it points to.
7316 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7317 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7318 return AD->getNamespace();
7319 return dyn_cast_or_null<NamespaceDecl>(D);
7322 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7323 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7324 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7325 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7326 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7327 Namespc->setRBraceLoc(RBrace);
7329 if (Namespc->hasAttr<VisibilityAttr>())
7330 PopPragmaVisibility(true, RBrace);
7333 CXXRecordDecl *Sema::getStdBadAlloc() const {
7334 return cast_or_null<CXXRecordDecl>(
7335 StdBadAlloc.get(Context.getExternalSource()));
7338 NamespaceDecl *Sema::getStdNamespace() const {
7339 return cast_or_null<NamespaceDecl>(
7340 StdNamespace.get(Context.getExternalSource()));
7343 /// \brief Retrieve the special "std" namespace, which may require us to
7344 /// implicitly define the namespace.
7345 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7346 if (!StdNamespace) {
7347 // The "std" namespace has not yet been defined, so build one implicitly.
7348 StdNamespace = NamespaceDecl::Create(Context,
7349 Context.getTranslationUnitDecl(),
7351 SourceLocation(), SourceLocation(),
7352 &PP.getIdentifierTable().get("std"),
7353 /*PrevDecl=*/nullptr);
7354 getStdNamespace()->setImplicit(true);
7357 return getStdNamespace();
7360 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7361 assert(getLangOpts().CPlusPlus &&
7362 "Looking for std::initializer_list outside of C++.");
7364 // We're looking for implicit instantiations of
7365 // template <typename E> class std::initializer_list.
7367 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7370 ClassTemplateDecl *Template = nullptr;
7371 const TemplateArgument *Arguments = nullptr;
7373 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7375 ClassTemplateSpecializationDecl *Specialization =
7376 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7377 if (!Specialization)
7380 Template = Specialization->getSpecializedTemplate();
7381 Arguments = Specialization->getTemplateArgs().data();
7382 } else if (const TemplateSpecializationType *TST =
7383 Ty->getAs<TemplateSpecializationType>()) {
7384 Template = dyn_cast_or_null<ClassTemplateDecl>(
7385 TST->getTemplateName().getAsTemplateDecl());
7386 Arguments = TST->getArgs();
7391 if (!StdInitializerList) {
7392 // Haven't recognized std::initializer_list yet, maybe this is it.
7393 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7394 if (TemplateClass->getIdentifier() !=
7395 &PP.getIdentifierTable().get("initializer_list") ||
7396 !getStdNamespace()->InEnclosingNamespaceSetOf(
7397 TemplateClass->getDeclContext()))
7399 // This is a template called std::initializer_list, but is it the right
7401 TemplateParameterList *Params = Template->getTemplateParameters();
7402 if (Params->getMinRequiredArguments() != 1)
7404 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7407 // It's the right template.
7408 StdInitializerList = Template;
7411 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7414 // This is an instance of std::initializer_list. Find the argument type.
7416 *Element = Arguments[0].getAsType();
7420 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7421 NamespaceDecl *Std = S.getStdNamespace();
7423 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7427 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7428 Loc, Sema::LookupOrdinaryName);
7429 if (!S.LookupQualifiedName(Result, Std)) {
7430 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7433 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7435 Result.suppressDiagnostics();
7436 // We found something weird. Complain about the first thing we found.
7437 NamedDecl *Found = *Result.begin();
7438 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7442 // We found some template called std::initializer_list. Now verify that it's
7444 TemplateParameterList *Params = Template->getTemplateParameters();
7445 if (Params->getMinRequiredArguments() != 1 ||
7446 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7447 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7454 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7455 if (!StdInitializerList) {
7456 StdInitializerList = LookupStdInitializerList(*this, Loc);
7457 if (!StdInitializerList)
7461 TemplateArgumentListInfo Args(Loc, Loc);
7462 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7463 Context.getTrivialTypeSourceInfo(Element,
7465 return Context.getCanonicalType(
7466 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7469 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7470 // C++ [dcl.init.list]p2:
7471 // A constructor is an initializer-list constructor if its first parameter
7472 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7473 // std::initializer_list<E> for some type E, and either there are no other
7474 // parameters or else all other parameters have default arguments.
7475 if (Ctor->getNumParams() < 1 ||
7476 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7479 QualType ArgType = Ctor->getParamDecl(0)->getType();
7480 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7481 ArgType = RT->getPointeeType().getUnqualifiedType();
7483 return isStdInitializerList(ArgType, nullptr);
7486 /// \brief Determine whether a using statement is in a context where it will be
7487 /// apply in all contexts.
7488 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7489 switch (CurContext->getDeclKind()) {
7490 case Decl::TranslationUnit:
7492 case Decl::LinkageSpec:
7493 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7501 // Callback to only accept typo corrections that are namespaces.
7502 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7504 bool ValidateCandidate(const TypoCorrection &candidate) override {
7505 if (NamedDecl *ND = candidate.getCorrectionDecl())
7506 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7513 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7515 SourceLocation IdentLoc,
7516 IdentifierInfo *Ident) {
7518 if (TypoCorrection Corrected =
7519 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7520 llvm::make_unique<NamespaceValidatorCCC>(),
7521 Sema::CTK_ErrorRecovery)) {
7522 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7523 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7524 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7525 Ident->getName().equals(CorrectedStr);
7526 S.diagnoseTypo(Corrected,
7527 S.PDiag(diag::err_using_directive_member_suggest)
7528 << Ident << DC << DroppedSpecifier << SS.getRange(),
7529 S.PDiag(diag::note_namespace_defined_here));
7531 S.diagnoseTypo(Corrected,
7532 S.PDiag(diag::err_using_directive_suggest) << Ident,
7533 S.PDiag(diag::note_namespace_defined_here));
7535 R.addDecl(Corrected.getFoundDecl());
7541 Decl *Sema::ActOnUsingDirective(Scope *S,
7542 SourceLocation UsingLoc,
7543 SourceLocation NamespcLoc,
7545 SourceLocation IdentLoc,
7546 IdentifierInfo *NamespcName,
7547 AttributeList *AttrList) {
7548 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7549 assert(NamespcName && "Invalid NamespcName.");
7550 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7552 // This can only happen along a recovery path.
7553 while (S->isTemplateParamScope())
7555 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7557 UsingDirectiveDecl *UDir = nullptr;
7558 NestedNameSpecifier *Qualifier = nullptr;
7560 Qualifier = SS.getScopeRep();
7562 // Lookup namespace name.
7563 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7564 LookupParsedName(R, S, &SS);
7565 if (R.isAmbiguous())
7570 // Allow "using namespace std;" or "using namespace ::std;" even if
7571 // "std" hasn't been defined yet, for GCC compatibility.
7572 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7573 NamespcName->isStr("std")) {
7574 Diag(IdentLoc, diag::ext_using_undefined_std);
7575 R.addDecl(getOrCreateStdNamespace());
7578 // Otherwise, attempt typo correction.
7579 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7583 NamedDecl *Named = R.getRepresentativeDecl();
7584 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
7585 assert(NS && "expected namespace decl");
7587 // The use of a nested name specifier may trigger deprecation warnings.
7588 DiagnoseUseOfDecl(Named, IdentLoc);
7590 // C++ [namespace.udir]p1:
7591 // A using-directive specifies that the names in the nominated
7592 // namespace can be used in the scope in which the
7593 // using-directive appears after the using-directive. During
7594 // unqualified name lookup (3.4.1), the names appear as if they
7595 // were declared in the nearest enclosing namespace which
7596 // contains both the using-directive and the nominated
7597 // namespace. [Note: in this context, "contains" means "contains
7598 // directly or indirectly". ]
7600 // Find enclosing context containing both using-directive and
7601 // nominated namespace.
7602 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7603 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7604 CommonAncestor = CommonAncestor->getParent();
7606 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7607 SS.getWithLocInContext(Context),
7608 IdentLoc, Named, CommonAncestor);
7610 if (IsUsingDirectiveInToplevelContext(CurContext) &&
7611 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7612 Diag(IdentLoc, diag::warn_using_directive_in_header);
7615 PushUsingDirective(S, UDir);
7617 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7621 ProcessDeclAttributeList(S, UDir, AttrList);
7626 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7627 // If the scope has an associated entity and the using directive is at
7628 // namespace or translation unit scope, add the UsingDirectiveDecl into
7629 // its lookup structure so qualified name lookup can find it.
7630 DeclContext *Ctx = S->getEntity();
7631 if (Ctx && !Ctx->isFunctionOrMethod())
7634 // Otherwise, it is at block scope. The using-directives will affect lookup
7635 // only to the end of the scope.
7636 S->PushUsingDirective(UDir);
7640 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7642 bool HasUsingKeyword,
7643 SourceLocation UsingLoc,
7645 UnqualifiedId &Name,
7646 AttributeList *AttrList,
7647 bool HasTypenameKeyword,
7648 SourceLocation TypenameLoc) {
7649 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7651 switch (Name.getKind()) {
7652 case UnqualifiedId::IK_ImplicitSelfParam:
7653 case UnqualifiedId::IK_Identifier:
7654 case UnqualifiedId::IK_OperatorFunctionId:
7655 case UnqualifiedId::IK_LiteralOperatorId:
7656 case UnqualifiedId::IK_ConversionFunctionId:
7659 case UnqualifiedId::IK_ConstructorName:
7660 case UnqualifiedId::IK_ConstructorTemplateId:
7661 // C++11 inheriting constructors.
7662 Diag(Name.getLocStart(),
7663 getLangOpts().CPlusPlus11 ?
7664 diag::warn_cxx98_compat_using_decl_constructor :
7665 diag::err_using_decl_constructor)
7668 if (getLangOpts().CPlusPlus11) break;
7672 case UnqualifiedId::IK_DestructorName:
7673 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7677 case UnqualifiedId::IK_TemplateId:
7678 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7679 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7683 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7684 DeclarationName TargetName = TargetNameInfo.getName();
7688 // Warn about access declarations.
7689 if (!HasUsingKeyword) {
7690 Diag(Name.getLocStart(),
7691 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7692 : diag::warn_access_decl_deprecated)
7693 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7696 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7697 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7700 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7701 TargetNameInfo, AttrList,
7702 /* IsInstantiation */ false,
7703 HasTypenameKeyword, TypenameLoc);
7705 PushOnScopeChains(UD, S, /*AddToContext*/ false);
7710 /// \brief Determine whether a using declaration considers the given
7711 /// declarations as "equivalent", e.g., if they are redeclarations of
7712 /// the same entity or are both typedefs of the same type.
7714 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7715 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7718 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7719 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7720 return Context.hasSameType(TD1->getUnderlyingType(),
7721 TD2->getUnderlyingType());
7727 /// Determines whether to create a using shadow decl for a particular
7728 /// decl, given the set of decls existing prior to this using lookup.
7729 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7730 const LookupResult &Previous,
7731 UsingShadowDecl *&PrevShadow) {
7732 // Diagnose finding a decl which is not from a base class of the
7733 // current class. We do this now because there are cases where this
7734 // function will silently decide not to build a shadow decl, which
7735 // will pre-empt further diagnostics.
7737 // We don't need to do this in C++0x because we do the check once on
7740 // FIXME: diagnose the following if we care enough:
7741 // struct A { int foo; };
7742 // struct B : A { using A::foo; };
7743 // template <class T> struct C : A {};
7744 // template <class T> struct D : C<T> { using B::foo; } // <---
7745 // This is invalid (during instantiation) in C++03 because B::foo
7746 // resolves to the using decl in B, which is not a base class of D<T>.
7747 // We can't diagnose it immediately because C<T> is an unknown
7748 // specialization. The UsingShadowDecl in D<T> then points directly
7749 // to A::foo, which will look well-formed when we instantiate.
7750 // The right solution is to not collapse the shadow-decl chain.
7751 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7752 DeclContext *OrigDC = Orig->getDeclContext();
7754 // Handle enums and anonymous structs.
7755 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7756 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7757 while (OrigRec->isAnonymousStructOrUnion())
7758 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7760 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7761 if (OrigDC == CurContext) {
7762 Diag(Using->getLocation(),
7763 diag::err_using_decl_nested_name_specifier_is_current_class)
7764 << Using->getQualifierLoc().getSourceRange();
7765 Diag(Orig->getLocation(), diag::note_using_decl_target);
7769 Diag(Using->getQualifierLoc().getBeginLoc(),
7770 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7771 << Using->getQualifier()
7772 << cast<CXXRecordDecl>(CurContext)
7773 << Using->getQualifierLoc().getSourceRange();
7774 Diag(Orig->getLocation(), diag::note_using_decl_target);
7779 if (Previous.empty()) return false;
7781 NamedDecl *Target = Orig;
7782 if (isa<UsingShadowDecl>(Target))
7783 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7785 // If the target happens to be one of the previous declarations, we
7786 // don't have a conflict.
7788 // FIXME: but we might be increasing its access, in which case we
7789 // should redeclare it.
7790 NamedDecl *NonTag = nullptr, *Tag = nullptr;
7791 bool FoundEquivalentDecl = false;
7792 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7794 NamedDecl *D = (*I)->getUnderlyingDecl();
7795 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7796 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7797 PrevShadow = Shadow;
7798 FoundEquivalentDecl = true;
7802 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7805 if (FoundEquivalentDecl)
7808 if (FunctionDecl *FD = Target->getAsFunction()) {
7809 NamedDecl *OldDecl = nullptr;
7810 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7811 /*IsForUsingDecl*/ true)) {
7815 case Ovl_NonFunction:
7816 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7819 // We found a decl with the exact signature.
7821 // If we're in a record, we want to hide the target, so we
7822 // return true (without a diagnostic) to tell the caller not to
7823 // build a shadow decl.
7824 if (CurContext->isRecord())
7827 // If we're not in a record, this is an error.
7828 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7832 Diag(Target->getLocation(), diag::note_using_decl_target);
7833 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7837 // Target is not a function.
7839 if (isa<TagDecl>(Target)) {
7840 // No conflict between a tag and a non-tag.
7841 if (!Tag) return false;
7843 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7844 Diag(Target->getLocation(), diag::note_using_decl_target);
7845 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7849 // No conflict between a tag and a non-tag.
7850 if (!NonTag) return false;
7852 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7853 Diag(Target->getLocation(), diag::note_using_decl_target);
7854 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7858 /// Builds a shadow declaration corresponding to a 'using' declaration.
7859 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7862 UsingShadowDecl *PrevDecl) {
7864 // If we resolved to another shadow declaration, just coalesce them.
7865 NamedDecl *Target = Orig;
7866 if (isa<UsingShadowDecl>(Target)) {
7867 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7868 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7871 UsingShadowDecl *Shadow
7872 = UsingShadowDecl::Create(Context, CurContext,
7873 UD->getLocation(), UD, Target);
7874 UD->addShadowDecl(Shadow);
7876 Shadow->setAccess(UD->getAccess());
7877 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7878 Shadow->setInvalidDecl();
7880 Shadow->setPreviousDecl(PrevDecl);
7883 PushOnScopeChains(Shadow, S);
7885 CurContext->addDecl(Shadow);
7891 /// Hides a using shadow declaration. This is required by the current
7892 /// using-decl implementation when a resolvable using declaration in a
7893 /// class is followed by a declaration which would hide or override
7894 /// one or more of the using decl's targets; for example:
7896 /// struct Base { void foo(int); };
7897 /// struct Derived : Base {
7898 /// using Base::foo;
7902 /// The governing language is C++03 [namespace.udecl]p12:
7904 /// When a using-declaration brings names from a base class into a
7905 /// derived class scope, member functions in the derived class
7906 /// override and/or hide member functions with the same name and
7907 /// parameter types in a base class (rather than conflicting).
7909 /// There are two ways to implement this:
7910 /// (1) optimistically create shadow decls when they're not hidden
7911 /// by existing declarations, or
7912 /// (2) don't create any shadow decls (or at least don't make them
7913 /// visible) until we've fully parsed/instantiated the class.
7914 /// The problem with (1) is that we might have to retroactively remove
7915 /// a shadow decl, which requires several O(n) operations because the
7916 /// decl structures are (very reasonably) not designed for removal.
7917 /// (2) avoids this but is very fiddly and phase-dependent.
7918 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7919 if (Shadow->getDeclName().getNameKind() ==
7920 DeclarationName::CXXConversionFunctionName)
7921 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7923 // Remove it from the DeclContext...
7924 Shadow->getDeclContext()->removeDecl(Shadow);
7926 // ...and the scope, if applicable...
7928 S->RemoveDecl(Shadow);
7929 IdResolver.RemoveDecl(Shadow);
7932 // ...and the using decl.
7933 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7935 // TODO: complain somehow if Shadow was used. It shouldn't
7936 // be possible for this to happen, because...?
7939 /// Find the base specifier for a base class with the given type.
7940 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7941 QualType DesiredBase,
7942 bool &AnyDependentBases) {
7943 // Check whether the named type is a direct base class.
7944 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7945 for (auto &Base : Derived->bases()) {
7946 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7947 if (CanonicalDesiredBase == BaseType)
7949 if (BaseType->isDependentType())
7950 AnyDependentBases = true;
7956 class UsingValidatorCCC : public CorrectionCandidateCallback {
7958 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7959 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7960 : HasTypenameKeyword(HasTypenameKeyword),
7961 IsInstantiation(IsInstantiation), OldNNS(NNS),
7962 RequireMemberOf(RequireMemberOf) {}
7964 bool ValidateCandidate(const TypoCorrection &Candidate) override {
7965 NamedDecl *ND = Candidate.getCorrectionDecl();
7967 // Keywords are not valid here.
7968 if (!ND || isa<NamespaceDecl>(ND))
7971 // Completely unqualified names are invalid for a 'using' declaration.
7972 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7975 if (RequireMemberOf) {
7976 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7977 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7978 // No-one ever wants a using-declaration to name an injected-class-name
7979 // of a base class, unless they're declaring an inheriting constructor.
7980 ASTContext &Ctx = ND->getASTContext();
7981 if (!Ctx.getLangOpts().CPlusPlus11)
7983 QualType FoundType = Ctx.getRecordType(FoundRecord);
7985 // Check that the injected-class-name is named as a member of its own
7986 // type; we don't want to suggest 'using Derived::Base;', since that
7987 // means something else.
7988 NestedNameSpecifier *Specifier =
7989 Candidate.WillReplaceSpecifier()
7990 ? Candidate.getCorrectionSpecifier()
7992 if (!Specifier->getAsType() ||
7993 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7996 // Check that this inheriting constructor declaration actually names a
7997 // direct base class of the current class.
7998 bool AnyDependentBases = false;
7999 if (!findDirectBaseWithType(RequireMemberOf,
8000 Ctx.getRecordType(FoundRecord),
8001 AnyDependentBases) &&
8005 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8006 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8009 // FIXME: Check that the base class member is accessible?
8012 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8013 if (FoundRecord && FoundRecord->isInjectedClassName())
8017 if (isa<TypeDecl>(ND))
8018 return HasTypenameKeyword || !IsInstantiation;
8020 return !HasTypenameKeyword;
8024 bool HasTypenameKeyword;
8025 bool IsInstantiation;
8026 NestedNameSpecifier *OldNNS;
8027 CXXRecordDecl *RequireMemberOf;
8029 } // end anonymous namespace
8031 /// Builds a using declaration.
8033 /// \param IsInstantiation - Whether this call arises from an
8034 /// instantiation of an unresolved using declaration. We treat
8035 /// the lookup differently for these declarations.
8036 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8037 SourceLocation UsingLoc,
8039 DeclarationNameInfo NameInfo,
8040 AttributeList *AttrList,
8041 bool IsInstantiation,
8042 bool HasTypenameKeyword,
8043 SourceLocation TypenameLoc) {
8044 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8045 SourceLocation IdentLoc = NameInfo.getLoc();
8046 assert(IdentLoc.isValid() && "Invalid TargetName location.");
8048 // FIXME: We ignore attributes for now.
8051 Diag(IdentLoc, diag::err_using_requires_qualname);
8055 // Do the redeclaration lookup in the current scope.
8056 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8058 Previous.setHideTags(false);
8060 LookupName(Previous, S);
8062 // It is really dumb that we have to do this.
8063 LookupResult::Filter F = Previous.makeFilter();
8064 while (F.hasNext()) {
8065 NamedDecl *D = F.next();
8066 if (!isDeclInScope(D, CurContext, S))
8068 // If we found a local extern declaration that's not ordinarily visible,
8069 // and this declaration is being added to a non-block scope, ignore it.
8070 // We're only checking for scope conflicts here, not also for violations
8071 // of the linkage rules.
8072 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8073 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8078 assert(IsInstantiation && "no scope in non-instantiation");
8079 assert(CurContext->isRecord() && "scope not record in instantiation");
8080 LookupQualifiedName(Previous, CurContext);
8083 // Check for invalid redeclarations.
8084 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8085 SS, IdentLoc, Previous))
8088 // Check for bad qualifiers.
8089 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8092 DeclContext *LookupContext = computeDeclContext(SS);
8094 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8095 if (!LookupContext) {
8096 if (HasTypenameKeyword) {
8097 // FIXME: not all declaration name kinds are legal here
8098 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8099 UsingLoc, TypenameLoc,
8101 IdentLoc, NameInfo.getName());
8103 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8104 QualifierLoc, NameInfo);
8107 CurContext->addDecl(D);
8111 auto Build = [&](bool Invalid) {
8113 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8114 HasTypenameKeyword);
8116 CurContext->addDecl(UD);
8117 UD->setInvalidDecl(Invalid);
8120 auto BuildInvalid = [&]{ return Build(true); };
8121 auto BuildValid = [&]{ return Build(false); };
8123 if (RequireCompleteDeclContext(SS, LookupContext))
8124 return BuildInvalid();
8126 // Look up the target name.
8127 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8129 // Unlike most lookups, we don't always want to hide tag
8130 // declarations: tag names are visible through the using declaration
8131 // even if hidden by ordinary names, *except* in a dependent context
8132 // where it's important for the sanity of two-phase lookup.
8133 if (!IsInstantiation)
8134 R.setHideTags(false);
8136 // For the purposes of this lookup, we have a base object type
8137 // equal to that of the current context.
8138 if (CurContext->isRecord()) {
8139 R.setBaseObjectType(
8140 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8143 LookupQualifiedName(R, LookupContext);
8145 // Try to correct typos if possible. If constructor name lookup finds no
8146 // results, that means the named class has no explicit constructors, and we
8147 // suppressed declaring implicit ones (probably because it's dependent or
8150 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8151 if (TypoCorrection Corrected = CorrectTypo(
8152 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8153 llvm::make_unique<UsingValidatorCCC>(
8154 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8155 dyn_cast<CXXRecordDecl>(CurContext)),
8156 CTK_ErrorRecovery)) {
8157 // We reject any correction for which ND would be NULL.
8158 NamedDecl *ND = Corrected.getCorrectionDecl();
8160 // We reject candidates where DroppedSpecifier == true, hence the
8161 // literal '0' below.
8162 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8163 << NameInfo.getName() << LookupContext << 0
8166 // If we corrected to an inheriting constructor, handle it as one.
8167 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8168 if (RD && RD->isInjectedClassName()) {
8169 // Fix up the information we'll use to build the using declaration.
8170 if (Corrected.WillReplaceSpecifier()) {
8171 NestedNameSpecifierLocBuilder Builder;
8172 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8173 QualifierLoc.getSourceRange());
8174 QualifierLoc = Builder.getWithLocInContext(Context);
8177 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8178 Context.getCanonicalType(Context.getRecordType(RD))));
8179 NameInfo.setNamedTypeInfo(nullptr);
8180 for (auto *Ctor : LookupConstructors(RD))
8183 // FIXME: Pick up all the declarations if we found an overloaded function.
8187 Diag(IdentLoc, diag::err_no_member)
8188 << NameInfo.getName() << LookupContext << SS.getRange();
8189 return BuildInvalid();
8193 if (R.isAmbiguous())
8194 return BuildInvalid();
8196 if (HasTypenameKeyword) {
8197 // If we asked for a typename and got a non-type decl, error out.
8198 if (!R.getAsSingle<TypeDecl>()) {
8199 Diag(IdentLoc, diag::err_using_typename_non_type);
8200 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8201 Diag((*I)->getUnderlyingDecl()->getLocation(),
8202 diag::note_using_decl_target);
8203 return BuildInvalid();
8206 // If we asked for a non-typename and we got a type, error out,
8207 // but only if this is an instantiation of an unresolved using
8208 // decl. Otherwise just silently find the type name.
8209 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8210 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8211 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8212 return BuildInvalid();
8216 // C++0x N2914 [namespace.udecl]p6:
8217 // A using-declaration shall not name a namespace.
8218 if (R.getAsSingle<NamespaceDecl>()) {
8219 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8221 return BuildInvalid();
8224 UsingDecl *UD = BuildValid();
8226 // The normal rules do not apply to inheriting constructor declarations.
8227 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8228 // Suppress access diagnostics; the access check is instead performed at the
8229 // point of use for an inheriting constructor.
8230 R.suppressDiagnostics();
8231 CheckInheritingConstructorUsingDecl(UD);
8235 // Otherwise, look up the target name.
8237 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8238 UsingShadowDecl *PrevDecl = nullptr;
8239 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8240 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8246 /// Additional checks for a using declaration referring to a constructor name.
8247 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8248 assert(!UD->hasTypename() && "expecting a constructor name");
8250 const Type *SourceType = UD->getQualifier()->getAsType();
8251 assert(SourceType &&
8252 "Using decl naming constructor doesn't have type in scope spec.");
8253 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8255 // Check whether the named type is a direct base class.
8256 bool AnyDependentBases = false;
8257 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8259 if (!Base && !AnyDependentBases) {
8260 Diag(UD->getUsingLoc(),
8261 diag::err_using_decl_constructor_not_in_direct_base)
8262 << UD->getNameInfo().getSourceRange()
8263 << QualType(SourceType, 0) << TargetClass;
8264 UD->setInvalidDecl();
8269 Base->setInheritConstructors();
8274 /// Checks that the given using declaration is not an invalid
8275 /// redeclaration. Note that this is checking only for the using decl
8276 /// itself, not for any ill-formedness among the UsingShadowDecls.
8277 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8278 bool HasTypenameKeyword,
8279 const CXXScopeSpec &SS,
8280 SourceLocation NameLoc,
8281 const LookupResult &Prev) {
8282 // C++03 [namespace.udecl]p8:
8283 // C++0x [namespace.udecl]p10:
8284 // A using-declaration is a declaration and can therefore be used
8285 // repeatedly where (and only where) multiple declarations are
8288 // That's in non-member contexts.
8289 if (!CurContext->getRedeclContext()->isRecord())
8292 NestedNameSpecifier *Qual = SS.getScopeRep();
8294 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8298 NestedNameSpecifier *DQual;
8299 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8300 DTypename = UD->hasTypename();
8301 DQual = UD->getQualifier();
8302 } else if (UnresolvedUsingValueDecl *UD
8303 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8305 DQual = UD->getQualifier();
8306 } else if (UnresolvedUsingTypenameDecl *UD
8307 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8309 DQual = UD->getQualifier();
8312 // using decls differ if one says 'typename' and the other doesn't.
8313 // FIXME: non-dependent using decls?
8314 if (HasTypenameKeyword != DTypename) continue;
8316 // using decls differ if they name different scopes (but note that
8317 // template instantiation can cause this check to trigger when it
8318 // didn't before instantiation).
8319 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8320 Context.getCanonicalNestedNameSpecifier(DQual))
8323 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8324 Diag(D->getLocation(), diag::note_using_decl) << 1;
8332 /// Checks that the given nested-name qualifier used in a using decl
8333 /// in the current context is appropriately related to the current
8334 /// scope. If an error is found, diagnoses it and returns true.
8335 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8336 const CXXScopeSpec &SS,
8337 const DeclarationNameInfo &NameInfo,
8338 SourceLocation NameLoc) {
8339 DeclContext *NamedContext = computeDeclContext(SS);
8341 if (!CurContext->isRecord()) {
8342 // C++03 [namespace.udecl]p3:
8343 // C++0x [namespace.udecl]p8:
8344 // A using-declaration for a class member shall be a member-declaration.
8346 // If we weren't able to compute a valid scope, it must be a
8347 // dependent class scope.
8348 if (!NamedContext || NamedContext->isRecord()) {
8349 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8350 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8353 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8356 // If we have a complete, non-dependent source type, try to suggest a
8357 // way to get the same effect.
8361 // Find what this using-declaration was referring to.
8362 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8363 R.setHideTags(false);
8364 R.suppressDiagnostics();
8365 LookupQualifiedName(R, RD);
8367 if (R.getAsSingle<TypeDecl>()) {
8368 if (getLangOpts().CPlusPlus11) {
8369 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8370 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8371 << 0 // alias declaration
8372 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8373 NameInfo.getName().getAsString() +
8376 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8377 SourceLocation InsertLoc =
8378 getLocForEndOfToken(NameInfo.getLocEnd());
8379 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8380 << 1 // typedef declaration
8381 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8382 << FixItHint::CreateInsertion(
8383 InsertLoc, " " + NameInfo.getName().getAsString());
8385 } else if (R.getAsSingle<VarDecl>()) {
8386 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8387 // repeating the type of the static data member here.
8389 if (getLangOpts().CPlusPlus11) {
8390 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8391 FixIt = FixItHint::CreateReplacement(
8392 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8395 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8396 << 2 // reference declaration
8402 // Otherwise, everything is known to be fine.
8406 // The current scope is a record.
8408 // If the named context is dependent, we can't decide much.
8409 if (!NamedContext) {
8410 // FIXME: in C++0x, we can diagnose if we can prove that the
8411 // nested-name-specifier does not refer to a base class, which is
8412 // still possible in some cases.
8414 // Otherwise we have to conservatively report that things might be
8419 if (!NamedContext->isRecord()) {
8420 // Ideally this would point at the last name in the specifier,
8421 // but we don't have that level of source info.
8422 Diag(SS.getRange().getBegin(),
8423 diag::err_using_decl_nested_name_specifier_is_not_class)
8424 << SS.getScopeRep() << SS.getRange();
8428 if (!NamedContext->isDependentContext() &&
8429 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8432 if (getLangOpts().CPlusPlus11) {
8433 // C++0x [namespace.udecl]p3:
8434 // In a using-declaration used as a member-declaration, the
8435 // nested-name-specifier shall name a base class of the class
8438 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8439 cast<CXXRecordDecl>(NamedContext))) {
8440 if (CurContext == NamedContext) {
8442 diag::err_using_decl_nested_name_specifier_is_current_class)
8447 Diag(SS.getRange().getBegin(),
8448 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8450 << cast<CXXRecordDecl>(CurContext)
8458 // C++03 [namespace.udecl]p4:
8459 // A using-declaration used as a member-declaration shall refer
8460 // to a member of a base class of the class being defined [etc.].
8462 // Salient point: SS doesn't have to name a base class as long as
8463 // lookup only finds members from base classes. Therefore we can
8464 // diagnose here only if we can prove that that can't happen,
8465 // i.e. if the class hierarchies provably don't intersect.
8467 // TODO: it would be nice if "definitely valid" results were cached
8468 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8469 // need to be repeated.
8471 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8472 auto Collect = [&Bases](const CXXRecordDecl *Base) {
8477 // Collect all bases. Return false if we find a dependent base.
8478 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
8481 // Returns true if the base is dependent or is one of the accumulated base
8483 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8484 return !Bases.count(Base);
8487 // Return false if the class has a dependent base or if it or one
8488 // of its bases is present in the base set of the current context.
8489 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8490 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
8493 Diag(SS.getRange().getBegin(),
8494 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8496 << cast<CXXRecordDecl>(CurContext)
8502 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8504 MultiTemplateParamsArg TemplateParamLists,
8505 SourceLocation UsingLoc,
8506 UnqualifiedId &Name,
8507 AttributeList *AttrList,
8509 Decl *DeclFromDeclSpec) {
8510 // Skip up to the relevant declaration scope.
8511 while (S->isTemplateParamScope())
8513 assert((S->getFlags() & Scope::DeclScope) &&
8514 "got alias-declaration outside of declaration scope");
8516 if (Type.isInvalid())
8519 bool Invalid = false;
8520 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8521 TypeSourceInfo *TInfo = nullptr;
8522 GetTypeFromParser(Type.get(), &TInfo);
8524 if (DiagnoseClassNameShadow(CurContext, NameInfo))
8527 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8528 UPPC_DeclarationType)) {
8530 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8531 TInfo->getTypeLoc().getBeginLoc());
8534 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8535 LookupName(Previous, S);
8537 // Warn about shadowing the name of a template parameter.
8538 if (Previous.isSingleResult() &&
8539 Previous.getFoundDecl()->isTemplateParameter()) {
8540 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8544 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8545 "name in alias declaration must be an identifier");
8546 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8548 Name.Identifier, TInfo);
8550 NewTD->setAccess(AS);
8553 NewTD->setInvalidDecl();
8555 ProcessDeclAttributeList(S, NewTD, AttrList);
8557 CheckTypedefForVariablyModifiedType(S, NewTD);
8558 Invalid |= NewTD->isInvalidDecl();
8560 bool Redeclaration = false;
8563 if (TemplateParamLists.size()) {
8564 TypeAliasTemplateDecl *OldDecl = nullptr;
8565 TemplateParameterList *OldTemplateParams = nullptr;
8567 if (TemplateParamLists.size() != 1) {
8568 Diag(UsingLoc, diag::err_alias_template_extra_headers)
8569 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8570 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8572 TemplateParameterList *TemplateParams = TemplateParamLists[0];
8574 // Only consider previous declarations in the same scope.
8575 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8576 /*ExplicitInstantiationOrSpecialization*/false);
8577 if (!Previous.empty()) {
8578 Redeclaration = true;
8580 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8581 if (!OldDecl && !Invalid) {
8582 Diag(UsingLoc, diag::err_redefinition_different_kind)
8585 NamedDecl *OldD = Previous.getRepresentativeDecl();
8586 if (OldD->getLocation().isValid())
8587 Diag(OldD->getLocation(), diag::note_previous_definition);
8592 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8593 if (TemplateParameterListsAreEqual(TemplateParams,
8594 OldDecl->getTemplateParameters(),
8597 OldTemplateParams = OldDecl->getTemplateParameters();
8601 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8603 !Context.hasSameType(OldTD->getUnderlyingType(),
8604 NewTD->getUnderlyingType())) {
8605 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8606 // but we can't reasonably accept it.
8607 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8608 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8609 if (OldTD->getLocation().isValid())
8610 Diag(OldTD->getLocation(), diag::note_previous_definition);
8616 // Merge any previous default template arguments into our parameters,
8617 // and check the parameter list.
8618 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8619 TPC_TypeAliasTemplate))
8622 TypeAliasTemplateDecl *NewDecl =
8623 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8624 Name.Identifier, TemplateParams,
8626 NewTD->setDescribedAliasTemplate(NewDecl);
8628 NewDecl->setAccess(AS);
8631 NewDecl->setInvalidDecl();
8633 NewDecl->setPreviousDecl(OldDecl);
8637 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8638 setTagNameForLinkagePurposes(TD, NewTD);
8639 handleTagNumbering(TD, S);
8641 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8646 PushOnScopeChains(NewND, S);
8648 ActOnDocumentableDecl(NewND);
8652 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8653 SourceLocation AliasLoc,
8654 IdentifierInfo *Alias, CXXScopeSpec &SS,
8655 SourceLocation IdentLoc,
8656 IdentifierInfo *Ident) {
8658 // Lookup the namespace name.
8659 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8660 LookupParsedName(R, S, &SS);
8662 if (R.isAmbiguous())
8666 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8667 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8671 assert(!R.isAmbiguous() && !R.empty());
8672 NamedDecl *ND = R.getRepresentativeDecl();
8674 // Check if we have a previous declaration with the same name.
8675 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8677 LookupName(PrevR, S);
8679 // Check we're not shadowing a template parameter.
8680 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8681 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8685 // Filter out any other lookup result from an enclosing scope.
8686 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8687 /*AllowInlineNamespace*/false);
8689 // Find the previous declaration and check that we can redeclare it.
8690 NamespaceAliasDecl *Prev = nullptr;
8691 if (PrevR.isSingleResult()) {
8692 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
8693 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8694 // We already have an alias with the same name that points to the same
8695 // namespace; check that it matches.
8696 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8698 } else if (isVisible(PrevDecl)) {
8699 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8701 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
8702 << AD->getNamespace();
8705 } else if (isVisible(PrevDecl)) {
8706 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
8707 ? diag::err_redefinition
8708 : diag::err_redefinition_different_kind;
8709 Diag(AliasLoc, DiagID) << Alias;
8710 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8715 // The use of a nested name specifier may trigger deprecation warnings.
8716 DiagnoseUseOfDecl(ND, IdentLoc);
8718 NamespaceAliasDecl *AliasDecl =
8719 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8720 Alias, SS.getWithLocInContext(Context),
8723 AliasDecl->setPreviousDecl(Prev);
8725 PushOnScopeChains(AliasDecl, S);
8729 Sema::ImplicitExceptionSpecification
8730 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8731 CXXMethodDecl *MD) {
8732 CXXRecordDecl *ClassDecl = MD->getParent();
8734 // C++ [except.spec]p14:
8735 // An implicitly declared special member function (Clause 12) shall have an
8736 // exception-specification. [...]
8737 ImplicitExceptionSpecification ExceptSpec(*this);
8738 if (ClassDecl->isInvalidDecl())
8741 // Direct base-class constructors.
8742 for (const auto &B : ClassDecl->bases()) {
8743 if (B.isVirtual()) // Handled below.
8746 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8747 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8748 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8749 // If this is a deleted function, add it anyway. This might be conformant
8750 // with the standard. This might not. I'm not sure. It might not matter.
8752 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8756 // Virtual base-class constructors.
8757 for (const auto &B : ClassDecl->vbases()) {
8758 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8759 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8760 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8761 // If this is a deleted function, add it anyway. This might be conformant
8762 // with the standard. This might not. I'm not sure. It might not matter.
8764 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8768 // Field constructors.
8769 for (const auto *F : ClassDecl->fields()) {
8770 if (F->hasInClassInitializer()) {
8771 if (Expr *E = F->getInClassInitializer())
8772 ExceptSpec.CalledExpr(E);
8773 } else if (const RecordType *RecordTy
8774 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8775 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8776 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8777 // If this is a deleted function, add it anyway. This might be conformant
8778 // with the standard. This might not. I'm not sure. It might not matter.
8779 // In particular, the problem is that this function never gets called. It
8780 // might just be ill-formed because this function attempts to refer to
8781 // a deleted function here.
8783 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8790 Sema::ImplicitExceptionSpecification
8791 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8792 CXXRecordDecl *ClassDecl = CD->getParent();
8794 // C++ [except.spec]p14:
8795 // An inheriting constructor [...] shall have an exception-specification. [...]
8796 ImplicitExceptionSpecification ExceptSpec(*this);
8797 if (ClassDecl->isInvalidDecl())
8800 // Inherited constructor.
8801 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8802 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8803 // FIXME: Copying or moving the parameters could add extra exceptions to the
8804 // set, as could the default arguments for the inherited constructor. This
8805 // will be addressed when we implement the resolution of core issue 1351.
8806 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8808 // Direct base-class constructors.
8809 for (const auto &B : ClassDecl->bases()) {
8810 if (B.isVirtual()) // Handled below.
8813 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8814 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8815 if (BaseClassDecl == InheritedDecl)
8817 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8819 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8823 // Virtual base-class constructors.
8824 for (const auto &B : ClassDecl->vbases()) {
8825 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8826 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8827 if (BaseClassDecl == InheritedDecl)
8829 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8831 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8835 // Field constructors.
8836 for (const auto *F : ClassDecl->fields()) {
8837 if (F->hasInClassInitializer()) {
8838 if (Expr *E = F->getInClassInitializer())
8839 ExceptSpec.CalledExpr(E);
8840 } else if (const RecordType *RecordTy
8841 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8842 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8843 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8845 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8853 /// RAII object to register a special member as being currently declared.
8854 struct DeclaringSpecialMember {
8856 Sema::SpecialMemberDecl D;
8857 bool WasAlreadyBeingDeclared;
8859 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8860 : S(S), D(RD, CSM) {
8861 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8862 if (WasAlreadyBeingDeclared)
8863 // This almost never happens, but if it does, ensure that our cache
8864 // doesn't contain a stale result.
8865 S.SpecialMemberCache.clear();
8867 // FIXME: Register a note to be produced if we encounter an error while
8868 // declaring the special member.
8870 ~DeclaringSpecialMember() {
8871 if (!WasAlreadyBeingDeclared)
8872 S.SpecialMembersBeingDeclared.erase(D);
8875 /// \brief Are we already trying to declare this special member?
8876 bool isAlreadyBeingDeclared() const {
8877 return WasAlreadyBeingDeclared;
8882 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8883 CXXRecordDecl *ClassDecl) {
8884 // C++ [class.ctor]p5:
8885 // A default constructor for a class X is a constructor of class X
8886 // that can be called without an argument. If there is no
8887 // user-declared constructor for class X, a default constructor is
8888 // implicitly declared. An implicitly-declared default constructor
8889 // is an inline public member of its class.
8890 assert(ClassDecl->needsImplicitDefaultConstructor() &&
8891 "Should not build implicit default constructor!");
8893 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8894 if (DSM.isAlreadyBeingDeclared())
8897 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8898 CXXDefaultConstructor,
8901 // Create the actual constructor declaration.
8902 CanQualType ClassType
8903 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8904 SourceLocation ClassLoc = ClassDecl->getLocation();
8905 DeclarationName Name
8906 = Context.DeclarationNames.getCXXConstructorName(ClassType);
8907 DeclarationNameInfo NameInfo(Name, ClassLoc);
8908 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8909 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8910 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8911 /*isImplicitlyDeclared=*/true, Constexpr);
8912 DefaultCon->setAccess(AS_public);
8913 DefaultCon->setDefaulted();
8915 if (getLangOpts().CUDA) {
8916 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8918 /* ConstRHS */ false,
8919 /* Diagnose */ false);
8922 // Build an exception specification pointing back at this constructor.
8923 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8924 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8926 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8927 // constructors is easy to compute.
8928 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8930 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8931 SetDeclDeleted(DefaultCon, ClassLoc);
8933 // Note that we have declared this constructor.
8934 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8936 if (Scope *S = getScopeForContext(ClassDecl))
8937 PushOnScopeChains(DefaultCon, S, false);
8938 ClassDecl->addDecl(DefaultCon);
8943 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8944 CXXConstructorDecl *Constructor) {
8945 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8946 !Constructor->doesThisDeclarationHaveABody() &&
8947 !Constructor->isDeleted()) &&
8948 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8950 CXXRecordDecl *ClassDecl = Constructor->getParent();
8951 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8953 SynthesizedFunctionScope Scope(*this, Constructor);
8954 DiagnosticErrorTrap Trap(Diags);
8955 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8956 Trap.hasErrorOccurred()) {
8957 Diag(CurrentLocation, diag::note_member_synthesized_at)
8958 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8959 Constructor->setInvalidDecl();
8963 // The exception specification is needed because we are defining the
8965 ResolveExceptionSpec(CurrentLocation,
8966 Constructor->getType()->castAs<FunctionProtoType>());
8968 SourceLocation Loc = Constructor->getLocEnd().isValid()
8969 ? Constructor->getLocEnd()
8970 : Constructor->getLocation();
8971 Constructor->setBody(new (Context) CompoundStmt(Loc));
8973 Constructor->markUsed(Context);
8974 MarkVTableUsed(CurrentLocation, ClassDecl);
8976 if (ASTMutationListener *L = getASTMutationListener()) {
8977 L->CompletedImplicitDefinition(Constructor);
8980 DiagnoseUninitializedFields(*this, Constructor);
8983 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8984 // Perform any delayed checks on exception specifications.
8985 CheckDelayedMemberExceptionSpecs();
8989 /// Information on inheriting constructors to declare.
8990 class InheritingConstructorInfo {
8992 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8993 : SemaRef(SemaRef), Derived(Derived) {
8994 // Mark the constructors that we already have in the derived class.
8996 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8997 // unless there is a user-declared constructor with the same signature in
8998 // the class where the using-declaration appears.
8999 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9002 void inheritAll(CXXRecordDecl *RD) {
9003 visitAll(RD, &InheritingConstructorInfo::inherit);
9007 /// Information about an inheriting constructor.
9008 struct InheritingConstructor {
9009 InheritingConstructor()
9010 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9012 /// If \c true, a constructor with this signature is already declared
9013 /// in the derived class.
9014 bool DeclaredInDerived;
9016 /// The constructor which is inherited.
9017 const CXXConstructorDecl *BaseCtor;
9019 /// The derived constructor we declared.
9020 CXXConstructorDecl *DerivedCtor;
9023 /// Inheriting constructors with a given canonical type. There can be at
9024 /// most one such non-template constructor, and any number of templated
9026 struct InheritingConstructorsForType {
9027 InheritingConstructor NonTemplate;
9028 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9031 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9032 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9033 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9034 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9035 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9036 false, S.TPL_TemplateMatch))
9037 return Templates[I].second;
9038 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9039 return Templates.back().second;
9046 /// Get or create the inheriting constructor record for a constructor.
9047 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9048 QualType CtorType) {
9049 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9050 .getEntry(SemaRef, Ctor);
9053 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9055 /// Process all constructors for a class.
9056 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9057 for (const auto *Ctor : RD->ctors())
9058 (this->*Callback)(Ctor);
9059 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9060 I(RD->decls_begin()), E(RD->decls_end());
9062 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9063 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9064 (this->*Callback)(CD);
9068 /// Note that a constructor (or constructor template) was declared in Derived.
9069 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9070 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9073 /// Inherit a single constructor.
9074 void inherit(const CXXConstructorDecl *Ctor) {
9075 const FunctionProtoType *CtorType =
9076 Ctor->getType()->castAs<FunctionProtoType>();
9077 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9078 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9080 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9082 // Core issue (no number yet): the ellipsis is always discarded.
9084 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9085 SemaRef.Diag(Ctor->getLocation(),
9086 diag::note_using_decl_constructor_ellipsis);
9087 EPI.Variadic = false;
9090 // Declare a constructor for each number of parameters.
9092 // C++11 [class.inhctor]p1:
9093 // The candidate set of inherited constructors from the class X named in
9094 // the using-declaration consists of [... modulo defects ...] for each
9095 // constructor or constructor template of X, the set of constructors or
9096 // constructor templates that results from omitting any ellipsis parameter
9097 // specification and successively omitting parameters with a default
9098 // argument from the end of the parameter-type-list
9099 unsigned MinParams = minParamsToInherit(Ctor);
9100 unsigned Params = Ctor->getNumParams();
9101 if (Params >= MinParams) {
9103 declareCtor(UsingLoc, Ctor,
9104 SemaRef.Context.getFunctionType(
9105 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9106 while (Params > MinParams &&
9107 Ctor->getParamDecl(--Params)->hasDefaultArg());
9111 /// Find the using-declaration which specified that we should inherit the
9112 /// constructors of \p Base.
9113 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9114 // No fancy lookup required; just look for the base constructor name
9115 // directly within the derived class.
9116 ASTContext &Context = SemaRef.Context;
9117 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9118 Context.getCanonicalType(Context.getRecordType(Base)));
9119 DeclContext::lookup_result Decls = Derived->lookup(Name);
9120 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9123 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9124 // C++11 [class.inhctor]p3:
9125 // [F]or each constructor template in the candidate set of inherited
9126 // constructors, a constructor template is implicitly declared
9127 if (Ctor->getDescribedFunctionTemplate())
9130 // For each non-template constructor in the candidate set of inherited
9131 // constructors other than a constructor having no parameters or a
9132 // copy/move constructor having a single parameter, a constructor is
9133 // implicitly declared [...]
9134 if (Ctor->getNumParams() == 0)
9136 if (Ctor->isCopyOrMoveConstructor())
9139 // Per discussion on core reflector, never inherit a constructor which
9140 // would become a default, copy, or move constructor of Derived either.
9141 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9142 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9143 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9146 /// Declare a single inheriting constructor, inheriting the specified
9147 /// constructor, with the given type.
9148 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9149 QualType DerivedType) {
9150 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9152 // C++11 [class.inhctor]p3:
9153 // ... a constructor is implicitly declared with the same constructor
9154 // characteristics unless there is a user-declared constructor with
9155 // the same signature in the class where the using-declaration appears
9156 if (Entry.DeclaredInDerived)
9159 // C++11 [class.inhctor]p7:
9160 // If two using-declarations declare inheriting constructors with the
9161 // same signature, the program is ill-formed
9162 if (Entry.DerivedCtor) {
9163 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9164 // Only diagnose this once per constructor.
9165 if (Entry.DerivedCtor->isInvalidDecl())
9167 Entry.DerivedCtor->setInvalidDecl();
9169 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9170 SemaRef.Diag(BaseCtor->getLocation(),
9171 diag::note_using_decl_constructor_conflict_current_ctor);
9172 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9173 diag::note_using_decl_constructor_conflict_previous_ctor);
9174 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9175 diag::note_using_decl_constructor_conflict_previous_using);
9177 // Core issue (no number): if the same inheriting constructor is
9178 // produced by multiple base class constructors from the same base
9179 // class, the inheriting constructor is defined as deleted.
9180 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9186 ASTContext &Context = SemaRef.Context;
9187 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9188 Context.getCanonicalType(Context.getRecordType(Derived)));
9189 DeclarationNameInfo NameInfo(Name, UsingLoc);
9191 TemplateParameterList *TemplateParams = nullptr;
9192 if (const FunctionTemplateDecl *FTD =
9193 BaseCtor->getDescribedFunctionTemplate()) {
9194 TemplateParams = FTD->getTemplateParameters();
9195 // We're reusing template parameters from a different DeclContext. This
9196 // is questionable at best, but works out because the template depth in
9197 // both places is guaranteed to be 0.
9198 // FIXME: Rebuild the template parameters in the new context, and
9199 // transform the function type to refer to them.
9202 // Build type source info pointing at the using-declaration. This is
9203 // required by template instantiation.
9204 TypeSourceInfo *TInfo =
9205 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9206 FunctionProtoTypeLoc ProtoLoc =
9207 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9209 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9210 Context, Derived, UsingLoc, NameInfo, DerivedType,
9211 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9212 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9214 // Build an unevaluated exception specification for this constructor.
9215 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9216 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9217 EPI.ExceptionSpec.Type = EST_Unevaluated;
9218 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9219 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9220 FPT->getParamTypes(), EPI));
9222 // Build the parameter declarations.
9223 SmallVector<ParmVarDecl *, 16> ParamDecls;
9224 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9225 TypeSourceInfo *TInfo =
9226 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9227 ParmVarDecl *PD = ParmVarDecl::Create(
9228 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9229 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9230 PD->setScopeInfo(0, I);
9232 ParamDecls.push_back(PD);
9233 ProtoLoc.setParam(I, PD);
9236 // Set up the new constructor.
9237 DerivedCtor->setAccess(BaseCtor->getAccess());
9238 DerivedCtor->setParams(ParamDecls);
9239 DerivedCtor->setInheritedConstructor(BaseCtor);
9240 if (BaseCtor->isDeleted())
9241 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9243 // If this is a constructor template, build the template declaration.
9244 if (TemplateParams) {
9245 FunctionTemplateDecl *DerivedTemplate =
9246 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9247 TemplateParams, DerivedCtor);
9248 DerivedTemplate->setAccess(BaseCtor->getAccess());
9249 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9250 Derived->addDecl(DerivedTemplate);
9252 Derived->addDecl(DerivedCtor);
9255 Entry.BaseCtor = BaseCtor;
9256 Entry.DerivedCtor = DerivedCtor;
9260 CXXRecordDecl *Derived;
9261 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9266 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9267 // Defer declaring the inheriting constructors until the class is
9269 if (ClassDecl->isDependentContext())
9272 // Find base classes from which we might inherit constructors.
9273 SmallVector<CXXRecordDecl*, 4> InheritedBases;
9274 for (const auto &BaseIt : ClassDecl->bases())
9275 if (BaseIt.getInheritConstructors())
9276 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9278 // Go no further if we're not inheriting any constructors.
9279 if (InheritedBases.empty())
9282 // Declare the inherited constructors.
9283 InheritingConstructorInfo ICI(*this, ClassDecl);
9284 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9285 ICI.inheritAll(InheritedBases[I]);
9288 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9289 CXXConstructorDecl *Constructor) {
9290 CXXRecordDecl *ClassDecl = Constructor->getParent();
9291 assert(Constructor->getInheritedConstructor() &&
9292 !Constructor->doesThisDeclarationHaveABody() &&
9293 !Constructor->isDeleted());
9295 SynthesizedFunctionScope Scope(*this, Constructor);
9296 DiagnosticErrorTrap Trap(Diags);
9297 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9298 Trap.hasErrorOccurred()) {
9299 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9300 << Context.getTagDeclType(ClassDecl);
9301 Constructor->setInvalidDecl();
9305 SourceLocation Loc = Constructor->getLocation();
9306 Constructor->setBody(new (Context) CompoundStmt(Loc));
9308 Constructor->markUsed(Context);
9309 MarkVTableUsed(CurrentLocation, ClassDecl);
9311 if (ASTMutationListener *L = getASTMutationListener()) {
9312 L->CompletedImplicitDefinition(Constructor);
9317 Sema::ImplicitExceptionSpecification
9318 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9319 CXXRecordDecl *ClassDecl = MD->getParent();
9321 // C++ [except.spec]p14:
9322 // An implicitly declared special member function (Clause 12) shall have
9323 // an exception-specification.
9324 ImplicitExceptionSpecification ExceptSpec(*this);
9325 if (ClassDecl->isInvalidDecl())
9328 // Direct base-class destructors.
9329 for (const auto &B : ClassDecl->bases()) {
9330 if (B.isVirtual()) // Handled below.
9333 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9334 ExceptSpec.CalledDecl(B.getLocStart(),
9335 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9338 // Virtual base-class destructors.
9339 for (const auto &B : ClassDecl->vbases()) {
9340 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9341 ExceptSpec.CalledDecl(B.getLocStart(),
9342 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9345 // Field destructors.
9346 for (const auto *F : ClassDecl->fields()) {
9347 if (const RecordType *RecordTy
9348 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9349 ExceptSpec.CalledDecl(F->getLocation(),
9350 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9356 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9357 // C++ [class.dtor]p2:
9358 // If a class has no user-declared destructor, a destructor is
9359 // declared implicitly. An implicitly-declared destructor is an
9360 // inline public member of its class.
9361 assert(ClassDecl->needsImplicitDestructor());
9363 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9364 if (DSM.isAlreadyBeingDeclared())
9367 // Create the actual destructor declaration.
9368 CanQualType ClassType
9369 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9370 SourceLocation ClassLoc = ClassDecl->getLocation();
9371 DeclarationName Name
9372 = Context.DeclarationNames.getCXXDestructorName(ClassType);
9373 DeclarationNameInfo NameInfo(Name, ClassLoc);
9374 CXXDestructorDecl *Destructor
9375 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9376 QualType(), nullptr, /*isInline=*/true,
9377 /*isImplicitlyDeclared=*/true);
9378 Destructor->setAccess(AS_public);
9379 Destructor->setDefaulted();
9381 if (getLangOpts().CUDA) {
9382 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9384 /* ConstRHS */ false,
9385 /* Diagnose */ false);
9388 // Build an exception specification pointing back at this destructor.
9389 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9390 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9392 AddOverriddenMethods(ClassDecl, Destructor);
9394 // We don't need to use SpecialMemberIsTrivial here; triviality for
9395 // destructors is easy to compute.
9396 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9398 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9399 SetDeclDeleted(Destructor, ClassLoc);
9401 // Note that we have declared this destructor.
9402 ++ASTContext::NumImplicitDestructorsDeclared;
9404 // Introduce this destructor into its scope.
9405 if (Scope *S = getScopeForContext(ClassDecl))
9406 PushOnScopeChains(Destructor, S, false);
9407 ClassDecl->addDecl(Destructor);
9412 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9413 CXXDestructorDecl *Destructor) {
9414 assert((Destructor->isDefaulted() &&
9415 !Destructor->doesThisDeclarationHaveABody() &&
9416 !Destructor->isDeleted()) &&
9417 "DefineImplicitDestructor - call it for implicit default dtor");
9418 CXXRecordDecl *ClassDecl = Destructor->getParent();
9419 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9421 if (Destructor->isInvalidDecl())
9424 SynthesizedFunctionScope Scope(*this, Destructor);
9426 DiagnosticErrorTrap Trap(Diags);
9427 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9428 Destructor->getParent());
9430 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9431 Diag(CurrentLocation, diag::note_member_synthesized_at)
9432 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9434 Destructor->setInvalidDecl();
9438 // The exception specification is needed because we are defining the
9440 ResolveExceptionSpec(CurrentLocation,
9441 Destructor->getType()->castAs<FunctionProtoType>());
9443 SourceLocation Loc = Destructor->getLocEnd().isValid()
9444 ? Destructor->getLocEnd()
9445 : Destructor->getLocation();
9446 Destructor->setBody(new (Context) CompoundStmt(Loc));
9447 Destructor->markUsed(Context);
9448 MarkVTableUsed(CurrentLocation, ClassDecl);
9450 if (ASTMutationListener *L = getASTMutationListener()) {
9451 L->CompletedImplicitDefinition(Destructor);
9455 /// \brief Perform any semantic analysis which needs to be delayed until all
9456 /// pending class member declarations have been parsed.
9457 void Sema::ActOnFinishCXXMemberDecls() {
9458 // If the context is an invalid C++ class, just suppress these checks.
9459 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9460 if (Record->isInvalidDecl()) {
9461 DelayedDefaultedMemberExceptionSpecs.clear();
9462 DelayedExceptionSpecChecks.clear();
9468 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9469 // Don't do anything for template patterns.
9470 if (Class->getDescribedClassTemplate())
9473 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
9474 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
9476 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
9477 for (Decl *Member : Class->decls()) {
9478 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9480 // Recurse on nested classes.
9481 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9482 getDefaultArgExprsForConstructors(S, NestedRD);
9484 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9488 CallingConv ActualCallingConv =
9489 CD->getType()->getAs<FunctionProtoType>()->getCallConv();
9491 // Skip default constructors with typical calling conventions and no default
9493 unsigned NumParams = CD->getNumParams();
9494 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
9497 if (LastExportedDefaultCtor) {
9498 S.Diag(LastExportedDefaultCtor->getLocation(),
9499 diag::err_attribute_dll_ambiguous_default_ctor) << Class;
9500 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
9501 << CD->getDeclName();
9504 LastExportedDefaultCtor = CD;
9506 for (unsigned I = 0; I != NumParams; ++I) {
9507 // Skip any default arguments that we've already instantiated.
9508 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9511 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9512 CD->getParamDecl(I)).get();
9513 S.DiscardCleanupsInEvaluationContext();
9514 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9519 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
9520 auto *RD = dyn_cast<CXXRecordDecl>(D);
9522 // Default constructors that are annotated with __declspec(dllexport) which
9523 // have default arguments or don't use the standard calling convention are
9524 // wrapped with a thunk called the default constructor closure.
9525 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9526 getDefaultArgExprsForConstructors(*this, RD);
9528 if (!DelayedDllExportClasses.empty()) {
9529 // Calling ReferenceDllExportedMethods might cause the current function to
9530 // be called again, so use a local copy of DelayedDllExportClasses.
9531 SmallVector<CXXRecordDecl *, 4> WorkList;
9532 std::swap(DelayedDllExportClasses, WorkList);
9533 for (CXXRecordDecl *Class : WorkList)
9534 ReferenceDllExportedMethods(*this, Class);
9538 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9539 CXXDestructorDecl *Destructor) {
9540 assert(getLangOpts().CPlusPlus11 &&
9541 "adjusting dtor exception specs was introduced in c++11");
9543 // C++11 [class.dtor]p3:
9544 // A declaration of a destructor that does not have an exception-
9545 // specification is implicitly considered to have the same exception-
9546 // specification as an implicit declaration.
9547 const FunctionProtoType *DtorType = Destructor->getType()->
9548 getAs<FunctionProtoType>();
9549 if (DtorType->hasExceptionSpec())
9552 // Replace the destructor's type, building off the existing one. Fortunately,
9553 // the only thing of interest in the destructor type is its extended info.
9554 // The return and arguments are fixed.
9555 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9556 EPI.ExceptionSpec.Type = EST_Unevaluated;
9557 EPI.ExceptionSpec.SourceDecl = Destructor;
9558 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9560 // FIXME: If the destructor has a body that could throw, and the newly created
9561 // spec doesn't allow exceptions, we should emit a warning, because this
9562 // change in behavior can break conforming C++03 programs at runtime.
9563 // However, we don't have a body or an exception specification yet, so it
9564 // needs to be done somewhere else.
9568 /// \brief An abstract base class for all helper classes used in building the
9569 // copy/move operators. These classes serve as factory functions and help us
9570 // avoid using the same Expr* in the AST twice.
9572 ExprBuilder(const ExprBuilder&) = delete;
9573 ExprBuilder &operator=(const ExprBuilder&) = delete;
9576 static Expr *assertNotNull(Expr *E) {
9577 assert(E && "Expression construction must not fail.");
9583 virtual ~ExprBuilder() {}
9585 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9588 class RefBuilder: public ExprBuilder {
9593 Expr *build(Sema &S, SourceLocation Loc) const override {
9594 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9597 RefBuilder(VarDecl *Var, QualType VarType)
9598 : Var(Var), VarType(VarType) {}
9601 class ThisBuilder: public ExprBuilder {
9603 Expr *build(Sema &S, SourceLocation Loc) const override {
9604 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9608 class CastBuilder: public ExprBuilder {
9609 const ExprBuilder &Builder;
9612 const CXXCastPath &Path;
9615 Expr *build(Sema &S, SourceLocation Loc) const override {
9616 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9617 CK_UncheckedDerivedToBase, Kind,
9621 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9622 const CXXCastPath &Path)
9623 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9626 class DerefBuilder: public ExprBuilder {
9627 const ExprBuilder &Builder;
9630 Expr *build(Sema &S, SourceLocation Loc) const override {
9631 return assertNotNull(
9632 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9635 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9638 class MemberBuilder: public ExprBuilder {
9639 const ExprBuilder &Builder;
9643 LookupResult &MemberLookup;
9646 Expr *build(Sema &S, SourceLocation Loc) const override {
9647 return assertNotNull(S.BuildMemberReferenceExpr(
9648 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9649 nullptr, MemberLookup, nullptr, nullptr).get());
9652 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9653 LookupResult &MemberLookup)
9654 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9655 MemberLookup(MemberLookup) {}
9658 class MoveCastBuilder: public ExprBuilder {
9659 const ExprBuilder &Builder;
9662 Expr *build(Sema &S, SourceLocation Loc) const override {
9663 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9666 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9669 class LvalueConvBuilder: public ExprBuilder {
9670 const ExprBuilder &Builder;
9673 Expr *build(Sema &S, SourceLocation Loc) const override {
9674 return assertNotNull(
9675 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9678 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9681 class SubscriptBuilder: public ExprBuilder {
9682 const ExprBuilder &Base;
9683 const ExprBuilder &Index;
9686 Expr *build(Sema &S, SourceLocation Loc) const override {
9687 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9688 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9691 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9692 : Base(Base), Index(Index) {}
9695 } // end anonymous namespace
9697 /// When generating a defaulted copy or move assignment operator, if a field
9698 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9699 /// do so. This optimization only applies for arrays of scalars, and for arrays
9700 /// of class type where the selected copy/move-assignment operator is trivial.
9702 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9703 const ExprBuilder &ToB, const ExprBuilder &FromB) {
9704 // Compute the size of the memory buffer to be copied.
9705 QualType SizeType = S.Context.getSizeType();
9706 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9707 S.Context.getTypeSizeInChars(T).getQuantity());
9709 // Take the address of the field references for "from" and "to". We
9710 // directly construct UnaryOperators here because semantic analysis
9711 // does not permit us to take the address of an xvalue.
9712 Expr *From = FromB.build(S, Loc);
9713 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9714 S.Context.getPointerType(From->getType()),
9715 VK_RValue, OK_Ordinary, Loc);
9716 Expr *To = ToB.build(S, Loc);
9717 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9718 S.Context.getPointerType(To->getType()),
9719 VK_RValue, OK_Ordinary, Loc);
9721 const Type *E = T->getBaseElementTypeUnsafe();
9722 bool NeedsCollectableMemCpy =
9723 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9725 // Create a reference to the __builtin_objc_memmove_collectable function
9726 StringRef MemCpyName = NeedsCollectableMemCpy ?
9727 "__builtin_objc_memmove_collectable" :
9729 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9730 Sema::LookupOrdinaryName);
9731 S.LookupName(R, S.TUScope, true);
9733 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9735 // Something went horribly wrong earlier, and we will have complained
9739 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9740 VK_RValue, Loc, nullptr);
9741 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9743 Expr *CallArgs[] = {
9744 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9746 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9747 Loc, CallArgs, Loc);
9749 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9750 return Call.getAs<Stmt>();
9753 /// \brief Builds a statement that copies/moves the given entity from \p From to
9756 /// This routine is used to copy/move the members of a class with an
9757 /// implicitly-declared copy/move assignment operator. When the entities being
9758 /// copied are arrays, this routine builds for loops to copy them.
9760 /// \param S The Sema object used for type-checking.
9762 /// \param Loc The location where the implicit copy/move is being generated.
9764 /// \param T The type of the expressions being copied/moved. Both expressions
9765 /// must have this type.
9767 /// \param To The expression we are copying/moving to.
9769 /// \param From The expression we are copying/moving from.
9771 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9772 /// Otherwise, it's a non-static member subobject.
9774 /// \param Copying Whether we're copying or moving.
9776 /// \param Depth Internal parameter recording the depth of the recursion.
9778 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9779 /// if a memcpy should be used instead.
9781 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9782 const ExprBuilder &To, const ExprBuilder &From,
9783 bool CopyingBaseSubobject, bool Copying,
9784 unsigned Depth = 0) {
9785 // C++11 [class.copy]p28:
9786 // Each subobject is assigned in the manner appropriate to its type:
9788 // - if the subobject is of class type, as if by a call to operator= with
9789 // the subobject as the object expression and the corresponding
9790 // subobject of x as a single function argument (as if by explicit
9791 // qualification; that is, ignoring any possible virtual overriding
9792 // functions in more derived classes);
9794 // C++03 [class.copy]p13:
9795 // - if the subobject is of class type, the copy assignment operator for
9796 // the class is used (as if by explicit qualification; that is,
9797 // ignoring any possible virtual overriding functions in more derived
9799 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9800 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9802 // Look for operator=.
9803 DeclarationName Name
9804 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9805 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9806 S.LookupQualifiedName(OpLookup, ClassDecl, false);
9808 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9810 if (!S.getLangOpts().CPlusPlus11) {
9811 LookupResult::Filter F = OpLookup.makeFilter();
9812 while (F.hasNext()) {
9813 NamedDecl *D = F.next();
9814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9815 if (Method->isCopyAssignmentOperator() ||
9816 (!Copying && Method->isMoveAssignmentOperator()))
9824 // Suppress the protected check (C++ [class.protected]) for each of the
9825 // assignment operators we found. This strange dance is required when
9826 // we're assigning via a base classes's copy-assignment operator. To
9827 // ensure that we're getting the right base class subobject (without
9828 // ambiguities), we need to cast "this" to that subobject type; to
9829 // ensure that we don't go through the virtual call mechanism, we need
9830 // to qualify the operator= name with the base class (see below). However,
9831 // this means that if the base class has a protected copy assignment
9832 // operator, the protected member access check will fail. So, we
9833 // rewrite "protected" access to "public" access in this case, since we
9834 // know by construction that we're calling from a derived class.
9835 if (CopyingBaseSubobject) {
9836 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9838 if (L.getAccess() == AS_protected)
9839 L.setAccess(AS_public);
9843 // Create the nested-name-specifier that will be used to qualify the
9844 // reference to operator=; this is required to suppress the virtual
9847 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9848 SS.MakeTrivial(S.Context,
9849 NestedNameSpecifier::Create(S.Context, nullptr, false,
9853 // Create the reference to operator=.
9854 ExprResult OpEqualRef
9855 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9856 SS, /*TemplateKWLoc=*/SourceLocation(),
9857 /*FirstQualifierInScope=*/nullptr,
9859 /*TemplateArgs=*/nullptr, /*S*/nullptr,
9860 /*SuppressQualifierCheck=*/true);
9861 if (OpEqualRef.isInvalid())
9864 // Build the call to the assignment operator.
9866 Expr *FromInst = From.build(S, Loc);
9867 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9868 OpEqualRef.getAs<Expr>(),
9869 Loc, FromInst, Loc);
9870 if (Call.isInvalid())
9873 // If we built a call to a trivial 'operator=' while copying an array,
9874 // bail out. We'll replace the whole shebang with a memcpy.
9875 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9876 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9877 return StmtResult((Stmt*)nullptr);
9879 // Convert to an expression-statement, and clean up any produced
9881 return S.ActOnExprStmt(Call);
9884 // - if the subobject is of scalar type, the built-in assignment
9885 // operator is used.
9886 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9888 ExprResult Assignment = S.CreateBuiltinBinOp(
9889 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9890 if (Assignment.isInvalid())
9892 return S.ActOnExprStmt(Assignment);
9895 // - if the subobject is an array, each element is assigned, in the
9896 // manner appropriate to the element type;
9898 // Construct a loop over the array bounds, e.g.,
9900 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9902 // that will copy each of the array elements.
9903 QualType SizeType = S.Context.getSizeType();
9905 // Create the iteration variable.
9906 IdentifierInfo *IterationVarName = nullptr;
9909 llvm::raw_svector_ostream OS(Str);
9910 OS << "__i" << Depth;
9911 IterationVarName = &S.Context.Idents.get(OS.str());
9913 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9914 IterationVarName, SizeType,
9915 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9918 // Initialize the iteration variable to zero.
9919 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9920 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9922 // Creates a reference to the iteration variable.
9923 RefBuilder IterationVarRef(IterationVar, SizeType);
9924 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9926 // Create the DeclStmt that holds the iteration variable.
9927 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9929 // Subscript the "from" and "to" expressions with the iteration variable.
9930 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9931 MoveCastBuilder FromIndexMove(FromIndexCopy);
9932 const ExprBuilder *FromIndex;
9934 FromIndex = &FromIndexCopy;
9936 FromIndex = &FromIndexMove;
9938 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9940 // Build the copy/move for an individual element of the array.
9942 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9943 ToIndex, *FromIndex, CopyingBaseSubobject,
9944 Copying, Depth + 1);
9945 // Bail out if copying fails or if we determined that we should use memcpy.
9946 if (Copy.isInvalid() || !Copy.get())
9949 // Create the comparison against the array bound.
9951 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9953 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9954 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9955 BO_NE, S.Context.BoolTy,
9956 VK_RValue, OK_Ordinary, Loc, false);
9958 // Create the pre-increment of the iteration variable.
9960 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9961 SizeType, VK_LValue, OK_Ordinary, Loc);
9963 // Construct the loop that copies all elements of this array.
9964 return S.ActOnForStmt(Loc, Loc, InitStmt,
9965 S.MakeFullExpr(Comparison),
9966 nullptr, S.MakeFullDiscardedValueExpr(Increment),
9971 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9972 const ExprBuilder &To, const ExprBuilder &From,
9973 bool CopyingBaseSubobject, bool Copying) {
9974 // Maybe we should use a memcpy?
9975 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9976 T.isTriviallyCopyableType(S.Context))
9977 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9979 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9980 CopyingBaseSubobject,
9983 // If we ended up picking a trivial assignment operator for an array of a
9984 // non-trivially-copyable class type, just emit a memcpy.
9985 if (!Result.isInvalid() && !Result.get())
9986 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9991 Sema::ImplicitExceptionSpecification
9992 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9993 CXXRecordDecl *ClassDecl = MD->getParent();
9995 ImplicitExceptionSpecification ExceptSpec(*this);
9996 if (ClassDecl->isInvalidDecl())
9999 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10000 assert(T->getNumParams() == 1 && "not a copy assignment op");
10001 unsigned ArgQuals =
10002 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10004 // C++ [except.spec]p14:
10005 // An implicitly declared special member function (Clause 12) shall have an
10006 // exception-specification. [...]
10008 // It is unspecified whether or not an implicit copy assignment operator
10009 // attempts to deduplicate calls to assignment operators of virtual bases are
10010 // made. As such, this exception specification is effectively unspecified.
10011 // Based on a similar decision made for constness in C++0x, we're erring on
10012 // the side of assuming such calls to be made regardless of whether they
10013 // actually happen.
10014 for (const auto &Base : ClassDecl->bases()) {
10015 if (Base.isVirtual())
10018 CXXRecordDecl *BaseClassDecl
10019 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10020 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10021 ArgQuals, false, 0))
10022 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10025 for (const auto &Base : ClassDecl->vbases()) {
10026 CXXRecordDecl *BaseClassDecl
10027 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10028 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10029 ArgQuals, false, 0))
10030 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10033 for (const auto *Field : ClassDecl->fields()) {
10034 QualType FieldType = Context.getBaseElementType(Field->getType());
10035 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10036 if (CXXMethodDecl *CopyAssign =
10037 LookupCopyingAssignment(FieldClassDecl,
10038 ArgQuals | FieldType.getCVRQualifiers(),
10040 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10047 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10048 // Note: The following rules are largely analoguous to the copy
10049 // constructor rules. Note that virtual bases are not taken into account
10050 // for determining the argument type of the operator. Note also that
10051 // operators taking an object instead of a reference are allowed.
10052 assert(ClassDecl->needsImplicitCopyAssignment());
10054 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10055 if (DSM.isAlreadyBeingDeclared())
10058 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10059 QualType RetType = Context.getLValueReferenceType(ArgType);
10060 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10062 ArgType = ArgType.withConst();
10063 ArgType = Context.getLValueReferenceType(ArgType);
10065 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10069 // An implicitly-declared copy assignment operator is an inline public
10070 // member of its class.
10071 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10072 SourceLocation ClassLoc = ClassDecl->getLocation();
10073 DeclarationNameInfo NameInfo(Name, ClassLoc);
10074 CXXMethodDecl *CopyAssignment =
10075 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10076 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10077 /*isInline=*/true, Constexpr, SourceLocation());
10078 CopyAssignment->setAccess(AS_public);
10079 CopyAssignment->setDefaulted();
10080 CopyAssignment->setImplicit();
10082 if (getLangOpts().CUDA) {
10083 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10085 /* ConstRHS */ Const,
10086 /* Diagnose */ false);
10089 // Build an exception specification pointing back at this member.
10090 FunctionProtoType::ExtProtoInfo EPI =
10091 getImplicitMethodEPI(*this, CopyAssignment);
10092 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10094 // Add the parameter to the operator.
10095 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10096 ClassLoc, ClassLoc,
10097 /*Id=*/nullptr, ArgType,
10098 /*TInfo=*/nullptr, SC_None,
10100 CopyAssignment->setParams(FromParam);
10102 AddOverriddenMethods(ClassDecl, CopyAssignment);
10104 CopyAssignment->setTrivial(
10105 ClassDecl->needsOverloadResolutionForCopyAssignment()
10106 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10107 : ClassDecl->hasTrivialCopyAssignment());
10109 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10110 SetDeclDeleted(CopyAssignment, ClassLoc);
10112 // Note that we have added this copy-assignment operator.
10113 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10115 if (Scope *S = getScopeForContext(ClassDecl))
10116 PushOnScopeChains(CopyAssignment, S, false);
10117 ClassDecl->addDecl(CopyAssignment);
10119 return CopyAssignment;
10122 /// Diagnose an implicit copy operation for a class which is odr-used, but
10123 /// which is deprecated because the class has a user-declared copy constructor,
10124 /// copy assignment operator, or destructor.
10125 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10126 SourceLocation UseLoc) {
10127 assert(CopyOp->isImplicit());
10129 CXXRecordDecl *RD = CopyOp->getParent();
10130 CXXMethodDecl *UserDeclaredOperation = nullptr;
10132 // In Microsoft mode, assignment operations don't affect constructors and
10134 if (RD->hasUserDeclaredDestructor()) {
10135 UserDeclaredOperation = RD->getDestructor();
10136 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10137 RD->hasUserDeclaredCopyConstructor() &&
10138 !S.getLangOpts().MSVCCompat) {
10139 // Find any user-declared copy constructor.
10140 for (auto *I : RD->ctors()) {
10141 if (I->isCopyConstructor()) {
10142 UserDeclaredOperation = I;
10146 assert(UserDeclaredOperation);
10147 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10148 RD->hasUserDeclaredCopyAssignment() &&
10149 !S.getLangOpts().MSVCCompat) {
10150 // Find any user-declared move assignment operator.
10151 for (auto *I : RD->methods()) {
10152 if (I->isCopyAssignmentOperator()) {
10153 UserDeclaredOperation = I;
10157 assert(UserDeclaredOperation);
10160 if (UserDeclaredOperation) {
10161 S.Diag(UserDeclaredOperation->getLocation(),
10162 diag::warn_deprecated_copy_operation)
10163 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10164 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10165 S.Diag(UseLoc, diag::note_member_synthesized_at)
10166 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10167 : Sema::CXXCopyAssignment)
10172 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10173 CXXMethodDecl *CopyAssignOperator) {
10174 assert((CopyAssignOperator->isDefaulted() &&
10175 CopyAssignOperator->isOverloadedOperator() &&
10176 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10177 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10178 !CopyAssignOperator->isDeleted()) &&
10179 "DefineImplicitCopyAssignment called for wrong function");
10181 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10183 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10184 CopyAssignOperator->setInvalidDecl();
10188 // C++11 [class.copy]p18:
10189 // The [definition of an implicitly declared copy assignment operator] is
10190 // deprecated if the class has a user-declared copy constructor or a
10191 // user-declared destructor.
10192 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10193 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10195 CopyAssignOperator->markUsed(Context);
10197 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10198 DiagnosticErrorTrap Trap(Diags);
10200 // C++0x [class.copy]p30:
10201 // The implicitly-defined or explicitly-defaulted copy assignment operator
10202 // for a non-union class X performs memberwise copy assignment of its
10203 // subobjects. The direct base classes of X are assigned first, in the
10204 // order of their declaration in the base-specifier-list, and then the
10205 // immediate non-static data members of X are assigned, in the order in
10206 // which they were declared in the class definition.
10208 // The statements that form the synthesized function body.
10209 SmallVector<Stmt*, 8> Statements;
10211 // The parameter for the "other" object, which we are copying from.
10212 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10213 Qualifiers OtherQuals = Other->getType().getQualifiers();
10214 QualType OtherRefType = Other->getType();
10215 if (const LValueReferenceType *OtherRef
10216 = OtherRefType->getAs<LValueReferenceType>()) {
10217 OtherRefType = OtherRef->getPointeeType();
10218 OtherQuals = OtherRefType.getQualifiers();
10221 // Our location for everything implicitly-generated.
10222 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10223 ? CopyAssignOperator->getLocEnd()
10224 : CopyAssignOperator->getLocation();
10226 // Builds a DeclRefExpr for the "other" object.
10227 RefBuilder OtherRef(Other, OtherRefType);
10229 // Builds the "this" pointer.
10232 // Assign base classes.
10233 bool Invalid = false;
10234 for (auto &Base : ClassDecl->bases()) {
10235 // Form the assignment:
10236 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10237 QualType BaseType = Base.getType().getUnqualifiedType();
10238 if (!BaseType->isRecordType()) {
10243 CXXCastPath BasePath;
10244 BasePath.push_back(&Base);
10246 // Construct the "from" expression, which is an implicit cast to the
10247 // appropriately-qualified base type.
10248 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10249 VK_LValue, BasePath);
10251 // Dereference "this".
10252 DerefBuilder DerefThis(This);
10253 CastBuilder To(DerefThis,
10254 Context.getCVRQualifiedType(
10255 BaseType, CopyAssignOperator->getTypeQualifiers()),
10256 VK_LValue, BasePath);
10259 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10261 /*CopyingBaseSubobject=*/true,
10263 if (Copy.isInvalid()) {
10264 Diag(CurrentLocation, diag::note_member_synthesized_at)
10265 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10266 CopyAssignOperator->setInvalidDecl();
10270 // Success! Record the copy.
10271 Statements.push_back(Copy.getAs<Expr>());
10274 // Assign non-static members.
10275 for (auto *Field : ClassDecl->fields()) {
10276 // FIXME: We should form some kind of AST representation for the implied
10277 // memcpy in a union copy operation.
10278 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10281 if (Field->isInvalidDecl()) {
10286 // Check for members of reference type; we can't copy those.
10287 if (Field->getType()->isReferenceType()) {
10288 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10289 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10290 Diag(Field->getLocation(), diag::note_declared_at);
10291 Diag(CurrentLocation, diag::note_member_synthesized_at)
10292 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10297 // Check for members of const-qualified, non-class type.
10298 QualType BaseType = Context.getBaseElementType(Field->getType());
10299 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10300 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10301 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10302 Diag(Field->getLocation(), diag::note_declared_at);
10303 Diag(CurrentLocation, diag::note_member_synthesized_at)
10304 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10309 // Suppress assigning zero-width bitfields.
10310 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10313 QualType FieldType = Field->getType().getNonReferenceType();
10314 if (FieldType->isIncompleteArrayType()) {
10315 assert(ClassDecl->hasFlexibleArrayMember() &&
10316 "Incomplete array type is not valid");
10320 // Build references to the field in the object we're copying from and to.
10321 CXXScopeSpec SS; // Intentionally empty
10322 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10324 MemberLookup.addDecl(Field);
10325 MemberLookup.resolveKind();
10327 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10329 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10331 // Build the copy of this field.
10332 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10334 /*CopyingBaseSubobject=*/false,
10336 if (Copy.isInvalid()) {
10337 Diag(CurrentLocation, diag::note_member_synthesized_at)
10338 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10339 CopyAssignOperator->setInvalidDecl();
10343 // Success! Record the copy.
10344 Statements.push_back(Copy.getAs<Stmt>());
10348 // Add a "return *this;"
10349 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10351 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10352 if (Return.isInvalid())
10355 Statements.push_back(Return.getAs<Stmt>());
10357 if (Trap.hasErrorOccurred()) {
10358 Diag(CurrentLocation, diag::note_member_synthesized_at)
10359 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10365 // The exception specification is needed because we are defining the
10367 ResolveExceptionSpec(CurrentLocation,
10368 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10371 CopyAssignOperator->setInvalidDecl();
10377 CompoundScopeRAII CompoundScope(*this);
10378 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10379 /*isStmtExpr=*/false);
10380 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10382 CopyAssignOperator->setBody(Body.getAs<Stmt>());
10384 if (ASTMutationListener *L = getASTMutationListener()) {
10385 L->CompletedImplicitDefinition(CopyAssignOperator);
10389 Sema::ImplicitExceptionSpecification
10390 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10391 CXXRecordDecl *ClassDecl = MD->getParent();
10393 ImplicitExceptionSpecification ExceptSpec(*this);
10394 if (ClassDecl->isInvalidDecl())
10397 // C++0x [except.spec]p14:
10398 // An implicitly declared special member function (Clause 12) shall have an
10399 // exception-specification. [...]
10401 // It is unspecified whether or not an implicit move assignment operator
10402 // attempts to deduplicate calls to assignment operators of virtual bases are
10403 // made. As such, this exception specification is effectively unspecified.
10404 // Based on a similar decision made for constness in C++0x, we're erring on
10405 // the side of assuming such calls to be made regardless of whether they
10406 // actually happen.
10407 // Note that a move constructor is not implicitly declared when there are
10408 // virtual bases, but it can still be user-declared and explicitly defaulted.
10409 for (const auto &Base : ClassDecl->bases()) {
10410 if (Base.isVirtual())
10413 CXXRecordDecl *BaseClassDecl
10414 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10415 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10417 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10420 for (const auto &Base : ClassDecl->vbases()) {
10421 CXXRecordDecl *BaseClassDecl
10422 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10423 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10425 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10428 for (const auto *Field : ClassDecl->fields()) {
10429 QualType FieldType = Context.getBaseElementType(Field->getType());
10430 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10431 if (CXXMethodDecl *MoveAssign =
10432 LookupMovingAssignment(FieldClassDecl,
10433 FieldType.getCVRQualifiers(),
10435 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10442 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10443 assert(ClassDecl->needsImplicitMoveAssignment());
10445 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10446 if (DSM.isAlreadyBeingDeclared())
10449 // Note: The following rules are largely analoguous to the move
10450 // constructor rules.
10452 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10453 QualType RetType = Context.getLValueReferenceType(ArgType);
10454 ArgType = Context.getRValueReferenceType(ArgType);
10456 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10460 // An implicitly-declared move assignment operator is an inline public
10461 // member of its class.
10462 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10463 SourceLocation ClassLoc = ClassDecl->getLocation();
10464 DeclarationNameInfo NameInfo(Name, ClassLoc);
10465 CXXMethodDecl *MoveAssignment =
10466 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10467 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10468 /*isInline=*/true, Constexpr, SourceLocation());
10469 MoveAssignment->setAccess(AS_public);
10470 MoveAssignment->setDefaulted();
10471 MoveAssignment->setImplicit();
10473 if (getLangOpts().CUDA) {
10474 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10476 /* ConstRHS */ false,
10477 /* Diagnose */ false);
10480 // Build an exception specification pointing back at this member.
10481 FunctionProtoType::ExtProtoInfo EPI =
10482 getImplicitMethodEPI(*this, MoveAssignment);
10483 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10485 // Add the parameter to the operator.
10486 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10487 ClassLoc, ClassLoc,
10488 /*Id=*/nullptr, ArgType,
10489 /*TInfo=*/nullptr, SC_None,
10491 MoveAssignment->setParams(FromParam);
10493 AddOverriddenMethods(ClassDecl, MoveAssignment);
10495 MoveAssignment->setTrivial(
10496 ClassDecl->needsOverloadResolutionForMoveAssignment()
10497 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10498 : ClassDecl->hasTrivialMoveAssignment());
10500 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10501 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10502 SetDeclDeleted(MoveAssignment, ClassLoc);
10505 // Note that we have added this copy-assignment operator.
10506 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10508 if (Scope *S = getScopeForContext(ClassDecl))
10509 PushOnScopeChains(MoveAssignment, S, false);
10510 ClassDecl->addDecl(MoveAssignment);
10512 return MoveAssignment;
10515 /// Check if we're implicitly defining a move assignment operator for a class
10516 /// with virtual bases. Such a move assignment might move-assign the virtual
10517 /// base multiple times.
10518 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10519 SourceLocation CurrentLocation) {
10520 assert(!Class->isDependentContext() && "should not define dependent move");
10522 // Only a virtual base could get implicitly move-assigned multiple times.
10523 // Only a non-trivial move assignment can observe this. We only want to
10524 // diagnose if we implicitly define an assignment operator that assigns
10525 // two base classes, both of which move-assign the same virtual base.
10526 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10527 Class->getNumBases() < 2)
10530 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10531 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10534 for (auto &BI : Class->bases()) {
10535 Worklist.push_back(&BI);
10536 while (!Worklist.empty()) {
10537 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10538 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10540 // If the base has no non-trivial move assignment operators,
10541 // we don't care about moves from it.
10542 if (!Base->hasNonTrivialMoveAssignment())
10545 // If there's nothing virtual here, skip it.
10546 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10549 // If we're not actually going to call a move assignment for this base,
10550 // or the selected move assignment is trivial, skip it.
10551 Sema::SpecialMemberOverloadResult *SMOR =
10552 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10553 /*ConstArg*/false, /*VolatileArg*/false,
10554 /*RValueThis*/true, /*ConstThis*/false,
10555 /*VolatileThis*/false);
10556 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10557 !SMOR->getMethod()->isMoveAssignmentOperator())
10560 if (BaseSpec->isVirtual()) {
10561 // We're going to move-assign this virtual base, and its move
10562 // assignment operator is not trivial. If this can happen for
10563 // multiple distinct direct bases of Class, diagnose it. (If it
10564 // only happens in one base, we'll diagnose it when synthesizing
10565 // that base class's move assignment operator.)
10566 CXXBaseSpecifier *&Existing =
10567 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10569 if (Existing && Existing != &BI) {
10570 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10572 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10573 << (Base->getCanonicalDecl() ==
10574 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10575 << Base << Existing->getType() << Existing->getSourceRange();
10576 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10577 << (Base->getCanonicalDecl() ==
10578 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10579 << Base << BI.getType() << BaseSpec->getSourceRange();
10581 // Only diagnose each vbase once.
10582 Existing = nullptr;
10585 // Only walk over bases that have defaulted move assignment operators.
10586 // We assume that any user-provided move assignment operator handles
10587 // the multiple-moves-of-vbase case itself somehow.
10588 if (!SMOR->getMethod()->isDefaulted())
10591 // We're going to move the base classes of Base. Add them to the list.
10592 for (auto &BI : Base->bases())
10593 Worklist.push_back(&BI);
10599 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10600 CXXMethodDecl *MoveAssignOperator) {
10601 assert((MoveAssignOperator->isDefaulted() &&
10602 MoveAssignOperator->isOverloadedOperator() &&
10603 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10604 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10605 !MoveAssignOperator->isDeleted()) &&
10606 "DefineImplicitMoveAssignment called for wrong function");
10608 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10610 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10611 MoveAssignOperator->setInvalidDecl();
10615 MoveAssignOperator->markUsed(Context);
10617 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10618 DiagnosticErrorTrap Trap(Diags);
10620 // C++0x [class.copy]p28:
10621 // The implicitly-defined or move assignment operator for a non-union class
10622 // X performs memberwise move assignment of its subobjects. The direct base
10623 // classes of X are assigned first, in the order of their declaration in the
10624 // base-specifier-list, and then the immediate non-static data members of X
10625 // are assigned, in the order in which they were declared in the class
10628 // Issue a warning if our implicit move assignment operator will move
10629 // from a virtual base more than once.
10630 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10632 // The statements that form the synthesized function body.
10633 SmallVector<Stmt*, 8> Statements;
10635 // The parameter for the "other" object, which we are move from.
10636 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10637 QualType OtherRefType = Other->getType()->
10638 getAs<RValueReferenceType>()->getPointeeType();
10639 assert(!OtherRefType.getQualifiers() &&
10640 "Bad argument type of defaulted move assignment");
10642 // Our location for everything implicitly-generated.
10643 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10644 ? MoveAssignOperator->getLocEnd()
10645 : MoveAssignOperator->getLocation();
10647 // Builds a reference to the "other" object.
10648 RefBuilder OtherRef(Other, OtherRefType);
10650 MoveCastBuilder MoveOther(OtherRef);
10652 // Builds the "this" pointer.
10655 // Assign base classes.
10656 bool Invalid = false;
10657 for (auto &Base : ClassDecl->bases()) {
10658 // C++11 [class.copy]p28:
10659 // It is unspecified whether subobjects representing virtual base classes
10660 // are assigned more than once by the implicitly-defined copy assignment
10662 // FIXME: Do not assign to a vbase that will be assigned by some other base
10663 // class. For a move-assignment, this can result in the vbase being moved
10666 // Form the assignment:
10667 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10668 QualType BaseType = Base.getType().getUnqualifiedType();
10669 if (!BaseType->isRecordType()) {
10674 CXXCastPath BasePath;
10675 BasePath.push_back(&Base);
10677 // Construct the "from" expression, which is an implicit cast to the
10678 // appropriately-qualified base type.
10679 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10681 // Dereference "this".
10682 DerefBuilder DerefThis(This);
10684 // Implicitly cast "this" to the appropriately-qualified base type.
10685 CastBuilder To(DerefThis,
10686 Context.getCVRQualifiedType(
10687 BaseType, MoveAssignOperator->getTypeQualifiers()),
10688 VK_LValue, BasePath);
10691 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10693 /*CopyingBaseSubobject=*/true,
10694 /*Copying=*/false);
10695 if (Move.isInvalid()) {
10696 Diag(CurrentLocation, diag::note_member_synthesized_at)
10697 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10698 MoveAssignOperator->setInvalidDecl();
10702 // Success! Record the move.
10703 Statements.push_back(Move.getAs<Expr>());
10706 // Assign non-static members.
10707 for (auto *Field : ClassDecl->fields()) {
10708 // FIXME: We should form some kind of AST representation for the implied
10709 // memcpy in a union copy operation.
10710 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10713 if (Field->isInvalidDecl()) {
10718 // Check for members of reference type; we can't move those.
10719 if (Field->getType()->isReferenceType()) {
10720 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10721 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10722 Diag(Field->getLocation(), diag::note_declared_at);
10723 Diag(CurrentLocation, diag::note_member_synthesized_at)
10724 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10729 // Check for members of const-qualified, non-class type.
10730 QualType BaseType = Context.getBaseElementType(Field->getType());
10731 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10732 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10733 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10734 Diag(Field->getLocation(), diag::note_declared_at);
10735 Diag(CurrentLocation, diag::note_member_synthesized_at)
10736 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10741 // Suppress assigning zero-width bitfields.
10742 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10745 QualType FieldType = Field->getType().getNonReferenceType();
10746 if (FieldType->isIncompleteArrayType()) {
10747 assert(ClassDecl->hasFlexibleArrayMember() &&
10748 "Incomplete array type is not valid");
10752 // Build references to the field in the object we're copying from and to.
10753 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10755 MemberLookup.addDecl(Field);
10756 MemberLookup.resolveKind();
10757 MemberBuilder From(MoveOther, OtherRefType,
10758 /*IsArrow=*/false, MemberLookup);
10759 MemberBuilder To(This, getCurrentThisType(),
10760 /*IsArrow=*/true, MemberLookup);
10762 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10763 "Member reference with rvalue base must be rvalue except for reference "
10764 "members, which aren't allowed for move assignment.");
10766 // Build the move of this field.
10767 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10769 /*CopyingBaseSubobject=*/false,
10770 /*Copying=*/false);
10771 if (Move.isInvalid()) {
10772 Diag(CurrentLocation, diag::note_member_synthesized_at)
10773 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10774 MoveAssignOperator->setInvalidDecl();
10778 // Success! Record the copy.
10779 Statements.push_back(Move.getAs<Stmt>());
10783 // Add a "return *this;"
10784 ExprResult ThisObj =
10785 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10787 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10788 if (Return.isInvalid())
10791 Statements.push_back(Return.getAs<Stmt>());
10793 if (Trap.hasErrorOccurred()) {
10794 Diag(CurrentLocation, diag::note_member_synthesized_at)
10795 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10801 // The exception specification is needed because we are defining the
10803 ResolveExceptionSpec(CurrentLocation,
10804 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10807 MoveAssignOperator->setInvalidDecl();
10813 CompoundScopeRAII CompoundScope(*this);
10814 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10815 /*isStmtExpr=*/false);
10816 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10818 MoveAssignOperator->setBody(Body.getAs<Stmt>());
10820 if (ASTMutationListener *L = getASTMutationListener()) {
10821 L->CompletedImplicitDefinition(MoveAssignOperator);
10825 Sema::ImplicitExceptionSpecification
10826 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10827 CXXRecordDecl *ClassDecl = MD->getParent();
10829 ImplicitExceptionSpecification ExceptSpec(*this);
10830 if (ClassDecl->isInvalidDecl())
10833 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10834 assert(T->getNumParams() >= 1 && "not a copy ctor");
10835 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10837 // C++ [except.spec]p14:
10838 // An implicitly declared special member function (Clause 12) shall have an
10839 // exception-specification. [...]
10840 for (const auto &Base : ClassDecl->bases()) {
10841 // Virtual bases are handled below.
10842 if (Base.isVirtual())
10845 CXXRecordDecl *BaseClassDecl
10846 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10847 if (CXXConstructorDecl *CopyConstructor =
10848 LookupCopyingConstructor(BaseClassDecl, Quals))
10849 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10851 for (const auto &Base : ClassDecl->vbases()) {
10852 CXXRecordDecl *BaseClassDecl
10853 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10854 if (CXXConstructorDecl *CopyConstructor =
10855 LookupCopyingConstructor(BaseClassDecl, Quals))
10856 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10858 for (const auto *Field : ClassDecl->fields()) {
10859 QualType FieldType = Context.getBaseElementType(Field->getType());
10860 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10861 if (CXXConstructorDecl *CopyConstructor =
10862 LookupCopyingConstructor(FieldClassDecl,
10863 Quals | FieldType.getCVRQualifiers()))
10864 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10871 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10872 CXXRecordDecl *ClassDecl) {
10873 // C++ [class.copy]p4:
10874 // If the class definition does not explicitly declare a copy
10875 // constructor, one is declared implicitly.
10876 assert(ClassDecl->needsImplicitCopyConstructor());
10878 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10879 if (DSM.isAlreadyBeingDeclared())
10882 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10883 QualType ArgType = ClassType;
10884 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10886 ArgType = ArgType.withConst();
10887 ArgType = Context.getLValueReferenceType(ArgType);
10889 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10890 CXXCopyConstructor,
10893 DeclarationName Name
10894 = Context.DeclarationNames.getCXXConstructorName(
10895 Context.getCanonicalType(ClassType));
10896 SourceLocation ClassLoc = ClassDecl->getLocation();
10897 DeclarationNameInfo NameInfo(Name, ClassLoc);
10899 // An implicitly-declared copy constructor is an inline public
10900 // member of its class.
10901 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10902 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10903 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10905 CopyConstructor->setAccess(AS_public);
10906 CopyConstructor->setDefaulted();
10908 if (getLangOpts().CUDA) {
10909 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10911 /* ConstRHS */ Const,
10912 /* Diagnose */ false);
10915 // Build an exception specification pointing back at this member.
10916 FunctionProtoType::ExtProtoInfo EPI =
10917 getImplicitMethodEPI(*this, CopyConstructor);
10918 CopyConstructor->setType(
10919 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10921 // Add the parameter to the constructor.
10922 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10923 ClassLoc, ClassLoc,
10924 /*IdentifierInfo=*/nullptr,
10925 ArgType, /*TInfo=*/nullptr,
10927 CopyConstructor->setParams(FromParam);
10929 CopyConstructor->setTrivial(
10930 ClassDecl->needsOverloadResolutionForCopyConstructor()
10931 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10932 : ClassDecl->hasTrivialCopyConstructor());
10934 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10935 SetDeclDeleted(CopyConstructor, ClassLoc);
10937 // Note that we have declared this constructor.
10938 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10940 if (Scope *S = getScopeForContext(ClassDecl))
10941 PushOnScopeChains(CopyConstructor, S, false);
10942 ClassDecl->addDecl(CopyConstructor);
10944 return CopyConstructor;
10947 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10948 CXXConstructorDecl *CopyConstructor) {
10949 assert((CopyConstructor->isDefaulted() &&
10950 CopyConstructor->isCopyConstructor() &&
10951 !CopyConstructor->doesThisDeclarationHaveABody() &&
10952 !CopyConstructor->isDeleted()) &&
10953 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10955 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10956 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10958 // C++11 [class.copy]p7:
10959 // The [definition of an implicitly declared copy constructor] is
10960 // deprecated if the class has a user-declared copy assignment operator
10961 // or a user-declared destructor.
10962 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10963 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10965 SynthesizedFunctionScope Scope(*this, CopyConstructor);
10966 DiagnosticErrorTrap Trap(Diags);
10968 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10969 Trap.hasErrorOccurred()) {
10970 Diag(CurrentLocation, diag::note_member_synthesized_at)
10971 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10972 CopyConstructor->setInvalidDecl();
10974 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10975 ? CopyConstructor->getLocEnd()
10976 : CopyConstructor->getLocation();
10977 Sema::CompoundScopeRAII CompoundScope(*this);
10978 CopyConstructor->setBody(
10979 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10982 // The exception specification is needed because we are defining the
10984 ResolveExceptionSpec(CurrentLocation,
10985 CopyConstructor->getType()->castAs<FunctionProtoType>());
10987 CopyConstructor->markUsed(Context);
10988 MarkVTableUsed(CurrentLocation, ClassDecl);
10990 if (ASTMutationListener *L = getASTMutationListener()) {
10991 L->CompletedImplicitDefinition(CopyConstructor);
10995 Sema::ImplicitExceptionSpecification
10996 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10997 CXXRecordDecl *ClassDecl = MD->getParent();
10999 // C++ [except.spec]p14:
11000 // An implicitly declared special member function (Clause 12) shall have an
11001 // exception-specification. [...]
11002 ImplicitExceptionSpecification ExceptSpec(*this);
11003 if (ClassDecl->isInvalidDecl())
11006 // Direct base-class constructors.
11007 for (const auto &B : ClassDecl->bases()) {
11008 if (B.isVirtual()) // Handled below.
11011 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11012 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11013 CXXConstructorDecl *Constructor =
11014 LookupMovingConstructor(BaseClassDecl, 0);
11015 // If this is a deleted function, add it anyway. This might be conformant
11016 // with the standard. This might not. I'm not sure. It might not matter.
11018 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11022 // Virtual base-class constructors.
11023 for (const auto &B : ClassDecl->vbases()) {
11024 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11025 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11026 CXXConstructorDecl *Constructor =
11027 LookupMovingConstructor(BaseClassDecl, 0);
11028 // If this is a deleted function, add it anyway. This might be conformant
11029 // with the standard. This might not. I'm not sure. It might not matter.
11031 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11035 // Field constructors.
11036 for (const auto *F : ClassDecl->fields()) {
11037 QualType FieldType = Context.getBaseElementType(F->getType());
11038 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11039 CXXConstructorDecl *Constructor =
11040 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11041 // If this is a deleted function, add it anyway. This might be conformant
11042 // with the standard. This might not. I'm not sure. It might not matter.
11043 // In particular, the problem is that this function never gets called. It
11044 // might just be ill-formed because this function attempts to refer to
11045 // a deleted function here.
11047 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11054 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11055 CXXRecordDecl *ClassDecl) {
11056 assert(ClassDecl->needsImplicitMoveConstructor());
11058 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11059 if (DSM.isAlreadyBeingDeclared())
11062 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11063 QualType ArgType = Context.getRValueReferenceType(ClassType);
11065 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11066 CXXMoveConstructor,
11069 DeclarationName Name
11070 = Context.DeclarationNames.getCXXConstructorName(
11071 Context.getCanonicalType(ClassType));
11072 SourceLocation ClassLoc = ClassDecl->getLocation();
11073 DeclarationNameInfo NameInfo(Name, ClassLoc);
11075 // C++11 [class.copy]p11:
11076 // An implicitly-declared copy/move constructor is an inline public
11077 // member of its class.
11078 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11079 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11080 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11082 MoveConstructor->setAccess(AS_public);
11083 MoveConstructor->setDefaulted();
11085 if (getLangOpts().CUDA) {
11086 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11088 /* ConstRHS */ false,
11089 /* Diagnose */ false);
11092 // Build an exception specification pointing back at this member.
11093 FunctionProtoType::ExtProtoInfo EPI =
11094 getImplicitMethodEPI(*this, MoveConstructor);
11095 MoveConstructor->setType(
11096 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11098 // Add the parameter to the constructor.
11099 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11100 ClassLoc, ClassLoc,
11101 /*IdentifierInfo=*/nullptr,
11102 ArgType, /*TInfo=*/nullptr,
11104 MoveConstructor->setParams(FromParam);
11106 MoveConstructor->setTrivial(
11107 ClassDecl->needsOverloadResolutionForMoveConstructor()
11108 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11109 : ClassDecl->hasTrivialMoveConstructor());
11111 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11112 ClassDecl->setImplicitMoveConstructorIsDeleted();
11113 SetDeclDeleted(MoveConstructor, ClassLoc);
11116 // Note that we have declared this constructor.
11117 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11119 if (Scope *S = getScopeForContext(ClassDecl))
11120 PushOnScopeChains(MoveConstructor, S, false);
11121 ClassDecl->addDecl(MoveConstructor);
11123 return MoveConstructor;
11126 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11127 CXXConstructorDecl *MoveConstructor) {
11128 assert((MoveConstructor->isDefaulted() &&
11129 MoveConstructor->isMoveConstructor() &&
11130 !MoveConstructor->doesThisDeclarationHaveABody() &&
11131 !MoveConstructor->isDeleted()) &&
11132 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11134 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11135 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11137 SynthesizedFunctionScope Scope(*this, MoveConstructor);
11138 DiagnosticErrorTrap Trap(Diags);
11140 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11141 Trap.hasErrorOccurred()) {
11142 Diag(CurrentLocation, diag::note_member_synthesized_at)
11143 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11144 MoveConstructor->setInvalidDecl();
11146 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11147 ? MoveConstructor->getLocEnd()
11148 : MoveConstructor->getLocation();
11149 Sema::CompoundScopeRAII CompoundScope(*this);
11150 MoveConstructor->setBody(ActOnCompoundStmt(
11151 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11154 // The exception specification is needed because we are defining the
11156 ResolveExceptionSpec(CurrentLocation,
11157 MoveConstructor->getType()->castAs<FunctionProtoType>());
11159 MoveConstructor->markUsed(Context);
11160 MarkVTableUsed(CurrentLocation, ClassDecl);
11162 if (ASTMutationListener *L = getASTMutationListener()) {
11163 L->CompletedImplicitDefinition(MoveConstructor);
11167 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11168 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11171 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11172 SourceLocation CurrentLocation,
11173 CXXConversionDecl *Conv) {
11174 CXXRecordDecl *Lambda = Conv->getParent();
11175 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11176 // If we are defining a specialization of a conversion to function-ptr
11177 // cache the deduced template arguments for this specialization
11178 // so that we can use them to retrieve the corresponding call-operator
11179 // and static-invoker.
11180 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11182 // Retrieve the corresponding call-operator specialization.
11183 if (Lambda->isGenericLambda()) {
11184 assert(Conv->isFunctionTemplateSpecialization());
11185 FunctionTemplateDecl *CallOpTemplate =
11186 CallOp->getDescribedFunctionTemplate();
11187 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11188 void *InsertPos = nullptr;
11189 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11190 DeducedTemplateArgs->asArray(),
11192 assert(CallOpSpec &&
11193 "Conversion operator must have a corresponding call operator");
11194 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11196 // Mark the call operator referenced (and add to pending instantiations
11198 // For both the conversion and static-invoker template specializations
11199 // we construct their body's in this function, so no need to add them
11200 // to the PendingInstantiations.
11201 MarkFunctionReferenced(CurrentLocation, CallOp);
11203 SynthesizedFunctionScope Scope(*this, Conv);
11204 DiagnosticErrorTrap Trap(Diags);
11206 // Retrieve the static invoker...
11207 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11208 // ... and get the corresponding specialization for a generic lambda.
11209 if (Lambda->isGenericLambda()) {
11210 assert(DeducedTemplateArgs &&
11211 "Must have deduced template arguments from Conversion Operator");
11212 FunctionTemplateDecl *InvokeTemplate =
11213 Invoker->getDescribedFunctionTemplate();
11214 void *InsertPos = nullptr;
11215 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11216 DeducedTemplateArgs->asArray(),
11218 assert(InvokeSpec &&
11219 "Must have a corresponding static invoker specialization");
11220 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11222 // Construct the body of the conversion function { return __invoke; }.
11223 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11224 VK_LValue, Conv->getLocation()).get();
11225 assert(FunctionRef && "Can't refer to __invoke function?");
11226 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11227 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11228 Conv->getLocation(),
11229 Conv->getLocation()));
11231 Conv->markUsed(Context);
11232 Conv->setReferenced();
11234 // Fill in the __invoke function with a dummy implementation. IR generation
11235 // will fill in the actual details.
11236 Invoker->markUsed(Context);
11237 Invoker->setReferenced();
11238 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11240 if (ASTMutationListener *L = getASTMutationListener()) {
11241 L->CompletedImplicitDefinition(Conv);
11242 L->CompletedImplicitDefinition(Invoker);
11248 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11249 SourceLocation CurrentLocation,
11250 CXXConversionDecl *Conv)
11252 assert(!Conv->getParent()->isGenericLambda());
11254 Conv->markUsed(Context);
11256 SynthesizedFunctionScope Scope(*this, Conv);
11257 DiagnosticErrorTrap Trap(Diags);
11259 // Copy-initialize the lambda object as needed to capture it.
11260 Expr *This = ActOnCXXThis(CurrentLocation).get();
11261 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11263 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11264 Conv->getLocation(),
11267 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11268 // behavior. Note that only the general conversion function does this
11269 // (since it's unusable otherwise); in the case where we inline the
11270 // block literal, it has block literal lifetime semantics.
11271 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11272 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11273 CK_CopyAndAutoreleaseBlockObject,
11274 BuildBlock.get(), nullptr, VK_RValue);
11276 if (BuildBlock.isInvalid()) {
11277 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11278 Conv->setInvalidDecl();
11282 // Create the return statement that returns the block from the conversion
11284 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11285 if (Return.isInvalid()) {
11286 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11287 Conv->setInvalidDecl();
11291 // Set the body of the conversion function.
11292 Stmt *ReturnS = Return.get();
11293 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11294 Conv->getLocation(),
11295 Conv->getLocation()));
11297 // We're done; notify the mutation listener, if any.
11298 if (ASTMutationListener *L = getASTMutationListener()) {
11299 L->CompletedImplicitDefinition(Conv);
11303 /// \brief Determine whether the given list arguments contains exactly one
11304 /// "real" (non-default) argument.
11305 static bool hasOneRealArgument(MultiExprArg Args) {
11306 switch (Args.size()) {
11311 if (!Args[1]->isDefaultArgument())
11316 return !Args[0]->isDefaultArgument();
11323 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11324 CXXConstructorDecl *Constructor,
11325 MultiExprArg ExprArgs,
11326 bool HadMultipleCandidates,
11327 bool IsListInitialization,
11328 bool IsStdInitListInitialization,
11329 bool RequiresZeroInit,
11330 unsigned ConstructKind,
11331 SourceRange ParenRange) {
11332 bool Elidable = false;
11334 // C++0x [class.copy]p34:
11335 // When certain criteria are met, an implementation is allowed to
11336 // omit the copy/move construction of a class object, even if the
11337 // copy/move constructor and/or destructor for the object have
11338 // side effects. [...]
11339 // - when a temporary class object that has not been bound to a
11340 // reference (12.2) would be copied/moved to a class object
11341 // with the same cv-unqualified type, the copy/move operation
11342 // can be omitted by constructing the temporary object
11343 // directly into the target of the omitted copy/move
11344 if (ConstructKind == CXXConstructExpr::CK_Complete &&
11345 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11346 Expr *SubExpr = ExprArgs[0];
11347 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11350 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11351 Elidable, ExprArgs, HadMultipleCandidates,
11352 IsListInitialization,
11353 IsStdInitListInitialization, RequiresZeroInit,
11354 ConstructKind, ParenRange);
11357 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11358 /// including handling of its default argument expressions.
11360 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11361 CXXConstructorDecl *Constructor, bool Elidable,
11362 MultiExprArg ExprArgs,
11363 bool HadMultipleCandidates,
11364 bool IsListInitialization,
11365 bool IsStdInitListInitialization,
11366 bool RequiresZeroInit,
11367 unsigned ConstructKind,
11368 SourceRange ParenRange) {
11369 MarkFunctionReferenced(ConstructLoc, Constructor);
11370 return CXXConstructExpr::Create(
11371 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11372 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11374 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11378 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11379 assert(Field->hasInClassInitializer());
11381 // If we already have the in-class initializer nothing needs to be done.
11382 if (Field->getInClassInitializer())
11383 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11385 // Maybe we haven't instantiated the in-class initializer. Go check the
11386 // pattern FieldDecl to see if it has one.
11387 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11389 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11390 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11391 DeclContext::lookup_result Lookup =
11392 ClassPattern->lookup(Field->getDeclName());
11393 assert(Lookup.size() == 1);
11394 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11395 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11396 getTemplateInstantiationArgs(Field)))
11397 return ExprError();
11398 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11402 // If the brace-or-equal-initializer of a non-static data member
11403 // invokes a defaulted default constructor of its class or of an
11404 // enclosing class in a potentially evaluated subexpression, the
11405 // program is ill-formed.
11407 // This resolution is unworkable: the exception specification of the
11408 // default constructor can be needed in an unevaluated context, in
11409 // particular, in the operand of a noexcept-expression, and we can be
11410 // unable to compute an exception specification for an enclosed class.
11412 // Any attempt to resolve the exception specification of a defaulted default
11413 // constructor before the initializer is lexically complete will ultimately
11414 // come here at which point we can diagnose it.
11415 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11416 if (OutermostClass == ParentRD) {
11417 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11418 << ParentRD << Field;
11420 Diag(Field->getLocEnd(),
11421 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11422 << ParentRD << OutermostClass << Field;
11425 return ExprError();
11428 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11429 if (VD->isInvalidDecl()) return;
11431 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11432 if (ClassDecl->isInvalidDecl()) return;
11433 if (ClassDecl->hasIrrelevantDestructor()) return;
11434 if (ClassDecl->isDependentContext()) return;
11436 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11437 MarkFunctionReferenced(VD->getLocation(), Destructor);
11438 CheckDestructorAccess(VD->getLocation(), Destructor,
11439 PDiag(diag::err_access_dtor_var)
11440 << VD->getDeclName()
11442 DiagnoseUseOfDecl(Destructor, VD->getLocation());
11444 if (Destructor->isTrivial()) return;
11445 if (!VD->hasGlobalStorage()) return;
11447 // Emit warning for non-trivial dtor in global scope (a real global,
11448 // class-static, function-static).
11449 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11451 // TODO: this should be re-enabled for static locals by !CXAAtExit
11452 if (!VD->isStaticLocal())
11453 Diag(VD->getLocation(), diag::warn_global_destructor);
11456 /// \brief Given a constructor and the set of arguments provided for the
11457 /// constructor, convert the arguments and add any required default arguments
11458 /// to form a proper call to this constructor.
11460 /// \returns true if an error occurred, false otherwise.
11462 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11463 MultiExprArg ArgsPtr,
11464 SourceLocation Loc,
11465 SmallVectorImpl<Expr*> &ConvertedArgs,
11466 bool AllowExplicit,
11467 bool IsListInitialization) {
11468 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11469 unsigned NumArgs = ArgsPtr.size();
11470 Expr **Args = ArgsPtr.data();
11472 const FunctionProtoType *Proto
11473 = Constructor->getType()->getAs<FunctionProtoType>();
11474 assert(Proto && "Constructor without a prototype?");
11475 unsigned NumParams = Proto->getNumParams();
11477 // If too few arguments are available, we'll fill in the rest with defaults.
11478 if (NumArgs < NumParams)
11479 ConvertedArgs.reserve(NumParams);
11481 ConvertedArgs.reserve(NumArgs);
11483 VariadicCallType CallType =
11484 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11485 SmallVector<Expr *, 8> AllArgs;
11486 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11488 llvm::makeArrayRef(Args, NumArgs),
11490 CallType, AllowExplicit,
11491 IsListInitialization);
11492 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11494 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11496 CheckConstructorCall(Constructor,
11497 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11504 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11505 const FunctionDecl *FnDecl) {
11506 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11507 if (isa<NamespaceDecl>(DC)) {
11508 return SemaRef.Diag(FnDecl->getLocation(),
11509 diag::err_operator_new_delete_declared_in_namespace)
11510 << FnDecl->getDeclName();
11513 if (isa<TranslationUnitDecl>(DC) &&
11514 FnDecl->getStorageClass() == SC_Static) {
11515 return SemaRef.Diag(FnDecl->getLocation(),
11516 diag::err_operator_new_delete_declared_static)
11517 << FnDecl->getDeclName();
11524 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11525 CanQualType ExpectedResultType,
11526 CanQualType ExpectedFirstParamType,
11527 unsigned DependentParamTypeDiag,
11528 unsigned InvalidParamTypeDiag) {
11529 QualType ResultType =
11530 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11532 // Check that the result type is not dependent.
11533 if (ResultType->isDependentType())
11534 return SemaRef.Diag(FnDecl->getLocation(),
11535 diag::err_operator_new_delete_dependent_result_type)
11536 << FnDecl->getDeclName() << ExpectedResultType;
11538 // Check that the result type is what we expect.
11539 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11540 return SemaRef.Diag(FnDecl->getLocation(),
11541 diag::err_operator_new_delete_invalid_result_type)
11542 << FnDecl->getDeclName() << ExpectedResultType;
11544 // A function template must have at least 2 parameters.
11545 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11546 return SemaRef.Diag(FnDecl->getLocation(),
11547 diag::err_operator_new_delete_template_too_few_parameters)
11548 << FnDecl->getDeclName();
11550 // The function decl must have at least 1 parameter.
11551 if (FnDecl->getNumParams() == 0)
11552 return SemaRef.Diag(FnDecl->getLocation(),
11553 diag::err_operator_new_delete_too_few_parameters)
11554 << FnDecl->getDeclName();
11556 // Check the first parameter type is not dependent.
11557 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11558 if (FirstParamType->isDependentType())
11559 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11560 << FnDecl->getDeclName() << ExpectedFirstParamType;
11562 // Check that the first parameter type is what we expect.
11563 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11564 ExpectedFirstParamType)
11565 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11566 << FnDecl->getDeclName() << ExpectedFirstParamType;
11572 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11573 // C++ [basic.stc.dynamic.allocation]p1:
11574 // A program is ill-formed if an allocation function is declared in a
11575 // namespace scope other than global scope or declared static in global
11577 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11580 CanQualType SizeTy =
11581 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11583 // C++ [basic.stc.dynamic.allocation]p1:
11584 // The return type shall be void*. The first parameter shall have type
11586 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11588 diag::err_operator_new_dependent_param_type,
11589 diag::err_operator_new_param_type))
11592 // C++ [basic.stc.dynamic.allocation]p1:
11593 // The first parameter shall not have an associated default argument.
11594 if (FnDecl->getParamDecl(0)->hasDefaultArg())
11595 return SemaRef.Diag(FnDecl->getLocation(),
11596 diag::err_operator_new_default_arg)
11597 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11603 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11604 // C++ [basic.stc.dynamic.deallocation]p1:
11605 // A program is ill-formed if deallocation functions are declared in a
11606 // namespace scope other than global scope or declared static in global
11608 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11611 // C++ [basic.stc.dynamic.deallocation]p2:
11612 // Each deallocation function shall return void and its first parameter
11614 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11615 SemaRef.Context.VoidPtrTy,
11616 diag::err_operator_delete_dependent_param_type,
11617 diag::err_operator_delete_param_type))
11623 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11624 /// of this overloaded operator is well-formed. If so, returns false;
11625 /// otherwise, emits appropriate diagnostics and returns true.
11626 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11627 assert(FnDecl && FnDecl->isOverloadedOperator() &&
11628 "Expected an overloaded operator declaration");
11630 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11632 // C++ [over.oper]p5:
11633 // The allocation and deallocation functions, operator new,
11634 // operator new[], operator delete and operator delete[], are
11635 // described completely in 3.7.3. The attributes and restrictions
11636 // found in the rest of this subclause do not apply to them unless
11637 // explicitly stated in 3.7.3.
11638 if (Op == OO_Delete || Op == OO_Array_Delete)
11639 return CheckOperatorDeleteDeclaration(*this, FnDecl);
11641 if (Op == OO_New || Op == OO_Array_New)
11642 return CheckOperatorNewDeclaration(*this, FnDecl);
11644 // C++ [over.oper]p6:
11645 // An operator function shall either be a non-static member
11646 // function or be a non-member function and have at least one
11647 // parameter whose type is a class, a reference to a class, an
11648 // enumeration, or a reference to an enumeration.
11649 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11650 if (MethodDecl->isStatic())
11651 return Diag(FnDecl->getLocation(),
11652 diag::err_operator_overload_static) << FnDecl->getDeclName();
11654 bool ClassOrEnumParam = false;
11655 for (auto Param : FnDecl->params()) {
11656 QualType ParamType = Param->getType().getNonReferenceType();
11657 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11658 ParamType->isEnumeralType()) {
11659 ClassOrEnumParam = true;
11664 if (!ClassOrEnumParam)
11665 return Diag(FnDecl->getLocation(),
11666 diag::err_operator_overload_needs_class_or_enum)
11667 << FnDecl->getDeclName();
11670 // C++ [over.oper]p8:
11671 // An operator function cannot have default arguments (8.3.6),
11672 // except where explicitly stated below.
11674 // Only the function-call operator allows default arguments
11675 // (C++ [over.call]p1).
11676 if (Op != OO_Call) {
11677 for (auto Param : FnDecl->params()) {
11678 if (Param->hasDefaultArg())
11679 return Diag(Param->getLocation(),
11680 diag::err_operator_overload_default_arg)
11681 << FnDecl->getDeclName() << Param->getDefaultArgRange();
11685 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11686 { false, false, false }
11687 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11688 , { Unary, Binary, MemberOnly }
11689 #include "clang/Basic/OperatorKinds.def"
11692 bool CanBeUnaryOperator = OperatorUses[Op][0];
11693 bool CanBeBinaryOperator = OperatorUses[Op][1];
11694 bool MustBeMemberOperator = OperatorUses[Op][2];
11696 // C++ [over.oper]p8:
11697 // [...] Operator functions cannot have more or fewer parameters
11698 // than the number required for the corresponding operator, as
11699 // described in the rest of this subclause.
11700 unsigned NumParams = FnDecl->getNumParams()
11701 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11702 if (Op != OO_Call &&
11703 ((NumParams == 1 && !CanBeUnaryOperator) ||
11704 (NumParams == 2 && !CanBeBinaryOperator) ||
11705 (NumParams < 1) || (NumParams > 2))) {
11706 // We have the wrong number of parameters.
11707 unsigned ErrorKind;
11708 if (CanBeUnaryOperator && CanBeBinaryOperator) {
11709 ErrorKind = 2; // 2 -> unary or binary.
11710 } else if (CanBeUnaryOperator) {
11711 ErrorKind = 0; // 0 -> unary
11713 assert(CanBeBinaryOperator &&
11714 "All non-call overloaded operators are unary or binary!");
11715 ErrorKind = 1; // 1 -> binary
11718 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11719 << FnDecl->getDeclName() << NumParams << ErrorKind;
11722 // Overloaded operators other than operator() cannot be variadic.
11723 if (Op != OO_Call &&
11724 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11725 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11726 << FnDecl->getDeclName();
11729 // Some operators must be non-static member functions.
11730 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11731 return Diag(FnDecl->getLocation(),
11732 diag::err_operator_overload_must_be_member)
11733 << FnDecl->getDeclName();
11736 // C++ [over.inc]p1:
11737 // The user-defined function called operator++ implements the
11738 // prefix and postfix ++ operator. If this function is a member
11739 // function with no parameters, or a non-member function with one
11740 // parameter of class or enumeration type, it defines the prefix
11741 // increment operator ++ for objects of that type. If the function
11742 // is a member function with one parameter (which shall be of type
11743 // int) or a non-member function with two parameters (the second
11744 // of which shall be of type int), it defines the postfix
11745 // increment operator ++ for objects of that type.
11746 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11747 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11748 QualType ParamType = LastParam->getType();
11750 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11751 !ParamType->isDependentType())
11752 return Diag(LastParam->getLocation(),
11753 diag::err_operator_overload_post_incdec_must_be_int)
11754 << LastParam->getType() << (Op == OO_MinusMinus);
11760 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11761 /// of this literal operator function is well-formed. If so, returns
11762 /// false; otherwise, emits appropriate diagnostics and returns true.
11763 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11764 if (isa<CXXMethodDecl>(FnDecl)) {
11765 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11766 << FnDecl->getDeclName();
11770 if (FnDecl->isExternC()) {
11771 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11775 bool Valid = false;
11777 // This might be the definition of a literal operator template.
11778 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11779 // This might be a specialization of a literal operator template.
11781 TpDecl = FnDecl->getPrimaryTemplate();
11783 // template <char...> type operator "" name() and
11784 // template <class T, T...> type operator "" name() are the only valid
11785 // template signatures, and the only valid signatures with no parameters.
11787 if (FnDecl->param_size() == 0) {
11788 // Must have one or two template parameters
11789 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11790 if (Params->size() == 1) {
11791 NonTypeTemplateParmDecl *PmDecl =
11792 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11794 // The template parameter must be a char parameter pack.
11795 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11796 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11798 } else if (Params->size() == 2) {
11799 TemplateTypeParmDecl *PmType =
11800 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11801 NonTypeTemplateParmDecl *PmArgs =
11802 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11804 // The second template parameter must be a parameter pack with the
11805 // first template parameter as its type.
11806 if (PmType && PmArgs &&
11807 !PmType->isTemplateParameterPack() &&
11808 PmArgs->isTemplateParameterPack()) {
11809 const TemplateTypeParmType *TArgs =
11810 PmArgs->getType()->getAs<TemplateTypeParmType>();
11811 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11812 TArgs->getIndex() == PmType->getIndex()) {
11814 if (ActiveTemplateInstantiations.empty())
11815 Diag(FnDecl->getLocation(),
11816 diag::ext_string_literal_operator_template);
11821 } else if (FnDecl->param_size()) {
11822 // Check the first parameter
11823 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11825 QualType T = (*Param)->getType().getUnqualifiedType();
11827 // unsigned long long int, long double, and any character type are allowed
11828 // as the only parameters.
11829 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11830 Context.hasSameType(T, Context.LongDoubleTy) ||
11831 Context.hasSameType(T, Context.CharTy) ||
11832 Context.hasSameType(T, Context.WideCharTy) ||
11833 Context.hasSameType(T, Context.Char16Ty) ||
11834 Context.hasSameType(T, Context.Char32Ty)) {
11835 if (++Param == FnDecl->param_end())
11837 goto FinishedParams;
11840 // Otherwise it must be a pointer to const; let's strip those qualifiers.
11841 const PointerType *PT = T->getAs<PointerType>();
11843 goto FinishedParams;
11844 T = PT->getPointeeType();
11845 if (!T.isConstQualified() || T.isVolatileQualified())
11846 goto FinishedParams;
11847 T = T.getUnqualifiedType();
11849 // Move on to the second parameter;
11852 // If there is no second parameter, the first must be a const char *
11853 if (Param == FnDecl->param_end()) {
11854 if (Context.hasSameType(T, Context.CharTy))
11856 goto FinishedParams;
11859 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11860 // are allowed as the first parameter to a two-parameter function
11861 if (!(Context.hasSameType(T, Context.CharTy) ||
11862 Context.hasSameType(T, Context.WideCharTy) ||
11863 Context.hasSameType(T, Context.Char16Ty) ||
11864 Context.hasSameType(T, Context.Char32Ty)))
11865 goto FinishedParams;
11867 // The second and final parameter must be an std::size_t
11868 T = (*Param)->getType().getUnqualifiedType();
11869 if (Context.hasSameType(T, Context.getSizeType()) &&
11870 ++Param == FnDecl->param_end())
11874 // FIXME: This diagnostic is absolutely terrible.
11877 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11878 << FnDecl->getDeclName();
11882 // A parameter-declaration-clause containing a default argument is not
11883 // equivalent to any of the permitted forms.
11884 for (auto Param : FnDecl->params()) {
11885 if (Param->hasDefaultArg()) {
11886 Diag(Param->getDefaultArgRange().getBegin(),
11887 diag::err_literal_operator_default_argument)
11888 << Param->getDefaultArgRange();
11893 StringRef LiteralName
11894 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11895 if (LiteralName[0] != '_') {
11896 // C++11 [usrlit.suffix]p1:
11897 // Literal suffix identifiers that do not start with an underscore
11898 // are reserved for future standardization.
11899 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11900 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11906 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11907 /// linkage specification, including the language and (if present)
11908 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11909 /// language string literal. LBraceLoc, if valid, provides the location of
11910 /// the '{' brace. Otherwise, this linkage specification does not
11911 /// have any braces.
11912 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11914 SourceLocation LBraceLoc) {
11915 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11916 if (!Lit->isAscii()) {
11917 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11918 << LangStr->getSourceRange();
11922 StringRef Lang = Lit->getString();
11923 LinkageSpecDecl::LanguageIDs Language;
11925 Language = LinkageSpecDecl::lang_c;
11926 else if (Lang == "C++")
11927 Language = LinkageSpecDecl::lang_cxx;
11929 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11930 << LangStr->getSourceRange();
11934 // FIXME: Add all the various semantics of linkage specifications
11936 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11937 LangStr->getExprLoc(), Language,
11938 LBraceLoc.isValid());
11939 CurContext->addDecl(D);
11940 PushDeclContext(S, D);
11944 /// ActOnFinishLinkageSpecification - Complete the definition of
11945 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11946 /// valid, it's the position of the closing '}' brace in a linkage
11947 /// specification that uses braces.
11948 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11950 SourceLocation RBraceLoc) {
11951 if (RBraceLoc.isValid()) {
11952 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11953 LSDecl->setRBraceLoc(RBraceLoc);
11956 return LinkageSpec;
11959 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11960 AttributeList *AttrList,
11961 SourceLocation SemiLoc) {
11962 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11963 // Attribute declarations appertain to empty declaration so we handle
11966 ProcessDeclAttributeList(S, ED, AttrList);
11968 CurContext->addDecl(ED);
11972 /// \brief Perform semantic analysis for the variable declaration that
11973 /// occurs within a C++ catch clause, returning the newly-created
11975 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11976 TypeSourceInfo *TInfo,
11977 SourceLocation StartLoc,
11978 SourceLocation Loc,
11979 IdentifierInfo *Name) {
11980 bool Invalid = false;
11981 QualType ExDeclType = TInfo->getType();
11983 // Arrays and functions decay.
11984 if (ExDeclType->isArrayType())
11985 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11986 else if (ExDeclType->isFunctionType())
11987 ExDeclType = Context.getPointerType(ExDeclType);
11989 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11990 // The exception-declaration shall not denote a pointer or reference to an
11991 // incomplete type, other than [cv] void*.
11992 // N2844 forbids rvalue references.
11993 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11994 Diag(Loc, diag::err_catch_rvalue_ref);
11998 QualType BaseType = ExDeclType;
11999 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12000 unsigned DK = diag::err_catch_incomplete;
12001 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12002 BaseType = Ptr->getPointeeType();
12004 DK = diag::err_catch_incomplete_ptr;
12005 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12006 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12007 BaseType = Ref->getPointeeType();
12009 DK = diag::err_catch_incomplete_ref;
12011 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12012 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12015 if (!Invalid && !ExDeclType->isDependentType() &&
12016 RequireNonAbstractType(Loc, ExDeclType,
12017 diag::err_abstract_type_in_decl,
12018 AbstractVariableType))
12021 // Only the non-fragile NeXT runtime currently supports C++ catches
12022 // of ObjC types, and no runtime supports catching ObjC types by value.
12023 if (!Invalid && getLangOpts().ObjC1) {
12024 QualType T = ExDeclType;
12025 if (const ReferenceType *RT = T->getAs<ReferenceType>())
12026 T = RT->getPointeeType();
12028 if (T->isObjCObjectType()) {
12029 Diag(Loc, diag::err_objc_object_catch);
12031 } else if (T->isObjCObjectPointerType()) {
12032 // FIXME: should this be a test for macosx-fragile specifically?
12033 if (getLangOpts().ObjCRuntime.isFragile())
12034 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12038 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12039 ExDeclType, TInfo, SC_None);
12040 ExDecl->setExceptionVariable(true);
12042 // In ARC, infer 'retaining' for variables of retainable type.
12043 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12046 if (!Invalid && !ExDeclType->isDependentType()) {
12047 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12048 // Insulate this from anything else we might currently be parsing.
12049 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12051 // C++ [except.handle]p16:
12052 // The object declared in an exception-declaration or, if the
12053 // exception-declaration does not specify a name, a temporary (12.2) is
12054 // copy-initialized (8.5) from the exception object. [...]
12055 // The object is destroyed when the handler exits, after the destruction
12056 // of any automatic objects initialized within the handler.
12058 // We just pretend to initialize the object with itself, then make sure
12059 // it can be destroyed later.
12060 QualType initType = Context.getExceptionObjectType(ExDeclType);
12062 InitializedEntity entity =
12063 InitializedEntity::InitializeVariable(ExDecl);
12064 InitializationKind initKind =
12065 InitializationKind::CreateCopy(Loc, SourceLocation());
12067 Expr *opaqueValue =
12068 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12069 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12070 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12071 if (result.isInvalid())
12074 // If the constructor used was non-trivial, set this as the
12076 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12077 if (!construct->getConstructor()->isTrivial()) {
12078 Expr *init = MaybeCreateExprWithCleanups(construct);
12079 ExDecl->setInit(init);
12082 // And make sure it's destructable.
12083 FinalizeVarWithDestructor(ExDecl, recordType);
12089 ExDecl->setInvalidDecl();
12094 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12096 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12097 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12098 bool Invalid = D.isInvalidType();
12100 // Check for unexpanded parameter packs.
12101 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12102 UPPC_ExceptionType)) {
12103 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12104 D.getIdentifierLoc());
12108 IdentifierInfo *II = D.getIdentifier();
12109 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12110 LookupOrdinaryName,
12111 ForRedeclaration)) {
12112 // The scope should be freshly made just for us. There is just no way
12113 // it contains any previous declaration, except for function parameters in
12114 // a function-try-block's catch statement.
12115 assert(!S->isDeclScope(PrevDecl));
12116 if (isDeclInScope(PrevDecl, CurContext, S)) {
12117 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12118 << D.getIdentifier();
12119 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12121 } else if (PrevDecl->isTemplateParameter())
12122 // Maybe we will complain about the shadowed template parameter.
12123 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12126 if (D.getCXXScopeSpec().isSet() && !Invalid) {
12127 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12128 << D.getCXXScopeSpec().getRange();
12132 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12134 D.getIdentifierLoc(),
12135 D.getIdentifier());
12137 ExDecl->setInvalidDecl();
12139 // Add the exception declaration into this scope.
12141 PushOnScopeChains(ExDecl, S);
12143 CurContext->addDecl(ExDecl);
12145 ProcessDeclAttributes(S, ExDecl, D);
12149 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12151 Expr *AssertMessageExpr,
12152 SourceLocation RParenLoc) {
12153 StringLiteral *AssertMessage =
12154 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12156 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12159 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12160 AssertMessage, RParenLoc, false);
12163 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12165 StringLiteral *AssertMessage,
12166 SourceLocation RParenLoc,
12168 assert(AssertExpr != nullptr && "Expected non-null condition");
12169 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12171 // In a static_assert-declaration, the constant-expression shall be a
12172 // constant expression that can be contextually converted to bool.
12173 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12174 if (Converted.isInvalid())
12178 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12179 diag::err_static_assert_expression_is_not_constant,
12180 /*AllowFold=*/false).isInvalid())
12183 if (!Failed && !Cond) {
12184 SmallString<256> MsgBuffer;
12185 llvm::raw_svector_ostream Msg(MsgBuffer);
12187 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12188 Diag(StaticAssertLoc, diag::err_static_assert_failed)
12189 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12194 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12195 AssertExpr, AssertMessage, RParenLoc,
12198 CurContext->addDecl(Decl);
12202 /// \brief Perform semantic analysis of the given friend type declaration.
12204 /// \returns A friend declaration that.
12205 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12206 SourceLocation FriendLoc,
12207 TypeSourceInfo *TSInfo) {
12208 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12210 QualType T = TSInfo->getType();
12211 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12213 // C++03 [class.friend]p2:
12214 // An elaborated-type-specifier shall be used in a friend declaration
12217 // * The class-key of the elaborated-type-specifier is required.
12218 if (!ActiveTemplateInstantiations.empty()) {
12219 // Do not complain about the form of friend template types during
12220 // template instantiation; we will already have complained when the
12221 // template was declared.
12223 if (!T->isElaboratedTypeSpecifier()) {
12224 // If we evaluated the type to a record type, suggest putting
12226 if (const RecordType *RT = T->getAs<RecordType>()) {
12227 RecordDecl *RD = RT->getDecl();
12229 SmallString<16> InsertionText(" ");
12230 InsertionText += RD->getKindName();
12232 Diag(TypeRange.getBegin(),
12233 getLangOpts().CPlusPlus11 ?
12234 diag::warn_cxx98_compat_unelaborated_friend_type :
12235 diag::ext_unelaborated_friend_type)
12236 << (unsigned) RD->getTagKind()
12238 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
12242 getLangOpts().CPlusPlus11 ?
12243 diag::warn_cxx98_compat_nonclass_type_friend :
12244 diag::ext_nonclass_type_friend)
12248 } else if (T->getAs<EnumType>()) {
12250 getLangOpts().CPlusPlus11 ?
12251 diag::warn_cxx98_compat_enum_friend :
12252 diag::ext_enum_friend)
12257 // C++11 [class.friend]p3:
12258 // A friend declaration that does not declare a function shall have one
12259 // of the following forms:
12260 // friend elaborated-type-specifier ;
12261 // friend simple-type-specifier ;
12262 // friend typename-specifier ;
12263 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12264 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12267 // If the type specifier in a friend declaration designates a (possibly
12268 // cv-qualified) class type, that class is declared as a friend; otherwise,
12269 // the friend declaration is ignored.
12270 return FriendDecl::Create(Context, CurContext,
12271 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12275 /// Handle a friend tag declaration where the scope specifier was
12277 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12278 unsigned TagSpec, SourceLocation TagLoc,
12280 IdentifierInfo *Name,
12281 SourceLocation NameLoc,
12282 AttributeList *Attr,
12283 MultiTemplateParamsArg TempParamLists) {
12284 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12286 bool isExplicitSpecialization = false;
12287 bool Invalid = false;
12289 if (TemplateParameterList *TemplateParams =
12290 MatchTemplateParametersToScopeSpecifier(
12291 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12292 isExplicitSpecialization, Invalid)) {
12293 if (TemplateParams->size() > 0) {
12294 // This is a declaration of a class template.
12298 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12299 NameLoc, Attr, TemplateParams, AS_public,
12300 /*ModulePrivateLoc=*/SourceLocation(),
12301 FriendLoc, TempParamLists.size() - 1,
12302 TempParamLists.data()).get();
12304 // The "template<>" header is extraneous.
12305 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12306 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12307 isExplicitSpecialization = true;
12311 if (Invalid) return nullptr;
12313 bool isAllExplicitSpecializations = true;
12314 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12315 if (TempParamLists[I]->size()) {
12316 isAllExplicitSpecializations = false;
12321 // FIXME: don't ignore attributes.
12323 // If it's explicit specializations all the way down, just forget
12324 // about the template header and build an appropriate non-templated
12325 // friend. TODO: for source fidelity, remember the headers.
12326 if (isAllExplicitSpecializations) {
12327 if (SS.isEmpty()) {
12328 bool Owned = false;
12329 bool IsDependent = false;
12330 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12332 /*ModulePrivateLoc=*/SourceLocation(),
12333 MultiTemplateParamsArg(), Owned, IsDependent,
12334 /*ScopedEnumKWLoc=*/SourceLocation(),
12335 /*ScopedEnumUsesClassTag=*/false,
12336 /*UnderlyingType=*/TypeResult(),
12337 /*IsTypeSpecifier=*/false);
12340 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12341 ElaboratedTypeKeyword Keyword
12342 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12343 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12348 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12349 if (isa<DependentNameType>(T)) {
12350 DependentNameTypeLoc TL =
12351 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12352 TL.setElaboratedKeywordLoc(TagLoc);
12353 TL.setQualifierLoc(QualifierLoc);
12354 TL.setNameLoc(NameLoc);
12356 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12357 TL.setElaboratedKeywordLoc(TagLoc);
12358 TL.setQualifierLoc(QualifierLoc);
12359 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12362 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12363 TSI, FriendLoc, TempParamLists);
12364 Friend->setAccess(AS_public);
12365 CurContext->addDecl(Friend);
12369 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12373 // Handle the case of a templated-scope friend class. e.g.
12374 // template <class T> class A<T>::B;
12375 // FIXME: we don't support these right now.
12376 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12377 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12378 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12379 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12380 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12381 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12382 TL.setElaboratedKeywordLoc(TagLoc);
12383 TL.setQualifierLoc(SS.getWithLocInContext(Context));
12384 TL.setNameLoc(NameLoc);
12386 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12387 TSI, FriendLoc, TempParamLists);
12388 Friend->setAccess(AS_public);
12389 Friend->setUnsupportedFriend(true);
12390 CurContext->addDecl(Friend);
12395 /// Handle a friend type declaration. This works in tandem with
12398 /// Notes on friend class templates:
12400 /// We generally treat friend class declarations as if they were
12401 /// declaring a class. So, for example, the elaborated type specifier
12402 /// in a friend declaration is required to obey the restrictions of a
12403 /// class-head (i.e. no typedefs in the scope chain), template
12404 /// parameters are required to match up with simple template-ids, &c.
12405 /// However, unlike when declaring a template specialization, it's
12406 /// okay to refer to a template specialization without an empty
12407 /// template parameter declaration, e.g.
12408 /// friend class A<T>::B<unsigned>;
12409 /// We permit this as a special case; if there are any template
12410 /// parameters present at all, require proper matching, i.e.
12411 /// template <> template \<class T> friend class A<int>::B;
12412 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12413 MultiTemplateParamsArg TempParams) {
12414 SourceLocation Loc = DS.getLocStart();
12416 assert(DS.isFriendSpecified());
12417 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12419 // Try to convert the decl specifier to a type. This works for
12420 // friend templates because ActOnTag never produces a ClassTemplateDecl
12421 // for a TUK_Friend.
12422 Declarator TheDeclarator(DS, Declarator::MemberContext);
12423 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12424 QualType T = TSI->getType();
12425 if (TheDeclarator.isInvalidType())
12428 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12431 // This is definitely an error in C++98. It's probably meant to
12432 // be forbidden in C++0x, too, but the specification is just
12435 // The problem is with declarations like the following:
12436 // template <T> friend A<T>::foo;
12437 // where deciding whether a class C is a friend or not now hinges
12438 // on whether there exists an instantiation of A that causes
12439 // 'foo' to equal C. There are restrictions on class-heads
12440 // (which we declare (by fiat) elaborated friend declarations to
12441 // be) that makes this tractable.
12443 // FIXME: handle "template <> friend class A<T>;", which
12444 // is possibly well-formed? Who even knows?
12445 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12446 Diag(Loc, diag::err_tagless_friend_type_template)
12447 << DS.getSourceRange();
12451 // C++98 [class.friend]p1: A friend of a class is a function
12452 // or class that is not a member of the class . . .
12453 // This is fixed in DR77, which just barely didn't make the C++03
12454 // deadline. It's also a very silly restriction that seriously
12455 // affects inner classes and which nobody else seems to implement;
12456 // thus we never diagnose it, not even in -pedantic.
12458 // But note that we could warn about it: it's always useless to
12459 // friend one of your own members (it's not, however, worthless to
12460 // friend a member of an arbitrary specialization of your template).
12463 if (unsigned NumTempParamLists = TempParams.size())
12464 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12468 DS.getFriendSpecLoc());
12470 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12475 D->setAccess(AS_public);
12476 CurContext->addDecl(D);
12481 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12482 MultiTemplateParamsArg TemplateParams) {
12483 const DeclSpec &DS = D.getDeclSpec();
12485 assert(DS.isFriendSpecified());
12486 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12488 SourceLocation Loc = D.getIdentifierLoc();
12489 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12491 // C++ [class.friend]p1
12492 // A friend of a class is a function or class....
12493 // Note that this sees through typedefs, which is intended.
12494 // It *doesn't* see through dependent types, which is correct
12495 // according to [temp.arg.type]p3:
12496 // If a declaration acquires a function type through a
12497 // type dependent on a template-parameter and this causes
12498 // a declaration that does not use the syntactic form of a
12499 // function declarator to have a function type, the program
12501 if (!TInfo->getType()->isFunctionType()) {
12502 Diag(Loc, diag::err_unexpected_friend);
12504 // It might be worthwhile to try to recover by creating an
12505 // appropriate declaration.
12509 // C++ [namespace.memdef]p3
12510 // - If a friend declaration in a non-local class first declares a
12511 // class or function, the friend class or function is a member
12512 // of the innermost enclosing namespace.
12513 // - The name of the friend is not found by simple name lookup
12514 // until a matching declaration is provided in that namespace
12515 // scope (either before or after the class declaration granting
12517 // - If a friend function is called, its name may be found by the
12518 // name lookup that considers functions from namespaces and
12519 // classes associated with the types of the function arguments.
12520 // - When looking for a prior declaration of a class or a function
12521 // declared as a friend, scopes outside the innermost enclosing
12522 // namespace scope are not considered.
12524 CXXScopeSpec &SS = D.getCXXScopeSpec();
12525 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12526 DeclarationName Name = NameInfo.getName();
12529 // Check for unexpanded parameter packs.
12530 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12531 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12532 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12535 // The context we found the declaration in, or in which we should
12536 // create the declaration.
12538 Scope *DCScope = S;
12539 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12542 // There are five cases here.
12543 // - There's no scope specifier and we're in a local class. Only look
12544 // for functions declared in the immediately-enclosing block scope.
12545 // We recover from invalid scope qualifiers as if they just weren't there.
12546 FunctionDecl *FunctionContainingLocalClass = nullptr;
12547 if ((SS.isInvalid() || !SS.isSet()) &&
12548 (FunctionContainingLocalClass =
12549 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12550 // C++11 [class.friend]p11:
12551 // If a friend declaration appears in a local class and the name
12552 // specified is an unqualified name, a prior declaration is
12553 // looked up without considering scopes that are outside the
12554 // innermost enclosing non-class scope. For a friend function
12555 // declaration, if there is no prior declaration, the program is
12558 // Find the innermost enclosing non-class scope. This is the block
12559 // scope containing the local class definition (or for a nested class,
12560 // the outer local class).
12561 DCScope = S->getFnParent();
12563 // Look up the function name in the scope.
12564 Previous.clear(LookupLocalFriendName);
12565 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12567 if (!Previous.empty()) {
12568 // All possible previous declarations must have the same context:
12569 // either they were declared at block scope or they are members of
12570 // one of the enclosing local classes.
12571 DC = Previous.getRepresentativeDecl()->getDeclContext();
12573 // This is ill-formed, but provide the context that we would have
12574 // declared the function in, if we were permitted to, for error recovery.
12575 DC = FunctionContainingLocalClass;
12577 adjustContextForLocalExternDecl(DC);
12579 // C++ [class.friend]p6:
12580 // A function can be defined in a friend declaration of a class if and
12581 // only if the class is a non-local class (9.8), the function name is
12582 // unqualified, and the function has namespace scope.
12583 if (D.isFunctionDefinition()) {
12584 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12587 // - There's no scope specifier, in which case we just go to the
12588 // appropriate scope and look for a function or function template
12589 // there as appropriate.
12590 } else if (SS.isInvalid() || !SS.isSet()) {
12591 // C++11 [namespace.memdef]p3:
12592 // If the name in a friend declaration is neither qualified nor
12593 // a template-id and the declaration is a function or an
12594 // elaborated-type-specifier, the lookup to determine whether
12595 // the entity has been previously declared shall not consider
12596 // any scopes outside the innermost enclosing namespace.
12597 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12599 // Find the appropriate context according to the above.
12602 // Skip class contexts. If someone can cite chapter and verse
12603 // for this behavior, that would be nice --- it's what GCC and
12604 // EDG do, and it seems like a reasonable intent, but the spec
12605 // really only says that checks for unqualified existing
12606 // declarations should stop at the nearest enclosing namespace,
12607 // not that they should only consider the nearest enclosing
12609 while (DC->isRecord())
12610 DC = DC->getParent();
12612 DeclContext *LookupDC = DC;
12613 while (LookupDC->isTransparentContext())
12614 LookupDC = LookupDC->getParent();
12617 LookupQualifiedName(Previous, LookupDC);
12619 if (!Previous.empty()) {
12624 if (isTemplateId) {
12625 if (isa<TranslationUnitDecl>(LookupDC)) break;
12627 if (LookupDC->isFileContext()) break;
12629 LookupDC = LookupDC->getParent();
12632 DCScope = getScopeForDeclContext(S, DC);
12634 // - There's a non-dependent scope specifier, in which case we
12635 // compute it and do a previous lookup there for a function
12636 // or function template.
12637 } else if (!SS.getScopeRep()->isDependent()) {
12638 DC = computeDeclContext(SS);
12639 if (!DC) return nullptr;
12641 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12643 LookupQualifiedName(Previous, DC);
12645 // Ignore things found implicitly in the wrong scope.
12646 // TODO: better diagnostics for this case. Suggesting the right
12647 // qualified scope would be nice...
12648 LookupResult::Filter F = Previous.makeFilter();
12649 while (F.hasNext()) {
12650 NamedDecl *D = F.next();
12651 if (!DC->InEnclosingNamespaceSetOf(
12652 D->getDeclContext()->getRedeclContext()))
12657 if (Previous.empty()) {
12658 D.setInvalidType();
12659 Diag(Loc, diag::err_qualified_friend_not_found)
12660 << Name << TInfo->getType();
12664 // C++ [class.friend]p1: A friend of a class is a function or
12665 // class that is not a member of the class . . .
12666 if (DC->Equals(CurContext))
12667 Diag(DS.getFriendSpecLoc(),
12668 getLangOpts().CPlusPlus11 ?
12669 diag::warn_cxx98_compat_friend_is_member :
12670 diag::err_friend_is_member);
12672 if (D.isFunctionDefinition()) {
12673 // C++ [class.friend]p6:
12674 // A function can be defined in a friend declaration of a class if and
12675 // only if the class is a non-local class (9.8), the function name is
12676 // unqualified, and the function has namespace scope.
12677 SemaDiagnosticBuilder DB
12678 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12680 DB << SS.getScopeRep();
12681 if (DC->isFileContext())
12682 DB << FixItHint::CreateRemoval(SS.getRange());
12686 // - There's a scope specifier that does not match any template
12687 // parameter lists, in which case we use some arbitrary context,
12688 // create a method or method template, and wait for instantiation.
12689 // - There's a scope specifier that does match some template
12690 // parameter lists, which we don't handle right now.
12692 if (D.isFunctionDefinition()) {
12693 // C++ [class.friend]p6:
12694 // A function can be defined in a friend declaration of a class if and
12695 // only if the class is a non-local class (9.8), the function name is
12696 // unqualified, and the function has namespace scope.
12697 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12698 << SS.getScopeRep();
12702 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12705 if (!DC->isRecord()) {
12707 switch (D.getName().getKind()) {
12708 case UnqualifiedId::IK_ConstructorTemplateId:
12709 case UnqualifiedId::IK_ConstructorName:
12712 case UnqualifiedId::IK_DestructorName:
12715 case UnqualifiedId::IK_ConversionFunctionId:
12718 case UnqualifiedId::IK_Identifier:
12719 case UnqualifiedId::IK_ImplicitSelfParam:
12720 case UnqualifiedId::IK_LiteralOperatorId:
12721 case UnqualifiedId::IK_OperatorFunctionId:
12722 case UnqualifiedId::IK_TemplateId:
12725 // This implies that it has to be an operator or function.
12726 if (DiagArg >= 0) {
12727 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
12732 // FIXME: This is an egregious hack to cope with cases where the scope stack
12733 // does not contain the declaration context, i.e., in an out-of-line
12734 // definition of a class.
12735 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12737 FakeDCScope.setEntity(DC);
12738 DCScope = &FakeDCScope;
12741 bool AddToScope = true;
12742 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12743 TemplateParams, AddToScope);
12744 if (!ND) return nullptr;
12746 assert(ND->getLexicalDeclContext() == CurContext);
12748 // If we performed typo correction, we might have added a scope specifier
12749 // and changed the decl context.
12750 DC = ND->getDeclContext();
12752 // Add the function declaration to the appropriate lookup tables,
12753 // adjusting the redeclarations list as necessary. We don't
12754 // want to do this yet if the friending class is dependent.
12756 // Also update the scope-based lookup if the target context's
12757 // lookup context is in lexical scope.
12758 if (!CurContext->isDependentContext()) {
12759 DC = DC->getRedeclContext();
12760 DC->makeDeclVisibleInContext(ND);
12761 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12762 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12765 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12766 D.getIdentifierLoc(), ND,
12767 DS.getFriendSpecLoc());
12768 FrD->setAccess(AS_public);
12769 CurContext->addDecl(FrD);
12771 if (ND->isInvalidDecl()) {
12772 FrD->setInvalidDecl();
12774 if (DC->isRecord()) CheckFriendAccess(ND);
12777 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12778 FD = FTD->getTemplatedDecl();
12780 FD = cast<FunctionDecl>(ND);
12782 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12783 // default argument expression, that declaration shall be a definition
12784 // and shall be the only declaration of the function or function
12785 // template in the translation unit.
12786 if (functionDeclHasDefaultArgument(FD)) {
12787 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12788 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12789 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12790 } else if (!D.isFunctionDefinition())
12791 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12794 // Mark templated-scope function declarations as unsupported.
12795 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12796 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12797 << SS.getScopeRep() << SS.getRange()
12798 << cast<CXXRecordDecl>(CurContext);
12799 FrD->setUnsupportedFriend(true);
12806 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12807 AdjustDeclIfTemplate(Dcl);
12809 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12811 Diag(DelLoc, diag::err_deleted_non_function);
12815 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12816 // Don't consider the implicit declaration we generate for explicit
12817 // specializations. FIXME: Do not generate these implicit declarations.
12818 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12819 Prev->getPreviousDecl()) &&
12820 !Prev->isDefined()) {
12821 Diag(DelLoc, diag::err_deleted_decl_not_first);
12822 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12823 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12824 : diag::note_previous_declaration);
12826 // If the declaration wasn't the first, we delete the function anyway for
12828 Fn = Fn->getCanonicalDecl();
12831 // dllimport/dllexport cannot be deleted.
12832 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12833 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12834 Fn->setInvalidDecl();
12837 if (Fn->isDeleted())
12840 // See if we're deleting a function which is already known to override a
12841 // non-deleted virtual function.
12842 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12843 bool IssuedDiagnostic = false;
12844 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12845 E = MD->end_overridden_methods();
12847 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12848 if (!IssuedDiagnostic) {
12849 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12850 IssuedDiagnostic = true;
12852 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12857 // C++11 [basic.start.main]p3:
12858 // A program that defines main as deleted [...] is ill-formed.
12860 Diag(DelLoc, diag::err_deleted_main);
12862 Fn->setDeletedAsWritten();
12865 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12866 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12869 if (MD->getParent()->isDependentType()) {
12870 MD->setDefaulted();
12871 MD->setExplicitlyDefaulted();
12875 CXXSpecialMember Member = getSpecialMember(MD);
12876 if (Member == CXXInvalid) {
12877 if (!MD->isInvalidDecl())
12878 Diag(DefaultLoc, diag::err_default_special_members);
12882 MD->setDefaulted();
12883 MD->setExplicitlyDefaulted();
12885 // If this definition appears within the record, do the checking when
12886 // the record is complete.
12887 const FunctionDecl *Primary = MD;
12888 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12889 // Find the uninstantiated declaration that actually had the '= default'
12891 Pattern->isDefined(Primary);
12893 // If the method was defaulted on its first declaration, we will have
12894 // already performed the checking in CheckCompletedCXXClass. Such a
12895 // declaration doesn't trigger an implicit definition.
12896 if (Primary == Primary->getCanonicalDecl())
12899 CheckExplicitlyDefaultedSpecialMember(MD);
12901 if (MD->isInvalidDecl())
12905 case CXXDefaultConstructor:
12906 DefineImplicitDefaultConstructor(DefaultLoc,
12907 cast<CXXConstructorDecl>(MD));
12909 case CXXCopyConstructor:
12910 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12912 case CXXCopyAssignment:
12913 DefineImplicitCopyAssignment(DefaultLoc, MD);
12915 case CXXDestructor:
12916 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12918 case CXXMoveConstructor:
12919 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12921 case CXXMoveAssignment:
12922 DefineImplicitMoveAssignment(DefaultLoc, MD);
12925 llvm_unreachable("Invalid special member.");
12928 Diag(DefaultLoc, diag::err_default_special_members);
12932 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12933 for (Stmt *SubStmt : S->children()) {
12936 if (isa<ReturnStmt>(SubStmt))
12937 Self.Diag(SubStmt->getLocStart(),
12938 diag::err_return_in_constructor_handler);
12939 if (!isa<Expr>(SubStmt))
12940 SearchForReturnInStmt(Self, SubStmt);
12944 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12945 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12946 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12947 SearchForReturnInStmt(*this, Handler);
12951 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12952 const CXXMethodDecl *Old) {
12953 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12954 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12956 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12958 // If the calling conventions match, everything is fine
12959 if (NewCC == OldCC)
12962 // If the calling conventions mismatch because the new function is static,
12963 // suppress the calling convention mismatch error; the error about static
12964 // function override (err_static_overrides_virtual from
12965 // Sema::CheckFunctionDeclaration) is more clear.
12966 if (New->getStorageClass() == SC_Static)
12969 Diag(New->getLocation(),
12970 diag::err_conflicting_overriding_cc_attributes)
12971 << New->getDeclName() << New->getType() << Old->getType();
12972 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12976 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12977 const CXXMethodDecl *Old) {
12978 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12979 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12981 if (Context.hasSameType(NewTy, OldTy) ||
12982 NewTy->isDependentType() || OldTy->isDependentType())
12985 // Check if the return types are covariant
12986 QualType NewClassTy, OldClassTy;
12988 /// Both types must be pointers or references to classes.
12989 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12990 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12991 NewClassTy = NewPT->getPointeeType();
12992 OldClassTy = OldPT->getPointeeType();
12994 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12995 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12996 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12997 NewClassTy = NewRT->getPointeeType();
12998 OldClassTy = OldRT->getPointeeType();
13003 // The return types aren't either both pointers or references to a class type.
13004 if (NewClassTy.isNull()) {
13005 Diag(New->getLocation(),
13006 diag::err_different_return_type_for_overriding_virtual_function)
13007 << New->getDeclName() << NewTy << OldTy
13008 << New->getReturnTypeSourceRange();
13009 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13010 << Old->getReturnTypeSourceRange();
13015 // C++ [class.virtual]p6:
13016 // If the return type of D::f differs from the return type of B::f, the
13017 // class type in the return type of D::f shall be complete at the point of
13018 // declaration of D::f or shall be the class type D.
13019 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13020 if (!RT->isBeingDefined() &&
13021 RequireCompleteType(New->getLocation(), NewClassTy,
13022 diag::err_covariant_return_incomplete,
13023 New->getDeclName()))
13027 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13028 // Check if the new class derives from the old class.
13029 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13030 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13031 << New->getDeclName() << NewTy << OldTy
13032 << New->getReturnTypeSourceRange();
13033 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13034 << Old->getReturnTypeSourceRange();
13038 // Check if we the conversion from derived to base is valid.
13039 if (CheckDerivedToBaseConversion(
13040 NewClassTy, OldClassTy,
13041 diag::err_covariant_return_inaccessible_base,
13042 diag::err_covariant_return_ambiguous_derived_to_base_conv,
13043 New->getLocation(), New->getReturnTypeSourceRange(),
13044 New->getDeclName(), nullptr)) {
13045 // FIXME: this note won't trigger for delayed access control
13046 // diagnostics, and it's impossible to get an undelayed error
13047 // here from access control during the original parse because
13048 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13049 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13050 << Old->getReturnTypeSourceRange();
13055 // The qualifiers of the return types must be the same.
13056 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13057 Diag(New->getLocation(),
13058 diag::err_covariant_return_type_different_qualifications)
13059 << New->getDeclName() << NewTy << OldTy
13060 << New->getReturnTypeSourceRange();
13061 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13062 << Old->getReturnTypeSourceRange();
13067 // The new class type must have the same or less qualifiers as the old type.
13068 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13069 Diag(New->getLocation(),
13070 diag::err_covariant_return_type_class_type_more_qualified)
13071 << New->getDeclName() << NewTy << OldTy
13072 << New->getReturnTypeSourceRange();
13073 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13074 << Old->getReturnTypeSourceRange();
13081 /// \brief Mark the given method pure.
13083 /// \param Method the method to be marked pure.
13085 /// \param InitRange the source range that covers the "0" initializer.
13086 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13087 SourceLocation EndLoc = InitRange.getEnd();
13088 if (EndLoc.isValid())
13089 Method->setRangeEnd(EndLoc);
13091 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13096 if (!Method->isInvalidDecl())
13097 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13098 << Method->getDeclName() << InitRange;
13102 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13103 if (D->getFriendObjectKind())
13104 Diag(D->getLocation(), diag::err_pure_friend);
13105 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13106 CheckPureMethod(M, ZeroLoc);
13108 Diag(D->getLocation(), diag::err_illegal_initializer);
13111 /// \brief Determine whether the given declaration is a static data member.
13112 static bool isStaticDataMember(const Decl *D) {
13113 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13114 return Var->isStaticDataMember();
13119 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13120 /// an initializer for the out-of-line declaration 'Dcl'. The scope
13121 /// is a fresh scope pushed for just this purpose.
13123 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13124 /// static data member of class X, names should be looked up in the scope of
13126 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13127 // If there is no declaration, there was an error parsing it.
13128 if (!D || D->isInvalidDecl())
13131 // We will always have a nested name specifier here, but this declaration
13132 // might not be out of line if the specifier names the current namespace:
13135 if (D->isOutOfLine())
13136 EnterDeclaratorContext(S, D->getDeclContext());
13138 // If we are parsing the initializer for a static data member, push a
13139 // new expression evaluation context that is associated with this static
13141 if (isStaticDataMember(D))
13142 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13145 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13146 /// initializer for the out-of-line declaration 'D'.
13147 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13148 // If there is no declaration, there was an error parsing it.
13149 if (!D || D->isInvalidDecl())
13152 if (isStaticDataMember(D))
13153 PopExpressionEvaluationContext();
13155 if (D->isOutOfLine())
13156 ExitDeclaratorContext(S);
13159 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13160 /// C++ if/switch/while/for statement.
13161 /// e.g: "if (int x = f()) {...}"
13162 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13164 // The declarator shall not specify a function or an array.
13165 // The type-specifier-seq shall not contain typedef and shall not declare a
13166 // new class or enumeration.
13167 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13168 "Parser allowed 'typedef' as storage class of condition decl.");
13170 Decl *Dcl = ActOnDeclarator(S, D);
13174 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13175 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13176 << D.getSourceRange();
13183 void Sema::LoadExternalVTableUses() {
13184 if (!ExternalSource)
13187 SmallVector<ExternalVTableUse, 4> VTables;
13188 ExternalSource->ReadUsedVTables(VTables);
13189 SmallVector<VTableUse, 4> NewUses;
13190 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13191 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13192 = VTablesUsed.find(VTables[I].Record);
13193 // Even if a definition wasn't required before, it may be required now.
13194 if (Pos != VTablesUsed.end()) {
13195 if (!Pos->second && VTables[I].DefinitionRequired)
13196 Pos->second = true;
13200 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13201 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13204 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13207 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13208 bool DefinitionRequired) {
13209 // Ignore any vtable uses in unevaluated operands or for classes that do
13210 // not have a vtable.
13211 if (!Class->isDynamicClass() || Class->isDependentContext() ||
13212 CurContext->isDependentContext() || isUnevaluatedContext())
13215 // Try to insert this class into the map.
13216 LoadExternalVTableUses();
13217 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13218 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13219 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13221 // If we already had an entry, check to see if we are promoting this vtable
13222 // to require a definition. If so, we need to reappend to the VTableUses
13223 // list, since we may have already processed the first entry.
13224 if (DefinitionRequired && !Pos.first->second) {
13225 Pos.first->second = true;
13227 // Otherwise, we can early exit.
13231 // The Microsoft ABI requires that we perform the destructor body
13232 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13233 // the deleting destructor is emitted with the vtable, not with the
13234 // destructor definition as in the Itanium ABI.
13235 // If it has a definition, we do the check at that point instead.
13236 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13237 Class->hasUserDeclaredDestructor() &&
13238 !Class->getDestructor()->isDefined() &&
13239 !Class->getDestructor()->isDeleted()) {
13240 CXXDestructorDecl *DD = Class->getDestructor();
13241 ContextRAII SavedContext(*this, DD);
13242 CheckDestructor(DD);
13246 // Local classes need to have their virtual members marked
13247 // immediately. For all other classes, we mark their virtual members
13248 // at the end of the translation unit.
13249 if (Class->isLocalClass())
13250 MarkVirtualMembersReferenced(Loc, Class);
13252 VTableUses.push_back(std::make_pair(Class, Loc));
13255 bool Sema::DefineUsedVTables() {
13256 LoadExternalVTableUses();
13257 if (VTableUses.empty())
13260 // Note: The VTableUses vector could grow as a result of marking
13261 // the members of a class as "used", so we check the size each
13262 // time through the loop and prefer indices (which are stable) to
13263 // iterators (which are not).
13264 bool DefinedAnything = false;
13265 for (unsigned I = 0; I != VTableUses.size(); ++I) {
13266 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13270 SourceLocation Loc = VTableUses[I].second;
13272 bool DefineVTable = true;
13274 // If this class has a key function, but that key function is
13275 // defined in another translation unit, we don't need to emit the
13276 // vtable even though we're using it.
13277 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13278 if (KeyFunction && !KeyFunction->hasBody()) {
13279 // The key function is in another translation unit.
13280 DefineVTable = false;
13281 TemplateSpecializationKind TSK =
13282 KeyFunction->getTemplateSpecializationKind();
13283 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13284 TSK != TSK_ImplicitInstantiation &&
13285 "Instantiations don't have key functions");
13287 } else if (!KeyFunction) {
13288 // If we have a class with no key function that is the subject
13289 // of an explicit instantiation declaration, suppress the
13290 // vtable; it will live with the explicit instantiation
13292 bool IsExplicitInstantiationDeclaration
13293 = Class->getTemplateSpecializationKind()
13294 == TSK_ExplicitInstantiationDeclaration;
13295 for (auto R : Class->redecls()) {
13296 TemplateSpecializationKind TSK
13297 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13298 if (TSK == TSK_ExplicitInstantiationDeclaration)
13299 IsExplicitInstantiationDeclaration = true;
13300 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13301 IsExplicitInstantiationDeclaration = false;
13306 if (IsExplicitInstantiationDeclaration)
13307 DefineVTable = false;
13310 // The exception specifications for all virtual members may be needed even
13311 // if we are not providing an authoritative form of the vtable in this TU.
13312 // We may choose to emit it available_externally anyway.
13313 if (!DefineVTable) {
13314 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13318 // Mark all of the virtual members of this class as referenced, so
13319 // that we can build a vtable. Then, tell the AST consumer that a
13320 // vtable for this class is required.
13321 DefinedAnything = true;
13322 MarkVirtualMembersReferenced(Loc, Class);
13323 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13324 if (VTablesUsed[Canonical])
13325 Consumer.HandleVTable(Class);
13327 // Optionally warn if we're emitting a weak vtable.
13328 if (Class->isExternallyVisible() &&
13329 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13330 const FunctionDecl *KeyFunctionDef = nullptr;
13331 if (!KeyFunction ||
13332 (KeyFunction->hasBody(KeyFunctionDef) &&
13333 KeyFunctionDef->isInlined()))
13334 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13335 TSK_ExplicitInstantiationDefinition
13336 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13340 VTableUses.clear();
13342 return DefinedAnything;
13345 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13346 const CXXRecordDecl *RD) {
13347 for (const auto *I : RD->methods())
13348 if (I->isVirtual() && !I->isPure())
13349 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13352 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13353 const CXXRecordDecl *RD) {
13354 // Mark all functions which will appear in RD's vtable as used.
13355 CXXFinalOverriderMap FinalOverriders;
13356 RD->getFinalOverriders(FinalOverriders);
13357 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13358 E = FinalOverriders.end();
13360 for (OverridingMethods::const_iterator OI = I->second.begin(),
13361 OE = I->second.end();
13363 assert(OI->second.size() > 0 && "no final overrider");
13364 CXXMethodDecl *Overrider = OI->second.front().Method;
13366 // C++ [basic.def.odr]p2:
13367 // [...] A virtual member function is used if it is not pure. [...]
13368 if (!Overrider->isPure())
13369 MarkFunctionReferenced(Loc, Overrider);
13373 // Only classes that have virtual bases need a VTT.
13374 if (RD->getNumVBases() == 0)
13377 for (const auto &I : RD->bases()) {
13378 const CXXRecordDecl *Base =
13379 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13380 if (Base->getNumVBases() == 0)
13382 MarkVirtualMembersReferenced(Loc, Base);
13386 /// SetIvarInitializers - This routine builds initialization ASTs for the
13387 /// Objective-C implementation whose ivars need be initialized.
13388 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13389 if (!getLangOpts().CPlusPlus)
13391 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13392 SmallVector<ObjCIvarDecl*, 8> ivars;
13393 CollectIvarsToConstructOrDestruct(OID, ivars);
13396 SmallVector<CXXCtorInitializer*, 32> AllToInit;
13397 for (unsigned i = 0; i < ivars.size(); i++) {
13398 FieldDecl *Field = ivars[i];
13399 if (Field->isInvalidDecl())
13402 CXXCtorInitializer *Member;
13403 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13404 InitializationKind InitKind =
13405 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13407 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13408 ExprResult MemberInit =
13409 InitSeq.Perform(*this, InitEntity, InitKind, None);
13410 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13411 // Note, MemberInit could actually come back empty if no initialization
13412 // is required (e.g., because it would call a trivial default constructor)
13413 if (!MemberInit.get() || MemberInit.isInvalid())
13417 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13419 MemberInit.getAs<Expr>(),
13421 AllToInit.push_back(Member);
13423 // Be sure that the destructor is accessible and is marked as referenced.
13424 if (const RecordType *RecordTy =
13425 Context.getBaseElementType(Field->getType())
13426 ->getAs<RecordType>()) {
13427 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13428 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13429 MarkFunctionReferenced(Field->getLocation(), Destructor);
13430 CheckDestructorAccess(Field->getLocation(), Destructor,
13431 PDiag(diag::err_access_dtor_ivar)
13432 << Context.getBaseElementType(Field->getType()));
13436 ObjCImplementation->setIvarInitializers(Context,
13437 AllToInit.data(), AllToInit.size());
13442 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13443 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13444 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13445 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13447 if (Ctor->isInvalidDecl())
13450 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13452 // Target may not be determinable yet, for instance if this is a dependent
13453 // call in an uninstantiated template.
13455 const FunctionDecl *FNTarget = nullptr;
13456 (void)Target->hasBody(FNTarget);
13457 Target = const_cast<CXXConstructorDecl*>(
13458 cast_or_null<CXXConstructorDecl>(FNTarget));
13461 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13462 // Avoid dereferencing a null pointer here.
13463 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13465 if (!Current.insert(Canonical).second)
13468 // We know that beyond here, we aren't chaining into a cycle.
13469 if (!Target || !Target->isDelegatingConstructor() ||
13470 Target->isInvalidDecl() || Valid.count(TCanonical)) {
13471 Valid.insert(Current.begin(), Current.end());
13473 // We've hit a cycle.
13474 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13475 Current.count(TCanonical)) {
13476 // If we haven't diagnosed this cycle yet, do so now.
13477 if (!Invalid.count(TCanonical)) {
13478 S.Diag((*Ctor->init_begin())->getSourceLocation(),
13479 diag::warn_delegating_ctor_cycle)
13482 // Don't add a note for a function delegating directly to itself.
13483 if (TCanonical != Canonical)
13484 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13486 CXXConstructorDecl *C = Target;
13487 while (C->getCanonicalDecl() != Canonical) {
13488 const FunctionDecl *FNTarget = nullptr;
13489 (void)C->getTargetConstructor()->hasBody(FNTarget);
13490 assert(FNTarget && "Ctor cycle through bodiless function");
13492 C = const_cast<CXXConstructorDecl*>(
13493 cast<CXXConstructorDecl>(FNTarget));
13494 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13498 Invalid.insert(Current.begin(), Current.end());
13501 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13506 void Sema::CheckDelegatingCtorCycles() {
13507 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13509 for (DelegatingCtorDeclsType::iterator
13510 I = DelegatingCtorDecls.begin(ExternalSource),
13511 E = DelegatingCtorDecls.end();
13513 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13515 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13516 CE = Invalid.end();
13518 (*CI)->setInvalidDecl();
13522 /// \brief AST visitor that finds references to the 'this' expression.
13523 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13527 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13529 bool VisitCXXThisExpr(CXXThisExpr *E) {
13530 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13531 << E->isImplicit();
13537 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13538 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13542 TypeLoc TL = TSInfo->getTypeLoc();
13543 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13547 // C++11 [expr.prim.general]p3:
13548 // [The expression this] shall not appear before the optional
13549 // cv-qualifier-seq and it shall not appear within the declaration of a
13550 // static member function (although its type and value category are defined
13551 // within a static member function as they are within a non-static member
13552 // function). [ Note: this is because declaration matching does not occur
13553 // until the complete declarator is known. - end note ]
13554 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13555 FindCXXThisExpr Finder(*this);
13557 // If the return type came after the cv-qualifier-seq, check it now.
13558 if (Proto->hasTrailingReturn() &&
13559 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13562 // Check the exception specification.
13563 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13566 return checkThisInStaticMemberFunctionAttributes(Method);
13569 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13570 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13574 TypeLoc TL = TSInfo->getTypeLoc();
13575 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13579 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13580 FindCXXThisExpr Finder(*this);
13582 switch (Proto->getExceptionSpecType()) {
13584 case EST_Uninstantiated:
13585 case EST_Unevaluated:
13586 case EST_BasicNoexcept:
13587 case EST_DynamicNone:
13592 case EST_ComputedNoexcept:
13593 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13597 for (const auto &E : Proto->exceptions()) {
13598 if (!Finder.TraverseType(E))
13607 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13608 FindCXXThisExpr Finder(*this);
13610 // Check attributes.
13611 for (const auto *A : Method->attrs()) {
13612 // FIXME: This should be emitted by tblgen.
13613 Expr *Arg = nullptr;
13614 ArrayRef<Expr *> Args;
13615 if (const auto *G = dyn_cast<GuardedByAttr>(A))
13617 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13619 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13620 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13621 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13622 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13623 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13624 Arg = ETLF->getSuccessValue();
13625 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13626 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13627 Arg = STLF->getSuccessValue();
13628 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13629 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13630 Arg = LR->getArg();
13631 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13632 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13633 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13634 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13635 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13636 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13637 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13638 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13639 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13640 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13642 if (Arg && !Finder.TraverseStmt(Arg))
13645 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13646 if (!Finder.TraverseStmt(Args[I]))
13654 void Sema::checkExceptionSpecification(
13655 bool IsTopLevel, ExceptionSpecificationType EST,
13656 ArrayRef<ParsedType> DynamicExceptions,
13657 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13658 SmallVectorImpl<QualType> &Exceptions,
13659 FunctionProtoType::ExceptionSpecInfo &ESI) {
13660 Exceptions.clear();
13662 if (EST == EST_Dynamic) {
13663 Exceptions.reserve(DynamicExceptions.size());
13664 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13665 // FIXME: Preserve type source info.
13666 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13669 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13670 collectUnexpandedParameterPacks(ET, Unexpanded);
13671 if (!Unexpanded.empty()) {
13672 DiagnoseUnexpandedParameterPacks(
13673 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13679 // Check that the type is valid for an exception spec, and
13681 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13682 Exceptions.push_back(ET);
13684 ESI.Exceptions = Exceptions;
13688 if (EST == EST_ComputedNoexcept) {
13689 // If an error occurred, there's no expression here.
13690 if (NoexceptExpr) {
13691 assert((NoexceptExpr->isTypeDependent() ||
13692 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13694 "Parser should have made sure that the expression is boolean");
13695 if (IsTopLevel && NoexceptExpr &&
13696 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13697 ESI.Type = EST_BasicNoexcept;
13701 if (!NoexceptExpr->isValueDependent())
13702 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13703 diag::err_noexcept_needs_constant_expression,
13704 /*AllowFold*/ false).get();
13705 ESI.NoexceptExpr = NoexceptExpr;
13711 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13712 ExceptionSpecificationType EST,
13713 SourceRange SpecificationRange,
13714 ArrayRef<ParsedType> DynamicExceptions,
13715 ArrayRef<SourceRange> DynamicExceptionRanges,
13716 Expr *NoexceptExpr) {
13720 // Dig out the method we're referring to.
13721 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13722 MethodD = FunTmpl->getTemplatedDecl();
13724 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13728 // Check the exception specification.
13729 llvm::SmallVector<QualType, 4> Exceptions;
13730 FunctionProtoType::ExceptionSpecInfo ESI;
13731 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13732 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13735 // Update the exception specification on the function type.
13736 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13738 if (Method->isStatic())
13739 checkThisInStaticMemberFunctionExceptionSpec(Method);
13741 if (Method->isVirtual()) {
13742 // Check overrides, which we previously had to delay.
13743 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13744 OEnd = Method->end_overridden_methods();
13746 CheckOverridingFunctionExceptionSpec(Method, *O);
13750 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13752 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13753 SourceLocation DeclStart,
13754 Declarator &D, Expr *BitWidth,
13755 InClassInitStyle InitStyle,
13756 AccessSpecifier AS,
13757 AttributeList *MSPropertyAttr) {
13758 IdentifierInfo *II = D.getIdentifier();
13760 Diag(DeclStart, diag::err_anonymous_property);
13763 SourceLocation Loc = D.getIdentifierLoc();
13765 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13766 QualType T = TInfo->getType();
13767 if (getLangOpts().CPlusPlus) {
13768 CheckExtraCXXDefaultArguments(D);
13770 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13771 UPPC_DataMemberType)) {
13772 D.setInvalidType();
13774 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13778 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13780 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13781 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13782 diag::err_invalid_thread)
13783 << DeclSpec::getSpecifierName(TSCS);
13785 // Check to see if this name was declared as a member previously
13786 NamedDecl *PrevDecl = nullptr;
13787 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13788 LookupName(Previous, S);
13789 switch (Previous.getResultKind()) {
13790 case LookupResult::Found:
13791 case LookupResult::FoundUnresolvedValue:
13792 PrevDecl = Previous.getAsSingle<NamedDecl>();
13795 case LookupResult::FoundOverloaded:
13796 PrevDecl = Previous.getRepresentativeDecl();
13799 case LookupResult::NotFound:
13800 case LookupResult::NotFoundInCurrentInstantiation:
13801 case LookupResult::Ambiguous:
13805 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13806 // Maybe we will complain about the shadowed template parameter.
13807 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13808 // Just pretend that we didn't see the previous declaration.
13809 PrevDecl = nullptr;
13812 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13813 PrevDecl = nullptr;
13815 SourceLocation TSSL = D.getLocStart();
13816 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13817 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13818 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13819 ProcessDeclAttributes(TUScope, NewPD, D);
13820 NewPD->setAccess(AS);
13822 if (NewPD->isInvalidDecl())
13823 Record->setInvalidDecl();
13825 if (D.getDeclSpec().isModulePrivateSpecified())
13826 NewPD->setModulePrivate();
13828 if (NewPD->isInvalidDecl() && PrevDecl) {
13829 // Don't introduce NewFD into scope; there's already something
13830 // with the same name in the same scope.
13832 PushOnScopeChains(NewPD, S);
13834 Record->addDecl(NewPD);