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 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
1747 /// diagnostic for the respective type of error will be suppressed, but the
1748 /// check for ill-formed code will still be performed.
1750 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1751 unsigned InaccessibleBaseID,
1752 unsigned AmbigiousBaseConvID,
1753 SourceLocation Loc, SourceRange Range,
1754 DeclarationName Name,
1755 CXXCastPath *BasePath,
1756 bool IgnoreAccess) {
1757 // First, determine whether the path from Derived to Base is
1758 // ambiguous. This is slightly more expensive than checking whether
1759 // the Derived to Base conversion exists, because here we need to
1760 // explore multiple paths to determine if there is an ambiguity.
1761 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1762 /*DetectVirtual=*/false);
1763 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1764 assert(DerivationOkay &&
1765 "Can only be used with a derived-to-base conversion");
1766 (void)DerivationOkay;
1768 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1769 if (!IgnoreAccess) {
1770 // Check that the base class can be accessed.
1771 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1772 InaccessibleBaseID)) {
1773 case AR_inaccessible:
1782 // Build a base path if necessary.
1784 BuildBasePathArray(Paths, *BasePath);
1788 if (AmbigiousBaseConvID) {
1789 // We know that the derived-to-base conversion is ambiguous, and
1790 // we're going to produce a diagnostic. Perform the derived-to-base
1791 // search just one more time to compute all of the possible paths so
1792 // that we can print them out. This is more expensive than any of
1793 // the previous derived-to-base checks we've done, but at this point
1794 // performance isn't as much of an issue.
1796 Paths.setRecordingPaths(true);
1797 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1798 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1801 // Build up a textual representation of the ambiguous paths, e.g.,
1802 // D -> B -> A, that will be used to illustrate the ambiguous
1803 // conversions in the diagnostic. We only print one of the paths
1804 // to each base class subobject.
1805 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1807 Diag(Loc, AmbigiousBaseConvID)
1808 << Derived << Base << PathDisplayStr << Range << Name;
1814 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1815 SourceLocation Loc, SourceRange Range,
1816 CXXCastPath *BasePath,
1817 bool IgnoreAccess) {
1818 return CheckDerivedToBaseConversion(
1819 Derived, Base, diag::err_upcast_to_inaccessible_base,
1820 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
1821 BasePath, IgnoreAccess);
1825 /// @brief Builds a string representing ambiguous paths from a
1826 /// specific derived class to different subobjects of the same base
1829 /// This function builds a string that can be used in error messages
1830 /// to show the different paths that one can take through the
1831 /// inheritance hierarchy to go from the derived class to different
1832 /// subobjects of a base class. The result looks something like this:
1834 /// struct D -> struct B -> struct A
1835 /// struct D -> struct C -> struct A
1837 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1838 std::string PathDisplayStr;
1839 std::set<unsigned> DisplayedPaths;
1840 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1841 Path != Paths.end(); ++Path) {
1842 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1843 // We haven't displayed a path to this particular base
1844 // class subobject yet.
1845 PathDisplayStr += "\n ";
1846 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1847 for (CXXBasePath::const_iterator Element = Path->begin();
1848 Element != Path->end(); ++Element)
1849 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1853 return PathDisplayStr;
1856 //===----------------------------------------------------------------------===//
1857 // C++ class member Handling
1858 //===----------------------------------------------------------------------===//
1860 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1861 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1862 SourceLocation ASLoc,
1863 SourceLocation ColonLoc,
1864 AttributeList *Attrs) {
1865 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1866 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1868 CurContext->addHiddenDecl(ASDecl);
1869 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1872 /// CheckOverrideControl - Check C++11 override control semantics.
1873 void Sema::CheckOverrideControl(NamedDecl *D) {
1874 if (D->isInvalidDecl())
1877 // We only care about "override" and "final" declarations.
1878 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1881 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1883 // We can't check dependent instance methods.
1884 if (MD && MD->isInstance() &&
1885 (MD->getParent()->hasAnyDependentBases() ||
1886 MD->getType()->isDependentType()))
1889 if (MD && !MD->isVirtual()) {
1890 // If we have a non-virtual method, check if if hides a virtual method.
1891 // (In that case, it's most likely the method has the wrong type.)
1892 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1893 FindHiddenVirtualMethods(MD, OverloadedMethods);
1895 if (!OverloadedMethods.empty()) {
1896 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1897 Diag(OA->getLocation(),
1898 diag::override_keyword_hides_virtual_member_function)
1899 << "override" << (OverloadedMethods.size() > 1);
1900 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1901 Diag(FA->getLocation(),
1902 diag::override_keyword_hides_virtual_member_function)
1903 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1904 << (OverloadedMethods.size() > 1);
1906 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1907 MD->setInvalidDecl();
1910 // Fall through into the general case diagnostic.
1911 // FIXME: We might want to attempt typo correction here.
1914 if (!MD || !MD->isVirtual()) {
1915 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1916 Diag(OA->getLocation(),
1917 diag::override_keyword_only_allowed_on_virtual_member_functions)
1918 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1919 D->dropAttr<OverrideAttr>();
1921 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1922 Diag(FA->getLocation(),
1923 diag::override_keyword_only_allowed_on_virtual_member_functions)
1924 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1925 << FixItHint::CreateRemoval(FA->getLocation());
1926 D->dropAttr<FinalAttr>();
1931 // C++11 [class.virtual]p5:
1932 // If a function is marked with the virt-specifier override and
1933 // does not override a member function of a base class, the program is
1935 bool HasOverriddenMethods =
1936 MD->begin_overridden_methods() != MD->end_overridden_methods();
1937 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1938 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1939 << MD->getDeclName();
1942 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1943 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1945 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1946 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1947 isa<CXXDestructorDecl>(MD))
1950 SourceLocation Loc = MD->getLocation();
1951 SourceLocation SpellingLoc = Loc;
1952 if (getSourceManager().isMacroArgExpansion(Loc))
1953 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1954 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1955 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1958 if (MD->size_overridden_methods() > 0) {
1959 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1960 << MD->getDeclName();
1961 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1962 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1966 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1967 /// function overrides a virtual member function marked 'final', according to
1968 /// C++11 [class.virtual]p4.
1969 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1970 const CXXMethodDecl *Old) {
1971 FinalAttr *FA = Old->getAttr<FinalAttr>();
1975 Diag(New->getLocation(), diag::err_final_function_overridden)
1976 << New->getDeclName()
1977 << FA->isSpelledAsSealed();
1978 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1982 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1983 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1984 // FIXME: Destruction of ObjC lifetime types has side-effects.
1985 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1986 return !RD->isCompleteDefinition() ||
1987 !RD->hasTrivialDefaultConstructor() ||
1988 !RD->hasTrivialDestructor();
1992 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1993 for (AttributeList *it = list; it != nullptr; it = it->getNext())
1994 if (it->isDeclspecPropertyAttribute())
1999 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2000 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2001 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2002 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2003 /// present (but parsing it has been deferred).
2005 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2006 MultiTemplateParamsArg TemplateParameterLists,
2007 Expr *BW, const VirtSpecifiers &VS,
2008 InClassInitStyle InitStyle) {
2009 const DeclSpec &DS = D.getDeclSpec();
2010 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2011 DeclarationName Name = NameInfo.getName();
2012 SourceLocation Loc = NameInfo.getLoc();
2014 // For anonymous bitfields, the location should point to the type.
2015 if (Loc.isInvalid())
2016 Loc = D.getLocStart();
2018 Expr *BitWidth = static_cast<Expr*>(BW);
2020 assert(isa<CXXRecordDecl>(CurContext));
2021 assert(!DS.isFriendSpecified());
2023 bool isFunc = D.isDeclarationOfFunction();
2025 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2026 // The Microsoft extension __interface only permits public member functions
2027 // and prohibits constructors, destructors, operators, non-public member
2028 // functions, static methods and data members.
2029 unsigned InvalidDecl;
2030 bool ShowDeclName = true;
2032 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2033 else if (AS != AS_public)
2035 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2037 else switch (Name.getNameKind()) {
2038 case DeclarationName::CXXConstructorName:
2040 ShowDeclName = false;
2043 case DeclarationName::CXXDestructorName:
2045 ShowDeclName = false;
2048 case DeclarationName::CXXOperatorName:
2049 case DeclarationName::CXXConversionFunctionName:
2060 Diag(Loc, diag::err_invalid_member_in_interface)
2061 << (InvalidDecl-1) << Name;
2063 Diag(Loc, diag::err_invalid_member_in_interface)
2064 << (InvalidDecl-1) << "";
2069 // C++ 9.2p6: A member shall not be declared to have automatic storage
2070 // duration (auto, register) or with the extern storage-class-specifier.
2071 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2072 // data members and cannot be applied to names declared const or static,
2073 // and cannot be applied to reference members.
2074 switch (DS.getStorageClassSpec()) {
2075 case DeclSpec::SCS_unspecified:
2076 case DeclSpec::SCS_typedef:
2077 case DeclSpec::SCS_static:
2079 case DeclSpec::SCS_mutable:
2081 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2083 // FIXME: It would be nicer if the keyword was ignored only for this
2084 // declarator. Otherwise we could get follow-up errors.
2085 D.getMutableDeclSpec().ClearStorageClassSpecs();
2089 Diag(DS.getStorageClassSpecLoc(),
2090 diag::err_storageclass_invalid_for_member);
2091 D.getMutableDeclSpec().ClearStorageClassSpecs();
2095 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2096 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2099 if (DS.isConstexprSpecified() && isInstField) {
2100 SemaDiagnosticBuilder B =
2101 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2102 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2103 if (InitStyle == ICIS_NoInit) {
2105 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2106 B << FixItHint::CreateRemoval(ConstexprLoc);
2108 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2109 D.getMutableDeclSpec().ClearConstexprSpec();
2110 const char *PrevSpec;
2112 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2113 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2115 assert(!Failed && "Making a constexpr member const shouldn't fail");
2119 const char *PrevSpec;
2121 if (D.getMutableDeclSpec().SetStorageClassSpec(
2122 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2123 Context.getPrintingPolicy())) {
2124 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2125 "This is the only DeclSpec that should fail to be applied");
2128 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2129 isInstField = false;
2136 CXXScopeSpec &SS = D.getCXXScopeSpec();
2138 // Data members must have identifiers for names.
2139 if (!Name.isIdentifier()) {
2140 Diag(Loc, diag::err_bad_variable_name)
2145 IdentifierInfo *II = Name.getAsIdentifierInfo();
2147 // Member field could not be with "template" keyword.
2148 // So TemplateParameterLists should be empty in this case.
2149 if (TemplateParameterLists.size()) {
2150 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2151 if (TemplateParams->size()) {
2152 // There is no such thing as a member field template.
2153 Diag(D.getIdentifierLoc(), diag::err_template_member)
2155 << SourceRange(TemplateParams->getTemplateLoc(),
2156 TemplateParams->getRAngleLoc());
2158 // There is an extraneous 'template<>' for this member.
2159 Diag(TemplateParams->getTemplateLoc(),
2160 diag::err_template_member_noparams)
2162 << SourceRange(TemplateParams->getTemplateLoc(),
2163 TemplateParams->getRAngleLoc());
2168 if (SS.isSet() && !SS.isInvalid()) {
2169 // The user provided a superfluous scope specifier inside a class
2175 if (DeclContext *DC = computeDeclContext(SS, false))
2176 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2178 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2179 << Name << SS.getRange();
2184 AttributeList *MSPropertyAttr =
2185 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2186 if (MSPropertyAttr) {
2187 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2188 BitWidth, InitStyle, AS, MSPropertyAttr);
2191 isInstField = false;
2193 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2194 BitWidth, InitStyle, AS);
2195 assert(Member && "HandleField never returns null");
2198 Member = HandleDeclarator(S, D, TemplateParameterLists);
2202 // Non-instance-fields can't have a bitfield.
2204 if (Member->isInvalidDecl()) {
2205 // don't emit another diagnostic.
2206 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2207 // C++ 9.6p3: A bit-field shall not be a static member.
2208 // "static member 'A' cannot be a bit-field"
2209 Diag(Loc, diag::err_static_not_bitfield)
2210 << Name << BitWidth->getSourceRange();
2211 } else if (isa<TypedefDecl>(Member)) {
2212 // "typedef member 'x' cannot be a bit-field"
2213 Diag(Loc, diag::err_typedef_not_bitfield)
2214 << Name << BitWidth->getSourceRange();
2216 // A function typedef ("typedef int f(); f a;").
2217 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2218 Diag(Loc, diag::err_not_integral_type_bitfield)
2219 << Name << cast<ValueDecl>(Member)->getType()
2220 << BitWidth->getSourceRange();
2224 Member->setInvalidDecl();
2227 Member->setAccess(AS);
2229 // If we have declared a member function template or static data member
2230 // template, set the access of the templated declaration as well.
2231 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2232 FunTmpl->getTemplatedDecl()->setAccess(AS);
2233 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2234 VarTmpl->getTemplatedDecl()->setAccess(AS);
2237 if (VS.isOverrideSpecified())
2238 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2239 if (VS.isFinalSpecified())
2240 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2241 VS.isFinalSpelledSealed()));
2243 if (VS.getLastLocation().isValid()) {
2244 // Update the end location of a method that has a virt-specifiers.
2245 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2246 MD->setRangeEnd(VS.getLastLocation());
2249 CheckOverrideControl(Member);
2251 assert((Name || isInstField) && "No identifier for non-field ?");
2254 FieldDecl *FD = cast<FieldDecl>(Member);
2255 FieldCollector->Add(FD);
2257 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2258 // Remember all explicit private FieldDecls that have a name, no side
2259 // effects and are not part of a dependent type declaration.
2260 if (!FD->isImplicit() && FD->getDeclName() &&
2261 FD->getAccess() == AS_private &&
2262 !FD->hasAttr<UnusedAttr>() &&
2263 !FD->getParent()->isDependentContext() &&
2264 !InitializationHasSideEffects(*FD))
2265 UnusedPrivateFields.insert(FD);
2273 class UninitializedFieldVisitor
2274 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2276 // List of Decls to generate a warning on. Also remove Decls that become
2278 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2279 // List of base classes of the record. Classes are removed after their
2281 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2282 // Vector of decls to be removed from the Decl set prior to visiting the
2283 // nodes. These Decls may have been initialized in the prior initializer.
2284 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2285 // If non-null, add a note to the warning pointing back to the constructor.
2286 const CXXConstructorDecl *Constructor;
2287 // Variables to hold state when processing an initializer list. When
2288 // InitList is true, special case initialization of FieldDecls matching
2289 // InitListFieldDecl.
2291 FieldDecl *InitListFieldDecl;
2292 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2295 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2296 UninitializedFieldVisitor(Sema &S,
2297 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2298 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2299 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2300 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2302 // Returns true if the use of ME is not an uninitialized use.
2303 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2304 bool CheckReferenceOnly) {
2305 llvm::SmallVector<FieldDecl*, 4> Fields;
2306 bool ReferenceField = false;
2308 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2311 Fields.push_back(FD);
2312 if (FD->getType()->isReferenceType())
2313 ReferenceField = true;
2314 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2317 // Binding a reference to an unintialized field is not an
2318 // uninitialized use.
2319 if (CheckReferenceOnly && !ReferenceField)
2322 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2323 // Discard the first field since it is the field decl that is being
2325 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2326 UsedFieldIndex.push_back((*I)->getFieldIndex());
2329 for (auto UsedIter = UsedFieldIndex.begin(),
2330 UsedEnd = UsedFieldIndex.end(),
2331 OrigIter = InitFieldIndex.begin(),
2332 OrigEnd = InitFieldIndex.end();
2333 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2334 if (*UsedIter < *OrigIter)
2336 if (*UsedIter > *OrigIter)
2343 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2345 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2348 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2350 MemberExpr *FieldME = ME;
2352 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2355 while (MemberExpr *SubME =
2356 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2358 if (isa<VarDecl>(SubME->getMemberDecl()))
2361 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2362 if (!FD->isAnonymousStructOrUnion())
2365 if (!FieldME->getType().isPODType(S.Context))
2366 AllPODFields = false;
2368 Base = SubME->getBase();
2371 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2374 if (AddressOf && AllPODFields)
2377 ValueDecl* FoundVD = FieldME->getMemberDecl();
2379 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2380 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2381 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2384 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2385 QualType T = BaseCast->getType();
2386 if (T->isPointerType() &&
2387 BaseClasses.count(T->getPointeeType())) {
2388 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2389 << T->getPointeeType() << FoundVD;
2394 if (!Decls.count(FoundVD))
2397 const bool IsReference = FoundVD->getType()->isReferenceType();
2399 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2400 // Special checking for initializer lists.
2401 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2405 // Prevent double warnings on use of unbounded references.
2406 if (CheckReferenceOnly && !IsReference)
2410 unsigned diag = IsReference
2411 ? diag::warn_reference_field_is_uninit
2412 : diag::warn_field_is_uninit;
2413 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2415 S.Diag(Constructor->getLocation(),
2416 diag::note_uninit_in_this_constructor)
2417 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2421 void HandleValue(Expr *E, bool AddressOf) {
2422 E = E->IgnoreParens();
2424 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2425 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2426 AddressOf /*AddressOf*/);
2430 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2431 Visit(CO->getCond());
2432 HandleValue(CO->getTrueExpr(), AddressOf);
2433 HandleValue(CO->getFalseExpr(), AddressOf);
2437 if (BinaryConditionalOperator *BCO =
2438 dyn_cast<BinaryConditionalOperator>(E)) {
2439 Visit(BCO->getCond());
2440 HandleValue(BCO->getFalseExpr(), AddressOf);
2444 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2445 HandleValue(OVE->getSourceExpr(), AddressOf);
2449 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2450 switch (BO->getOpcode()) {
2455 HandleValue(BO->getLHS(), AddressOf);
2456 Visit(BO->getRHS());
2459 Visit(BO->getLHS());
2460 HandleValue(BO->getRHS(), AddressOf);
2468 void CheckInitListExpr(InitListExpr *ILE) {
2469 InitFieldIndex.push_back(0);
2470 for (auto Child : ILE->children()) {
2471 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2472 CheckInitListExpr(SubList);
2476 ++InitFieldIndex.back();
2478 InitFieldIndex.pop_back();
2481 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2482 FieldDecl *Field, const Type *BaseClass) {
2483 // Remove Decls that may have been initialized in the previous
2485 for (ValueDecl* VD : DeclsToRemove)
2487 DeclsToRemove.clear();
2489 Constructor = FieldConstructor;
2490 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2494 InitListFieldDecl = Field;
2495 InitFieldIndex.clear();
2496 CheckInitListExpr(ILE);
2505 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2508 void VisitMemberExpr(MemberExpr *ME) {
2509 // All uses of unbounded reference fields will warn.
2510 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2513 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2514 if (E->getCastKind() == CK_LValueToRValue) {
2515 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2519 Inherited::VisitImplicitCastExpr(E);
2522 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2523 if (E->getConstructor()->isCopyConstructor()) {
2524 Expr *ArgExpr = E->getArg(0);
2525 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2526 if (ILE->getNumInits() == 1)
2527 ArgExpr = ILE->getInit(0);
2528 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2529 if (ICE->getCastKind() == CK_NoOp)
2530 ArgExpr = ICE->getSubExpr();
2531 HandleValue(ArgExpr, false /*AddressOf*/);
2534 Inherited::VisitCXXConstructExpr(E);
2537 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2538 Expr *Callee = E->getCallee();
2539 if (isa<MemberExpr>(Callee)) {
2540 HandleValue(Callee, false /*AddressOf*/);
2541 for (auto Arg : E->arguments())
2546 Inherited::VisitCXXMemberCallExpr(E);
2549 void VisitCallExpr(CallExpr *E) {
2550 // Treat std::move as a use.
2551 if (E->getNumArgs() == 1) {
2552 if (FunctionDecl *FD = E->getDirectCallee()) {
2553 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2554 FD->getIdentifier()->isStr("move")) {
2555 HandleValue(E->getArg(0), false /*AddressOf*/);
2561 Inherited::VisitCallExpr(E);
2564 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2565 Expr *Callee = E->getCallee();
2567 if (isa<UnresolvedLookupExpr>(Callee))
2568 return Inherited::VisitCXXOperatorCallExpr(E);
2571 for (auto Arg : E->arguments())
2572 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2575 void VisitBinaryOperator(BinaryOperator *E) {
2576 // If a field assignment is detected, remove the field from the
2577 // uninitiailized field set.
2578 if (E->getOpcode() == BO_Assign)
2579 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2580 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2581 if (!FD->getType()->isReferenceType())
2582 DeclsToRemove.push_back(FD);
2584 if (E->isCompoundAssignmentOp()) {
2585 HandleValue(E->getLHS(), false /*AddressOf*/);
2590 Inherited::VisitBinaryOperator(E);
2593 void VisitUnaryOperator(UnaryOperator *E) {
2594 if (E->isIncrementDecrementOp()) {
2595 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2598 if (E->getOpcode() == UO_AddrOf) {
2599 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2600 HandleValue(ME->getBase(), true /*AddressOf*/);
2605 Inherited::VisitUnaryOperator(E);
2609 // Diagnose value-uses of fields to initialize themselves, e.g.
2611 // where foo is not also a parameter to the constructor.
2612 // Also diagnose across field uninitialized use such as
2614 // TODO: implement -Wuninitialized and fold this into that framework.
2615 static void DiagnoseUninitializedFields(
2616 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2618 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2619 Constructor->getLocation())) {
2623 if (Constructor->isInvalidDecl())
2626 const CXXRecordDecl *RD = Constructor->getParent();
2628 if (RD->getDescribedClassTemplate())
2631 // Holds fields that are uninitialized.
2632 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2634 // At the beginning, all fields are uninitialized.
2635 for (auto *I : RD->decls()) {
2636 if (auto *FD = dyn_cast<FieldDecl>(I)) {
2637 UninitializedFields.insert(FD);
2638 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2639 UninitializedFields.insert(IFD->getAnonField());
2643 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2644 for (auto I : RD->bases())
2645 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2647 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2650 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2651 UninitializedFields,
2652 UninitializedBaseClasses);
2654 for (const auto *FieldInit : Constructor->inits()) {
2655 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2658 Expr *InitExpr = FieldInit->getInit();
2662 if (CXXDefaultInitExpr *Default =
2663 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2664 InitExpr = Default->getExpr();
2667 // In class initializers will point to the constructor.
2668 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2669 FieldInit->getAnyMember(),
2670 FieldInit->getBaseClass());
2672 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2673 FieldInit->getAnyMember(),
2674 FieldInit->getBaseClass());
2680 /// \brief Enter a new C++ default initializer scope. After calling this, the
2681 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2682 /// parsing or instantiating the initializer failed.
2683 void Sema::ActOnStartCXXInClassMemberInitializer() {
2684 // Create a synthetic function scope to represent the call to the constructor
2685 // that notionally surrounds a use of this initializer.
2686 PushFunctionScope();
2689 /// \brief This is invoked after parsing an in-class initializer for a
2690 /// non-static C++ class member, and after instantiating an in-class initializer
2691 /// in a class template. Such actions are deferred until the class is complete.
2692 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2693 SourceLocation InitLoc,
2695 // Pop the notional constructor scope we created earlier.
2696 PopFunctionScopeInfo(nullptr, D);
2698 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2699 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2700 "must set init style when field is created");
2703 D->setInvalidDecl();
2705 FD->removeInClassInitializer();
2709 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2710 FD->setInvalidDecl();
2711 FD->removeInClassInitializer();
2715 ExprResult Init = InitExpr;
2716 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2717 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2718 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2719 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2720 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2721 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2722 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2723 if (Init.isInvalid()) {
2724 FD->setInvalidDecl();
2729 // C++11 [class.base.init]p7:
2730 // The initialization of each base and member constitutes a
2732 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2733 if (Init.isInvalid()) {
2734 FD->setInvalidDecl();
2738 InitExpr = Init.get();
2740 FD->setInClassInitializer(InitExpr);
2743 /// \brief Find the direct and/or virtual base specifiers that
2744 /// correspond to the given base type, for use in base initialization
2745 /// within a constructor.
2746 static bool FindBaseInitializer(Sema &SemaRef,
2747 CXXRecordDecl *ClassDecl,
2749 const CXXBaseSpecifier *&DirectBaseSpec,
2750 const CXXBaseSpecifier *&VirtualBaseSpec) {
2751 // First, check for a direct base class.
2752 DirectBaseSpec = nullptr;
2753 for (const auto &Base : ClassDecl->bases()) {
2754 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2755 // We found a direct base of this type. That's what we're
2757 DirectBaseSpec = &Base;
2762 // Check for a virtual base class.
2763 // FIXME: We might be able to short-circuit this if we know in advance that
2764 // there are no virtual bases.
2765 VirtualBaseSpec = nullptr;
2766 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2767 // We haven't found a base yet; search the class hierarchy for a
2768 // virtual base class.
2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770 /*DetectVirtual=*/false);
2771 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2772 SemaRef.Context.getTypeDeclType(ClassDecl),
2774 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2775 Path != Paths.end(); ++Path) {
2776 if (Path->back().Base->isVirtual()) {
2777 VirtualBaseSpec = Path->back().Base;
2784 return DirectBaseSpec || VirtualBaseSpec;
2787 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2789 Sema::ActOnMemInitializer(Decl *ConstructorD,
2792 IdentifierInfo *MemberOrBase,
2793 ParsedType TemplateTypeTy,
2795 SourceLocation IdLoc,
2797 SourceLocation EllipsisLoc) {
2798 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2799 DS, IdLoc, InitList,
2803 /// \brief Handle a C++ member initializer using parentheses syntax.
2805 Sema::ActOnMemInitializer(Decl *ConstructorD,
2808 IdentifierInfo *MemberOrBase,
2809 ParsedType TemplateTypeTy,
2811 SourceLocation IdLoc,
2812 SourceLocation LParenLoc,
2813 ArrayRef<Expr *> Args,
2814 SourceLocation RParenLoc,
2815 SourceLocation EllipsisLoc) {
2816 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2818 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2819 DS, IdLoc, List, EllipsisLoc);
2824 // Callback to only accept typo corrections that can be a valid C++ member
2825 // intializer: either a non-static field member or a base class.
2826 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2828 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2829 : ClassDecl(ClassDecl) {}
2831 bool ValidateCandidate(const TypoCorrection &candidate) override {
2832 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2833 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2834 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2835 return isa<TypeDecl>(ND);
2841 CXXRecordDecl *ClassDecl;
2846 /// \brief Handle a C++ member initializer.
2848 Sema::BuildMemInitializer(Decl *ConstructorD,
2851 IdentifierInfo *MemberOrBase,
2852 ParsedType TemplateTypeTy,
2854 SourceLocation IdLoc,
2856 SourceLocation EllipsisLoc) {
2857 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2858 if (!Res.isUsable())
2865 AdjustDeclIfTemplate(ConstructorD);
2867 CXXConstructorDecl *Constructor
2868 = dyn_cast<CXXConstructorDecl>(ConstructorD);
2870 // The user wrote a constructor initializer on a function that is
2871 // not a C++ constructor. Ignore the error for now, because we may
2872 // have more member initializers coming; we'll diagnose it just
2873 // once in ActOnMemInitializers.
2877 CXXRecordDecl *ClassDecl = Constructor->getParent();
2879 // C++ [class.base.init]p2:
2880 // Names in a mem-initializer-id are looked up in the scope of the
2881 // constructor's class and, if not found in that scope, are looked
2882 // up in the scope containing the constructor's definition.
2883 // [Note: if the constructor's class contains a member with the
2884 // same name as a direct or virtual base class of the class, a
2885 // mem-initializer-id naming the member or base class and composed
2886 // of a single identifier refers to the class member. A
2887 // mem-initializer-id for the hidden base class may be specified
2888 // using a qualified name. ]
2889 if (!SS.getScopeRep() && !TemplateTypeTy) {
2890 // Look for a member, first.
2891 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2892 if (!Result.empty()) {
2894 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2895 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2896 if (EllipsisLoc.isValid())
2897 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2899 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2901 return BuildMemberInitializer(Member, Init, IdLoc);
2905 // It didn't name a member, so see if it names a class.
2907 TypeSourceInfo *TInfo = nullptr;
2909 if (TemplateTypeTy) {
2910 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2911 } else if (DS.getTypeSpecType() == TST_decltype) {
2912 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2914 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2915 LookupParsedName(R, S, &SS);
2917 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2919 if (R.isAmbiguous()) return true;
2921 // We don't want access-control diagnostics here.
2922 R.suppressDiagnostics();
2924 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2925 bool NotUnknownSpecialization = false;
2926 DeclContext *DC = computeDeclContext(SS, false);
2927 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2928 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2930 if (!NotUnknownSpecialization) {
2931 // When the scope specifier can refer to a member of an unknown
2932 // specialization, we take it as a type name.
2933 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2934 SS.getWithLocInContext(Context),
2935 *MemberOrBase, IdLoc);
2936 if (BaseType.isNull())
2940 R.setLookupName(MemberOrBase);
2944 // If no results were found, try to correct typos.
2945 TypoCorrection Corr;
2946 if (R.empty() && BaseType.isNull() &&
2947 (Corr = CorrectTypo(
2948 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2949 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2950 CTK_ErrorRecovery, ClassDecl))) {
2951 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2952 // We have found a non-static data member with a similar
2953 // name to what was typed; complain and initialize that
2956 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2957 << MemberOrBase << true);
2958 return BuildMemberInitializer(Member, Init, IdLoc);
2959 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2960 const CXXBaseSpecifier *DirectBaseSpec;
2961 const CXXBaseSpecifier *VirtualBaseSpec;
2962 if (FindBaseInitializer(*this, ClassDecl,
2963 Context.getTypeDeclType(Type),
2964 DirectBaseSpec, VirtualBaseSpec)) {
2965 // We have found a direct or virtual base class with a
2966 // similar name to what was typed; complain and initialize
2969 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2970 << MemberOrBase << false,
2971 PDiag() /*Suppress note, we provide our own.*/);
2973 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2975 Diag(BaseSpec->getLocStart(),
2976 diag::note_base_class_specified_here)
2977 << BaseSpec->getType()
2978 << BaseSpec->getSourceRange();
2985 if (!TyD && BaseType.isNull()) {
2986 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2987 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2992 if (BaseType.isNull()) {
2993 BaseType = Context.getTypeDeclType(TyD);
2994 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2996 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2998 TInfo = Context.CreateTypeSourceInfo(BaseType);
2999 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3000 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3001 TL.setElaboratedKeywordLoc(SourceLocation());
3002 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3008 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3010 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3013 /// Checks a member initializer expression for cases where reference (or
3014 /// pointer) members are bound to by-value parameters (or their addresses).
3015 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3017 SourceLocation IdLoc) {
3018 QualType MemberTy = Member->getType();
3020 // We only handle pointers and references currently.
3021 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3022 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3025 const bool IsPointer = MemberTy->isPointerType();
3027 if (const UnaryOperator *Op
3028 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3029 // The only case we're worried about with pointers requires taking the
3031 if (Op->getOpcode() != UO_AddrOf)
3034 Init = Op->getSubExpr();
3036 // We only handle address-of expression initializers for pointers.
3041 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3042 // We only warn when referring to a non-reference parameter declaration.
3043 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3044 if (!Parameter || Parameter->getType()->isReferenceType())
3047 S.Diag(Init->getExprLoc(),
3048 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3049 : diag::warn_bind_ref_member_to_parameter)
3050 << Member << Parameter << Init->getSourceRange();
3052 // Other initializers are fine.
3056 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3057 << (unsigned)IsPointer;
3061 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3062 SourceLocation IdLoc) {
3063 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3064 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3065 assert((DirectMember || IndirectMember) &&
3066 "Member must be a FieldDecl or IndirectFieldDecl");
3068 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3071 if (Member->isInvalidDecl())
3075 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3076 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3077 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3078 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3080 // Template instantiation doesn't reconstruct ParenListExprs for us.
3084 SourceRange InitRange = Init->getSourceRange();
3086 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3087 // Can't check initialization for a member of dependent type or when
3088 // any of the arguments are type-dependent expressions.
3089 DiscardCleanupsInEvaluationContext();
3091 bool InitList = false;
3092 if (isa<InitListExpr>(Init)) {
3097 // Initialize the member.
3098 InitializedEntity MemberEntity =
3099 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3100 : InitializedEntity::InitializeMember(IndirectMember,
3102 InitializationKind Kind =
3103 InitList ? InitializationKind::CreateDirectList(IdLoc)
3104 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3105 InitRange.getEnd());
3107 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3108 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3110 if (MemberInit.isInvalid())
3113 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3115 // C++11 [class.base.init]p7:
3116 // The initialization of each base and member constitutes a
3118 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3119 if (MemberInit.isInvalid())
3122 Init = MemberInit.get();
3126 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3127 InitRange.getBegin(), Init,
3128 InitRange.getEnd());
3130 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3131 InitRange.getBegin(), Init,
3132 InitRange.getEnd());
3137 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3138 CXXRecordDecl *ClassDecl) {
3139 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3140 if (!LangOpts.CPlusPlus11)
3141 return Diag(NameLoc, diag::err_delegating_ctor)
3142 << TInfo->getTypeLoc().getLocalSourceRange();
3143 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3145 bool InitList = true;
3146 MultiExprArg Args = Init;
3147 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3149 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3152 SourceRange InitRange = Init->getSourceRange();
3153 // Initialize the object.
3154 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3155 QualType(ClassDecl->getTypeForDecl(), 0));
3156 InitializationKind Kind =
3157 InitList ? InitializationKind::CreateDirectList(NameLoc)
3158 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3159 InitRange.getEnd());
3160 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3161 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3163 if (DelegationInit.isInvalid())
3166 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3167 "Delegating constructor with no target?");
3169 // C++11 [class.base.init]p7:
3170 // The initialization of each base and member constitutes a
3172 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3173 InitRange.getBegin());
3174 if (DelegationInit.isInvalid())
3177 // If we are in a dependent context, template instantiation will
3178 // perform this type-checking again. Just save the arguments that we
3179 // received in a ParenListExpr.
3180 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3181 // of the information that we have about the base
3182 // initializer. However, deconstructing the ASTs is a dicey process,
3183 // and this approach is far more likely to get the corner cases right.
3184 if (CurContext->isDependentContext())
3185 DelegationInit = Init;
3187 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3188 DelegationInit.getAs<Expr>(),
3189 InitRange.getEnd());
3193 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3194 Expr *Init, CXXRecordDecl *ClassDecl,
3195 SourceLocation EllipsisLoc) {
3196 SourceLocation BaseLoc
3197 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3199 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3200 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3201 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3203 // C++ [class.base.init]p2:
3204 // [...] Unless the mem-initializer-id names a nonstatic data
3205 // member of the constructor's class or a direct or virtual base
3206 // of that class, the mem-initializer is ill-formed. A
3207 // mem-initializer-list can initialize a base class using any
3208 // name that denotes that base class type.
3209 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3211 SourceRange InitRange = Init->getSourceRange();
3212 if (EllipsisLoc.isValid()) {
3213 // This is a pack expansion.
3214 if (!BaseType->containsUnexpandedParameterPack()) {
3215 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3216 << SourceRange(BaseLoc, InitRange.getEnd());
3218 EllipsisLoc = SourceLocation();
3221 // Check for any unexpanded parameter packs.
3222 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3225 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3229 // Check for direct and virtual base classes.
3230 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3231 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3233 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3235 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3237 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3240 // C++ [base.class.init]p2:
3241 // Unless the mem-initializer-id names a nonstatic data member of the
3242 // constructor's class or a direct or virtual base of that class, the
3243 // mem-initializer is ill-formed.
3244 if (!DirectBaseSpec && !VirtualBaseSpec) {
3245 // If the class has any dependent bases, then it's possible that
3246 // one of those types will resolve to the same type as
3247 // BaseType. Therefore, just treat this as a dependent base
3248 // class initialization. FIXME: Should we try to check the
3249 // initialization anyway? It seems odd.
3250 if (ClassDecl->hasAnyDependentBases())
3253 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3254 << BaseType << Context.getTypeDeclType(ClassDecl)
3255 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3260 DiscardCleanupsInEvaluationContext();
3262 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3263 /*IsVirtual=*/false,
3264 InitRange.getBegin(), Init,
3265 InitRange.getEnd(), EllipsisLoc);
3268 // C++ [base.class.init]p2:
3269 // If a mem-initializer-id is ambiguous because it designates both
3270 // a direct non-virtual base class and an inherited virtual base
3271 // class, the mem-initializer is ill-formed.
3272 if (DirectBaseSpec && VirtualBaseSpec)
3273 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3274 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3276 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3278 BaseSpec = VirtualBaseSpec;
3280 // Initialize the base.
3281 bool InitList = true;
3282 MultiExprArg Args = Init;
3283 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3285 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3288 InitializedEntity BaseEntity =
3289 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3290 InitializationKind Kind =
3291 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3292 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3293 InitRange.getEnd());
3294 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3295 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3296 if (BaseInit.isInvalid())
3299 // C++11 [class.base.init]p7:
3300 // The initialization of each base and member constitutes a
3302 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3303 if (BaseInit.isInvalid())
3306 // If we are in a dependent context, template instantiation will
3307 // perform this type-checking again. Just save the arguments that we
3308 // received in a ParenListExpr.
3309 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3310 // of the information that we have about the base
3311 // initializer. However, deconstructing the ASTs is a dicey process,
3312 // and this approach is far more likely to get the corner cases right.
3313 if (CurContext->isDependentContext())
3316 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3317 BaseSpec->isVirtual(),
3318 InitRange.getBegin(),
3319 BaseInit.getAs<Expr>(),
3320 InitRange.getEnd(), EllipsisLoc);
3323 // Create a static_cast\<T&&>(expr).
3324 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3325 if (T.isNull()) T = E->getType();
3326 QualType TargetType = SemaRef.BuildReferenceType(
3327 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3328 SourceLocation ExprLoc = E->getLocStart();
3329 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3330 TargetType, ExprLoc);
3332 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3333 SourceRange(ExprLoc, ExprLoc),
3334 E->getSourceRange()).get();
3337 /// ImplicitInitializerKind - How an implicit base or member initializer should
3338 /// initialize its base or member.
3339 enum ImplicitInitializerKind {
3347 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3348 ImplicitInitializerKind ImplicitInitKind,
3349 CXXBaseSpecifier *BaseSpec,
3350 bool IsInheritedVirtualBase,
3351 CXXCtorInitializer *&CXXBaseInit) {
3352 InitializedEntity InitEntity
3353 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3354 IsInheritedVirtualBase);
3356 ExprResult BaseInit;
3358 switch (ImplicitInitKind) {
3360 const CXXRecordDecl *Inherited =
3361 Constructor->getInheritedConstructor()->getParent();
3362 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3363 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3364 // C++11 [class.inhctor]p8:
3365 // Each expression in the expression-list is of the form
3366 // static_cast<T&&>(p), where p is the name of the corresponding
3367 // constructor parameter and T is the declared type of p.
3368 SmallVector<Expr*, 16> Args;
3369 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3370 ParmVarDecl *PD = Constructor->getParamDecl(I);
3371 ExprResult ArgExpr =
3372 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3373 VK_LValue, SourceLocation());
3374 if (ArgExpr.isInvalid())
3376 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3379 InitializationKind InitKind = InitializationKind::CreateDirect(
3380 Constructor->getLocation(), SourceLocation(), SourceLocation());
3381 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3382 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3388 InitializationKind InitKind
3389 = InitializationKind::CreateDefault(Constructor->getLocation());
3390 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3391 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3397 bool Moving = ImplicitInitKind == IIK_Move;
3398 ParmVarDecl *Param = Constructor->getParamDecl(0);
3399 QualType ParamType = Param->getType().getNonReferenceType();
3402 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3403 SourceLocation(), Param, false,
3404 Constructor->getLocation(), ParamType,
3405 VK_LValue, nullptr);
3407 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3409 // Cast to the base class to avoid ambiguities.
3411 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3412 ParamType.getQualifiers());
3415 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3418 CXXCastPath BasePath;
3419 BasePath.push_back(BaseSpec);
3420 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3421 CK_UncheckedDerivedToBase,
3422 Moving ? VK_XValue : VK_LValue,
3425 InitializationKind InitKind
3426 = InitializationKind::CreateDirect(Constructor->getLocation(),
3427 SourceLocation(), SourceLocation());
3428 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3429 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3434 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3435 if (BaseInit.isInvalid())
3439 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3440 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3442 BaseSpec->isVirtual(),
3444 BaseInit.getAs<Expr>(),
3451 static bool RefersToRValueRef(Expr *MemRef) {
3452 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3453 return Referenced->getType()->isRValueReferenceType();
3457 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3458 ImplicitInitializerKind ImplicitInitKind,
3459 FieldDecl *Field, IndirectFieldDecl *Indirect,
3460 CXXCtorInitializer *&CXXMemberInit) {
3461 if (Field->isInvalidDecl())
3464 SourceLocation Loc = Constructor->getLocation();
3466 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3467 bool Moving = ImplicitInitKind == IIK_Move;
3468 ParmVarDecl *Param = Constructor->getParamDecl(0);
3469 QualType ParamType = Param->getType().getNonReferenceType();
3471 // Suppress copying zero-width bitfields.
3472 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3475 Expr *MemberExprBase =
3476 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3477 SourceLocation(), Param, false,
3478 Loc, ParamType, VK_LValue, nullptr);
3480 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3483 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3486 // Build a reference to this field within the parameter.
3488 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3489 Sema::LookupMemberName);
3490 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3491 : cast<ValueDecl>(Field), AS_public);
3492 MemberLookup.resolveKind();
3494 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3498 /*TemplateKWLoc=*/SourceLocation(),
3499 /*FirstQualifierInScope=*/nullptr,
3501 /*TemplateArgs=*/nullptr,
3503 if (CtorArg.isInvalid())
3506 // C++11 [class.copy]p15:
3507 // - if a member m has rvalue reference type T&&, it is direct-initialized
3508 // with static_cast<T&&>(x.m);
3509 if (RefersToRValueRef(CtorArg.get())) {
3510 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3513 // When the field we are copying is an array, create index variables for
3514 // each dimension of the array. We use these index variables to subscript
3515 // the source array, and other clients (e.g., CodeGen) will perform the
3516 // necessary iteration with these index variables.
3517 SmallVector<VarDecl *, 4> IndexVariables;
3518 QualType BaseType = Field->getType();
3519 QualType SizeType = SemaRef.Context.getSizeType();
3520 bool InitializingArray = false;
3521 while (const ConstantArrayType *Array
3522 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3523 InitializingArray = true;
3524 // Create the iteration variable for this array index.
3525 IdentifierInfo *IterationVarName = nullptr;
3528 llvm::raw_svector_ostream OS(Str);
3529 OS << "__i" << IndexVariables.size();
3530 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3532 VarDecl *IterationVar
3533 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3534 IterationVarName, SizeType,
3535 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3537 IndexVariables.push_back(IterationVar);
3539 // Create a reference to the iteration variable.
3540 ExprResult IterationVarRef
3541 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3542 assert(!IterationVarRef.isInvalid() &&
3543 "Reference to invented variable cannot fail!");
3544 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3545 assert(!IterationVarRef.isInvalid() &&
3546 "Conversion of invented variable cannot fail!");
3548 // Subscript the array with this iteration variable.
3549 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3550 IterationVarRef.get(),
3552 if (CtorArg.isInvalid())
3555 BaseType = Array->getElementType();
3558 // The array subscript expression is an lvalue, which is wrong for moving.
3559 if (Moving && InitializingArray)
3560 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3562 // Construct the entity that we will be initializing. For an array, this
3563 // will be first element in the array, which may require several levels
3564 // of array-subscript entities.
3565 SmallVector<InitializedEntity, 4> Entities;
3566 Entities.reserve(1 + IndexVariables.size());
3568 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3570 Entities.push_back(InitializedEntity::InitializeMember(Field));
3571 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3572 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3576 // Direct-initialize to use the copy constructor.
3577 InitializationKind InitKind =
3578 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3580 Expr *CtorArgE = CtorArg.getAs<Expr>();
3581 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3584 ExprResult MemberInit
3585 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3586 MultiExprArg(&CtorArgE, 1));
3587 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3588 if (MemberInit.isInvalid())
3592 assert(IndexVariables.size() == 0 &&
3593 "Indirect field improperly initialized");
3595 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3597 MemberInit.getAs<Expr>(),
3600 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3601 Loc, MemberInit.getAs<Expr>(),
3603 IndexVariables.data(),
3604 IndexVariables.size());
3608 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3609 "Unhandled implicit init kind!");
3611 QualType FieldBaseElementType =
3612 SemaRef.Context.getBaseElementType(Field->getType());
3614 if (FieldBaseElementType->isRecordType()) {
3615 InitializedEntity InitEntity
3616 = Indirect? InitializedEntity::InitializeMember(Indirect)
3617 : InitializedEntity::InitializeMember(Field);
3618 InitializationKind InitKind =
3619 InitializationKind::CreateDefault(Loc);
3621 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3622 ExprResult MemberInit =
3623 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3625 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3626 if (MemberInit.isInvalid())
3630 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3636 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3643 if (!Field->getParent()->isUnion()) {
3644 if (FieldBaseElementType->isReferenceType()) {
3645 SemaRef.Diag(Constructor->getLocation(),
3646 diag::err_uninitialized_member_in_ctor)
3647 << (int)Constructor->isImplicit()
3648 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3649 << 0 << Field->getDeclName();
3650 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3654 if (FieldBaseElementType.isConstQualified()) {
3655 SemaRef.Diag(Constructor->getLocation(),
3656 diag::err_uninitialized_member_in_ctor)
3657 << (int)Constructor->isImplicit()
3658 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3659 << 1 << Field->getDeclName();
3660 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3665 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3666 FieldBaseElementType->isObjCRetainableType() &&
3667 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3668 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3670 // Default-initialize Objective-C pointers to NULL.
3672 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3674 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3679 // Nothing to initialize.
3680 CXXMemberInit = nullptr;
3685 struct BaseAndFieldInfo {
3687 CXXConstructorDecl *Ctor;
3688 bool AnyErrorsInInits;
3689 ImplicitInitializerKind IIK;
3690 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3691 SmallVector<CXXCtorInitializer*, 8> AllToInit;
3692 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3694 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3695 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3696 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3697 if (Generated && Ctor->isCopyConstructor())
3699 else if (Generated && Ctor->isMoveConstructor())
3701 else if (Ctor->getInheritedConstructor())
3707 bool isImplicitCopyOrMove() const {
3718 llvm_unreachable("Invalid ImplicitInitializerKind!");
3721 bool addFieldInitializer(CXXCtorInitializer *Init) {
3722 AllToInit.push_back(Init);
3724 // Check whether this initializer makes the field "used".
3725 if (Init->getInit()->HasSideEffects(S.Context))
3726 S.UnusedPrivateFields.remove(Init->getAnyMember());
3731 bool isInactiveUnionMember(FieldDecl *Field) {
3732 RecordDecl *Record = Field->getParent();
3733 if (!Record->isUnion())
3736 if (FieldDecl *Active =
3737 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3738 return Active != Field->getCanonicalDecl();
3740 // In an implicit copy or move constructor, ignore any in-class initializer.
3741 if (isImplicitCopyOrMove())
3744 // If there's no explicit initialization, the field is active only if it
3745 // has an in-class initializer...
3746 if (Field->hasInClassInitializer())
3748 // ... or it's an anonymous struct or union whose class has an in-class
3750 if (!Field->isAnonymousStructOrUnion())
3752 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3753 return !FieldRD->hasInClassInitializer();
3756 /// \brief Determine whether the given field is, or is within, a union member
3757 /// that is inactive (because there was an initializer given for a different
3758 /// member of the union, or because the union was not initialized at all).
3759 bool isWithinInactiveUnionMember(FieldDecl *Field,
3760 IndirectFieldDecl *Indirect) {
3762 return isInactiveUnionMember(Field);
3764 for (auto *C : Indirect->chain()) {
3765 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3766 if (Field && isInactiveUnionMember(Field))
3774 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3776 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3777 if (T->isIncompleteArrayType())
3780 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3781 if (!ArrayT->getSize())
3784 T = ArrayT->getElementType();
3790 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3792 IndirectFieldDecl *Indirect = nullptr) {
3793 if (Field->isInvalidDecl())
3796 // Overwhelmingly common case: we have a direct initializer for this field.
3797 if (CXXCtorInitializer *Init =
3798 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3799 return Info.addFieldInitializer(Init);
3801 // C++11 [class.base.init]p8:
3802 // if the entity is a non-static data member that has a
3803 // brace-or-equal-initializer and either
3804 // -- the constructor's class is a union and no other variant member of that
3805 // union is designated by a mem-initializer-id or
3806 // -- the constructor's class is not a union, and, if the entity is a member
3807 // of an anonymous union, no other member of that union is designated by
3808 // a mem-initializer-id,
3809 // the entity is initialized as specified in [dcl.init].
3811 // We also apply the same rules to handle anonymous structs within anonymous
3813 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3816 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3818 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3819 if (DIE.isInvalid())
3821 CXXCtorInitializer *Init;
3823 Init = new (SemaRef.Context)
3824 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3825 SourceLocation(), DIE.get(), SourceLocation());
3827 Init = new (SemaRef.Context)
3828 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3829 SourceLocation(), DIE.get(), SourceLocation());
3830 return Info.addFieldInitializer(Init);
3833 // Don't initialize incomplete or zero-length arrays.
3834 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3837 // Don't try to build an implicit initializer if there were semantic
3838 // errors in any of the initializers (and therefore we might be
3839 // missing some that the user actually wrote).
3840 if (Info.AnyErrorsInInits)
3843 CXXCtorInitializer *Init = nullptr;
3844 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3851 return Info.addFieldInitializer(Init);
3855 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3856 CXXCtorInitializer *Initializer) {
3857 assert(Initializer->isDelegatingInitializer());
3858 Constructor->setNumCtorInitializers(1);
3859 CXXCtorInitializer **initializer =
3860 new (Context) CXXCtorInitializer*[1];
3861 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3862 Constructor->setCtorInitializers(initializer);
3864 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3865 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3866 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3869 DelegatingCtorDecls.push_back(Constructor);
3871 DiagnoseUninitializedFields(*this, Constructor);
3876 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3877 ArrayRef<CXXCtorInitializer *> Initializers) {
3878 if (Constructor->isDependentContext()) {
3879 // Just store the initializers as written, they will be checked during
3881 if (!Initializers.empty()) {
3882 Constructor->setNumCtorInitializers(Initializers.size());
3883 CXXCtorInitializer **baseOrMemberInitializers =
3884 new (Context) CXXCtorInitializer*[Initializers.size()];
3885 memcpy(baseOrMemberInitializers, Initializers.data(),
3886 Initializers.size() * sizeof(CXXCtorInitializer*));
3887 Constructor->setCtorInitializers(baseOrMemberInitializers);
3890 // Let template instantiation know whether we had errors.
3892 Constructor->setInvalidDecl();
3897 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3899 // We need to build the initializer AST according to order of construction
3900 // and not what user specified in the Initializers list.
3901 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3905 bool HadError = false;
3907 for (unsigned i = 0; i < Initializers.size(); i++) {
3908 CXXCtorInitializer *Member = Initializers[i];
3910 if (Member->isBaseInitializer())
3911 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3913 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3915 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3916 for (auto *C : F->chain()) {
3917 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3918 if (FD && FD->getParent()->isUnion())
3919 Info.ActiveUnionMember.insert(std::make_pair(
3920 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3922 } else if (FieldDecl *FD = Member->getMember()) {
3923 if (FD->getParent()->isUnion())
3924 Info.ActiveUnionMember.insert(std::make_pair(
3925 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3930 // Keep track of the direct virtual bases.
3931 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3932 for (auto &I : ClassDecl->bases()) {
3934 DirectVBases.insert(&I);
3937 // Push virtual bases before others.
3938 for (auto &VBase : ClassDecl->vbases()) {
3939 if (CXXCtorInitializer *Value
3940 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3941 // [class.base.init]p7, per DR257:
3942 // A mem-initializer where the mem-initializer-id names a virtual base
3943 // class is ignored during execution of a constructor of any class that
3944 // is not the most derived class.
3945 if (ClassDecl->isAbstract()) {
3946 // FIXME: Provide a fixit to remove the base specifier. This requires
3947 // tracking the location of the associated comma for a base specifier.
3948 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3949 << VBase.getType() << ClassDecl;
3950 DiagnoseAbstractType(ClassDecl);
3953 Info.AllToInit.push_back(Value);
3954 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3955 // [class.base.init]p8, per DR257:
3956 // If a given [...] base class is not named by a mem-initializer-id
3957 // [...] and the entity is not a virtual base class of an abstract
3958 // class, then [...] the entity is default-initialized.
3959 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3960 CXXCtorInitializer *CXXBaseInit;
3961 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3962 &VBase, IsInheritedVirtualBase,
3968 Info.AllToInit.push_back(CXXBaseInit);
3972 // Non-virtual bases.
3973 for (auto &Base : ClassDecl->bases()) {
3974 // Virtuals are in the virtual base list and already constructed.
3975 if (Base.isVirtual())
3978 if (CXXCtorInitializer *Value
3979 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3980 Info.AllToInit.push_back(Value);
3981 } else if (!AnyErrors) {
3982 CXXCtorInitializer *CXXBaseInit;
3983 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3984 &Base, /*IsInheritedVirtualBase=*/false,
3990 Info.AllToInit.push_back(CXXBaseInit);
3995 for (auto *Mem : ClassDecl->decls()) {
3996 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3997 // C++ [class.bit]p2:
3998 // A declaration for a bit-field that omits the identifier declares an
3999 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4001 if (F->isUnnamedBitfield())
4004 // If we're not generating the implicit copy/move constructor, then we'll
4005 // handle anonymous struct/union fields based on their individual
4007 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4010 if (CollectFieldInitializer(*this, Info, F))
4015 // Beyond this point, we only consider default initialization.
4016 if (Info.isImplicitCopyOrMove())
4019 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4020 if (F->getType()->isIncompleteArrayType()) {
4021 assert(ClassDecl->hasFlexibleArrayMember() &&
4022 "Incomplete array type is not valid");
4026 // Initialize each field of an anonymous struct individually.
4027 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4034 unsigned NumInitializers = Info.AllToInit.size();
4035 if (NumInitializers > 0) {
4036 Constructor->setNumCtorInitializers(NumInitializers);
4037 CXXCtorInitializer **baseOrMemberInitializers =
4038 new (Context) CXXCtorInitializer*[NumInitializers];
4039 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4040 NumInitializers * sizeof(CXXCtorInitializer*));
4041 Constructor->setCtorInitializers(baseOrMemberInitializers);
4043 // Constructors implicitly reference the base and member
4045 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4046 Constructor->getParent());
4052 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4053 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4054 const RecordDecl *RD = RT->getDecl();
4055 if (RD->isAnonymousStructOrUnion()) {
4056 for (auto *Field : RD->fields())
4057 PopulateKeysForFields(Field, IdealInits);
4061 IdealInits.push_back(Field->getCanonicalDecl());
4064 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4065 return Context.getCanonicalType(BaseType).getTypePtr();
4068 static const void *GetKeyForMember(ASTContext &Context,
4069 CXXCtorInitializer *Member) {
4070 if (!Member->isAnyMemberInitializer())
4071 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4073 return Member->getAnyMember()->getCanonicalDecl();
4076 static void DiagnoseBaseOrMemInitializerOrder(
4077 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4078 ArrayRef<CXXCtorInitializer *> Inits) {
4079 if (Constructor->getDeclContext()->isDependentContext())
4082 // Don't check initializers order unless the warning is enabled at the
4083 // location of at least one initializer.
4084 bool ShouldCheckOrder = false;
4085 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4086 CXXCtorInitializer *Init = Inits[InitIndex];
4087 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4088 Init->getSourceLocation())) {
4089 ShouldCheckOrder = true;
4093 if (!ShouldCheckOrder)
4096 // Build the list of bases and members in the order that they'll
4097 // actually be initialized. The explicit initializers should be in
4098 // this same order but may be missing things.
4099 SmallVector<const void*, 32> IdealInitKeys;
4101 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4103 // 1. Virtual bases.
4104 for (const auto &VBase : ClassDecl->vbases())
4105 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4107 // 2. Non-virtual bases.
4108 for (const auto &Base : ClassDecl->bases()) {
4109 if (Base.isVirtual())
4111 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4114 // 3. Direct fields.
4115 for (auto *Field : ClassDecl->fields()) {
4116 if (Field->isUnnamedBitfield())
4119 PopulateKeysForFields(Field, IdealInitKeys);
4122 unsigned NumIdealInits = IdealInitKeys.size();
4123 unsigned IdealIndex = 0;
4125 CXXCtorInitializer *PrevInit = nullptr;
4126 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4127 CXXCtorInitializer *Init = Inits[InitIndex];
4128 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4130 // Scan forward to try to find this initializer in the idealized
4131 // initializers list.
4132 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4133 if (InitKey == IdealInitKeys[IdealIndex])
4136 // If we didn't find this initializer, it must be because we
4137 // scanned past it on a previous iteration. That can only
4138 // happen if we're out of order; emit a warning.
4139 if (IdealIndex == NumIdealInits && PrevInit) {
4140 Sema::SemaDiagnosticBuilder D =
4141 SemaRef.Diag(PrevInit->getSourceLocation(),
4142 diag::warn_initializer_out_of_order);
4144 if (PrevInit->isAnyMemberInitializer())
4145 D << 0 << PrevInit->getAnyMember()->getDeclName();
4147 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4149 if (Init->isAnyMemberInitializer())
4150 D << 0 << Init->getAnyMember()->getDeclName();
4152 D << 1 << Init->getTypeSourceInfo()->getType();
4154 // Move back to the initializer's location in the ideal list.
4155 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4156 if (InitKey == IdealInitKeys[IdealIndex])
4159 assert(IdealIndex < NumIdealInits &&
4160 "initializer not found in initializer list");
4168 bool CheckRedundantInit(Sema &S,
4169 CXXCtorInitializer *Init,
4170 CXXCtorInitializer *&PrevInit) {
4176 if (FieldDecl *Field = Init->getAnyMember())
4177 S.Diag(Init->getSourceLocation(),
4178 diag::err_multiple_mem_initialization)
4179 << Field->getDeclName()
4180 << Init->getSourceRange();
4182 const Type *BaseClass = Init->getBaseClass();
4183 assert(BaseClass && "neither field nor base");
4184 S.Diag(Init->getSourceLocation(),
4185 diag::err_multiple_base_initialization)
4186 << QualType(BaseClass, 0)
4187 << Init->getSourceRange();
4189 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4190 << 0 << PrevInit->getSourceRange();
4195 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4196 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4198 bool CheckRedundantUnionInit(Sema &S,
4199 CXXCtorInitializer *Init,
4200 RedundantUnionMap &Unions) {
4201 FieldDecl *Field = Init->getAnyMember();
4202 RecordDecl *Parent = Field->getParent();
4203 NamedDecl *Child = Field;
4205 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4206 if (Parent->isUnion()) {
4207 UnionEntry &En = Unions[Parent];
4208 if (En.first && En.first != Child) {
4209 S.Diag(Init->getSourceLocation(),
4210 diag::err_multiple_mem_union_initialization)
4211 << Field->getDeclName()
4212 << Init->getSourceRange();
4213 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4214 << 0 << En.second->getSourceRange();
4221 if (!Parent->isAnonymousStructOrUnion())
4226 Parent = cast<RecordDecl>(Parent->getDeclContext());
4233 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4234 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4235 SourceLocation ColonLoc,
4236 ArrayRef<CXXCtorInitializer*> MemInits,
4238 if (!ConstructorDecl)
4241 AdjustDeclIfTemplate(ConstructorDecl);
4243 CXXConstructorDecl *Constructor
4244 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4247 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4251 // Mapping for the duplicate initializers check.
4252 // For member initializers, this is keyed with a FieldDecl*.
4253 // For base initializers, this is keyed with a Type*.
4254 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4256 // Mapping for the inconsistent anonymous-union initializers check.
4257 RedundantUnionMap MemberUnions;
4259 bool HadError = false;
4260 for (unsigned i = 0; i < MemInits.size(); i++) {
4261 CXXCtorInitializer *Init = MemInits[i];
4263 // Set the source order index.
4264 Init->setSourceOrder(i);
4266 if (Init->isAnyMemberInitializer()) {
4267 const void *Key = GetKeyForMember(Context, Init);
4268 if (CheckRedundantInit(*this, Init, Members[Key]) ||
4269 CheckRedundantUnionInit(*this, Init, MemberUnions))
4271 } else if (Init->isBaseInitializer()) {
4272 const void *Key = GetKeyForMember(Context, Init);
4273 if (CheckRedundantInit(*this, Init, Members[Key]))
4276 assert(Init->isDelegatingInitializer());
4277 // This must be the only initializer
4278 if (MemInits.size() != 1) {
4279 Diag(Init->getSourceLocation(),
4280 diag::err_delegating_initializer_alone)
4281 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4282 // We will treat this as being the only initializer.
4284 SetDelegatingInitializer(Constructor, MemInits[i]);
4285 // Return immediately as the initializer is set.
4293 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4295 SetCtorInitializers(Constructor, AnyErrors, MemInits);
4297 DiagnoseUninitializedFields(*this, Constructor);
4301 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4302 CXXRecordDecl *ClassDecl) {
4303 // Ignore dependent contexts. Also ignore unions, since their members never
4304 // have destructors implicitly called.
4305 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4308 // FIXME: all the access-control diagnostics are positioned on the
4309 // field/base declaration. That's probably good; that said, the
4310 // user might reasonably want to know why the destructor is being
4311 // emitted, and we currently don't say.
4313 // Non-static data members.
4314 for (auto *Field : ClassDecl->fields()) {
4315 if (Field->isInvalidDecl())
4318 // Don't destroy incomplete or zero-length arrays.
4319 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4322 QualType FieldType = Context.getBaseElementType(Field->getType());
4324 const RecordType* RT = FieldType->getAs<RecordType>();
4328 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4329 if (FieldClassDecl->isInvalidDecl())
4331 if (FieldClassDecl->hasIrrelevantDestructor())
4333 // The destructor for an implicit anonymous union member is never invoked.
4334 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4337 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4338 assert(Dtor && "No dtor found for FieldClassDecl!");
4339 CheckDestructorAccess(Field->getLocation(), Dtor,
4340 PDiag(diag::err_access_dtor_field)
4341 << Field->getDeclName()
4344 MarkFunctionReferenced(Location, Dtor);
4345 DiagnoseUseOfDecl(Dtor, Location);
4348 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4351 for (const auto &Base : ClassDecl->bases()) {
4352 // Bases are always records in a well-formed non-dependent class.
4353 const RecordType *RT = Base.getType()->getAs<RecordType>();
4355 // Remember direct virtual bases.
4356 if (Base.isVirtual())
4357 DirectVirtualBases.insert(RT);
4359 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4360 // If our base class is invalid, we probably can't get its dtor anyway.
4361 if (BaseClassDecl->isInvalidDecl())
4363 if (BaseClassDecl->hasIrrelevantDestructor())
4366 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4367 assert(Dtor && "No dtor found for BaseClassDecl!");
4369 // FIXME: caret should be on the start of the class name
4370 CheckDestructorAccess(Base.getLocStart(), Dtor,
4371 PDiag(diag::err_access_dtor_base)
4373 << Base.getSourceRange(),
4374 Context.getTypeDeclType(ClassDecl));
4376 MarkFunctionReferenced(Location, Dtor);
4377 DiagnoseUseOfDecl(Dtor, Location);
4381 for (const auto &VBase : ClassDecl->vbases()) {
4382 // Bases are always records in a well-formed non-dependent class.
4383 const RecordType *RT = VBase.getType()->castAs<RecordType>();
4385 // Ignore direct virtual bases.
4386 if (DirectVirtualBases.count(RT))
4389 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4390 // If our base class is invalid, we probably can't get its dtor anyway.
4391 if (BaseClassDecl->isInvalidDecl())
4393 if (BaseClassDecl->hasIrrelevantDestructor())
4396 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4397 assert(Dtor && "No dtor found for BaseClassDecl!");
4398 if (CheckDestructorAccess(
4399 ClassDecl->getLocation(), Dtor,
4400 PDiag(diag::err_access_dtor_vbase)
4401 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4402 Context.getTypeDeclType(ClassDecl)) ==
4404 CheckDerivedToBaseConversion(
4405 Context.getTypeDeclType(ClassDecl), VBase.getType(),
4406 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4407 SourceRange(), DeclarationName(), nullptr);
4410 MarkFunctionReferenced(Location, Dtor);
4411 DiagnoseUseOfDecl(Dtor, Location);
4415 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4419 if (CXXConstructorDecl *Constructor
4420 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4421 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4422 DiagnoseUninitializedFields(*this, Constructor);
4426 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
4427 if (!getLangOpts().CPlusPlus)
4430 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
4434 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
4435 // class template specialization here, but doing so breaks a lot of code.
4437 // We can't answer whether something is abstract until it has a
4438 // definition. If it's currently being defined, we'll walk back
4439 // over all the declarations when we have a full definition.
4440 const CXXRecordDecl *Def = RD->getDefinition();
4441 if (!Def || Def->isBeingDefined())
4444 return RD->isAbstract();
4447 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4448 TypeDiagnoser &Diagnoser) {
4449 if (!isAbstractType(Loc, T))
4452 T = Context.getBaseElementType(T);
4453 Diagnoser.diagnose(*this, Loc, T);
4454 DiagnoseAbstractType(T->getAsCXXRecordDecl());
4458 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4459 // Check if we've already emitted the list of pure virtual functions
4461 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4464 // If the diagnostic is suppressed, don't emit the notes. We're only
4465 // going to emit them once, so try to attach them to a diagnostic we're
4466 // actually going to show.
4467 if (Diags.isLastDiagnosticIgnored())
4470 CXXFinalOverriderMap FinalOverriders;
4471 RD->getFinalOverriders(FinalOverriders);
4473 // Keep a set of seen pure methods so we won't diagnose the same method
4475 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4477 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4478 MEnd = FinalOverriders.end();
4481 for (OverridingMethods::iterator SO = M->second.begin(),
4482 SOEnd = M->second.end();
4483 SO != SOEnd; ++SO) {
4484 // C++ [class.abstract]p4:
4485 // A class is abstract if it contains or inherits at least one
4486 // pure virtual function for which the final overrider is pure
4490 if (SO->second.size() != 1)
4493 if (!SO->second.front().Method->isPure())
4496 if (!SeenPureMethods.insert(SO->second.front().Method).second)
4499 Diag(SO->second.front().Method->getLocation(),
4500 diag::note_pure_virtual_function)
4501 << SO->second.front().Method->getDeclName() << RD->getDeclName();
4505 if (!PureVirtualClassDiagSet)
4506 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4507 PureVirtualClassDiagSet->insert(RD);
4511 struct AbstractUsageInfo {
4513 CXXRecordDecl *Record;
4514 CanQualType AbstractType;
4517 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4518 : S(S), Record(Record),
4519 AbstractType(S.Context.getCanonicalType(
4520 S.Context.getTypeDeclType(Record))),
4523 void DiagnoseAbstractType() {
4524 if (Invalid) return;
4525 S.DiagnoseAbstractType(Record);
4529 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4532 struct CheckAbstractUsage {
4533 AbstractUsageInfo &Info;
4534 const NamedDecl *Ctx;
4536 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4537 : Info(Info), Ctx(Ctx) {}
4539 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4540 switch (TL.getTypeLocClass()) {
4541 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4542 #define TYPELOC(CLASS, PARENT) \
4543 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4544 #include "clang/AST/TypeLocNodes.def"
4548 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4549 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4550 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4551 if (!TL.getParam(I))
4554 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4555 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4559 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4560 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4563 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4564 // Visit the type parameters from a permissive context.
4565 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4566 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4567 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4568 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4569 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4570 // TODO: other template argument types?
4574 // Visit pointee types from a permissive context.
4575 #define CheckPolymorphic(Type) \
4576 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4577 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4579 CheckPolymorphic(PointerTypeLoc)
4580 CheckPolymorphic(ReferenceTypeLoc)
4581 CheckPolymorphic(MemberPointerTypeLoc)
4582 CheckPolymorphic(BlockPointerTypeLoc)
4583 CheckPolymorphic(AtomicTypeLoc)
4585 /// Handle all the types we haven't given a more specific
4586 /// implementation for above.
4587 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4588 // Every other kind of type that we haven't called out already
4589 // that has an inner type is either (1) sugar or (2) contains that
4590 // inner type in some way as a subobject.
4591 if (TypeLoc Next = TL.getNextTypeLoc())
4592 return Visit(Next, Sel);
4594 // If there's no inner type and we're in a permissive context,
4596 if (Sel == Sema::AbstractNone) return;
4598 // Check whether the type matches the abstract type.
4599 QualType T = TL.getType();
4600 if (T->isArrayType()) {
4601 Sel = Sema::AbstractArrayType;
4602 T = Info.S.Context.getBaseElementType(T);
4604 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4605 if (CT != Info.AbstractType) return;
4607 // It matched; do some magic.
4608 if (Sel == Sema::AbstractArrayType) {
4609 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4610 << T << TL.getSourceRange();
4612 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4613 << Sel << T << TL.getSourceRange();
4615 Info.DiagnoseAbstractType();
4619 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4620 Sema::AbstractDiagSelID Sel) {
4621 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4626 /// Check for invalid uses of an abstract type in a method declaration.
4627 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4628 CXXMethodDecl *MD) {
4629 // No need to do the check on definitions, which require that
4630 // the return/param types be complete.
4631 if (MD->doesThisDeclarationHaveABody())
4634 // For safety's sake, just ignore it if we don't have type source
4635 // information. This should never happen for non-implicit methods,
4637 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4638 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4641 /// Check for invalid uses of an abstract type within a class definition.
4642 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4643 CXXRecordDecl *RD) {
4644 for (auto *D : RD->decls()) {
4645 if (D->isImplicit()) continue;
4647 // Methods and method templates.
4648 if (isa<CXXMethodDecl>(D)) {
4649 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4650 } else if (isa<FunctionTemplateDecl>(D)) {
4651 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4652 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4654 // Fields and static variables.
4655 } else if (isa<FieldDecl>(D)) {
4656 FieldDecl *FD = cast<FieldDecl>(D);
4657 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4658 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4659 } else if (isa<VarDecl>(D)) {
4660 VarDecl *VD = cast<VarDecl>(D);
4661 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4662 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4664 // Nested classes and class templates.
4665 } else if (isa<CXXRecordDecl>(D)) {
4666 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4667 } else if (isa<ClassTemplateDecl>(D)) {
4668 CheckAbstractClassUsage(Info,
4669 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4674 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4675 Attr *ClassAttr = getDLLAttr(Class);
4679 assert(ClassAttr->getKind() == attr::DLLExport);
4681 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4683 if (TSK == TSK_ExplicitInstantiationDeclaration)
4684 // Don't go any further if this is just an explicit instantiation
4688 for (Decl *Member : Class->decls()) {
4689 auto *MD = dyn_cast<CXXMethodDecl>(Member);
4693 if (Member->getAttr<DLLExportAttr>()) {
4694 if (MD->isUserProvided()) {
4695 // Instantiate non-default class member functions ...
4697 // .. except for certain kinds of template specializations.
4698 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4701 S.MarkFunctionReferenced(Class->getLocation(), MD);
4703 // The function will be passed to the consumer when its definition is
4705 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4706 MD->isCopyAssignmentOperator() ||
4707 MD->isMoveAssignmentOperator()) {
4708 // Synthesize and instantiate non-trivial implicit methods, explicitly
4709 // defaulted methods, and the copy and move assignment operators. The
4710 // latter are exported even if they are trivial, because the address of
4711 // an operator can be taken and should compare equal accross libraries.
4712 DiagnosticErrorTrap Trap(S.Diags);
4713 S.MarkFunctionReferenced(Class->getLocation(), MD);
4714 if (Trap.hasErrorOccurred()) {
4715 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4716 << Class->getName() << !S.getLangOpts().CPlusPlus11;
4720 // There is no later point when we will see the definition of this
4721 // function, so pass it to the consumer now.
4722 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4728 /// \brief Check class-level dllimport/dllexport attribute.
4729 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4730 Attr *ClassAttr = getDLLAttr(Class);
4732 // MSVC inherits DLL attributes to partial class template specializations.
4733 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4734 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4735 if (Attr *TemplateAttr =
4736 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4737 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4738 A->setInherited(true);
4747 if (!Class->isExternallyVisible()) {
4748 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4749 << Class << ClassAttr;
4753 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4754 !ClassAttr->isInherited()) {
4755 // Diagnose dll attributes on members of class with dll attribute.
4756 for (Decl *Member : Class->decls()) {
4757 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4759 InheritableAttr *MemberAttr = getDLLAttr(Member);
4760 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4763 Diag(MemberAttr->getLocation(),
4764 diag::err_attribute_dll_member_of_dll_class)
4765 << MemberAttr << ClassAttr;
4766 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4767 Member->setInvalidDecl();
4771 if (Class->getDescribedClassTemplate())
4772 // Don't inherit dll attribute until the template is instantiated.
4775 // The class is either imported or exported.
4776 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4777 const bool ClassImported = !ClassExported;
4779 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4781 // Ignore explicit dllexport on explicit class template instantiation declarations.
4782 if (ClassExported && !ClassAttr->isInherited() &&
4783 TSK == TSK_ExplicitInstantiationDeclaration) {
4784 Class->dropAttr<DLLExportAttr>();
4788 // Force declaration of implicit members so they can inherit the attribute.
4789 ForceDeclarationOfImplicitMembers(Class);
4791 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4792 // seem to be true in practice?
4794 for (Decl *Member : Class->decls()) {
4795 VarDecl *VD = dyn_cast<VarDecl>(Member);
4796 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4798 // Only methods and static fields inherit the attributes.
4803 // Don't process deleted methods.
4804 if (MD->isDeleted())
4807 if (MD->isInlined()) {
4808 // MinGW does not import or export inline methods.
4809 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4812 // MSVC versions before 2015 don't export the move assignment operators,
4813 // so don't attempt to import them if we have a definition.
4814 if (ClassImported && MD->isMoveAssignmentOperator() &&
4815 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4820 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4823 if (!getDLLAttr(Member)) {
4825 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4826 NewAttr->setInherited(true);
4827 Member->addAttr(NewAttr);
4832 DelayedDllExportClasses.push_back(Class);
4835 /// \brief Perform propagation of DLL attributes from a derived class to a
4836 /// templated base class for MS compatibility.
4837 void Sema::propagateDLLAttrToBaseClassTemplate(
4838 CXXRecordDecl *Class, Attr *ClassAttr,
4839 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4841 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4842 // If the base class template has a DLL attribute, don't try to change it.
4846 auto TSK = BaseTemplateSpec->getSpecializationKind();
4847 if (!getDLLAttr(BaseTemplateSpec) &&
4848 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4849 TSK == TSK_ImplicitInstantiation)) {
4850 // The template hasn't been instantiated yet (or it has, but only as an
4851 // explicit instantiation declaration or implicit instantiation, which means
4852 // we haven't codegenned any members yet), so propagate the attribute.
4853 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4854 NewAttr->setInherited(true);
4855 BaseTemplateSpec->addAttr(NewAttr);
4857 // If the template is already instantiated, checkDLLAttributeRedeclaration()
4858 // needs to be run again to work see the new attribute. Otherwise this will
4859 // get run whenever the template is instantiated.
4860 if (TSK != TSK_Undeclared)
4861 checkClassLevelDLLAttribute(BaseTemplateSpec);
4866 if (getDLLAttr(BaseTemplateSpec)) {
4867 // The template has already been specialized or instantiated with an
4868 // attribute, explicitly or through propagation. We should not try to change
4873 // The template was previously instantiated or explicitly specialized without
4874 // a dll attribute, It's too late for us to add an attribute, so warn that
4875 // this is unsupported.
4876 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4877 << BaseTemplateSpec->isExplicitSpecialization();
4878 Diag(ClassAttr->getLocation(), diag::note_attribute);
4879 if (BaseTemplateSpec->isExplicitSpecialization()) {
4880 Diag(BaseTemplateSpec->getLocation(),
4881 diag::note_template_class_explicit_specialization_was_here)
4882 << BaseTemplateSpec;
4884 Diag(BaseTemplateSpec->getPointOfInstantiation(),
4885 diag::note_template_class_instantiation_was_here)
4886 << BaseTemplateSpec;
4890 /// \brief Perform semantic checks on a class definition that has been
4891 /// completing, introducing implicitly-declared members, checking for
4892 /// abstract types, etc.
4893 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4897 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4898 AbstractUsageInfo Info(*this, Record);
4899 CheckAbstractClassUsage(Info, Record);
4902 // If this is not an aggregate type and has no user-declared constructor,
4903 // complain about any non-static data members of reference or const scalar
4904 // type, since they will never get initializers.
4905 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4906 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4907 !Record->isLambda()) {
4908 bool Complained = false;
4909 for (const auto *F : Record->fields()) {
4910 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4913 if (F->getType()->isReferenceType() ||
4914 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4916 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4917 << Record->getTagKind() << Record;
4921 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4922 << F->getType()->isReferenceType()
4923 << F->getDeclName();
4928 if (Record->getIdentifier()) {
4929 // C++ [class.mem]p13:
4930 // If T is the name of a class, then each of the following shall have a
4931 // name different from T:
4932 // - every member of every anonymous union that is a member of class T.
4934 // C++ [class.mem]p14:
4935 // In addition, if class T has a user-declared constructor (12.1), every
4936 // non-static data member of class T shall have a name different from T.
4937 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4938 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4941 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4942 isa<IndirectFieldDecl>(D)) {
4943 Diag(D->getLocation(), diag::err_member_name_of_class)
4944 << D->getDeclName();
4950 // Warn if the class has virtual methods but non-virtual public destructor.
4951 if (Record->isPolymorphic() && !Record->isDependentType()) {
4952 CXXDestructorDecl *dtor = Record->getDestructor();
4953 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4954 !Record->hasAttr<FinalAttr>())
4955 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4956 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4959 if (Record->isAbstract()) {
4960 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4961 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4962 << FA->isSpelledAsSealed();
4963 DiagnoseAbstractType(Record);
4967 bool HasMethodWithOverrideControl = false,
4968 HasOverridingMethodWithoutOverrideControl = false;
4969 if (!Record->isDependentType()) {
4970 for (auto *M : Record->methods()) {
4971 // See if a method overloads virtual methods in a base
4972 // class without overriding any.
4974 DiagnoseHiddenVirtualMethods(M);
4975 if (M->hasAttr<OverrideAttr>())
4976 HasMethodWithOverrideControl = true;
4977 else if (M->size_overridden_methods() > 0)
4978 HasOverridingMethodWithoutOverrideControl = true;
4979 // Check whether the explicitly-defaulted special members are valid.
4980 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4981 CheckExplicitlyDefaultedSpecialMember(M);
4983 // For an explicitly defaulted or deleted special member, we defer
4984 // determining triviality until the class is complete. That time is now!
4985 if (!M->isImplicit() && !M->isUserProvided()) {
4986 CXXSpecialMember CSM = getSpecialMember(M);
4987 if (CSM != CXXInvalid) {
4988 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4990 // Inform the class that we've finished declaring this member.
4991 Record->finishedDefaultedOrDeletedMember(M);
4997 if (HasMethodWithOverrideControl &&
4998 HasOverridingMethodWithoutOverrideControl) {
4999 // At least one method has the 'override' control declared.
5000 // Diagnose all other overridden methods which do not have 'override' specified on them.
5001 for (auto *M : Record->methods())
5002 DiagnoseAbsenceOfOverrideControl(M);
5005 // ms_struct is a request to use the same ABI rules as MSVC. Check
5006 // whether this class uses any C++ features that are implemented
5007 // completely differently in MSVC, and if so, emit a diagnostic.
5008 // That diagnostic defaults to an error, but we allow projects to
5009 // map it down to a warning (or ignore it). It's a fairly common
5010 // practice among users of the ms_struct pragma to mass-annotate
5011 // headers, sweeping up a bunch of types that the project doesn't
5012 // really rely on MSVC-compatible layout for. We must therefore
5013 // support "ms_struct except for C++ stuff" as a secondary ABI.
5014 if (Record->isMsStruct(Context) &&
5015 (Record->isPolymorphic() || Record->getNumBases())) {
5016 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5019 // Declare inheriting constructors. We do this eagerly here because:
5020 // - The standard requires an eager diagnostic for conflicting inheriting
5021 // constructors from different classes.
5022 // - The lazy declaration of the other implicit constructors is so as to not
5023 // waste space and performance on classes that are not meant to be
5024 // instantiated (e.g. meta-functions). This doesn't apply to classes that
5025 // have inheriting constructors.
5026 DeclareInheritingConstructors(Record);
5028 checkClassLevelDLLAttribute(Record);
5031 /// Look up the special member function that would be called by a special
5032 /// member function for a subobject of class type.
5034 /// \param Class The class type of the subobject.
5035 /// \param CSM The kind of special member function.
5036 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5037 /// \param ConstRHS True if this is a copy operation with a const object
5038 /// on its RHS, that is, if the argument to the outer special member
5039 /// function is 'const' and this is not a field marked 'mutable'.
5040 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5041 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5042 unsigned FieldQuals, bool ConstRHS) {
5043 unsigned LHSQuals = 0;
5044 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5045 LHSQuals = FieldQuals;
5047 unsigned RHSQuals = FieldQuals;
5048 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5051 RHSQuals |= Qualifiers::Const;
5053 return S.LookupSpecialMember(Class, CSM,
5054 RHSQuals & Qualifiers::Const,
5055 RHSQuals & Qualifiers::Volatile,
5057 LHSQuals & Qualifiers::Const,
5058 LHSQuals & Qualifiers::Volatile);
5061 /// Is the special member function which would be selected to perform the
5062 /// specified operation on the specified class type a constexpr constructor?
5063 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5064 Sema::CXXSpecialMember CSM,
5065 unsigned Quals, bool ConstRHS) {
5066 Sema::SpecialMemberOverloadResult *SMOR =
5067 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5068 if (!SMOR || !SMOR->getMethod())
5069 // A constructor we wouldn't select can't be "involved in initializing"
5072 return SMOR->getMethod()->isConstexpr();
5075 /// Determine whether the specified special member function would be constexpr
5076 /// if it were implicitly defined.
5077 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5078 Sema::CXXSpecialMember CSM,
5080 if (!S.getLangOpts().CPlusPlus11)
5083 // C++11 [dcl.constexpr]p4:
5084 // In the definition of a constexpr constructor [...]
5087 case Sema::CXXDefaultConstructor:
5088 // Since default constructor lookup is essentially trivial (and cannot
5089 // involve, for instance, template instantiation), we compute whether a
5090 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5092 // This is important for performance; we need to know whether the default
5093 // constructor is constexpr to determine whether the type is a literal type.
5094 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5096 case Sema::CXXCopyConstructor:
5097 case Sema::CXXMoveConstructor:
5098 // For copy or move constructors, we need to perform overload resolution.
5101 case Sema::CXXCopyAssignment:
5102 case Sema::CXXMoveAssignment:
5103 if (!S.getLangOpts().CPlusPlus14)
5105 // In C++1y, we need to perform overload resolution.
5109 case Sema::CXXDestructor:
5110 case Sema::CXXInvalid:
5114 // -- if the class is a non-empty union, or for each non-empty anonymous
5115 // union member of a non-union class, exactly one non-static data member
5116 // shall be initialized; [DR1359]
5118 // If we squint, this is guaranteed, since exactly one non-static data member
5119 // will be initialized (if the constructor isn't deleted), we just don't know
5121 if (Ctor && ClassDecl->isUnion())
5124 // -- the class shall not have any virtual base classes;
5125 if (Ctor && ClassDecl->getNumVBases())
5128 // C++1y [class.copy]p26:
5129 // -- [the class] is a literal type, and
5130 if (!Ctor && !ClassDecl->isLiteral())
5133 // -- every constructor involved in initializing [...] base class
5134 // sub-objects shall be a constexpr constructor;
5135 // -- the assignment operator selected to copy/move each direct base
5136 // class is a constexpr function, and
5137 for (const auto &B : ClassDecl->bases()) {
5138 const RecordType *BaseType = B.getType()->getAs<RecordType>();
5139 if (!BaseType) continue;
5141 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5142 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5146 // -- every constructor involved in initializing non-static data members
5147 // [...] shall be a constexpr constructor;
5148 // -- every non-static data member and base class sub-object shall be
5150 // -- for each non-static data member of X that is of class type (or array
5151 // thereof), the assignment operator selected to copy/move that member is
5152 // a constexpr function
5153 for (const auto *F : ClassDecl->fields()) {
5154 if (F->isInvalidDecl())
5156 QualType BaseType = S.Context.getBaseElementType(F->getType());
5157 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5158 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5159 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5160 BaseType.getCVRQualifiers(),
5161 ConstArg && !F->isMutable()))
5166 // All OK, it's constexpr!
5170 static Sema::ImplicitExceptionSpecification
5171 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5172 switch (S.getSpecialMember(MD)) {
5173 case Sema::CXXDefaultConstructor:
5174 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5175 case Sema::CXXCopyConstructor:
5176 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5177 case Sema::CXXCopyAssignment:
5178 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5179 case Sema::CXXMoveConstructor:
5180 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5181 case Sema::CXXMoveAssignment:
5182 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5183 case Sema::CXXDestructor:
5184 return S.ComputeDefaultedDtorExceptionSpec(MD);
5185 case Sema::CXXInvalid:
5188 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5189 "only special members have implicit exception specs");
5190 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5193 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5194 CXXMethodDecl *MD) {
5195 FunctionProtoType::ExtProtoInfo EPI;
5197 // Build an exception specification pointing back at this member.
5198 EPI.ExceptionSpec.Type = EST_Unevaluated;
5199 EPI.ExceptionSpec.SourceDecl = MD;
5201 // Set the calling convention to the default for C++ instance methods.
5202 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5203 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5204 /*IsCXXMethod=*/true));
5208 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5209 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5210 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5213 // Evaluate the exception specification.
5214 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5216 // Update the type of the special member to use it.
5217 UpdateExceptionSpec(MD, ESI);
5219 // A user-provided destructor can be defined outside the class. When that
5220 // happens, be sure to update the exception specification on both
5222 const FunctionProtoType *CanonicalFPT =
5223 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5224 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5225 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5228 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5229 CXXRecordDecl *RD = MD->getParent();
5230 CXXSpecialMember CSM = getSpecialMember(MD);
5232 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5233 "not an explicitly-defaulted special member");
5235 // Whether this was the first-declared instance of the constructor.
5236 // This affects whether we implicitly add an exception spec and constexpr.
5237 bool First = MD == MD->getCanonicalDecl();
5239 bool HadError = false;
5241 // C++11 [dcl.fct.def.default]p1:
5242 // A function that is explicitly defaulted shall
5243 // -- be a special member function (checked elsewhere),
5244 // -- have the same type (except for ref-qualifiers, and except that a
5245 // copy operation can take a non-const reference) as an implicit
5247 // -- not have default arguments.
5248 unsigned ExpectedParams = 1;
5249 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5251 if (MD->getNumParams() != ExpectedParams) {
5252 // This also checks for default arguments: a copy or move constructor with a
5253 // default argument is classified as a default constructor, and assignment
5254 // operations and destructors can't have default arguments.
5255 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5256 << CSM << MD->getSourceRange();
5258 } else if (MD->isVariadic()) {
5259 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5260 << CSM << MD->getSourceRange();
5264 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5266 bool CanHaveConstParam = false;
5267 if (CSM == CXXCopyConstructor)
5268 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5269 else if (CSM == CXXCopyAssignment)
5270 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5272 QualType ReturnType = Context.VoidTy;
5273 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5274 // Check for return type matching.
5275 ReturnType = Type->getReturnType();
5276 QualType ExpectedReturnType =
5277 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5278 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5279 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5280 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5284 // A defaulted special member cannot have cv-qualifiers.
5285 if (Type->getTypeQuals()) {
5286 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5287 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5292 // Check for parameter type matching.
5293 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5294 bool HasConstParam = false;
5295 if (ExpectedParams && ArgType->isReferenceType()) {
5296 // Argument must be reference to possibly-const T.
5297 QualType ReferentType = ArgType->getPointeeType();
5298 HasConstParam = ReferentType.isConstQualified();
5300 if (ReferentType.isVolatileQualified()) {
5301 Diag(MD->getLocation(),
5302 diag::err_defaulted_special_member_volatile_param) << CSM;
5306 if (HasConstParam && !CanHaveConstParam) {
5307 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5308 Diag(MD->getLocation(),
5309 diag::err_defaulted_special_member_copy_const_param)
5310 << (CSM == CXXCopyAssignment);
5311 // FIXME: Explain why this special member can't be const.
5313 Diag(MD->getLocation(),
5314 diag::err_defaulted_special_member_move_const_param)
5315 << (CSM == CXXMoveAssignment);
5319 } else if (ExpectedParams) {
5320 // A copy assignment operator can take its argument by value, but a
5321 // defaulted one cannot.
5322 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5323 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5327 // C++11 [dcl.fct.def.default]p2:
5328 // An explicitly-defaulted function may be declared constexpr only if it
5329 // would have been implicitly declared as constexpr,
5330 // Do not apply this rule to members of class templates, since core issue 1358
5331 // makes such functions always instantiate to constexpr functions. For
5332 // functions which cannot be constexpr (for non-constructors in C++11 and for
5333 // destructors in C++1y), this is checked elsewhere.
5334 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5336 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5337 : isa<CXXConstructorDecl>(MD)) &&
5338 MD->isConstexpr() && !Constexpr &&
5339 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5340 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5341 // FIXME: Explain why the special member can't be constexpr.
5345 // and may have an explicit exception-specification only if it is compatible
5346 // with the exception-specification on the implicit declaration.
5347 if (Type->hasExceptionSpec()) {
5348 // Delay the check if this is the first declaration of the special member,
5349 // since we may not have parsed some necessary in-class initializers yet.
5351 // If the exception specification needs to be instantiated, do so now,
5352 // before we clobber it with an EST_Unevaluated specification below.
5353 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5354 InstantiateExceptionSpec(MD->getLocStart(), MD);
5355 Type = MD->getType()->getAs<FunctionProtoType>();
5357 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5359 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5362 // If a function is explicitly defaulted on its first declaration,
5364 // -- it is implicitly considered to be constexpr if the implicit
5365 // definition would be,
5366 MD->setConstexpr(Constexpr);
5368 // -- it is implicitly considered to have the same exception-specification
5369 // as if it had been implicitly declared,
5370 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5371 EPI.ExceptionSpec.Type = EST_Unevaluated;
5372 EPI.ExceptionSpec.SourceDecl = MD;
5373 MD->setType(Context.getFunctionType(ReturnType,
5374 llvm::makeArrayRef(&ArgType,
5379 if (ShouldDeleteSpecialMember(MD, CSM)) {
5381 SetDeclDeleted(MD, MD->getLocation());
5383 // C++11 [dcl.fct.def.default]p4:
5384 // [For a] user-provided explicitly-defaulted function [...] if such a
5385 // function is implicitly defined as deleted, the program is ill-formed.
5386 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5387 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5393 MD->setInvalidDecl();
5396 /// Check whether the exception specification provided for an
5397 /// explicitly-defaulted special member matches the exception specification
5398 /// that would have been generated for an implicit special member, per
5399 /// C++11 [dcl.fct.def.default]p2.
5400 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5401 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5402 // If the exception specification was explicitly specified but hadn't been
5403 // parsed when the method was defaulted, grab it now.
5404 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5406 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5408 // Compute the implicit exception specification.
5409 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5410 /*IsCXXMethod=*/true);
5411 FunctionProtoType::ExtProtoInfo EPI(CC);
5412 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5413 .getExceptionSpec();
5414 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5415 Context.getFunctionType(Context.VoidTy, None, EPI));
5417 // Ensure that it matches.
5418 CheckEquivalentExceptionSpec(
5419 PDiag(diag::err_incorrect_defaulted_exception_spec)
5420 << getSpecialMember(MD), PDiag(),
5421 ImplicitType, SourceLocation(),
5422 SpecifiedType, MD->getLocation());
5425 void Sema::CheckDelayedMemberExceptionSpecs() {
5426 decltype(DelayedExceptionSpecChecks) Checks;
5427 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5429 std::swap(Checks, DelayedExceptionSpecChecks);
5430 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5432 // Perform any deferred checking of exception specifications for virtual
5434 for (auto &Check : Checks)
5435 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5437 // Check that any explicitly-defaulted methods have exception specifications
5438 // compatible with their implicit exception specifications.
5439 for (auto &Spec : Specs)
5440 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5444 struct SpecialMemberDeletionInfo {
5447 Sema::CXXSpecialMember CSM;
5450 // Properties of the special member, computed for convenience.
5451 bool IsConstructor, IsAssignment, IsMove, ConstArg;
5454 bool AllFieldsAreConst;
5456 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5457 Sema::CXXSpecialMember CSM, bool Diagnose)
5458 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5459 IsConstructor(false), IsAssignment(false), IsMove(false),
5460 ConstArg(false), Loc(MD->getLocation()),
5461 AllFieldsAreConst(true) {
5463 case Sema::CXXDefaultConstructor:
5464 case Sema::CXXCopyConstructor:
5465 IsConstructor = true;
5467 case Sema::CXXMoveConstructor:
5468 IsConstructor = true;
5471 case Sema::CXXCopyAssignment:
5472 IsAssignment = true;
5474 case Sema::CXXMoveAssignment:
5475 IsAssignment = true;
5478 case Sema::CXXDestructor:
5480 case Sema::CXXInvalid:
5481 llvm_unreachable("invalid special member kind");
5484 if (MD->getNumParams()) {
5485 if (const ReferenceType *RT =
5486 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5487 ConstArg = RT->getPointeeType().isConstQualified();
5491 bool inUnion() const { return MD->getParent()->isUnion(); }
5493 /// Look up the corresponding special member in the given class.
5494 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5495 unsigned Quals, bool IsMutable) {
5496 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5497 ConstArg && !IsMutable);
5500 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5502 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5503 bool shouldDeleteForField(FieldDecl *FD);
5504 bool shouldDeleteForAllConstMembers();
5506 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5508 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5509 Sema::SpecialMemberOverloadResult *SMOR,
5510 bool IsDtorCallInCtor);
5512 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5516 /// Is the given special member inaccessible when used on the given
5518 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5519 CXXMethodDecl *target) {
5520 /// If we're operating on a base class, the object type is the
5521 /// type of this special member.
5523 AccessSpecifier access = target->getAccess();
5524 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5525 objectTy = S.Context.getTypeDeclType(MD->getParent());
5526 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5528 // If we're operating on a field, the object type is the type of the field.
5530 objectTy = S.Context.getTypeDeclType(target->getParent());
5533 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5536 /// Check whether we should delete a special member due to the implicit
5537 /// definition containing a call to a special member of a subobject.
5538 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5539 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5540 bool IsDtorCallInCtor) {
5541 CXXMethodDecl *Decl = SMOR->getMethod();
5542 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5546 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5547 DiagKind = !Decl ? 0 : 1;
5548 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5550 else if (!isAccessible(Subobj, Decl))
5552 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5553 !Decl->isTrivial()) {
5554 // A member of a union must have a trivial corresponding special member.
5555 // As a weird special case, a destructor call from a union's constructor
5556 // must be accessible and non-deleted, but need not be trivial. Such a
5557 // destructor is never actually called, but is semantically checked as
5567 S.Diag(Field->getLocation(),
5568 diag::note_deleted_special_member_class_subobject)
5569 << CSM << MD->getParent() << /*IsField*/true
5570 << Field << DiagKind << IsDtorCallInCtor;
5572 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5573 S.Diag(Base->getLocStart(),
5574 diag::note_deleted_special_member_class_subobject)
5575 << CSM << MD->getParent() << /*IsField*/false
5576 << Base->getType() << DiagKind << IsDtorCallInCtor;
5580 S.NoteDeletedFunction(Decl);
5581 // FIXME: Explain inaccessibility if DiagKind == 3.
5587 /// Check whether we should delete a special member function due to having a
5588 /// direct or virtual base class or non-static data member of class type M.
5589 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5590 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5591 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5592 bool IsMutable = Field && Field->isMutable();
5594 // C++11 [class.ctor]p5:
5595 // -- any direct or virtual base class, or non-static data member with no
5596 // brace-or-equal-initializer, has class type M (or array thereof) and
5597 // either M has no default constructor or overload resolution as applied
5598 // to M's default constructor results in an ambiguity or in a function
5599 // that is deleted or inaccessible
5600 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5601 // -- a direct or virtual base class B that cannot be copied/moved because
5602 // overload resolution, as applied to B's corresponding special member,
5603 // results in an ambiguity or a function that is deleted or inaccessible
5604 // from the defaulted special member
5605 // C++11 [class.dtor]p5:
5606 // -- any direct or virtual base class [...] has a type with a destructor
5607 // that is deleted or inaccessible
5608 if (!(CSM == Sema::CXXDefaultConstructor &&
5609 Field && Field->hasInClassInitializer()) &&
5610 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5614 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5615 // -- any direct or virtual base class or non-static data member has a
5616 // type with a destructor that is deleted or inaccessible
5617 if (IsConstructor) {
5618 Sema::SpecialMemberOverloadResult *SMOR =
5619 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5620 false, false, false, false, false);
5621 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5628 /// Check whether we should delete a special member function due to the class
5629 /// having a particular direct or virtual base class.
5630 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5631 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5632 // If program is correct, BaseClass cannot be null, but if it is, the error
5633 // must be reported elsewhere.
5634 return BaseClass && shouldDeleteForClassSubobject(BaseClass, Base, 0);
5637 /// Check whether we should delete a special member function due to the class
5638 /// having a particular non-static data member.
5639 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5640 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5641 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5643 if (CSM == Sema::CXXDefaultConstructor) {
5644 // For a default constructor, all references must be initialized in-class
5645 // and, if a union, it must have a non-const member.
5646 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5648 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5649 << MD->getParent() << FD << FieldType << /*Reference*/0;
5652 // C++11 [class.ctor]p5: any non-variant non-static data member of
5653 // const-qualified type (or array thereof) with no
5654 // brace-or-equal-initializer does not have a user-provided default
5656 if (!inUnion() && FieldType.isConstQualified() &&
5657 !FD->hasInClassInitializer() &&
5658 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5660 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5661 << MD->getParent() << FD << FD->getType() << /*Const*/1;
5665 if (inUnion() && !FieldType.isConstQualified())
5666 AllFieldsAreConst = false;
5667 } else if (CSM == Sema::CXXCopyConstructor) {
5668 // For a copy constructor, data members must not be of rvalue reference
5670 if (FieldType->isRValueReferenceType()) {
5672 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5673 << MD->getParent() << FD << FieldType;
5676 } else if (IsAssignment) {
5677 // For an assignment operator, data members must not be of reference type.
5678 if (FieldType->isReferenceType()) {
5680 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5681 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5684 if (!FieldRecord && FieldType.isConstQualified()) {
5685 // C++11 [class.copy]p23:
5686 // -- a non-static data member of const non-class type (or array thereof)
5688 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5689 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5695 // Some additional restrictions exist on the variant members.
5696 if (!inUnion() && FieldRecord->isUnion() &&
5697 FieldRecord->isAnonymousStructOrUnion()) {
5698 bool AllVariantFieldsAreConst = true;
5700 // FIXME: Handle anonymous unions declared within anonymous unions.
5701 for (auto *UI : FieldRecord->fields()) {
5702 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5704 if (!UnionFieldType.isConstQualified())
5705 AllVariantFieldsAreConst = false;
5707 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5708 if (UnionFieldRecord &&
5709 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5710 UnionFieldType.getCVRQualifiers()))
5714 // At least one member in each anonymous union must be non-const
5715 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5716 !FieldRecord->field_empty()) {
5718 S.Diag(FieldRecord->getLocation(),
5719 diag::note_deleted_default_ctor_all_const)
5720 << MD->getParent() << /*anonymous union*/1;
5724 // Don't check the implicit member of the anonymous union type.
5725 // This is technically non-conformant, but sanity demands it.
5729 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5730 FieldType.getCVRQualifiers()))
5737 /// C++11 [class.ctor] p5:
5738 /// A defaulted default constructor for a class X is defined as deleted if
5739 /// X is a union and all of its variant members are of const-qualified type.
5740 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5741 // This is a silly definition, because it gives an empty union a deleted
5742 // default constructor. Don't do that.
5743 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5744 !MD->getParent()->field_empty()) {
5746 S.Diag(MD->getParent()->getLocation(),
5747 diag::note_deleted_default_ctor_all_const)
5748 << MD->getParent() << /*not anonymous union*/0;
5754 /// Determine whether a defaulted special member function should be defined as
5755 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5756 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5757 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5759 if (MD->isInvalidDecl())
5761 CXXRecordDecl *RD = MD->getParent();
5762 assert(!RD->isDependentType() && "do deletion after instantiation");
5763 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5766 // C++11 [expr.lambda.prim]p19:
5767 // The closure type associated with a lambda-expression has a
5768 // deleted (8.4.3) default constructor and a deleted copy
5769 // assignment operator.
5770 if (RD->isLambda() &&
5771 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5773 Diag(RD->getLocation(), diag::note_lambda_decl);
5777 // For an anonymous struct or union, the copy and assignment special members
5778 // will never be used, so skip the check. For an anonymous union declared at
5779 // namespace scope, the constructor and destructor are used.
5780 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5781 RD->isAnonymousStructOrUnion())
5784 // C++11 [class.copy]p7, p18:
5785 // If the class definition declares a move constructor or move assignment
5786 // operator, an implicitly declared copy constructor or copy assignment
5787 // operator is defined as deleted.
5788 if (MD->isImplicit() &&
5789 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5790 CXXMethodDecl *UserDeclaredMove = nullptr;
5792 // In Microsoft mode, a user-declared move only causes the deletion of the
5793 // corresponding copy operation, not both copy operations.
5794 if (RD->hasUserDeclaredMoveConstructor() &&
5795 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5796 if (!Diagnose) return true;
5798 // Find any user-declared move constructor.
5799 for (auto *I : RD->ctors()) {
5800 if (I->isMoveConstructor()) {
5801 UserDeclaredMove = I;
5805 assert(UserDeclaredMove);
5806 } else if (RD->hasUserDeclaredMoveAssignment() &&
5807 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5808 if (!Diagnose) return true;
5810 // Find any user-declared move assignment operator.
5811 for (auto *I : RD->methods()) {
5812 if (I->isMoveAssignmentOperator()) {
5813 UserDeclaredMove = I;
5817 assert(UserDeclaredMove);
5820 if (UserDeclaredMove) {
5821 Diag(UserDeclaredMove->getLocation(),
5822 diag::note_deleted_copy_user_declared_move)
5823 << (CSM == CXXCopyAssignment) << RD
5824 << UserDeclaredMove->isMoveAssignmentOperator();
5829 // Do access control from the special member function
5830 ContextRAII MethodContext(*this, MD);
5832 // C++11 [class.dtor]p5:
5833 // -- for a virtual destructor, lookup of the non-array deallocation function
5834 // results in an ambiguity or in a function that is deleted or inaccessible
5835 if (CSM == CXXDestructor && MD->isVirtual()) {
5836 FunctionDecl *OperatorDelete = nullptr;
5837 DeclarationName Name =
5838 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5839 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5840 OperatorDelete, false)) {
5842 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5847 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5849 for (auto &BI : RD->bases())
5850 if (!BI.isVirtual() &&
5851 SMI.shouldDeleteForBase(&BI))
5854 // Per DR1611, do not consider virtual bases of constructors of abstract
5855 // classes, since we are not going to construct them.
5856 if (!RD->isAbstract() || !SMI.IsConstructor) {
5857 for (auto &BI : RD->vbases())
5858 if (SMI.shouldDeleteForBase(&BI))
5862 for (auto *FI : RD->fields())
5863 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5864 SMI.shouldDeleteForField(FI))
5867 if (SMI.shouldDeleteForAllConstMembers())
5870 if (getLangOpts().CUDA) {
5871 // We should delete the special member in CUDA mode if target inference
5873 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5880 /// Perform lookup for a special member of the specified kind, and determine
5881 /// whether it is trivial. If the triviality can be determined without the
5882 /// lookup, skip it. This is intended for use when determining whether a
5883 /// special member of a containing object is trivial, and thus does not ever
5884 /// perform overload resolution for default constructors.
5886 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5887 /// member that was most likely to be intended to be trivial, if any.
5888 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5889 Sema::CXXSpecialMember CSM, unsigned Quals,
5890 bool ConstRHS, CXXMethodDecl **Selected) {
5892 *Selected = nullptr;
5895 case Sema::CXXInvalid:
5896 llvm_unreachable("not a special member");
5898 case Sema::CXXDefaultConstructor:
5899 // C++11 [class.ctor]p5:
5900 // A default constructor is trivial if:
5901 // - all the [direct subobjects] have trivial default constructors
5903 // Note, no overload resolution is performed in this case.
5904 if (RD->hasTrivialDefaultConstructor())
5908 // If there's a default constructor which could have been trivial, dig it
5909 // out. Otherwise, if there's any user-provided default constructor, point
5910 // to that as an example of why there's not a trivial one.
5911 CXXConstructorDecl *DefCtor = nullptr;
5912 if (RD->needsImplicitDefaultConstructor())
5913 S.DeclareImplicitDefaultConstructor(RD);
5914 for (auto *CI : RD->ctors()) {
5915 if (!CI->isDefaultConstructor())
5918 if (!DefCtor->isUserProvided())
5922 *Selected = DefCtor;
5927 case Sema::CXXDestructor:
5928 // C++11 [class.dtor]p5:
5929 // A destructor is trivial if:
5930 // - all the direct [subobjects] have trivial destructors
5931 if (RD->hasTrivialDestructor())
5935 if (RD->needsImplicitDestructor())
5936 S.DeclareImplicitDestructor(RD);
5937 *Selected = RD->getDestructor();
5942 case Sema::CXXCopyConstructor:
5943 // C++11 [class.copy]p12:
5944 // A copy constructor is trivial if:
5945 // - the constructor selected to copy each direct [subobject] is trivial
5946 if (RD->hasTrivialCopyConstructor()) {
5947 if (Quals == Qualifiers::Const)
5948 // We must either select the trivial copy constructor or reach an
5949 // ambiguity; no need to actually perform overload resolution.
5951 } else if (!Selected) {
5954 // In C++98, we are not supposed to perform overload resolution here, but we
5955 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5956 // cases like B as having a non-trivial copy constructor:
5957 // struct A { template<typename T> A(T&); };
5958 // struct B { mutable A a; };
5959 goto NeedOverloadResolution;
5961 case Sema::CXXCopyAssignment:
5962 // C++11 [class.copy]p25:
5963 // A copy assignment operator is trivial if:
5964 // - the assignment operator selected to copy each direct [subobject] is
5966 if (RD->hasTrivialCopyAssignment()) {
5967 if (Quals == Qualifiers::Const)
5969 } else if (!Selected) {
5972 // In C++98, we are not supposed to perform overload resolution here, but we
5973 // treat that as a language defect.
5974 goto NeedOverloadResolution;
5976 case Sema::CXXMoveConstructor:
5977 case Sema::CXXMoveAssignment:
5978 NeedOverloadResolution:
5979 Sema::SpecialMemberOverloadResult *SMOR =
5980 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5982 // The standard doesn't describe how to behave if the lookup is ambiguous.
5983 // We treat it as not making the member non-trivial, just like the standard
5984 // mandates for the default constructor. This should rarely matter, because
5985 // the member will also be deleted.
5986 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5989 if (!SMOR->getMethod()) {
5990 assert(SMOR->getKind() ==
5991 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5995 // We deliberately don't check if we found a deleted special member. We're
5998 *Selected = SMOR->getMethod();
5999 return SMOR->getMethod()->isTrivial();
6002 llvm_unreachable("unknown special method kind");
6005 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6006 for (auto *CI : RD->ctors())
6007 if (!CI->isImplicit())
6010 // Look for constructor templates.
6011 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6012 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6013 if (CXXConstructorDecl *CD =
6014 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6021 /// The kind of subobject we are checking for triviality. The values of this
6022 /// enumeration are used in diagnostics.
6023 enum TrivialSubobjectKind {
6024 /// The subobject is a base class.
6026 /// The subobject is a non-static data member.
6028 /// The object is actually the complete object.
6032 /// Check whether the special member selected for a given type would be trivial.
6033 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6034 QualType SubType, bool ConstRHS,
6035 Sema::CXXSpecialMember CSM,
6036 TrivialSubobjectKind Kind,
6038 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6042 CXXMethodDecl *Selected;
6043 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6044 ConstRHS, Diagnose ? &Selected : nullptr))
6051 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6052 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6053 << Kind << SubType.getUnqualifiedType();
6054 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6055 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6056 } else if (!Selected)
6057 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6058 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6059 else if (Selected->isUserProvided()) {
6060 if (Kind == TSK_CompleteObject)
6061 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6062 << Kind << SubType.getUnqualifiedType() << CSM;
6064 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6065 << Kind << SubType.getUnqualifiedType() << CSM;
6066 S.Diag(Selected->getLocation(), diag::note_declared_at);
6069 if (Kind != TSK_CompleteObject)
6070 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6071 << Kind << SubType.getUnqualifiedType() << CSM;
6073 // Explain why the defaulted or deleted special member isn't trivial.
6074 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6081 /// Check whether the members of a class type allow a special member to be
6083 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6084 Sema::CXXSpecialMember CSM,
6085 bool ConstArg, bool Diagnose) {
6086 for (const auto *FI : RD->fields()) {
6087 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6090 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6092 // Pretend anonymous struct or union members are members of this class.
6093 if (FI->isAnonymousStructOrUnion()) {
6094 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6095 CSM, ConstArg, Diagnose))
6100 // C++11 [class.ctor]p5:
6101 // A default constructor is trivial if [...]
6102 // -- no non-static data member of its class has a
6103 // brace-or-equal-initializer
6104 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6106 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6110 // Objective C ARC 4.3.5:
6111 // [...] nontrivally ownership-qualified types are [...] not trivially
6112 // default constructible, copy constructible, move constructible, copy
6113 // assignable, move assignable, or destructible [...]
6114 if (S.getLangOpts().ObjCAutoRefCount &&
6115 FieldType.hasNonTrivialObjCLifetime()) {
6117 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6118 << RD << FieldType.getObjCLifetime();
6122 bool ConstRHS = ConstArg && !FI->isMutable();
6123 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6124 CSM, TSK_Field, Diagnose))
6131 /// Diagnose why the specified class does not have a trivial special member of
6133 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6134 QualType Ty = Context.getRecordType(RD);
6136 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6137 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6138 TSK_CompleteObject, /*Diagnose*/true);
6141 /// Determine whether a defaulted or deleted special member function is trivial,
6142 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6143 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6144 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6146 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6148 CXXRecordDecl *RD = MD->getParent();
6150 bool ConstArg = false;
6152 // C++11 [class.copy]p12, p25: [DR1593]
6153 // A [special member] is trivial if [...] its parameter-type-list is
6154 // equivalent to the parameter-type-list of an implicit declaration [...]
6156 case CXXDefaultConstructor:
6158 // Trivial default constructors and destructors cannot have parameters.
6161 case CXXCopyConstructor:
6162 case CXXCopyAssignment: {
6163 // Trivial copy operations always have const, non-volatile parameter types.
6165 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6166 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6167 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6169 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6170 << Param0->getSourceRange() << Param0->getType()
6171 << Context.getLValueReferenceType(
6172 Context.getRecordType(RD).withConst());
6178 case CXXMoveConstructor:
6179 case CXXMoveAssignment: {
6180 // Trivial move operations always have non-cv-qualified parameters.
6181 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6182 const RValueReferenceType *RT =
6183 Param0->getType()->getAs<RValueReferenceType>();
6184 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6186 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6187 << Param0->getSourceRange() << Param0->getType()
6188 << Context.getRValueReferenceType(Context.getRecordType(RD));
6195 llvm_unreachable("not a special member");
6198 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6200 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6201 diag::note_nontrivial_default_arg)
6202 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6205 if (MD->isVariadic()) {
6207 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6211 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6212 // A copy/move [constructor or assignment operator] is trivial if
6213 // -- the [member] selected to copy/move each direct base class subobject
6216 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6217 // A [default constructor or destructor] is trivial if
6218 // -- all the direct base classes have trivial [default constructors or
6220 for (const auto &BI : RD->bases())
6221 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6222 ConstArg, CSM, TSK_BaseClass, Diagnose))
6225 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6226 // A copy/move [constructor or assignment operator] for a class X is
6228 // -- for each non-static data member of X that is of class type (or array
6229 // thereof), the constructor selected to copy/move that member is
6232 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6233 // A [default constructor or destructor] is trivial if
6234 // -- for all of the non-static data members of its class that are of class
6235 // type (or array thereof), each such class has a trivial [default
6236 // constructor or destructor]
6237 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6240 // C++11 [class.dtor]p5:
6241 // A destructor is trivial if [...]
6242 // -- the destructor is not virtual
6243 if (CSM == CXXDestructor && MD->isVirtual()) {
6245 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6249 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6250 // A [special member] for class X is trivial if [...]
6251 // -- class X has no virtual functions and no virtual base classes
6252 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6256 if (RD->getNumVBases()) {
6257 // Check for virtual bases. We already know that the corresponding
6258 // member in all bases is trivial, so vbases must all be direct.
6259 CXXBaseSpecifier &BS = *RD->vbases_begin();
6260 assert(BS.isVirtual());
6261 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6265 // Must have a virtual method.
6266 for (const auto *MI : RD->methods()) {
6267 if (MI->isVirtual()) {
6268 SourceLocation MLoc = MI->getLocStart();
6269 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6274 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6277 // Looks like it's trivial!
6282 struct FindHiddenVirtualMethod {
6284 CXXMethodDecl *Method;
6285 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6286 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6289 /// Check whether any most overriden method from MD in Methods
6290 static bool CheckMostOverridenMethods(
6291 const CXXMethodDecl *MD,
6292 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6293 if (MD->size_overridden_methods() == 0)
6294 return Methods.count(MD->getCanonicalDecl());
6295 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6296 E = MD->end_overridden_methods();
6298 if (CheckMostOverridenMethods(*I, Methods))
6304 /// Member lookup function that determines whether a given C++
6305 /// method overloads virtual methods in a base class without overriding any,
6306 /// to be used with CXXRecordDecl::lookupInBases().
6307 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6308 RecordDecl *BaseRecord =
6309 Specifier->getType()->getAs<RecordType>()->getDecl();
6311 DeclarationName Name = Method->getDeclName();
6312 assert(Name.getNameKind() == DeclarationName::Identifier);
6314 bool foundSameNameMethod = false;
6315 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6316 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6317 Path.Decls = Path.Decls.slice(1)) {
6318 NamedDecl *D = Path.Decls.front();
6319 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6320 MD = MD->getCanonicalDecl();
6321 foundSameNameMethod = true;
6322 // Interested only in hidden virtual methods.
6323 if (!MD->isVirtual())
6325 // If the method we are checking overrides a method from its base
6326 // don't warn about the other overloaded methods. Clang deviates from
6327 // GCC by only diagnosing overloads of inherited virtual functions that
6328 // do not override any other virtual functions in the base. GCC's
6329 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6330 // function from a base class. These cases may be better served by a
6331 // warning (not specific to virtual functions) on call sites when the
6332 // call would select a different function from the base class, were it
6334 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6335 if (!S->IsOverload(Method, MD, false))
6337 // Collect the overload only if its hidden.
6338 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6339 overloadedMethods.push_back(MD);
6343 if (foundSameNameMethod)
6344 OverloadedMethods.append(overloadedMethods.begin(),
6345 overloadedMethods.end());
6346 return foundSameNameMethod;
6349 } // end anonymous namespace
6351 /// \brief Add the most overriden methods from MD to Methods
6352 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6353 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6354 if (MD->size_overridden_methods() == 0)
6355 Methods.insert(MD->getCanonicalDecl());
6356 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6357 E = MD->end_overridden_methods();
6359 AddMostOverridenMethods(*I, Methods);
6362 /// \brief Check if a method overloads virtual methods in a base class without
6364 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6365 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6366 if (!MD->getDeclName().isIdentifier())
6369 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6370 /*bool RecordPaths=*/false,
6371 /*bool DetectVirtual=*/false);
6372 FindHiddenVirtualMethod FHVM;
6376 // Keep the base methods that were overriden or introduced in the subclass
6377 // by 'using' in a set. A base method not in this set is hidden.
6378 CXXRecordDecl *DC = MD->getParent();
6379 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6380 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6382 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6383 ND = shad->getTargetDecl();
6384 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6385 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
6388 if (DC->lookupInBases(FHVM, Paths))
6389 OverloadedMethods = FHVM.OverloadedMethods;
6392 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6393 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6394 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6395 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6396 PartialDiagnostic PD = PDiag(
6397 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6398 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6399 Diag(overloadedMD->getLocation(), PD);
6403 /// \brief Diagnose methods which overload virtual methods in a base class
6404 /// without overriding any.
6405 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6406 if (MD->isInvalidDecl())
6409 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6412 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6413 FindHiddenVirtualMethods(MD, OverloadedMethods);
6414 if (!OverloadedMethods.empty()) {
6415 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6416 << MD << (OverloadedMethods.size() > 1);
6418 NoteHiddenVirtualMethods(MD, OverloadedMethods);
6422 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6424 SourceLocation LBrac,
6425 SourceLocation RBrac,
6426 AttributeList *AttrList) {
6430 AdjustDeclIfTemplate(TagDecl);
6432 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6433 if (l->getKind() != AttributeList::AT_Visibility)
6436 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6440 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6441 // strict aliasing violation!
6442 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6443 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6445 CheckCompletedCXXClass(
6446 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6449 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6450 /// special functions, such as the default constructor, copy
6451 /// constructor, or destructor, to the given C++ class (C++
6452 /// [special]p1). This routine can only be executed just before the
6453 /// definition of the class is complete.
6454 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6455 if (!ClassDecl->hasUserDeclaredConstructor())
6456 ++ASTContext::NumImplicitDefaultConstructors;
6458 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6459 ++ASTContext::NumImplicitCopyConstructors;
6461 // If the properties or semantics of the copy constructor couldn't be
6462 // determined while the class was being declared, force a declaration
6464 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6465 DeclareImplicitCopyConstructor(ClassDecl);
6468 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6469 ++ASTContext::NumImplicitMoveConstructors;
6471 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6472 DeclareImplicitMoveConstructor(ClassDecl);
6475 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6476 ++ASTContext::NumImplicitCopyAssignmentOperators;
6478 // If we have a dynamic class, then the copy assignment operator may be
6479 // virtual, so we have to declare it immediately. This ensures that, e.g.,
6480 // it shows up in the right place in the vtable and that we diagnose
6481 // problems with the implicit exception specification.
6482 if (ClassDecl->isDynamicClass() ||
6483 ClassDecl->needsOverloadResolutionForCopyAssignment())
6484 DeclareImplicitCopyAssignment(ClassDecl);
6487 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6488 ++ASTContext::NumImplicitMoveAssignmentOperators;
6490 // Likewise for the move assignment operator.
6491 if (ClassDecl->isDynamicClass() ||
6492 ClassDecl->needsOverloadResolutionForMoveAssignment())
6493 DeclareImplicitMoveAssignment(ClassDecl);
6496 if (!ClassDecl->hasUserDeclaredDestructor()) {
6497 ++ASTContext::NumImplicitDestructors;
6499 // If we have a dynamic class, then the destructor may be virtual, so we
6500 // have to declare the destructor immediately. This ensures that, e.g., it
6501 // shows up in the right place in the vtable and that we diagnose problems
6502 // with the implicit exception specification.
6503 if (ClassDecl->isDynamicClass() ||
6504 ClassDecl->needsOverloadResolutionForDestructor())
6505 DeclareImplicitDestructor(ClassDecl);
6509 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6513 // The order of template parameters is not important here. All names
6514 // get added to the same scope.
6515 SmallVector<TemplateParameterList *, 4> ParameterLists;
6517 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6518 D = TD->getTemplatedDecl();
6520 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6521 ParameterLists.push_back(PSD->getTemplateParameters());
6523 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6524 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6525 ParameterLists.push_back(DD->getTemplateParameterList(i));
6527 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6528 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6529 ParameterLists.push_back(FTD->getTemplateParameters());
6533 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6534 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6535 ParameterLists.push_back(TD->getTemplateParameterList(i));
6537 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6538 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6539 ParameterLists.push_back(CTD->getTemplateParameters());
6544 for (TemplateParameterList *Params : ParameterLists) {
6545 if (Params->size() > 0)
6546 // Ignore explicit specializations; they don't contribute to the template
6549 for (NamedDecl *Param : *Params) {
6550 if (Param->getDeclName()) {
6552 IdResolver.AddDecl(Param);
6560 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6561 if (!RecordD) return;
6562 AdjustDeclIfTemplate(RecordD);
6563 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6564 PushDeclContext(S, Record);
6567 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6568 if (!RecordD) return;
6572 /// This is used to implement the constant expression evaluation part of the
6573 /// attribute enable_if extension. There is nothing in standard C++ which would
6574 /// require reentering parameters.
6575 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6580 if (Param->getDeclName())
6581 IdResolver.AddDecl(Param);
6584 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6585 /// parsing a top-level (non-nested) C++ class, and we are now
6586 /// parsing those parts of the given Method declaration that could
6587 /// not be parsed earlier (C++ [class.mem]p2), such as default
6588 /// arguments. This action should enter the scope of the given
6589 /// Method declaration as if we had just parsed the qualified method
6590 /// name. However, it should not bring the parameters into scope;
6591 /// that will be performed by ActOnDelayedCXXMethodParameter.
6592 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6595 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6596 /// C++ method declaration. We're (re-)introducing the given
6597 /// function parameter into scope for use in parsing later parts of
6598 /// the method declaration. For example, we could see an
6599 /// ActOnParamDefaultArgument event for this parameter.
6600 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6604 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6606 // If this parameter has an unparsed default argument, clear it out
6607 // to make way for the parsed default argument.
6608 if (Param->hasUnparsedDefaultArg())
6609 Param->setDefaultArg(nullptr);
6612 if (Param->getDeclName())
6613 IdResolver.AddDecl(Param);
6616 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6617 /// processing the delayed method declaration for Method. The method
6618 /// declaration is now considered finished. There may be a separate
6619 /// ActOnStartOfFunctionDef action later (not necessarily
6620 /// immediately!) for this method, if it was also defined inside the
6622 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6626 AdjustDeclIfTemplate(MethodD);
6628 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6630 // Now that we have our default arguments, check the constructor
6631 // again. It could produce additional diagnostics or affect whether
6632 // the class has implicitly-declared destructors, among other
6634 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6635 CheckConstructor(Constructor);
6637 // Check the default arguments, which we may have added.
6638 if (!Method->isInvalidDecl())
6639 CheckCXXDefaultArguments(Method);
6642 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6643 /// the well-formedness of the constructor declarator @p D with type @p
6644 /// R. If there are any errors in the declarator, this routine will
6645 /// emit diagnostics and set the invalid bit to true. In any case, the type
6646 /// will be updated to reflect a well-formed type for the constructor and
6648 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6650 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6652 // C++ [class.ctor]p3:
6653 // A constructor shall not be virtual (10.3) or static (9.4). A
6654 // constructor can be invoked for a const, volatile or const
6655 // volatile object. A constructor shall not be declared const,
6656 // volatile, or const volatile (9.3.2).
6658 if (!D.isInvalidType())
6659 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6660 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6661 << SourceRange(D.getIdentifierLoc());
6664 if (SC == SC_Static) {
6665 if (!D.isInvalidType())
6666 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6667 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6668 << SourceRange(D.getIdentifierLoc());
6673 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6674 diagnoseIgnoredQualifiers(
6675 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6676 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6677 D.getDeclSpec().getRestrictSpecLoc(),
6678 D.getDeclSpec().getAtomicSpecLoc());
6682 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6683 if (FTI.TypeQuals != 0) {
6684 if (FTI.TypeQuals & Qualifiers::Const)
6685 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6686 << "const" << SourceRange(D.getIdentifierLoc());
6687 if (FTI.TypeQuals & Qualifiers::Volatile)
6688 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6689 << "volatile" << SourceRange(D.getIdentifierLoc());
6690 if (FTI.TypeQuals & Qualifiers::Restrict)
6691 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6692 << "restrict" << SourceRange(D.getIdentifierLoc());
6696 // C++0x [class.ctor]p4:
6697 // A constructor shall not be declared with a ref-qualifier.
6698 if (FTI.hasRefQualifier()) {
6699 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6700 << FTI.RefQualifierIsLValueRef
6701 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6705 // Rebuild the function type "R" without any type qualifiers (in
6706 // case any of the errors above fired) and with "void" as the
6707 // return type, since constructors don't have return types.
6708 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6709 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6712 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6714 EPI.RefQualifier = RQ_None;
6716 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6719 /// CheckConstructor - Checks a fully-formed constructor for
6720 /// well-formedness, issuing any diagnostics required. Returns true if
6721 /// the constructor declarator is invalid.
6722 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6723 CXXRecordDecl *ClassDecl
6724 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6726 return Constructor->setInvalidDecl();
6728 // C++ [class.copy]p3:
6729 // A declaration of a constructor for a class X is ill-formed if
6730 // its first parameter is of type (optionally cv-qualified) X and
6731 // either there are no other parameters or else all other
6732 // parameters have default arguments.
6733 if (!Constructor->isInvalidDecl() &&
6734 ((Constructor->getNumParams() == 1) ||
6735 (Constructor->getNumParams() > 1 &&
6736 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6737 Constructor->getTemplateSpecializationKind()
6738 != TSK_ImplicitInstantiation) {
6739 QualType ParamType = Constructor->getParamDecl(0)->getType();
6740 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6741 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6742 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6743 const char *ConstRef
6744 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6746 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6747 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6749 // FIXME: Rather that making the constructor invalid, we should endeavor
6751 Constructor->setInvalidDecl();
6756 /// CheckDestructor - Checks a fully-formed destructor definition for
6757 /// well-formedness, issuing any diagnostics required. Returns true
6759 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6760 CXXRecordDecl *RD = Destructor->getParent();
6762 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6765 if (!Destructor->isImplicit())
6766 Loc = Destructor->getLocation();
6768 Loc = RD->getLocation();
6770 // If we have a virtual destructor, look up the deallocation function
6771 FunctionDecl *OperatorDelete = nullptr;
6772 DeclarationName Name =
6773 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6774 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6776 // If there's no class-specific operator delete, look up the global
6777 // non-array delete.
6778 if (!OperatorDelete)
6779 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6781 MarkFunctionReferenced(Loc, OperatorDelete);
6783 Destructor->setOperatorDelete(OperatorDelete);
6789 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6790 /// the well-formednes of the destructor declarator @p D with type @p
6791 /// R. If there are any errors in the declarator, this routine will
6792 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6793 /// will be updated to reflect a well-formed type for the destructor and
6795 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6797 // C++ [class.dtor]p1:
6798 // [...] A typedef-name that names a class is a class-name
6799 // (7.1.3); however, a typedef-name that names a class shall not
6800 // be used as the identifier in the declarator for a destructor
6802 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6803 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6804 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6805 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6806 else if (const TemplateSpecializationType *TST =
6807 DeclaratorType->getAs<TemplateSpecializationType>())
6808 if (TST->isTypeAlias())
6809 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6810 << DeclaratorType << 1;
6812 // C++ [class.dtor]p2:
6813 // A destructor is used to destroy objects of its class type. A
6814 // destructor takes no parameters, and no return type can be
6815 // specified for it (not even void). The address of a destructor
6816 // shall not be taken. A destructor shall not be static. A
6817 // destructor can be invoked for a const, volatile or const
6818 // volatile object. A destructor shall not be declared const,
6819 // volatile or const volatile (9.3.2).
6820 if (SC == SC_Static) {
6821 if (!D.isInvalidType())
6822 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6823 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6824 << SourceRange(D.getIdentifierLoc())
6825 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6829 if (!D.isInvalidType()) {
6830 // Destructors don't have return types, but the parser will
6831 // happily parse something like:
6837 // The return type will be eliminated later.
6838 if (D.getDeclSpec().hasTypeSpecifier())
6839 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6840 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6841 << SourceRange(D.getIdentifierLoc());
6842 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6843 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6845 D.getDeclSpec().getConstSpecLoc(),
6846 D.getDeclSpec().getVolatileSpecLoc(),
6847 D.getDeclSpec().getRestrictSpecLoc(),
6848 D.getDeclSpec().getAtomicSpecLoc());
6853 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6854 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6855 if (FTI.TypeQuals & Qualifiers::Const)
6856 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6857 << "const" << SourceRange(D.getIdentifierLoc());
6858 if (FTI.TypeQuals & Qualifiers::Volatile)
6859 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6860 << "volatile" << SourceRange(D.getIdentifierLoc());
6861 if (FTI.TypeQuals & Qualifiers::Restrict)
6862 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6863 << "restrict" << SourceRange(D.getIdentifierLoc());
6867 // C++0x [class.dtor]p2:
6868 // A destructor shall not be declared with a ref-qualifier.
6869 if (FTI.hasRefQualifier()) {
6870 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6871 << FTI.RefQualifierIsLValueRef
6872 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6876 // Make sure we don't have any parameters.
6877 if (FTIHasNonVoidParameters(FTI)) {
6878 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6880 // Delete the parameters.
6885 // Make sure the destructor isn't variadic.
6886 if (FTI.isVariadic) {
6887 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6891 // Rebuild the function type "R" without any type qualifiers or
6892 // parameters (in case any of the errors above fired) and with
6893 // "void" as the return type, since destructors don't have return
6895 if (!D.isInvalidType())
6898 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6899 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6900 EPI.Variadic = false;
6902 EPI.RefQualifier = RQ_None;
6903 return Context.getFunctionType(Context.VoidTy, None, EPI);
6906 static void extendLeft(SourceRange &R, SourceRange Before) {
6907 if (Before.isInvalid())
6909 R.setBegin(Before.getBegin());
6910 if (R.getEnd().isInvalid())
6911 R.setEnd(Before.getEnd());
6914 static void extendRight(SourceRange &R, SourceRange After) {
6915 if (After.isInvalid())
6917 if (R.getBegin().isInvalid())
6918 R.setBegin(After.getBegin());
6919 R.setEnd(After.getEnd());
6922 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6923 /// well-formednes of the conversion function declarator @p D with
6924 /// type @p R. If there are any errors in the declarator, this routine
6925 /// will emit diagnostics and return true. Otherwise, it will return
6926 /// false. Either way, the type @p R will be updated to reflect a
6927 /// well-formed type for the conversion operator.
6928 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6930 // C++ [class.conv.fct]p1:
6931 // Neither parameter types nor return type can be specified. The
6932 // type of a conversion function (8.3.5) is "function taking no
6933 // parameter returning conversion-type-id."
6934 if (SC == SC_Static) {
6935 if (!D.isInvalidType())
6936 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6937 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6938 << D.getName().getSourceRange();
6943 TypeSourceInfo *ConvTSI = nullptr;
6945 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6947 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6948 // Conversion functions don't have return types, but the parser will
6949 // happily parse something like:
6952 // float operator bool();
6955 // The return type will be changed later anyway.
6956 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6957 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6958 << SourceRange(D.getIdentifierLoc());
6962 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6964 // Make sure we don't have any parameters.
6965 if (Proto->getNumParams() > 0) {
6966 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6968 // Delete the parameters.
6969 D.getFunctionTypeInfo().freeParams();
6971 } else if (Proto->isVariadic()) {
6972 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6976 // Diagnose "&operator bool()" and other such nonsense. This
6977 // is actually a gcc extension which we don't support.
6978 if (Proto->getReturnType() != ConvType) {
6979 bool NeedsTypedef = false;
6980 SourceRange Before, After;
6982 // Walk the chunks and extract information on them for our diagnostic.
6983 bool PastFunctionChunk = false;
6984 for (auto &Chunk : D.type_objects()) {
6985 switch (Chunk.Kind) {
6986 case DeclaratorChunk::Function:
6987 if (!PastFunctionChunk) {
6988 if (Chunk.Fun.HasTrailingReturnType) {
6989 TypeSourceInfo *TRT = nullptr;
6990 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6991 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6993 PastFunctionChunk = true;
6997 case DeclaratorChunk::Array:
6998 NeedsTypedef = true;
6999 extendRight(After, Chunk.getSourceRange());
7002 case DeclaratorChunk::Pointer:
7003 case DeclaratorChunk::BlockPointer:
7004 case DeclaratorChunk::Reference:
7005 case DeclaratorChunk::MemberPointer:
7006 case DeclaratorChunk::Pipe:
7007 extendLeft(Before, Chunk.getSourceRange());
7010 case DeclaratorChunk::Paren:
7011 extendLeft(Before, Chunk.Loc);
7012 extendRight(After, Chunk.EndLoc);
7017 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7018 After.isValid() ? After.getBegin() :
7019 D.getIdentifierLoc();
7020 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7021 DB << Before << After;
7023 if (!NeedsTypedef) {
7024 DB << /*don't need a typedef*/0;
7026 // If we can provide a correct fix-it hint, do so.
7027 if (After.isInvalid() && ConvTSI) {
7028 SourceLocation InsertLoc =
7029 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7030 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7031 << FixItHint::CreateInsertionFromRange(
7032 InsertLoc, CharSourceRange::getTokenRange(Before))
7033 << FixItHint::CreateRemoval(Before);
7035 } else if (!Proto->getReturnType()->isDependentType()) {
7036 DB << /*typedef*/1 << Proto->getReturnType();
7037 } else if (getLangOpts().CPlusPlus11) {
7038 DB << /*alias template*/2 << Proto->getReturnType();
7040 DB << /*might not be fixable*/3;
7043 // Recover by incorporating the other type chunks into the result type.
7044 // Note, this does *not* change the name of the function. This is compatible
7045 // with the GCC extension:
7046 // struct S { &operator int(); } s;
7047 // int &r = s.operator int(); // ok in GCC
7048 // S::operator int&() {} // error in GCC, function name is 'operator int'.
7049 ConvType = Proto->getReturnType();
7052 // C++ [class.conv.fct]p4:
7053 // The conversion-type-id shall not represent a function type nor
7055 if (ConvType->isArrayType()) {
7056 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7057 ConvType = Context.getPointerType(ConvType);
7059 } else if (ConvType->isFunctionType()) {
7060 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7061 ConvType = Context.getPointerType(ConvType);
7065 // Rebuild the function type "R" without any parameters (in case any
7066 // of the errors above fired) and with the conversion type as the
7068 if (D.isInvalidType())
7069 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7071 // C++0x explicit conversion operators.
7072 if (D.getDeclSpec().isExplicitSpecified())
7073 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7074 getLangOpts().CPlusPlus11 ?
7075 diag::warn_cxx98_compat_explicit_conversion_functions :
7076 diag::ext_explicit_conversion_functions)
7077 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7080 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7081 /// the declaration of the given C++ conversion function. This routine
7082 /// is responsible for recording the conversion function in the C++
7083 /// class, if possible.
7084 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7085 assert(Conversion && "Expected to receive a conversion function declaration");
7087 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7089 // Make sure we aren't redeclaring the conversion function.
7090 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7092 // C++ [class.conv.fct]p1:
7093 // [...] A conversion function is never used to convert a
7094 // (possibly cv-qualified) object to the (possibly cv-qualified)
7095 // same object type (or a reference to it), to a (possibly
7096 // cv-qualified) base class of that type (or a reference to it),
7097 // or to (possibly cv-qualified) void.
7098 // FIXME: Suppress this warning if the conversion function ends up being a
7099 // virtual function that overrides a virtual function in a base class.
7101 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7102 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7103 ConvType = ConvTypeRef->getPointeeType();
7104 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7105 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7106 /* Suppress diagnostics for instantiations. */;
7107 else if (ConvType->isRecordType()) {
7108 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7109 if (ConvType == ClassType)
7110 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7112 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
7113 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7114 << ClassType << ConvType;
7115 } else if (ConvType->isVoidType()) {
7116 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7117 << ClassType << ConvType;
7120 if (FunctionTemplateDecl *ConversionTemplate
7121 = Conversion->getDescribedFunctionTemplate())
7122 return ConversionTemplate;
7127 //===----------------------------------------------------------------------===//
7128 // Namespace Handling
7129 //===----------------------------------------------------------------------===//
7131 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7133 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7135 IdentifierInfo *II, bool *IsInline,
7136 NamespaceDecl *PrevNS) {
7137 assert(*IsInline != PrevNS->isInline());
7139 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7140 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7141 // inline namespaces, with the intention of bringing names into namespace std.
7143 // We support this just well enough to get that case working; this is not
7144 // sufficient to support reopening namespaces as inline in general.
7145 if (*IsInline && II && II->getName().startswith("__atomic") &&
7146 S.getSourceManager().isInSystemHeader(Loc)) {
7147 // Mark all prior declarations of the namespace as inline.
7148 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7149 NS = NS->getPreviousDecl())
7150 NS->setInline(*IsInline);
7151 // Patch up the lookup table for the containing namespace. This isn't really
7152 // correct, but it's good enough for this particular case.
7153 for (auto *I : PrevNS->decls())
7154 if (auto *ND = dyn_cast<NamedDecl>(I))
7155 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7159 if (PrevNS->isInline())
7160 // The user probably just forgot the 'inline', so suggest that it
7162 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7163 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7165 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7167 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7168 *IsInline = PrevNS->isInline();
7171 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7173 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7174 SourceLocation InlineLoc,
7175 SourceLocation NamespaceLoc,
7176 SourceLocation IdentLoc,
7178 SourceLocation LBrace,
7179 AttributeList *AttrList,
7180 UsingDirectiveDecl *&UD) {
7181 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7182 // For anonymous namespace, take the location of the left brace.
7183 SourceLocation Loc = II ? IdentLoc : LBrace;
7184 bool IsInline = InlineLoc.isValid();
7185 bool IsInvalid = false;
7187 bool AddToKnown = false;
7188 Scope *DeclRegionScope = NamespcScope->getParent();
7190 NamespaceDecl *PrevNS = nullptr;
7192 // C++ [namespace.def]p2:
7193 // The identifier in an original-namespace-definition shall not
7194 // have been previously defined in the declarative region in
7195 // which the original-namespace-definition appears. The
7196 // identifier in an original-namespace-definition is the name of
7197 // the namespace. Subsequently in that declarative region, it is
7198 // treated as an original-namespace-name.
7200 // Since namespace names are unique in their scope, and we don't
7201 // look through using directives, just look for any ordinary names
7202 // as if by qualified name lookup.
7203 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7204 LookupQualifiedName(R, CurContext->getRedeclContext());
7205 NamedDecl *PrevDecl =
7206 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
7207 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7210 // This is an extended namespace definition.
7211 if (IsInline != PrevNS->isInline())
7212 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7214 } else if (PrevDecl) {
7215 // This is an invalid name redefinition.
7216 Diag(Loc, diag::err_redefinition_different_kind)
7218 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7220 // Continue on to push Namespc as current DeclContext and return it.
7221 } else if (II->isStr("std") &&
7222 CurContext->getRedeclContext()->isTranslationUnit()) {
7223 // This is the first "real" definition of the namespace "std", so update
7224 // our cache of the "std" namespace to point at this definition.
7225 PrevNS = getStdNamespace();
7227 AddToKnown = !IsInline;
7229 // We've seen this namespace for the first time.
7230 AddToKnown = !IsInline;
7233 // Anonymous namespaces.
7235 // Determine whether the parent already has an anonymous namespace.
7236 DeclContext *Parent = CurContext->getRedeclContext();
7237 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7238 PrevNS = TU->getAnonymousNamespace();
7240 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7241 PrevNS = ND->getAnonymousNamespace();
7244 if (PrevNS && IsInline != PrevNS->isInline())
7245 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7249 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7250 StartLoc, Loc, II, PrevNS);
7252 Namespc->setInvalidDecl();
7254 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7256 // FIXME: Should we be merging attributes?
7257 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7258 PushNamespaceVisibilityAttr(Attr, Loc);
7261 StdNamespace = Namespc;
7263 KnownNamespaces[Namespc] = false;
7266 PushOnScopeChains(Namespc, DeclRegionScope);
7268 // Link the anonymous namespace into its parent.
7269 DeclContext *Parent = CurContext->getRedeclContext();
7270 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7271 TU->setAnonymousNamespace(Namespc);
7273 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7276 CurContext->addDecl(Namespc);
7278 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7279 // behaves as if it were replaced by
7280 // namespace unique { /* empty body */ }
7281 // using namespace unique;
7282 // namespace unique { namespace-body }
7283 // where all occurrences of 'unique' in a translation unit are
7284 // replaced by the same identifier and this identifier differs
7285 // from all other identifiers in the entire program.
7287 // We just create the namespace with an empty name and then add an
7288 // implicit using declaration, just like the standard suggests.
7290 // CodeGen enforces the "universally unique" aspect by giving all
7291 // declarations semantically contained within an anonymous
7292 // namespace internal linkage.
7295 UD = UsingDirectiveDecl::Create(Context, Parent,
7296 /* 'using' */ LBrace,
7297 /* 'namespace' */ SourceLocation(),
7298 /* qualifier */ NestedNameSpecifierLoc(),
7299 /* identifier */ SourceLocation(),
7301 /* Ancestor */ Parent);
7303 Parent->addDecl(UD);
7307 ActOnDocumentableDecl(Namespc);
7309 // Although we could have an invalid decl (i.e. the namespace name is a
7310 // redefinition), push it as current DeclContext and try to continue parsing.
7311 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7312 // for the namespace has the declarations that showed up in that particular
7313 // namespace definition.
7314 PushDeclContext(NamespcScope, Namespc);
7318 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7319 /// is a namespace alias, returns the namespace it points to.
7320 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7321 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7322 return AD->getNamespace();
7323 return dyn_cast_or_null<NamespaceDecl>(D);
7326 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7327 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7328 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7329 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7330 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7331 Namespc->setRBraceLoc(RBrace);
7333 if (Namespc->hasAttr<VisibilityAttr>())
7334 PopPragmaVisibility(true, RBrace);
7337 CXXRecordDecl *Sema::getStdBadAlloc() const {
7338 return cast_or_null<CXXRecordDecl>(
7339 StdBadAlloc.get(Context.getExternalSource()));
7342 NamespaceDecl *Sema::getStdNamespace() const {
7343 return cast_or_null<NamespaceDecl>(
7344 StdNamespace.get(Context.getExternalSource()));
7347 /// \brief Retrieve the special "std" namespace, which may require us to
7348 /// implicitly define the namespace.
7349 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7350 if (!StdNamespace) {
7351 // The "std" namespace has not yet been defined, so build one implicitly.
7352 StdNamespace = NamespaceDecl::Create(Context,
7353 Context.getTranslationUnitDecl(),
7355 SourceLocation(), SourceLocation(),
7356 &PP.getIdentifierTable().get("std"),
7357 /*PrevDecl=*/nullptr);
7358 getStdNamespace()->setImplicit(true);
7361 return getStdNamespace();
7364 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7365 assert(getLangOpts().CPlusPlus &&
7366 "Looking for std::initializer_list outside of C++.");
7368 // We're looking for implicit instantiations of
7369 // template <typename E> class std::initializer_list.
7371 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7374 ClassTemplateDecl *Template = nullptr;
7375 const TemplateArgument *Arguments = nullptr;
7377 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7379 ClassTemplateSpecializationDecl *Specialization =
7380 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7381 if (!Specialization)
7384 Template = Specialization->getSpecializedTemplate();
7385 Arguments = Specialization->getTemplateArgs().data();
7386 } else if (const TemplateSpecializationType *TST =
7387 Ty->getAs<TemplateSpecializationType>()) {
7388 Template = dyn_cast_or_null<ClassTemplateDecl>(
7389 TST->getTemplateName().getAsTemplateDecl());
7390 Arguments = TST->getArgs();
7395 if (!StdInitializerList) {
7396 // Haven't recognized std::initializer_list yet, maybe this is it.
7397 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7398 if (TemplateClass->getIdentifier() !=
7399 &PP.getIdentifierTable().get("initializer_list") ||
7400 !getStdNamespace()->InEnclosingNamespaceSetOf(
7401 TemplateClass->getDeclContext()))
7403 // This is a template called std::initializer_list, but is it the right
7405 TemplateParameterList *Params = Template->getTemplateParameters();
7406 if (Params->getMinRequiredArguments() != 1)
7408 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7411 // It's the right template.
7412 StdInitializerList = Template;
7415 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7418 // This is an instance of std::initializer_list. Find the argument type.
7420 *Element = Arguments[0].getAsType();
7424 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7425 NamespaceDecl *Std = S.getStdNamespace();
7427 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7431 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7432 Loc, Sema::LookupOrdinaryName);
7433 if (!S.LookupQualifiedName(Result, Std)) {
7434 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7437 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7439 Result.suppressDiagnostics();
7440 // We found something weird. Complain about the first thing we found.
7441 NamedDecl *Found = *Result.begin();
7442 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7446 // We found some template called std::initializer_list. Now verify that it's
7448 TemplateParameterList *Params = Template->getTemplateParameters();
7449 if (Params->getMinRequiredArguments() != 1 ||
7450 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7451 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7458 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7459 if (!StdInitializerList) {
7460 StdInitializerList = LookupStdInitializerList(*this, Loc);
7461 if (!StdInitializerList)
7465 TemplateArgumentListInfo Args(Loc, Loc);
7466 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7467 Context.getTrivialTypeSourceInfo(Element,
7469 return Context.getCanonicalType(
7470 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7473 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7474 // C++ [dcl.init.list]p2:
7475 // A constructor is an initializer-list constructor if its first parameter
7476 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7477 // std::initializer_list<E> for some type E, and either there are no other
7478 // parameters or else all other parameters have default arguments.
7479 if (Ctor->getNumParams() < 1 ||
7480 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7483 QualType ArgType = Ctor->getParamDecl(0)->getType();
7484 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7485 ArgType = RT->getPointeeType().getUnqualifiedType();
7487 return isStdInitializerList(ArgType, nullptr);
7490 /// \brief Determine whether a using statement is in a context where it will be
7491 /// apply in all contexts.
7492 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7493 switch (CurContext->getDeclKind()) {
7494 case Decl::TranslationUnit:
7496 case Decl::LinkageSpec:
7497 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7505 // Callback to only accept typo corrections that are namespaces.
7506 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7508 bool ValidateCandidate(const TypoCorrection &candidate) override {
7509 if (NamedDecl *ND = candidate.getCorrectionDecl())
7510 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7517 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7519 SourceLocation IdentLoc,
7520 IdentifierInfo *Ident) {
7522 if (TypoCorrection Corrected =
7523 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7524 llvm::make_unique<NamespaceValidatorCCC>(),
7525 Sema::CTK_ErrorRecovery)) {
7526 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7527 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7528 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7529 Ident->getName().equals(CorrectedStr);
7530 S.diagnoseTypo(Corrected,
7531 S.PDiag(diag::err_using_directive_member_suggest)
7532 << Ident << DC << DroppedSpecifier << SS.getRange(),
7533 S.PDiag(diag::note_namespace_defined_here));
7535 S.diagnoseTypo(Corrected,
7536 S.PDiag(diag::err_using_directive_suggest) << Ident,
7537 S.PDiag(diag::note_namespace_defined_here));
7539 R.addDecl(Corrected.getFoundDecl());
7545 Decl *Sema::ActOnUsingDirective(Scope *S,
7546 SourceLocation UsingLoc,
7547 SourceLocation NamespcLoc,
7549 SourceLocation IdentLoc,
7550 IdentifierInfo *NamespcName,
7551 AttributeList *AttrList) {
7552 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7553 assert(NamespcName && "Invalid NamespcName.");
7554 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7556 // This can only happen along a recovery path.
7557 while (S->isTemplateParamScope())
7559 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7561 UsingDirectiveDecl *UDir = nullptr;
7562 NestedNameSpecifier *Qualifier = nullptr;
7564 Qualifier = SS.getScopeRep();
7566 // Lookup namespace name.
7567 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7568 LookupParsedName(R, S, &SS);
7569 if (R.isAmbiguous())
7574 // Allow "using namespace std;" or "using namespace ::std;" even if
7575 // "std" hasn't been defined yet, for GCC compatibility.
7576 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7577 NamespcName->isStr("std")) {
7578 Diag(IdentLoc, diag::ext_using_undefined_std);
7579 R.addDecl(getOrCreateStdNamespace());
7582 // Otherwise, attempt typo correction.
7583 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7587 NamedDecl *Named = R.getRepresentativeDecl();
7588 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
7589 assert(NS && "expected namespace decl");
7591 // The use of a nested name specifier may trigger deprecation warnings.
7592 DiagnoseUseOfDecl(Named, IdentLoc);
7594 // C++ [namespace.udir]p1:
7595 // A using-directive specifies that the names in the nominated
7596 // namespace can be used in the scope in which the
7597 // using-directive appears after the using-directive. During
7598 // unqualified name lookup (3.4.1), the names appear as if they
7599 // were declared in the nearest enclosing namespace which
7600 // contains both the using-directive and the nominated
7601 // namespace. [Note: in this context, "contains" means "contains
7602 // directly or indirectly". ]
7604 // Find enclosing context containing both using-directive and
7605 // nominated namespace.
7606 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7607 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7608 CommonAncestor = CommonAncestor->getParent();
7610 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7611 SS.getWithLocInContext(Context),
7612 IdentLoc, Named, CommonAncestor);
7614 if (IsUsingDirectiveInToplevelContext(CurContext) &&
7615 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7616 Diag(IdentLoc, diag::warn_using_directive_in_header);
7619 PushUsingDirective(S, UDir);
7621 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7625 ProcessDeclAttributeList(S, UDir, AttrList);
7630 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7631 // If the scope has an associated entity and the using directive is at
7632 // namespace or translation unit scope, add the UsingDirectiveDecl into
7633 // its lookup structure so qualified name lookup can find it.
7634 DeclContext *Ctx = S->getEntity();
7635 if (Ctx && !Ctx->isFunctionOrMethod())
7638 // Otherwise, it is at block scope. The using-directives will affect lookup
7639 // only to the end of the scope.
7640 S->PushUsingDirective(UDir);
7644 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7646 bool HasUsingKeyword,
7647 SourceLocation UsingLoc,
7649 UnqualifiedId &Name,
7650 AttributeList *AttrList,
7651 bool HasTypenameKeyword,
7652 SourceLocation TypenameLoc) {
7653 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7655 switch (Name.getKind()) {
7656 case UnqualifiedId::IK_ImplicitSelfParam:
7657 case UnqualifiedId::IK_Identifier:
7658 case UnqualifiedId::IK_OperatorFunctionId:
7659 case UnqualifiedId::IK_LiteralOperatorId:
7660 case UnqualifiedId::IK_ConversionFunctionId:
7663 case UnqualifiedId::IK_ConstructorName:
7664 case UnqualifiedId::IK_ConstructorTemplateId:
7665 // C++11 inheriting constructors.
7666 Diag(Name.getLocStart(),
7667 getLangOpts().CPlusPlus11 ?
7668 diag::warn_cxx98_compat_using_decl_constructor :
7669 diag::err_using_decl_constructor)
7672 if (getLangOpts().CPlusPlus11) break;
7676 case UnqualifiedId::IK_DestructorName:
7677 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7681 case UnqualifiedId::IK_TemplateId:
7682 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7683 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7687 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7688 DeclarationName TargetName = TargetNameInfo.getName();
7692 // Warn about access declarations.
7693 if (!HasUsingKeyword) {
7694 Diag(Name.getLocStart(),
7695 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7696 : diag::warn_access_decl_deprecated)
7697 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7700 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7701 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7704 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7705 TargetNameInfo, AttrList,
7706 /* IsInstantiation */ false,
7707 HasTypenameKeyword, TypenameLoc);
7709 PushOnScopeChains(UD, S, /*AddToContext*/ false);
7714 /// \brief Determine whether a using declaration considers the given
7715 /// declarations as "equivalent", e.g., if they are redeclarations of
7716 /// the same entity or are both typedefs of the same type.
7718 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7719 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7722 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7723 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7724 return Context.hasSameType(TD1->getUnderlyingType(),
7725 TD2->getUnderlyingType());
7731 /// Determines whether to create a using shadow decl for a particular
7732 /// decl, given the set of decls existing prior to this using lookup.
7733 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7734 const LookupResult &Previous,
7735 UsingShadowDecl *&PrevShadow) {
7736 // Diagnose finding a decl which is not from a base class of the
7737 // current class. We do this now because there are cases where this
7738 // function will silently decide not to build a shadow decl, which
7739 // will pre-empt further diagnostics.
7741 // We don't need to do this in C++0x because we do the check once on
7744 // FIXME: diagnose the following if we care enough:
7745 // struct A { int foo; };
7746 // struct B : A { using A::foo; };
7747 // template <class T> struct C : A {};
7748 // template <class T> struct D : C<T> { using B::foo; } // <---
7749 // This is invalid (during instantiation) in C++03 because B::foo
7750 // resolves to the using decl in B, which is not a base class of D<T>.
7751 // We can't diagnose it immediately because C<T> is an unknown
7752 // specialization. The UsingShadowDecl in D<T> then points directly
7753 // to A::foo, which will look well-formed when we instantiate.
7754 // The right solution is to not collapse the shadow-decl chain.
7755 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7756 DeclContext *OrigDC = Orig->getDeclContext();
7758 // Handle enums and anonymous structs.
7759 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7760 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7761 while (OrigRec->isAnonymousStructOrUnion())
7762 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7764 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7765 if (OrigDC == CurContext) {
7766 Diag(Using->getLocation(),
7767 diag::err_using_decl_nested_name_specifier_is_current_class)
7768 << Using->getQualifierLoc().getSourceRange();
7769 Diag(Orig->getLocation(), diag::note_using_decl_target);
7773 Diag(Using->getQualifierLoc().getBeginLoc(),
7774 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7775 << Using->getQualifier()
7776 << cast<CXXRecordDecl>(CurContext)
7777 << Using->getQualifierLoc().getSourceRange();
7778 Diag(Orig->getLocation(), diag::note_using_decl_target);
7783 if (Previous.empty()) return false;
7785 NamedDecl *Target = Orig;
7786 if (isa<UsingShadowDecl>(Target))
7787 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7789 // If the target happens to be one of the previous declarations, we
7790 // don't have a conflict.
7792 // FIXME: but we might be increasing its access, in which case we
7793 // should redeclare it.
7794 NamedDecl *NonTag = nullptr, *Tag = nullptr;
7795 bool FoundEquivalentDecl = false;
7796 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7798 NamedDecl *D = (*I)->getUnderlyingDecl();
7799 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7800 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7801 PrevShadow = Shadow;
7802 FoundEquivalentDecl = true;
7803 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
7804 // We don't conflict with an existing using shadow decl of an equivalent
7805 // declaration, but we're not a redeclaration of it.
7806 FoundEquivalentDecl = true;
7810 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7813 if (FoundEquivalentDecl)
7816 if (FunctionDecl *FD = Target->getAsFunction()) {
7817 NamedDecl *OldDecl = nullptr;
7818 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7819 /*IsForUsingDecl*/ true)) {
7823 case Ovl_NonFunction:
7824 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7827 // We found a decl with the exact signature.
7829 // If we're in a record, we want to hide the target, so we
7830 // return true (without a diagnostic) to tell the caller not to
7831 // build a shadow decl.
7832 if (CurContext->isRecord())
7835 // If we're not in a record, this is an error.
7836 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7840 Diag(Target->getLocation(), diag::note_using_decl_target);
7841 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7845 // Target is not a function.
7847 if (isa<TagDecl>(Target)) {
7848 // No conflict between a tag and a non-tag.
7849 if (!Tag) return false;
7851 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7852 Diag(Target->getLocation(), diag::note_using_decl_target);
7853 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7857 // No conflict between a tag and a non-tag.
7858 if (!NonTag) return false;
7860 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7861 Diag(Target->getLocation(), diag::note_using_decl_target);
7862 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7866 /// Builds a shadow declaration corresponding to a 'using' declaration.
7867 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7870 UsingShadowDecl *PrevDecl) {
7872 // If we resolved to another shadow declaration, just coalesce them.
7873 NamedDecl *Target = Orig;
7874 if (isa<UsingShadowDecl>(Target)) {
7875 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7876 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7879 UsingShadowDecl *Shadow
7880 = UsingShadowDecl::Create(Context, CurContext,
7881 UD->getLocation(), UD, Target);
7882 UD->addShadowDecl(Shadow);
7884 Shadow->setAccess(UD->getAccess());
7885 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7886 Shadow->setInvalidDecl();
7888 Shadow->setPreviousDecl(PrevDecl);
7891 PushOnScopeChains(Shadow, S);
7893 CurContext->addDecl(Shadow);
7899 /// Hides a using shadow declaration. This is required by the current
7900 /// using-decl implementation when a resolvable using declaration in a
7901 /// class is followed by a declaration which would hide or override
7902 /// one or more of the using decl's targets; for example:
7904 /// struct Base { void foo(int); };
7905 /// struct Derived : Base {
7906 /// using Base::foo;
7910 /// The governing language is C++03 [namespace.udecl]p12:
7912 /// When a using-declaration brings names from a base class into a
7913 /// derived class scope, member functions in the derived class
7914 /// override and/or hide member functions with the same name and
7915 /// parameter types in a base class (rather than conflicting).
7917 /// There are two ways to implement this:
7918 /// (1) optimistically create shadow decls when they're not hidden
7919 /// by existing declarations, or
7920 /// (2) don't create any shadow decls (or at least don't make them
7921 /// visible) until we've fully parsed/instantiated the class.
7922 /// The problem with (1) is that we might have to retroactively remove
7923 /// a shadow decl, which requires several O(n) operations because the
7924 /// decl structures are (very reasonably) not designed for removal.
7925 /// (2) avoids this but is very fiddly and phase-dependent.
7926 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7927 if (Shadow->getDeclName().getNameKind() ==
7928 DeclarationName::CXXConversionFunctionName)
7929 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7931 // Remove it from the DeclContext...
7932 Shadow->getDeclContext()->removeDecl(Shadow);
7934 // ...and the scope, if applicable...
7936 S->RemoveDecl(Shadow);
7937 IdResolver.RemoveDecl(Shadow);
7940 // ...and the using decl.
7941 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7943 // TODO: complain somehow if Shadow was used. It shouldn't
7944 // be possible for this to happen, because...?
7947 /// Find the base specifier for a base class with the given type.
7948 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7949 QualType DesiredBase,
7950 bool &AnyDependentBases) {
7951 // Check whether the named type is a direct base class.
7952 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7953 for (auto &Base : Derived->bases()) {
7954 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7955 if (CanonicalDesiredBase == BaseType)
7957 if (BaseType->isDependentType())
7958 AnyDependentBases = true;
7964 class UsingValidatorCCC : public CorrectionCandidateCallback {
7966 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7967 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7968 : HasTypenameKeyword(HasTypenameKeyword),
7969 IsInstantiation(IsInstantiation), OldNNS(NNS),
7970 RequireMemberOf(RequireMemberOf) {}
7972 bool ValidateCandidate(const TypoCorrection &Candidate) override {
7973 NamedDecl *ND = Candidate.getCorrectionDecl();
7975 // Keywords are not valid here.
7976 if (!ND || isa<NamespaceDecl>(ND))
7979 // Completely unqualified names are invalid for a 'using' declaration.
7980 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7983 if (RequireMemberOf) {
7984 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7985 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7986 // No-one ever wants a using-declaration to name an injected-class-name
7987 // of a base class, unless they're declaring an inheriting constructor.
7988 ASTContext &Ctx = ND->getASTContext();
7989 if (!Ctx.getLangOpts().CPlusPlus11)
7991 QualType FoundType = Ctx.getRecordType(FoundRecord);
7993 // Check that the injected-class-name is named as a member of its own
7994 // type; we don't want to suggest 'using Derived::Base;', since that
7995 // means something else.
7996 NestedNameSpecifier *Specifier =
7997 Candidate.WillReplaceSpecifier()
7998 ? Candidate.getCorrectionSpecifier()
8000 if (!Specifier->getAsType() ||
8001 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8004 // Check that this inheriting constructor declaration actually names a
8005 // direct base class of the current class.
8006 bool AnyDependentBases = false;
8007 if (!findDirectBaseWithType(RequireMemberOf,
8008 Ctx.getRecordType(FoundRecord),
8009 AnyDependentBases) &&
8013 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8014 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8017 // FIXME: Check that the base class member is accessible?
8020 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8021 if (FoundRecord && FoundRecord->isInjectedClassName())
8025 if (isa<TypeDecl>(ND))
8026 return HasTypenameKeyword || !IsInstantiation;
8028 return !HasTypenameKeyword;
8032 bool HasTypenameKeyword;
8033 bool IsInstantiation;
8034 NestedNameSpecifier *OldNNS;
8035 CXXRecordDecl *RequireMemberOf;
8037 } // end anonymous namespace
8039 /// Builds a using declaration.
8041 /// \param IsInstantiation - Whether this call arises from an
8042 /// instantiation of an unresolved using declaration. We treat
8043 /// the lookup differently for these declarations.
8044 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8045 SourceLocation UsingLoc,
8047 DeclarationNameInfo NameInfo,
8048 AttributeList *AttrList,
8049 bool IsInstantiation,
8050 bool HasTypenameKeyword,
8051 SourceLocation TypenameLoc) {
8052 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8053 SourceLocation IdentLoc = NameInfo.getLoc();
8054 assert(IdentLoc.isValid() && "Invalid TargetName location.");
8056 // FIXME: We ignore attributes for now.
8059 Diag(IdentLoc, diag::err_using_requires_qualname);
8063 // Do the redeclaration lookup in the current scope.
8064 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8066 Previous.setHideTags(false);
8068 LookupName(Previous, S);
8070 // It is really dumb that we have to do this.
8071 LookupResult::Filter F = Previous.makeFilter();
8072 while (F.hasNext()) {
8073 NamedDecl *D = F.next();
8074 if (!isDeclInScope(D, CurContext, S))
8076 // If we found a local extern declaration that's not ordinarily visible,
8077 // and this declaration is being added to a non-block scope, ignore it.
8078 // We're only checking for scope conflicts here, not also for violations
8079 // of the linkage rules.
8080 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8081 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8086 assert(IsInstantiation && "no scope in non-instantiation");
8087 assert(CurContext->isRecord() && "scope not record in instantiation");
8088 LookupQualifiedName(Previous, CurContext);
8091 // Check for invalid redeclarations.
8092 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8093 SS, IdentLoc, Previous))
8096 // Check for bad qualifiers.
8097 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8100 DeclContext *LookupContext = computeDeclContext(SS);
8102 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8103 if (!LookupContext) {
8104 if (HasTypenameKeyword) {
8105 // FIXME: not all declaration name kinds are legal here
8106 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8107 UsingLoc, TypenameLoc,
8109 IdentLoc, NameInfo.getName());
8111 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8112 QualifierLoc, NameInfo);
8115 CurContext->addDecl(D);
8119 auto Build = [&](bool Invalid) {
8121 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8122 HasTypenameKeyword);
8124 CurContext->addDecl(UD);
8125 UD->setInvalidDecl(Invalid);
8128 auto BuildInvalid = [&]{ return Build(true); };
8129 auto BuildValid = [&]{ return Build(false); };
8131 if (RequireCompleteDeclContext(SS, LookupContext))
8132 return BuildInvalid();
8134 // Look up the target name.
8135 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8137 // Unlike most lookups, we don't always want to hide tag
8138 // declarations: tag names are visible through the using declaration
8139 // even if hidden by ordinary names, *except* in a dependent context
8140 // where it's important for the sanity of two-phase lookup.
8141 if (!IsInstantiation)
8142 R.setHideTags(false);
8144 // For the purposes of this lookup, we have a base object type
8145 // equal to that of the current context.
8146 if (CurContext->isRecord()) {
8147 R.setBaseObjectType(
8148 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8151 LookupQualifiedName(R, LookupContext);
8153 // Try to correct typos if possible. If constructor name lookup finds no
8154 // results, that means the named class has no explicit constructors, and we
8155 // suppressed declaring implicit ones (probably because it's dependent or
8158 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8159 if (TypoCorrection Corrected = CorrectTypo(
8160 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8161 llvm::make_unique<UsingValidatorCCC>(
8162 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8163 dyn_cast<CXXRecordDecl>(CurContext)),
8164 CTK_ErrorRecovery)) {
8165 // We reject any correction for which ND would be NULL.
8166 NamedDecl *ND = Corrected.getCorrectionDecl();
8168 // We reject candidates where DroppedSpecifier == true, hence the
8169 // literal '0' below.
8170 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8171 << NameInfo.getName() << LookupContext << 0
8174 // If we corrected to an inheriting constructor, handle it as one.
8175 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8176 if (RD && RD->isInjectedClassName()) {
8177 // Fix up the information we'll use to build the using declaration.
8178 if (Corrected.WillReplaceSpecifier()) {
8179 NestedNameSpecifierLocBuilder Builder;
8180 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8181 QualifierLoc.getSourceRange());
8182 QualifierLoc = Builder.getWithLocInContext(Context);
8185 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8186 Context.getCanonicalType(Context.getRecordType(RD))));
8187 NameInfo.setNamedTypeInfo(nullptr);
8188 for (auto *Ctor : LookupConstructors(RD))
8191 // FIXME: Pick up all the declarations if we found an overloaded function.
8195 Diag(IdentLoc, diag::err_no_member)
8196 << NameInfo.getName() << LookupContext << SS.getRange();
8197 return BuildInvalid();
8201 if (R.isAmbiguous())
8202 return BuildInvalid();
8204 if (HasTypenameKeyword) {
8205 // If we asked for a typename and got a non-type decl, error out.
8206 if (!R.getAsSingle<TypeDecl>()) {
8207 Diag(IdentLoc, diag::err_using_typename_non_type);
8208 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8209 Diag((*I)->getUnderlyingDecl()->getLocation(),
8210 diag::note_using_decl_target);
8211 return BuildInvalid();
8214 // If we asked for a non-typename and we got a type, error out,
8215 // but only if this is an instantiation of an unresolved using
8216 // decl. Otherwise just silently find the type name.
8217 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8218 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8219 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8220 return BuildInvalid();
8224 // C++0x N2914 [namespace.udecl]p6:
8225 // A using-declaration shall not name a namespace.
8226 if (R.getAsSingle<NamespaceDecl>()) {
8227 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8229 return BuildInvalid();
8232 UsingDecl *UD = BuildValid();
8234 // The normal rules do not apply to inheriting constructor declarations.
8235 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8236 // Suppress access diagnostics; the access check is instead performed at the
8237 // point of use for an inheriting constructor.
8238 R.suppressDiagnostics();
8239 CheckInheritingConstructorUsingDecl(UD);
8243 // Otherwise, look up the target name.
8245 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8246 UsingShadowDecl *PrevDecl = nullptr;
8247 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8248 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8254 /// Additional checks for a using declaration referring to a constructor name.
8255 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8256 assert(!UD->hasTypename() && "expecting a constructor name");
8258 const Type *SourceType = UD->getQualifier()->getAsType();
8259 assert(SourceType &&
8260 "Using decl naming constructor doesn't have type in scope spec.");
8261 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8263 // Check whether the named type is a direct base class.
8264 bool AnyDependentBases = false;
8265 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8267 if (!Base && !AnyDependentBases) {
8268 Diag(UD->getUsingLoc(),
8269 diag::err_using_decl_constructor_not_in_direct_base)
8270 << UD->getNameInfo().getSourceRange()
8271 << QualType(SourceType, 0) << TargetClass;
8272 UD->setInvalidDecl();
8277 Base->setInheritConstructors();
8282 /// Checks that the given using declaration is not an invalid
8283 /// redeclaration. Note that this is checking only for the using decl
8284 /// itself, not for any ill-formedness among the UsingShadowDecls.
8285 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8286 bool HasTypenameKeyword,
8287 const CXXScopeSpec &SS,
8288 SourceLocation NameLoc,
8289 const LookupResult &Prev) {
8290 // C++03 [namespace.udecl]p8:
8291 // C++0x [namespace.udecl]p10:
8292 // A using-declaration is a declaration and can therefore be used
8293 // repeatedly where (and only where) multiple declarations are
8296 // That's in non-member contexts.
8297 if (!CurContext->getRedeclContext()->isRecord())
8300 NestedNameSpecifier *Qual = SS.getScopeRep();
8302 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8306 NestedNameSpecifier *DQual;
8307 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8308 DTypename = UD->hasTypename();
8309 DQual = UD->getQualifier();
8310 } else if (UnresolvedUsingValueDecl *UD
8311 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8313 DQual = UD->getQualifier();
8314 } else if (UnresolvedUsingTypenameDecl *UD
8315 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8317 DQual = UD->getQualifier();
8320 // using decls differ if one says 'typename' and the other doesn't.
8321 // FIXME: non-dependent using decls?
8322 if (HasTypenameKeyword != DTypename) continue;
8324 // using decls differ if they name different scopes (but note that
8325 // template instantiation can cause this check to trigger when it
8326 // didn't before instantiation).
8327 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8328 Context.getCanonicalNestedNameSpecifier(DQual))
8331 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8332 Diag(D->getLocation(), diag::note_using_decl) << 1;
8340 /// Checks that the given nested-name qualifier used in a using decl
8341 /// in the current context is appropriately related to the current
8342 /// scope. If an error is found, diagnoses it and returns true.
8343 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8344 const CXXScopeSpec &SS,
8345 const DeclarationNameInfo &NameInfo,
8346 SourceLocation NameLoc) {
8347 DeclContext *NamedContext = computeDeclContext(SS);
8349 if (!CurContext->isRecord()) {
8350 // C++03 [namespace.udecl]p3:
8351 // C++0x [namespace.udecl]p8:
8352 // A using-declaration for a class member shall be a member-declaration.
8354 // If we weren't able to compute a valid scope, it must be a
8355 // dependent class scope.
8356 if (!NamedContext || NamedContext->isRecord()) {
8357 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8358 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8361 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8364 // If we have a complete, non-dependent source type, try to suggest a
8365 // way to get the same effect.
8369 // Find what this using-declaration was referring to.
8370 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8371 R.setHideTags(false);
8372 R.suppressDiagnostics();
8373 LookupQualifiedName(R, RD);
8375 if (R.getAsSingle<TypeDecl>()) {
8376 if (getLangOpts().CPlusPlus11) {
8377 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8378 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8379 << 0 // alias declaration
8380 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8381 NameInfo.getName().getAsString() +
8384 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8385 SourceLocation InsertLoc =
8386 getLocForEndOfToken(NameInfo.getLocEnd());
8387 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8388 << 1 // typedef declaration
8389 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8390 << FixItHint::CreateInsertion(
8391 InsertLoc, " " + NameInfo.getName().getAsString());
8393 } else if (R.getAsSingle<VarDecl>()) {
8394 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8395 // repeating the type of the static data member here.
8397 if (getLangOpts().CPlusPlus11) {
8398 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8399 FixIt = FixItHint::CreateReplacement(
8400 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8403 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8404 << 2 // reference declaration
8410 // Otherwise, everything is known to be fine.
8414 // The current scope is a record.
8416 // If the named context is dependent, we can't decide much.
8417 if (!NamedContext) {
8418 // FIXME: in C++0x, we can diagnose if we can prove that the
8419 // nested-name-specifier does not refer to a base class, which is
8420 // still possible in some cases.
8422 // Otherwise we have to conservatively report that things might be
8427 if (!NamedContext->isRecord()) {
8428 // Ideally this would point at the last name in the specifier,
8429 // but we don't have that level of source info.
8430 Diag(SS.getRange().getBegin(),
8431 diag::err_using_decl_nested_name_specifier_is_not_class)
8432 << SS.getScopeRep() << SS.getRange();
8436 if (!NamedContext->isDependentContext() &&
8437 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8440 if (getLangOpts().CPlusPlus11) {
8441 // C++0x [namespace.udecl]p3:
8442 // In a using-declaration used as a member-declaration, the
8443 // nested-name-specifier shall name a base class of the class
8446 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8447 cast<CXXRecordDecl>(NamedContext))) {
8448 if (CurContext == NamedContext) {
8450 diag::err_using_decl_nested_name_specifier_is_current_class)
8455 Diag(SS.getRange().getBegin(),
8456 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8458 << cast<CXXRecordDecl>(CurContext)
8466 // C++03 [namespace.udecl]p4:
8467 // A using-declaration used as a member-declaration shall refer
8468 // to a member of a base class of the class being defined [etc.].
8470 // Salient point: SS doesn't have to name a base class as long as
8471 // lookup only finds members from base classes. Therefore we can
8472 // diagnose here only if we can prove that that can't happen,
8473 // i.e. if the class hierarchies provably don't intersect.
8475 // TODO: it would be nice if "definitely valid" results were cached
8476 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8477 // need to be repeated.
8479 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8480 auto Collect = [&Bases](const CXXRecordDecl *Base) {
8485 // Collect all bases. Return false if we find a dependent base.
8486 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
8489 // Returns true if the base is dependent or is one of the accumulated base
8491 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8492 return !Bases.count(Base);
8495 // Return false if the class has a dependent base or if it or one
8496 // of its bases is present in the base set of the current context.
8497 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8498 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
8501 Diag(SS.getRange().getBegin(),
8502 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8504 << cast<CXXRecordDecl>(CurContext)
8510 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8512 MultiTemplateParamsArg TemplateParamLists,
8513 SourceLocation UsingLoc,
8514 UnqualifiedId &Name,
8515 AttributeList *AttrList,
8517 Decl *DeclFromDeclSpec) {
8518 // Skip up to the relevant declaration scope.
8519 while (S->isTemplateParamScope())
8521 assert((S->getFlags() & Scope::DeclScope) &&
8522 "got alias-declaration outside of declaration scope");
8524 if (Type.isInvalid())
8527 bool Invalid = false;
8528 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8529 TypeSourceInfo *TInfo = nullptr;
8530 GetTypeFromParser(Type.get(), &TInfo);
8532 if (DiagnoseClassNameShadow(CurContext, NameInfo))
8535 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8536 UPPC_DeclarationType)) {
8538 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8539 TInfo->getTypeLoc().getBeginLoc());
8542 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8543 LookupName(Previous, S);
8545 // Warn about shadowing the name of a template parameter.
8546 if (Previous.isSingleResult() &&
8547 Previous.getFoundDecl()->isTemplateParameter()) {
8548 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8552 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8553 "name in alias declaration must be an identifier");
8554 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8556 Name.Identifier, TInfo);
8558 NewTD->setAccess(AS);
8561 NewTD->setInvalidDecl();
8563 ProcessDeclAttributeList(S, NewTD, AttrList);
8565 CheckTypedefForVariablyModifiedType(S, NewTD);
8566 Invalid |= NewTD->isInvalidDecl();
8568 bool Redeclaration = false;
8571 if (TemplateParamLists.size()) {
8572 TypeAliasTemplateDecl *OldDecl = nullptr;
8573 TemplateParameterList *OldTemplateParams = nullptr;
8575 if (TemplateParamLists.size() != 1) {
8576 Diag(UsingLoc, diag::err_alias_template_extra_headers)
8577 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8578 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8580 TemplateParameterList *TemplateParams = TemplateParamLists[0];
8582 // Only consider previous declarations in the same scope.
8583 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8584 /*ExplicitInstantiationOrSpecialization*/false);
8585 if (!Previous.empty()) {
8586 Redeclaration = true;
8588 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8589 if (!OldDecl && !Invalid) {
8590 Diag(UsingLoc, diag::err_redefinition_different_kind)
8593 NamedDecl *OldD = Previous.getRepresentativeDecl();
8594 if (OldD->getLocation().isValid())
8595 Diag(OldD->getLocation(), diag::note_previous_definition);
8600 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8601 if (TemplateParameterListsAreEqual(TemplateParams,
8602 OldDecl->getTemplateParameters(),
8605 OldTemplateParams = OldDecl->getTemplateParameters();
8609 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8611 !Context.hasSameType(OldTD->getUnderlyingType(),
8612 NewTD->getUnderlyingType())) {
8613 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8614 // but we can't reasonably accept it.
8615 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8616 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8617 if (OldTD->getLocation().isValid())
8618 Diag(OldTD->getLocation(), diag::note_previous_definition);
8624 // Merge any previous default template arguments into our parameters,
8625 // and check the parameter list.
8626 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8627 TPC_TypeAliasTemplate))
8630 TypeAliasTemplateDecl *NewDecl =
8631 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8632 Name.Identifier, TemplateParams,
8634 NewTD->setDescribedAliasTemplate(NewDecl);
8636 NewDecl->setAccess(AS);
8639 NewDecl->setInvalidDecl();
8641 NewDecl->setPreviousDecl(OldDecl);
8645 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8646 setTagNameForLinkagePurposes(TD, NewTD);
8647 handleTagNumbering(TD, S);
8649 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8654 PushOnScopeChains(NewND, S);
8656 ActOnDocumentableDecl(NewND);
8660 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8661 SourceLocation AliasLoc,
8662 IdentifierInfo *Alias, CXXScopeSpec &SS,
8663 SourceLocation IdentLoc,
8664 IdentifierInfo *Ident) {
8666 // Lookup the namespace name.
8667 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8668 LookupParsedName(R, S, &SS);
8670 if (R.isAmbiguous())
8674 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8675 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8679 assert(!R.isAmbiguous() && !R.empty());
8680 NamedDecl *ND = R.getRepresentativeDecl();
8682 // Check if we have a previous declaration with the same name.
8683 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8685 LookupName(PrevR, S);
8687 // Check we're not shadowing a template parameter.
8688 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8689 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8693 // Filter out any other lookup result from an enclosing scope.
8694 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8695 /*AllowInlineNamespace*/false);
8697 // Find the previous declaration and check that we can redeclare it.
8698 NamespaceAliasDecl *Prev = nullptr;
8699 if (PrevR.isSingleResult()) {
8700 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
8701 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8702 // We already have an alias with the same name that points to the same
8703 // namespace; check that it matches.
8704 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8706 } else if (isVisible(PrevDecl)) {
8707 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8709 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
8710 << AD->getNamespace();
8713 } else if (isVisible(PrevDecl)) {
8714 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
8715 ? diag::err_redefinition
8716 : diag::err_redefinition_different_kind;
8717 Diag(AliasLoc, DiagID) << Alias;
8718 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8723 // The use of a nested name specifier may trigger deprecation warnings.
8724 DiagnoseUseOfDecl(ND, IdentLoc);
8726 NamespaceAliasDecl *AliasDecl =
8727 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8728 Alias, SS.getWithLocInContext(Context),
8731 AliasDecl->setPreviousDecl(Prev);
8733 PushOnScopeChains(AliasDecl, S);
8737 Sema::ImplicitExceptionSpecification
8738 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8739 CXXMethodDecl *MD) {
8740 CXXRecordDecl *ClassDecl = MD->getParent();
8742 // C++ [except.spec]p14:
8743 // An implicitly declared special member function (Clause 12) shall have an
8744 // exception-specification. [...]
8745 ImplicitExceptionSpecification ExceptSpec(*this);
8746 if (ClassDecl->isInvalidDecl())
8749 // Direct base-class constructors.
8750 for (const auto &B : ClassDecl->bases()) {
8751 if (B.isVirtual()) // Handled below.
8754 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8755 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8756 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8757 // If this is a deleted function, add it anyway. This might be conformant
8758 // with the standard. This might not. I'm not sure. It might not matter.
8760 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8764 // Virtual base-class constructors.
8765 for (const auto &B : ClassDecl->vbases()) {
8766 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8767 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8768 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8769 // If this is a deleted function, add it anyway. This might be conformant
8770 // with the standard. This might not. I'm not sure. It might not matter.
8772 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8776 // Field constructors.
8777 for (const auto *F : ClassDecl->fields()) {
8778 if (F->hasInClassInitializer()) {
8779 if (Expr *E = F->getInClassInitializer())
8780 ExceptSpec.CalledExpr(E);
8781 } else if (const RecordType *RecordTy
8782 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8783 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8784 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8785 // If this is a deleted function, add it anyway. This might be conformant
8786 // with the standard. This might not. I'm not sure. It might not matter.
8787 // In particular, the problem is that this function never gets called. It
8788 // might just be ill-formed because this function attempts to refer to
8789 // a deleted function here.
8791 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8798 Sema::ImplicitExceptionSpecification
8799 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8800 CXXRecordDecl *ClassDecl = CD->getParent();
8802 // C++ [except.spec]p14:
8803 // An inheriting constructor [...] shall have an exception-specification. [...]
8804 ImplicitExceptionSpecification ExceptSpec(*this);
8805 if (ClassDecl->isInvalidDecl())
8808 // Inherited constructor.
8809 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8810 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8811 // FIXME: Copying or moving the parameters could add extra exceptions to the
8812 // set, as could the default arguments for the inherited constructor. This
8813 // will be addressed when we implement the resolution of core issue 1351.
8814 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8816 // Direct base-class constructors.
8817 for (const auto &B : ClassDecl->bases()) {
8818 if (B.isVirtual()) // Handled below.
8821 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8822 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8823 if (BaseClassDecl == InheritedDecl)
8825 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8827 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8831 // Virtual base-class constructors.
8832 for (const auto &B : ClassDecl->vbases()) {
8833 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8834 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8835 if (BaseClassDecl == InheritedDecl)
8837 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8839 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8843 // Field constructors.
8844 for (const auto *F : ClassDecl->fields()) {
8845 if (F->hasInClassInitializer()) {
8846 if (Expr *E = F->getInClassInitializer())
8847 ExceptSpec.CalledExpr(E);
8848 } else if (const RecordType *RecordTy
8849 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8850 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8851 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8853 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8861 /// RAII object to register a special member as being currently declared.
8862 struct DeclaringSpecialMember {
8864 Sema::SpecialMemberDecl D;
8865 bool WasAlreadyBeingDeclared;
8867 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8868 : S(S), D(RD, CSM) {
8869 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8870 if (WasAlreadyBeingDeclared)
8871 // This almost never happens, but if it does, ensure that our cache
8872 // doesn't contain a stale result.
8873 S.SpecialMemberCache.clear();
8875 // FIXME: Register a note to be produced if we encounter an error while
8876 // declaring the special member.
8878 ~DeclaringSpecialMember() {
8879 if (!WasAlreadyBeingDeclared)
8880 S.SpecialMembersBeingDeclared.erase(D);
8883 /// \brief Are we already trying to declare this special member?
8884 bool isAlreadyBeingDeclared() const {
8885 return WasAlreadyBeingDeclared;
8890 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8891 CXXRecordDecl *ClassDecl) {
8892 // C++ [class.ctor]p5:
8893 // A default constructor for a class X is a constructor of class X
8894 // that can be called without an argument. If there is no
8895 // user-declared constructor for class X, a default constructor is
8896 // implicitly declared. An implicitly-declared default constructor
8897 // is an inline public member of its class.
8898 assert(ClassDecl->needsImplicitDefaultConstructor() &&
8899 "Should not build implicit default constructor!");
8901 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8902 if (DSM.isAlreadyBeingDeclared())
8905 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8906 CXXDefaultConstructor,
8909 // Create the actual constructor declaration.
8910 CanQualType ClassType
8911 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8912 SourceLocation ClassLoc = ClassDecl->getLocation();
8913 DeclarationName Name
8914 = Context.DeclarationNames.getCXXConstructorName(ClassType);
8915 DeclarationNameInfo NameInfo(Name, ClassLoc);
8916 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8917 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8918 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8919 /*isImplicitlyDeclared=*/true, Constexpr);
8920 DefaultCon->setAccess(AS_public);
8921 DefaultCon->setDefaulted();
8923 if (getLangOpts().CUDA) {
8924 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8926 /* ConstRHS */ false,
8927 /* Diagnose */ false);
8930 // Build an exception specification pointing back at this constructor.
8931 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8932 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8934 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8935 // constructors is easy to compute.
8936 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8938 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8939 SetDeclDeleted(DefaultCon, ClassLoc);
8941 // Note that we have declared this constructor.
8942 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8944 if (Scope *S = getScopeForContext(ClassDecl))
8945 PushOnScopeChains(DefaultCon, S, false);
8946 ClassDecl->addDecl(DefaultCon);
8951 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8952 CXXConstructorDecl *Constructor) {
8953 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8954 !Constructor->doesThisDeclarationHaveABody() &&
8955 !Constructor->isDeleted()) &&
8956 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8958 CXXRecordDecl *ClassDecl = Constructor->getParent();
8959 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8961 SynthesizedFunctionScope Scope(*this, Constructor);
8962 DiagnosticErrorTrap Trap(Diags);
8963 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8964 Trap.hasErrorOccurred()) {
8965 Diag(CurrentLocation, diag::note_member_synthesized_at)
8966 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8967 Constructor->setInvalidDecl();
8971 // The exception specification is needed because we are defining the
8973 ResolveExceptionSpec(CurrentLocation,
8974 Constructor->getType()->castAs<FunctionProtoType>());
8976 SourceLocation Loc = Constructor->getLocEnd().isValid()
8977 ? Constructor->getLocEnd()
8978 : Constructor->getLocation();
8979 Constructor->setBody(new (Context) CompoundStmt(Loc));
8981 Constructor->markUsed(Context);
8982 MarkVTableUsed(CurrentLocation, ClassDecl);
8984 if (ASTMutationListener *L = getASTMutationListener()) {
8985 L->CompletedImplicitDefinition(Constructor);
8988 DiagnoseUninitializedFields(*this, Constructor);
8991 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8992 // Perform any delayed checks on exception specifications.
8993 CheckDelayedMemberExceptionSpecs();
8997 /// Information on inheriting constructors to declare.
8998 class InheritingConstructorInfo {
9000 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
9001 : SemaRef(SemaRef), Derived(Derived) {
9002 // Mark the constructors that we already have in the derived class.
9004 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9005 // unless there is a user-declared constructor with the same signature in
9006 // the class where the using-declaration appears.
9007 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9010 void inheritAll(CXXRecordDecl *RD) {
9011 visitAll(RD, &InheritingConstructorInfo::inherit);
9015 /// Information about an inheriting constructor.
9016 struct InheritingConstructor {
9017 InheritingConstructor()
9018 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9020 /// If \c true, a constructor with this signature is already declared
9021 /// in the derived class.
9022 bool DeclaredInDerived;
9024 /// The constructor which is inherited.
9025 const CXXConstructorDecl *BaseCtor;
9027 /// The derived constructor we declared.
9028 CXXConstructorDecl *DerivedCtor;
9031 /// Inheriting constructors with a given canonical type. There can be at
9032 /// most one such non-template constructor, and any number of templated
9034 struct InheritingConstructorsForType {
9035 InheritingConstructor NonTemplate;
9036 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9039 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9040 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9041 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9042 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9043 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9044 false, S.TPL_TemplateMatch))
9045 return Templates[I].second;
9046 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9047 return Templates.back().second;
9054 /// Get or create the inheriting constructor record for a constructor.
9055 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9056 QualType CtorType) {
9057 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9058 .getEntry(SemaRef, Ctor);
9061 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9063 /// Process all constructors for a class.
9064 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9065 for (const auto *Ctor : RD->ctors())
9066 (this->*Callback)(Ctor);
9067 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9068 I(RD->decls_begin()), E(RD->decls_end());
9070 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9071 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9072 (this->*Callback)(CD);
9076 /// Note that a constructor (or constructor template) was declared in Derived.
9077 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9078 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9081 /// Inherit a single constructor.
9082 void inherit(const CXXConstructorDecl *Ctor) {
9083 const FunctionProtoType *CtorType =
9084 Ctor->getType()->castAs<FunctionProtoType>();
9085 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9086 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9088 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9090 // Core issue (no number yet): the ellipsis is always discarded.
9092 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9093 SemaRef.Diag(Ctor->getLocation(),
9094 diag::note_using_decl_constructor_ellipsis);
9095 EPI.Variadic = false;
9098 // Declare a constructor for each number of parameters.
9100 // C++11 [class.inhctor]p1:
9101 // The candidate set of inherited constructors from the class X named in
9102 // the using-declaration consists of [... modulo defects ...] for each
9103 // constructor or constructor template of X, the set of constructors or
9104 // constructor templates that results from omitting any ellipsis parameter
9105 // specification and successively omitting parameters with a default
9106 // argument from the end of the parameter-type-list
9107 unsigned MinParams = minParamsToInherit(Ctor);
9108 unsigned Params = Ctor->getNumParams();
9109 if (Params >= MinParams) {
9111 declareCtor(UsingLoc, Ctor,
9112 SemaRef.Context.getFunctionType(
9113 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9114 while (Params > MinParams &&
9115 Ctor->getParamDecl(--Params)->hasDefaultArg());
9119 /// Find the using-declaration which specified that we should inherit the
9120 /// constructors of \p Base.
9121 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9122 // No fancy lookup required; just look for the base constructor name
9123 // directly within the derived class.
9124 ASTContext &Context = SemaRef.Context;
9125 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9126 Context.getCanonicalType(Context.getRecordType(Base)));
9127 DeclContext::lookup_result Decls = Derived->lookup(Name);
9128 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9131 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9132 // C++11 [class.inhctor]p3:
9133 // [F]or each constructor template in the candidate set of inherited
9134 // constructors, a constructor template is implicitly declared
9135 if (Ctor->getDescribedFunctionTemplate())
9138 // For each non-template constructor in the candidate set of inherited
9139 // constructors other than a constructor having no parameters or a
9140 // copy/move constructor having a single parameter, a constructor is
9141 // implicitly declared [...]
9142 if (Ctor->getNumParams() == 0)
9144 if (Ctor->isCopyOrMoveConstructor())
9147 // Per discussion on core reflector, never inherit a constructor which
9148 // would become a default, copy, or move constructor of Derived either.
9149 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9150 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9151 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9154 /// Declare a single inheriting constructor, inheriting the specified
9155 /// constructor, with the given type.
9156 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9157 QualType DerivedType) {
9158 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9160 // C++11 [class.inhctor]p3:
9161 // ... a constructor is implicitly declared with the same constructor
9162 // characteristics unless there is a user-declared constructor with
9163 // the same signature in the class where the using-declaration appears
9164 if (Entry.DeclaredInDerived)
9167 // C++11 [class.inhctor]p7:
9168 // If two using-declarations declare inheriting constructors with the
9169 // same signature, the program is ill-formed
9170 if (Entry.DerivedCtor) {
9171 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9172 // Only diagnose this once per constructor.
9173 if (Entry.DerivedCtor->isInvalidDecl())
9175 Entry.DerivedCtor->setInvalidDecl();
9177 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9178 SemaRef.Diag(BaseCtor->getLocation(),
9179 diag::note_using_decl_constructor_conflict_current_ctor);
9180 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9181 diag::note_using_decl_constructor_conflict_previous_ctor);
9182 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9183 diag::note_using_decl_constructor_conflict_previous_using);
9185 // Core issue (no number): if the same inheriting constructor is
9186 // produced by multiple base class constructors from the same base
9187 // class, the inheriting constructor is defined as deleted.
9188 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9194 ASTContext &Context = SemaRef.Context;
9195 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9196 Context.getCanonicalType(Context.getRecordType(Derived)));
9197 DeclarationNameInfo NameInfo(Name, UsingLoc);
9199 TemplateParameterList *TemplateParams = nullptr;
9200 if (const FunctionTemplateDecl *FTD =
9201 BaseCtor->getDescribedFunctionTemplate()) {
9202 TemplateParams = FTD->getTemplateParameters();
9203 // We're reusing template parameters from a different DeclContext. This
9204 // is questionable at best, but works out because the template depth in
9205 // both places is guaranteed to be 0.
9206 // FIXME: Rebuild the template parameters in the new context, and
9207 // transform the function type to refer to them.
9210 // Build type source info pointing at the using-declaration. This is
9211 // required by template instantiation.
9212 TypeSourceInfo *TInfo =
9213 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9214 FunctionProtoTypeLoc ProtoLoc =
9215 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9217 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9218 Context, Derived, UsingLoc, NameInfo, DerivedType,
9219 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9220 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9222 // Build an unevaluated exception specification for this constructor.
9223 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9224 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9225 EPI.ExceptionSpec.Type = EST_Unevaluated;
9226 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9227 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9228 FPT->getParamTypes(), EPI));
9230 // Build the parameter declarations.
9231 SmallVector<ParmVarDecl *, 16> ParamDecls;
9232 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9233 TypeSourceInfo *TInfo =
9234 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9235 ParmVarDecl *PD = ParmVarDecl::Create(
9236 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9237 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9238 PD->setScopeInfo(0, I);
9240 ParamDecls.push_back(PD);
9241 ProtoLoc.setParam(I, PD);
9244 // Set up the new constructor.
9245 DerivedCtor->setAccess(BaseCtor->getAccess());
9246 DerivedCtor->setParams(ParamDecls);
9247 DerivedCtor->setInheritedConstructor(BaseCtor);
9248 if (BaseCtor->isDeleted())
9249 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9251 // If this is a constructor template, build the template declaration.
9252 if (TemplateParams) {
9253 FunctionTemplateDecl *DerivedTemplate =
9254 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9255 TemplateParams, DerivedCtor);
9256 DerivedTemplate->setAccess(BaseCtor->getAccess());
9257 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9258 Derived->addDecl(DerivedTemplate);
9260 Derived->addDecl(DerivedCtor);
9263 Entry.BaseCtor = BaseCtor;
9264 Entry.DerivedCtor = DerivedCtor;
9268 CXXRecordDecl *Derived;
9269 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9274 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9275 // Defer declaring the inheriting constructors until the class is
9277 if (ClassDecl->isDependentContext())
9280 // Find base classes from which we might inherit constructors.
9281 SmallVector<CXXRecordDecl*, 4> InheritedBases;
9282 for (const auto &BaseIt : ClassDecl->bases())
9283 if (BaseIt.getInheritConstructors())
9284 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9286 // Go no further if we're not inheriting any constructors.
9287 if (InheritedBases.empty())
9290 // Declare the inherited constructors.
9291 InheritingConstructorInfo ICI(*this, ClassDecl);
9292 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9293 ICI.inheritAll(InheritedBases[I]);
9296 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9297 CXXConstructorDecl *Constructor) {
9298 CXXRecordDecl *ClassDecl = Constructor->getParent();
9299 assert(Constructor->getInheritedConstructor() &&
9300 !Constructor->doesThisDeclarationHaveABody() &&
9301 !Constructor->isDeleted());
9303 SynthesizedFunctionScope Scope(*this, Constructor);
9304 DiagnosticErrorTrap Trap(Diags);
9305 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9306 Trap.hasErrorOccurred()) {
9307 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9308 << Context.getTagDeclType(ClassDecl);
9309 Constructor->setInvalidDecl();
9313 SourceLocation Loc = Constructor->getLocation();
9314 Constructor->setBody(new (Context) CompoundStmt(Loc));
9316 Constructor->markUsed(Context);
9317 MarkVTableUsed(CurrentLocation, ClassDecl);
9319 if (ASTMutationListener *L = getASTMutationListener()) {
9320 L->CompletedImplicitDefinition(Constructor);
9325 Sema::ImplicitExceptionSpecification
9326 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9327 CXXRecordDecl *ClassDecl = MD->getParent();
9329 // C++ [except.spec]p14:
9330 // An implicitly declared special member function (Clause 12) shall have
9331 // an exception-specification.
9332 ImplicitExceptionSpecification ExceptSpec(*this);
9333 if (ClassDecl->isInvalidDecl())
9336 // Direct base-class destructors.
9337 for (const auto &B : ClassDecl->bases()) {
9338 if (B.isVirtual()) // Handled below.
9341 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9342 ExceptSpec.CalledDecl(B.getLocStart(),
9343 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9346 // Virtual base-class destructors.
9347 for (const auto &B : ClassDecl->vbases()) {
9348 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9349 ExceptSpec.CalledDecl(B.getLocStart(),
9350 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9353 // Field destructors.
9354 for (const auto *F : ClassDecl->fields()) {
9355 if (const RecordType *RecordTy
9356 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9357 ExceptSpec.CalledDecl(F->getLocation(),
9358 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9364 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9365 // C++ [class.dtor]p2:
9366 // If a class has no user-declared destructor, a destructor is
9367 // declared implicitly. An implicitly-declared destructor is an
9368 // inline public member of its class.
9369 assert(ClassDecl->needsImplicitDestructor());
9371 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9372 if (DSM.isAlreadyBeingDeclared())
9375 // Create the actual destructor declaration.
9376 CanQualType ClassType
9377 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9378 SourceLocation ClassLoc = ClassDecl->getLocation();
9379 DeclarationName Name
9380 = Context.DeclarationNames.getCXXDestructorName(ClassType);
9381 DeclarationNameInfo NameInfo(Name, ClassLoc);
9382 CXXDestructorDecl *Destructor
9383 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9384 QualType(), nullptr, /*isInline=*/true,
9385 /*isImplicitlyDeclared=*/true);
9386 Destructor->setAccess(AS_public);
9387 Destructor->setDefaulted();
9389 if (getLangOpts().CUDA) {
9390 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9392 /* ConstRHS */ false,
9393 /* Diagnose */ false);
9396 // Build an exception specification pointing back at this destructor.
9397 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9398 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9400 AddOverriddenMethods(ClassDecl, Destructor);
9402 // We don't need to use SpecialMemberIsTrivial here; triviality for
9403 // destructors is easy to compute.
9404 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9406 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9407 SetDeclDeleted(Destructor, ClassLoc);
9409 // Note that we have declared this destructor.
9410 ++ASTContext::NumImplicitDestructorsDeclared;
9412 // Introduce this destructor into its scope.
9413 if (Scope *S = getScopeForContext(ClassDecl))
9414 PushOnScopeChains(Destructor, S, false);
9415 ClassDecl->addDecl(Destructor);
9420 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9421 CXXDestructorDecl *Destructor) {
9422 assert((Destructor->isDefaulted() &&
9423 !Destructor->doesThisDeclarationHaveABody() &&
9424 !Destructor->isDeleted()) &&
9425 "DefineImplicitDestructor - call it for implicit default dtor");
9426 CXXRecordDecl *ClassDecl = Destructor->getParent();
9427 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9429 if (Destructor->isInvalidDecl())
9432 SynthesizedFunctionScope Scope(*this, Destructor);
9434 DiagnosticErrorTrap Trap(Diags);
9435 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9436 Destructor->getParent());
9438 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9439 Diag(CurrentLocation, diag::note_member_synthesized_at)
9440 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9442 Destructor->setInvalidDecl();
9446 // The exception specification is needed because we are defining the
9448 ResolveExceptionSpec(CurrentLocation,
9449 Destructor->getType()->castAs<FunctionProtoType>());
9451 SourceLocation Loc = Destructor->getLocEnd().isValid()
9452 ? Destructor->getLocEnd()
9453 : Destructor->getLocation();
9454 Destructor->setBody(new (Context) CompoundStmt(Loc));
9455 Destructor->markUsed(Context);
9456 MarkVTableUsed(CurrentLocation, ClassDecl);
9458 if (ASTMutationListener *L = getASTMutationListener()) {
9459 L->CompletedImplicitDefinition(Destructor);
9463 /// \brief Perform any semantic analysis which needs to be delayed until all
9464 /// pending class member declarations have been parsed.
9465 void Sema::ActOnFinishCXXMemberDecls() {
9466 // If the context is an invalid C++ class, just suppress these checks.
9467 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9468 if (Record->isInvalidDecl()) {
9469 DelayedDefaultedMemberExceptionSpecs.clear();
9470 DelayedExceptionSpecChecks.clear();
9476 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9477 // Don't do anything for template patterns.
9478 if (Class->getDescribedClassTemplate())
9481 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
9482 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
9484 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
9485 for (Decl *Member : Class->decls()) {
9486 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9488 // Recurse on nested classes.
9489 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9490 getDefaultArgExprsForConstructors(S, NestedRD);
9492 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9496 CallingConv ActualCallingConv =
9497 CD->getType()->getAs<FunctionProtoType>()->getCallConv();
9499 // Skip default constructors with typical calling conventions and no default
9501 unsigned NumParams = CD->getNumParams();
9502 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
9505 if (LastExportedDefaultCtor) {
9506 S.Diag(LastExportedDefaultCtor->getLocation(),
9507 diag::err_attribute_dll_ambiguous_default_ctor) << Class;
9508 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
9509 << CD->getDeclName();
9512 LastExportedDefaultCtor = CD;
9514 for (unsigned I = 0; I != NumParams; ++I) {
9515 // Skip any default arguments that we've already instantiated.
9516 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9519 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9520 CD->getParamDecl(I)).get();
9521 S.DiscardCleanupsInEvaluationContext();
9522 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9527 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
9528 auto *RD = dyn_cast<CXXRecordDecl>(D);
9530 // Default constructors that are annotated with __declspec(dllexport) which
9531 // have default arguments or don't use the standard calling convention are
9532 // wrapped with a thunk called the default constructor closure.
9533 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9534 getDefaultArgExprsForConstructors(*this, RD);
9536 if (!DelayedDllExportClasses.empty()) {
9537 // Calling ReferenceDllExportedMethods might cause the current function to
9538 // be called again, so use a local copy of DelayedDllExportClasses.
9539 SmallVector<CXXRecordDecl *, 4> WorkList;
9540 std::swap(DelayedDllExportClasses, WorkList);
9541 for (CXXRecordDecl *Class : WorkList)
9542 ReferenceDllExportedMethods(*this, Class);
9546 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9547 CXXDestructorDecl *Destructor) {
9548 assert(getLangOpts().CPlusPlus11 &&
9549 "adjusting dtor exception specs was introduced in c++11");
9551 // C++11 [class.dtor]p3:
9552 // A declaration of a destructor that does not have an exception-
9553 // specification is implicitly considered to have the same exception-
9554 // specification as an implicit declaration.
9555 const FunctionProtoType *DtorType = Destructor->getType()->
9556 getAs<FunctionProtoType>();
9557 if (DtorType->hasExceptionSpec())
9560 // Replace the destructor's type, building off the existing one. Fortunately,
9561 // the only thing of interest in the destructor type is its extended info.
9562 // The return and arguments are fixed.
9563 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9564 EPI.ExceptionSpec.Type = EST_Unevaluated;
9565 EPI.ExceptionSpec.SourceDecl = Destructor;
9566 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9568 // FIXME: If the destructor has a body that could throw, and the newly created
9569 // spec doesn't allow exceptions, we should emit a warning, because this
9570 // change in behavior can break conforming C++03 programs at runtime.
9571 // However, we don't have a body or an exception specification yet, so it
9572 // needs to be done somewhere else.
9576 /// \brief An abstract base class for all helper classes used in building the
9577 // copy/move operators. These classes serve as factory functions and help us
9578 // avoid using the same Expr* in the AST twice.
9580 ExprBuilder(const ExprBuilder&) = delete;
9581 ExprBuilder &operator=(const ExprBuilder&) = delete;
9584 static Expr *assertNotNull(Expr *E) {
9585 assert(E && "Expression construction must not fail.");
9591 virtual ~ExprBuilder() {}
9593 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9596 class RefBuilder: public ExprBuilder {
9601 Expr *build(Sema &S, SourceLocation Loc) const override {
9602 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9605 RefBuilder(VarDecl *Var, QualType VarType)
9606 : Var(Var), VarType(VarType) {}
9609 class ThisBuilder: public ExprBuilder {
9611 Expr *build(Sema &S, SourceLocation Loc) const override {
9612 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9616 class CastBuilder: public ExprBuilder {
9617 const ExprBuilder &Builder;
9620 const CXXCastPath &Path;
9623 Expr *build(Sema &S, SourceLocation Loc) const override {
9624 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9625 CK_UncheckedDerivedToBase, Kind,
9629 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9630 const CXXCastPath &Path)
9631 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9634 class DerefBuilder: public ExprBuilder {
9635 const ExprBuilder &Builder;
9638 Expr *build(Sema &S, SourceLocation Loc) const override {
9639 return assertNotNull(
9640 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9643 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9646 class MemberBuilder: public ExprBuilder {
9647 const ExprBuilder &Builder;
9651 LookupResult &MemberLookup;
9654 Expr *build(Sema &S, SourceLocation Loc) const override {
9655 return assertNotNull(S.BuildMemberReferenceExpr(
9656 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9657 nullptr, MemberLookup, nullptr, nullptr).get());
9660 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9661 LookupResult &MemberLookup)
9662 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9663 MemberLookup(MemberLookup) {}
9666 class MoveCastBuilder: public ExprBuilder {
9667 const ExprBuilder &Builder;
9670 Expr *build(Sema &S, SourceLocation Loc) const override {
9671 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9674 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9677 class LvalueConvBuilder: public ExprBuilder {
9678 const ExprBuilder &Builder;
9681 Expr *build(Sema &S, SourceLocation Loc) const override {
9682 return assertNotNull(
9683 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9686 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9689 class SubscriptBuilder: public ExprBuilder {
9690 const ExprBuilder &Base;
9691 const ExprBuilder &Index;
9694 Expr *build(Sema &S, SourceLocation Loc) const override {
9695 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9696 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9699 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9700 : Base(Base), Index(Index) {}
9703 } // end anonymous namespace
9705 /// When generating a defaulted copy or move assignment operator, if a field
9706 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9707 /// do so. This optimization only applies for arrays of scalars, and for arrays
9708 /// of class type where the selected copy/move-assignment operator is trivial.
9710 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9711 const ExprBuilder &ToB, const ExprBuilder &FromB) {
9712 // Compute the size of the memory buffer to be copied.
9713 QualType SizeType = S.Context.getSizeType();
9714 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9715 S.Context.getTypeSizeInChars(T).getQuantity());
9717 // Take the address of the field references for "from" and "to". We
9718 // directly construct UnaryOperators here because semantic analysis
9719 // does not permit us to take the address of an xvalue.
9720 Expr *From = FromB.build(S, Loc);
9721 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9722 S.Context.getPointerType(From->getType()),
9723 VK_RValue, OK_Ordinary, Loc);
9724 Expr *To = ToB.build(S, Loc);
9725 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9726 S.Context.getPointerType(To->getType()),
9727 VK_RValue, OK_Ordinary, Loc);
9729 const Type *E = T->getBaseElementTypeUnsafe();
9730 bool NeedsCollectableMemCpy =
9731 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9733 // Create a reference to the __builtin_objc_memmove_collectable function
9734 StringRef MemCpyName = NeedsCollectableMemCpy ?
9735 "__builtin_objc_memmove_collectable" :
9737 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9738 Sema::LookupOrdinaryName);
9739 S.LookupName(R, S.TUScope, true);
9741 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9743 // Something went horribly wrong earlier, and we will have complained
9747 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9748 VK_RValue, Loc, nullptr);
9749 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9751 Expr *CallArgs[] = {
9752 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9754 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9755 Loc, CallArgs, Loc);
9757 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9758 return Call.getAs<Stmt>();
9761 /// \brief Builds a statement that copies/moves the given entity from \p From to
9764 /// This routine is used to copy/move the members of a class with an
9765 /// implicitly-declared copy/move assignment operator. When the entities being
9766 /// copied are arrays, this routine builds for loops to copy them.
9768 /// \param S The Sema object used for type-checking.
9770 /// \param Loc The location where the implicit copy/move is being generated.
9772 /// \param T The type of the expressions being copied/moved. Both expressions
9773 /// must have this type.
9775 /// \param To The expression we are copying/moving to.
9777 /// \param From The expression we are copying/moving from.
9779 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9780 /// Otherwise, it's a non-static member subobject.
9782 /// \param Copying Whether we're copying or moving.
9784 /// \param Depth Internal parameter recording the depth of the recursion.
9786 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9787 /// if a memcpy should be used instead.
9789 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9790 const ExprBuilder &To, const ExprBuilder &From,
9791 bool CopyingBaseSubobject, bool Copying,
9792 unsigned Depth = 0) {
9793 // C++11 [class.copy]p28:
9794 // Each subobject is assigned in the manner appropriate to its type:
9796 // - if the subobject is of class type, as if by a call to operator= with
9797 // the subobject as the object expression and the corresponding
9798 // subobject of x as a single function argument (as if by explicit
9799 // qualification; that is, ignoring any possible virtual overriding
9800 // functions in more derived classes);
9802 // C++03 [class.copy]p13:
9803 // - if the subobject is of class type, the copy assignment operator for
9804 // the class is used (as if by explicit qualification; that is,
9805 // ignoring any possible virtual overriding functions in more derived
9807 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9808 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9810 // Look for operator=.
9811 DeclarationName Name
9812 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9813 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9814 S.LookupQualifiedName(OpLookup, ClassDecl, false);
9816 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9818 if (!S.getLangOpts().CPlusPlus11) {
9819 LookupResult::Filter F = OpLookup.makeFilter();
9820 while (F.hasNext()) {
9821 NamedDecl *D = F.next();
9822 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9823 if (Method->isCopyAssignmentOperator() ||
9824 (!Copying && Method->isMoveAssignmentOperator()))
9832 // Suppress the protected check (C++ [class.protected]) for each of the
9833 // assignment operators we found. This strange dance is required when
9834 // we're assigning via a base classes's copy-assignment operator. To
9835 // ensure that we're getting the right base class subobject (without
9836 // ambiguities), we need to cast "this" to that subobject type; to
9837 // ensure that we don't go through the virtual call mechanism, we need
9838 // to qualify the operator= name with the base class (see below). However,
9839 // this means that if the base class has a protected copy assignment
9840 // operator, the protected member access check will fail. So, we
9841 // rewrite "protected" access to "public" access in this case, since we
9842 // know by construction that we're calling from a derived class.
9843 if (CopyingBaseSubobject) {
9844 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9846 if (L.getAccess() == AS_protected)
9847 L.setAccess(AS_public);
9851 // Create the nested-name-specifier that will be used to qualify the
9852 // reference to operator=; this is required to suppress the virtual
9855 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9856 SS.MakeTrivial(S.Context,
9857 NestedNameSpecifier::Create(S.Context, nullptr, false,
9861 // Create the reference to operator=.
9862 ExprResult OpEqualRef
9863 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9864 SS, /*TemplateKWLoc=*/SourceLocation(),
9865 /*FirstQualifierInScope=*/nullptr,
9867 /*TemplateArgs=*/nullptr, /*S*/nullptr,
9868 /*SuppressQualifierCheck=*/true);
9869 if (OpEqualRef.isInvalid())
9872 // Build the call to the assignment operator.
9874 Expr *FromInst = From.build(S, Loc);
9875 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9876 OpEqualRef.getAs<Expr>(),
9877 Loc, FromInst, Loc);
9878 if (Call.isInvalid())
9881 // If we built a call to a trivial 'operator=' while copying an array,
9882 // bail out. We'll replace the whole shebang with a memcpy.
9883 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9884 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9885 return StmtResult((Stmt*)nullptr);
9887 // Convert to an expression-statement, and clean up any produced
9889 return S.ActOnExprStmt(Call);
9892 // - if the subobject is of scalar type, the built-in assignment
9893 // operator is used.
9894 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9896 ExprResult Assignment = S.CreateBuiltinBinOp(
9897 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9898 if (Assignment.isInvalid())
9900 return S.ActOnExprStmt(Assignment);
9903 // - if the subobject is an array, each element is assigned, in the
9904 // manner appropriate to the element type;
9906 // Construct a loop over the array bounds, e.g.,
9908 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9910 // that will copy each of the array elements.
9911 QualType SizeType = S.Context.getSizeType();
9913 // Create the iteration variable.
9914 IdentifierInfo *IterationVarName = nullptr;
9917 llvm::raw_svector_ostream OS(Str);
9918 OS << "__i" << Depth;
9919 IterationVarName = &S.Context.Idents.get(OS.str());
9921 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9922 IterationVarName, SizeType,
9923 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9926 // Initialize the iteration variable to zero.
9927 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9928 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9930 // Creates a reference to the iteration variable.
9931 RefBuilder IterationVarRef(IterationVar, SizeType);
9932 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9934 // Create the DeclStmt that holds the iteration variable.
9935 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9937 // Subscript the "from" and "to" expressions with the iteration variable.
9938 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9939 MoveCastBuilder FromIndexMove(FromIndexCopy);
9940 const ExprBuilder *FromIndex;
9942 FromIndex = &FromIndexCopy;
9944 FromIndex = &FromIndexMove;
9946 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9948 // Build the copy/move for an individual element of the array.
9950 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9951 ToIndex, *FromIndex, CopyingBaseSubobject,
9952 Copying, Depth + 1);
9953 // Bail out if copying fails or if we determined that we should use memcpy.
9954 if (Copy.isInvalid() || !Copy.get())
9957 // Create the comparison against the array bound.
9959 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9961 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9962 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9963 BO_NE, S.Context.BoolTy,
9964 VK_RValue, OK_Ordinary, Loc, false);
9966 // Create the pre-increment of the iteration variable.
9968 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9969 SizeType, VK_LValue, OK_Ordinary, Loc);
9971 // Construct the loop that copies all elements of this array.
9972 return S.ActOnForStmt(Loc, Loc, InitStmt,
9973 S.MakeFullExpr(Comparison),
9974 nullptr, S.MakeFullDiscardedValueExpr(Increment),
9979 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9980 const ExprBuilder &To, const ExprBuilder &From,
9981 bool CopyingBaseSubobject, bool Copying) {
9982 // Maybe we should use a memcpy?
9983 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9984 T.isTriviallyCopyableType(S.Context))
9985 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9987 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9988 CopyingBaseSubobject,
9991 // If we ended up picking a trivial assignment operator for an array of a
9992 // non-trivially-copyable class type, just emit a memcpy.
9993 if (!Result.isInvalid() && !Result.get())
9994 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9999 Sema::ImplicitExceptionSpecification
10000 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10001 CXXRecordDecl *ClassDecl = MD->getParent();
10003 ImplicitExceptionSpecification ExceptSpec(*this);
10004 if (ClassDecl->isInvalidDecl())
10007 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10008 assert(T->getNumParams() == 1 && "not a copy assignment op");
10009 unsigned ArgQuals =
10010 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10012 // C++ [except.spec]p14:
10013 // An implicitly declared special member function (Clause 12) shall have an
10014 // exception-specification. [...]
10016 // It is unspecified whether or not an implicit copy assignment operator
10017 // attempts to deduplicate calls to assignment operators of virtual bases are
10018 // made. As such, this exception specification is effectively unspecified.
10019 // Based on a similar decision made for constness in C++0x, we're erring on
10020 // the side of assuming such calls to be made regardless of whether they
10021 // actually happen.
10022 for (const auto &Base : ClassDecl->bases()) {
10023 if (Base.isVirtual())
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 &Base : ClassDecl->vbases()) {
10034 CXXRecordDecl *BaseClassDecl
10035 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10036 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10037 ArgQuals, false, 0))
10038 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10041 for (const auto *Field : ClassDecl->fields()) {
10042 QualType FieldType = Context.getBaseElementType(Field->getType());
10043 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10044 if (CXXMethodDecl *CopyAssign =
10045 LookupCopyingAssignment(FieldClassDecl,
10046 ArgQuals | FieldType.getCVRQualifiers(),
10048 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10055 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10056 // Note: The following rules are largely analoguous to the copy
10057 // constructor rules. Note that virtual bases are not taken into account
10058 // for determining the argument type of the operator. Note also that
10059 // operators taking an object instead of a reference are allowed.
10060 assert(ClassDecl->needsImplicitCopyAssignment());
10062 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10063 if (DSM.isAlreadyBeingDeclared())
10066 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10067 QualType RetType = Context.getLValueReferenceType(ArgType);
10068 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10070 ArgType = ArgType.withConst();
10071 ArgType = Context.getLValueReferenceType(ArgType);
10073 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10077 // An implicitly-declared copy assignment operator is an inline public
10078 // member of its class.
10079 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10080 SourceLocation ClassLoc = ClassDecl->getLocation();
10081 DeclarationNameInfo NameInfo(Name, ClassLoc);
10082 CXXMethodDecl *CopyAssignment =
10083 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10084 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10085 /*isInline=*/true, Constexpr, SourceLocation());
10086 CopyAssignment->setAccess(AS_public);
10087 CopyAssignment->setDefaulted();
10088 CopyAssignment->setImplicit();
10090 if (getLangOpts().CUDA) {
10091 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10093 /* ConstRHS */ Const,
10094 /* Diagnose */ false);
10097 // Build an exception specification pointing back at this member.
10098 FunctionProtoType::ExtProtoInfo EPI =
10099 getImplicitMethodEPI(*this, CopyAssignment);
10100 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10102 // Add the parameter to the operator.
10103 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10104 ClassLoc, ClassLoc,
10105 /*Id=*/nullptr, ArgType,
10106 /*TInfo=*/nullptr, SC_None,
10108 CopyAssignment->setParams(FromParam);
10110 AddOverriddenMethods(ClassDecl, CopyAssignment);
10112 CopyAssignment->setTrivial(
10113 ClassDecl->needsOverloadResolutionForCopyAssignment()
10114 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10115 : ClassDecl->hasTrivialCopyAssignment());
10117 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10118 SetDeclDeleted(CopyAssignment, ClassLoc);
10120 // Note that we have added this copy-assignment operator.
10121 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10123 if (Scope *S = getScopeForContext(ClassDecl))
10124 PushOnScopeChains(CopyAssignment, S, false);
10125 ClassDecl->addDecl(CopyAssignment);
10127 return CopyAssignment;
10130 /// Diagnose an implicit copy operation for a class which is odr-used, but
10131 /// which is deprecated because the class has a user-declared copy constructor,
10132 /// copy assignment operator, or destructor.
10133 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10134 SourceLocation UseLoc) {
10135 assert(CopyOp->isImplicit());
10137 CXXRecordDecl *RD = CopyOp->getParent();
10138 CXXMethodDecl *UserDeclaredOperation = nullptr;
10140 // In Microsoft mode, assignment operations don't affect constructors and
10142 if (RD->hasUserDeclaredDestructor()) {
10143 UserDeclaredOperation = RD->getDestructor();
10144 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10145 RD->hasUserDeclaredCopyConstructor() &&
10146 !S.getLangOpts().MSVCCompat) {
10147 // Find any user-declared copy constructor.
10148 for (auto *I : RD->ctors()) {
10149 if (I->isCopyConstructor()) {
10150 UserDeclaredOperation = I;
10154 assert(UserDeclaredOperation);
10155 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10156 RD->hasUserDeclaredCopyAssignment() &&
10157 !S.getLangOpts().MSVCCompat) {
10158 // Find any user-declared move assignment operator.
10159 for (auto *I : RD->methods()) {
10160 if (I->isCopyAssignmentOperator()) {
10161 UserDeclaredOperation = I;
10165 assert(UserDeclaredOperation);
10168 if (UserDeclaredOperation) {
10169 S.Diag(UserDeclaredOperation->getLocation(),
10170 diag::warn_deprecated_copy_operation)
10171 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10172 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10173 S.Diag(UseLoc, diag::note_member_synthesized_at)
10174 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10175 : Sema::CXXCopyAssignment)
10180 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10181 CXXMethodDecl *CopyAssignOperator) {
10182 assert((CopyAssignOperator->isDefaulted() &&
10183 CopyAssignOperator->isOverloadedOperator() &&
10184 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10185 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10186 !CopyAssignOperator->isDeleted()) &&
10187 "DefineImplicitCopyAssignment called for wrong function");
10189 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10191 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10192 CopyAssignOperator->setInvalidDecl();
10196 // C++11 [class.copy]p18:
10197 // The [definition of an implicitly declared copy assignment operator] is
10198 // deprecated if the class has a user-declared copy constructor or a
10199 // user-declared destructor.
10200 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10201 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10203 CopyAssignOperator->markUsed(Context);
10205 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10206 DiagnosticErrorTrap Trap(Diags);
10208 // C++0x [class.copy]p30:
10209 // The implicitly-defined or explicitly-defaulted copy assignment operator
10210 // for a non-union class X performs memberwise copy assignment of its
10211 // subobjects. The direct base classes of X are assigned first, in the
10212 // order of their declaration in the base-specifier-list, and then the
10213 // immediate non-static data members of X are assigned, in the order in
10214 // which they were declared in the class definition.
10216 // The statements that form the synthesized function body.
10217 SmallVector<Stmt*, 8> Statements;
10219 // The parameter for the "other" object, which we are copying from.
10220 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10221 Qualifiers OtherQuals = Other->getType().getQualifiers();
10222 QualType OtherRefType = Other->getType();
10223 if (const LValueReferenceType *OtherRef
10224 = OtherRefType->getAs<LValueReferenceType>()) {
10225 OtherRefType = OtherRef->getPointeeType();
10226 OtherQuals = OtherRefType.getQualifiers();
10229 // Our location for everything implicitly-generated.
10230 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10231 ? CopyAssignOperator->getLocEnd()
10232 : CopyAssignOperator->getLocation();
10234 // Builds a DeclRefExpr for the "other" object.
10235 RefBuilder OtherRef(Other, OtherRefType);
10237 // Builds the "this" pointer.
10240 // Assign base classes.
10241 bool Invalid = false;
10242 for (auto &Base : ClassDecl->bases()) {
10243 // Form the assignment:
10244 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10245 QualType BaseType = Base.getType().getUnqualifiedType();
10246 if (!BaseType->isRecordType()) {
10251 CXXCastPath BasePath;
10252 BasePath.push_back(&Base);
10254 // Construct the "from" expression, which is an implicit cast to the
10255 // appropriately-qualified base type.
10256 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10257 VK_LValue, BasePath);
10259 // Dereference "this".
10260 DerefBuilder DerefThis(This);
10261 CastBuilder To(DerefThis,
10262 Context.getCVRQualifiedType(
10263 BaseType, CopyAssignOperator->getTypeQualifiers()),
10264 VK_LValue, BasePath);
10267 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10269 /*CopyingBaseSubobject=*/true,
10271 if (Copy.isInvalid()) {
10272 Diag(CurrentLocation, diag::note_member_synthesized_at)
10273 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10274 CopyAssignOperator->setInvalidDecl();
10278 // Success! Record the copy.
10279 Statements.push_back(Copy.getAs<Expr>());
10282 // Assign non-static members.
10283 for (auto *Field : ClassDecl->fields()) {
10284 // FIXME: We should form some kind of AST representation for the implied
10285 // memcpy in a union copy operation.
10286 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10289 if (Field->isInvalidDecl()) {
10294 // Check for members of reference type; we can't copy those.
10295 if (Field->getType()->isReferenceType()) {
10296 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10297 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10298 Diag(Field->getLocation(), diag::note_declared_at);
10299 Diag(CurrentLocation, diag::note_member_synthesized_at)
10300 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10305 // Check for members of const-qualified, non-class type.
10306 QualType BaseType = Context.getBaseElementType(Field->getType());
10307 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10308 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10309 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10310 Diag(Field->getLocation(), diag::note_declared_at);
10311 Diag(CurrentLocation, diag::note_member_synthesized_at)
10312 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10317 // Suppress assigning zero-width bitfields.
10318 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10321 QualType FieldType = Field->getType().getNonReferenceType();
10322 if (FieldType->isIncompleteArrayType()) {
10323 assert(ClassDecl->hasFlexibleArrayMember() &&
10324 "Incomplete array type is not valid");
10328 // Build references to the field in the object we're copying from and to.
10329 CXXScopeSpec SS; // Intentionally empty
10330 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10332 MemberLookup.addDecl(Field);
10333 MemberLookup.resolveKind();
10335 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10337 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10339 // Build the copy of this field.
10340 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10342 /*CopyingBaseSubobject=*/false,
10344 if (Copy.isInvalid()) {
10345 Diag(CurrentLocation, diag::note_member_synthesized_at)
10346 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10347 CopyAssignOperator->setInvalidDecl();
10351 // Success! Record the copy.
10352 Statements.push_back(Copy.getAs<Stmt>());
10356 // Add a "return *this;"
10357 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10359 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10360 if (Return.isInvalid())
10363 Statements.push_back(Return.getAs<Stmt>());
10365 if (Trap.hasErrorOccurred()) {
10366 Diag(CurrentLocation, diag::note_member_synthesized_at)
10367 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10373 // The exception specification is needed because we are defining the
10375 ResolveExceptionSpec(CurrentLocation,
10376 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10379 CopyAssignOperator->setInvalidDecl();
10385 CompoundScopeRAII CompoundScope(*this);
10386 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10387 /*isStmtExpr=*/false);
10388 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10390 CopyAssignOperator->setBody(Body.getAs<Stmt>());
10392 if (ASTMutationListener *L = getASTMutationListener()) {
10393 L->CompletedImplicitDefinition(CopyAssignOperator);
10397 Sema::ImplicitExceptionSpecification
10398 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10399 CXXRecordDecl *ClassDecl = MD->getParent();
10401 ImplicitExceptionSpecification ExceptSpec(*this);
10402 if (ClassDecl->isInvalidDecl())
10405 // C++0x [except.spec]p14:
10406 // An implicitly declared special member function (Clause 12) shall have an
10407 // exception-specification. [...]
10409 // It is unspecified whether or not an implicit move assignment operator
10410 // attempts to deduplicate calls to assignment operators of virtual bases are
10411 // made. As such, this exception specification is effectively unspecified.
10412 // Based on a similar decision made for constness in C++0x, we're erring on
10413 // the side of assuming such calls to be made regardless of whether they
10414 // actually happen.
10415 // Note that a move constructor is not implicitly declared when there are
10416 // virtual bases, but it can still be user-declared and explicitly defaulted.
10417 for (const auto &Base : ClassDecl->bases()) {
10418 if (Base.isVirtual())
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 &Base : ClassDecl->vbases()) {
10429 CXXRecordDecl *BaseClassDecl
10430 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10431 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10433 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10436 for (const auto *Field : ClassDecl->fields()) {
10437 QualType FieldType = Context.getBaseElementType(Field->getType());
10438 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10439 if (CXXMethodDecl *MoveAssign =
10440 LookupMovingAssignment(FieldClassDecl,
10441 FieldType.getCVRQualifiers(),
10443 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10450 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10451 assert(ClassDecl->needsImplicitMoveAssignment());
10453 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10454 if (DSM.isAlreadyBeingDeclared())
10457 // Note: The following rules are largely analoguous to the move
10458 // constructor rules.
10460 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10461 QualType RetType = Context.getLValueReferenceType(ArgType);
10462 ArgType = Context.getRValueReferenceType(ArgType);
10464 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10468 // An implicitly-declared move assignment operator is an inline public
10469 // member of its class.
10470 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10471 SourceLocation ClassLoc = ClassDecl->getLocation();
10472 DeclarationNameInfo NameInfo(Name, ClassLoc);
10473 CXXMethodDecl *MoveAssignment =
10474 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10475 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10476 /*isInline=*/true, Constexpr, SourceLocation());
10477 MoveAssignment->setAccess(AS_public);
10478 MoveAssignment->setDefaulted();
10479 MoveAssignment->setImplicit();
10481 if (getLangOpts().CUDA) {
10482 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10484 /* ConstRHS */ false,
10485 /* Diagnose */ false);
10488 // Build an exception specification pointing back at this member.
10489 FunctionProtoType::ExtProtoInfo EPI =
10490 getImplicitMethodEPI(*this, MoveAssignment);
10491 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10493 // Add the parameter to the operator.
10494 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10495 ClassLoc, ClassLoc,
10496 /*Id=*/nullptr, ArgType,
10497 /*TInfo=*/nullptr, SC_None,
10499 MoveAssignment->setParams(FromParam);
10501 AddOverriddenMethods(ClassDecl, MoveAssignment);
10503 MoveAssignment->setTrivial(
10504 ClassDecl->needsOverloadResolutionForMoveAssignment()
10505 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10506 : ClassDecl->hasTrivialMoveAssignment());
10508 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10509 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10510 SetDeclDeleted(MoveAssignment, ClassLoc);
10513 // Note that we have added this copy-assignment operator.
10514 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10516 if (Scope *S = getScopeForContext(ClassDecl))
10517 PushOnScopeChains(MoveAssignment, S, false);
10518 ClassDecl->addDecl(MoveAssignment);
10520 return MoveAssignment;
10523 /// Check if we're implicitly defining a move assignment operator for a class
10524 /// with virtual bases. Such a move assignment might move-assign the virtual
10525 /// base multiple times.
10526 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10527 SourceLocation CurrentLocation) {
10528 assert(!Class->isDependentContext() && "should not define dependent move");
10530 // Only a virtual base could get implicitly move-assigned multiple times.
10531 // Only a non-trivial move assignment can observe this. We only want to
10532 // diagnose if we implicitly define an assignment operator that assigns
10533 // two base classes, both of which move-assign the same virtual base.
10534 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10535 Class->getNumBases() < 2)
10538 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10539 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10542 for (auto &BI : Class->bases()) {
10543 Worklist.push_back(&BI);
10544 while (!Worklist.empty()) {
10545 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10546 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10548 // If the base has no non-trivial move assignment operators,
10549 // we don't care about moves from it.
10550 if (!Base->hasNonTrivialMoveAssignment())
10553 // If there's nothing virtual here, skip it.
10554 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10557 // If we're not actually going to call a move assignment for this base,
10558 // or the selected move assignment is trivial, skip it.
10559 Sema::SpecialMemberOverloadResult *SMOR =
10560 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10561 /*ConstArg*/false, /*VolatileArg*/false,
10562 /*RValueThis*/true, /*ConstThis*/false,
10563 /*VolatileThis*/false);
10564 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10565 !SMOR->getMethod()->isMoveAssignmentOperator())
10568 if (BaseSpec->isVirtual()) {
10569 // We're going to move-assign this virtual base, and its move
10570 // assignment operator is not trivial. If this can happen for
10571 // multiple distinct direct bases of Class, diagnose it. (If it
10572 // only happens in one base, we'll diagnose it when synthesizing
10573 // that base class's move assignment operator.)
10574 CXXBaseSpecifier *&Existing =
10575 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10577 if (Existing && Existing != &BI) {
10578 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10580 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10581 << (Base->getCanonicalDecl() ==
10582 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10583 << Base << Existing->getType() << Existing->getSourceRange();
10584 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10585 << (Base->getCanonicalDecl() ==
10586 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10587 << Base << BI.getType() << BaseSpec->getSourceRange();
10589 // Only diagnose each vbase once.
10590 Existing = nullptr;
10593 // Only walk over bases that have defaulted move assignment operators.
10594 // We assume that any user-provided move assignment operator handles
10595 // the multiple-moves-of-vbase case itself somehow.
10596 if (!SMOR->getMethod()->isDefaulted())
10599 // We're going to move the base classes of Base. Add them to the list.
10600 for (auto &BI : Base->bases())
10601 Worklist.push_back(&BI);
10607 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10608 CXXMethodDecl *MoveAssignOperator) {
10609 assert((MoveAssignOperator->isDefaulted() &&
10610 MoveAssignOperator->isOverloadedOperator() &&
10611 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10612 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10613 !MoveAssignOperator->isDeleted()) &&
10614 "DefineImplicitMoveAssignment called for wrong function");
10616 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10618 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10619 MoveAssignOperator->setInvalidDecl();
10623 MoveAssignOperator->markUsed(Context);
10625 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10626 DiagnosticErrorTrap Trap(Diags);
10628 // C++0x [class.copy]p28:
10629 // The implicitly-defined or move assignment operator for a non-union class
10630 // X performs memberwise move assignment of its subobjects. The direct base
10631 // classes of X are assigned first, in the order of their declaration in the
10632 // base-specifier-list, and then the immediate non-static data members of X
10633 // are assigned, in the order in which they were declared in the class
10636 // Issue a warning if our implicit move assignment operator will move
10637 // from a virtual base more than once.
10638 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10640 // The statements that form the synthesized function body.
10641 SmallVector<Stmt*, 8> Statements;
10643 // The parameter for the "other" object, which we are move from.
10644 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10645 QualType OtherRefType = Other->getType()->
10646 getAs<RValueReferenceType>()->getPointeeType();
10647 assert(!OtherRefType.getQualifiers() &&
10648 "Bad argument type of defaulted move assignment");
10650 // Our location for everything implicitly-generated.
10651 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10652 ? MoveAssignOperator->getLocEnd()
10653 : MoveAssignOperator->getLocation();
10655 // Builds a reference to the "other" object.
10656 RefBuilder OtherRef(Other, OtherRefType);
10658 MoveCastBuilder MoveOther(OtherRef);
10660 // Builds the "this" pointer.
10663 // Assign base classes.
10664 bool Invalid = false;
10665 for (auto &Base : ClassDecl->bases()) {
10666 // C++11 [class.copy]p28:
10667 // It is unspecified whether subobjects representing virtual base classes
10668 // are assigned more than once by the implicitly-defined copy assignment
10670 // FIXME: Do not assign to a vbase that will be assigned by some other base
10671 // class. For a move-assignment, this can result in the vbase being moved
10674 // Form the assignment:
10675 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10676 QualType BaseType = Base.getType().getUnqualifiedType();
10677 if (!BaseType->isRecordType()) {
10682 CXXCastPath BasePath;
10683 BasePath.push_back(&Base);
10685 // Construct the "from" expression, which is an implicit cast to the
10686 // appropriately-qualified base type.
10687 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10689 // Dereference "this".
10690 DerefBuilder DerefThis(This);
10692 // Implicitly cast "this" to the appropriately-qualified base type.
10693 CastBuilder To(DerefThis,
10694 Context.getCVRQualifiedType(
10695 BaseType, MoveAssignOperator->getTypeQualifiers()),
10696 VK_LValue, BasePath);
10699 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10701 /*CopyingBaseSubobject=*/true,
10702 /*Copying=*/false);
10703 if (Move.isInvalid()) {
10704 Diag(CurrentLocation, diag::note_member_synthesized_at)
10705 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10706 MoveAssignOperator->setInvalidDecl();
10710 // Success! Record the move.
10711 Statements.push_back(Move.getAs<Expr>());
10714 // Assign non-static members.
10715 for (auto *Field : ClassDecl->fields()) {
10716 // FIXME: We should form some kind of AST representation for the implied
10717 // memcpy in a union copy operation.
10718 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10721 if (Field->isInvalidDecl()) {
10726 // Check for members of reference type; we can't move those.
10727 if (Field->getType()->isReferenceType()) {
10728 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10729 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10730 Diag(Field->getLocation(), diag::note_declared_at);
10731 Diag(CurrentLocation, diag::note_member_synthesized_at)
10732 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10737 // Check for members of const-qualified, non-class type.
10738 QualType BaseType = Context.getBaseElementType(Field->getType());
10739 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10740 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10741 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10742 Diag(Field->getLocation(), diag::note_declared_at);
10743 Diag(CurrentLocation, diag::note_member_synthesized_at)
10744 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10749 // Suppress assigning zero-width bitfields.
10750 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10753 QualType FieldType = Field->getType().getNonReferenceType();
10754 if (FieldType->isIncompleteArrayType()) {
10755 assert(ClassDecl->hasFlexibleArrayMember() &&
10756 "Incomplete array type is not valid");
10760 // Build references to the field in the object we're copying from and to.
10761 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10763 MemberLookup.addDecl(Field);
10764 MemberLookup.resolveKind();
10765 MemberBuilder From(MoveOther, OtherRefType,
10766 /*IsArrow=*/false, MemberLookup);
10767 MemberBuilder To(This, getCurrentThisType(),
10768 /*IsArrow=*/true, MemberLookup);
10770 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10771 "Member reference with rvalue base must be rvalue except for reference "
10772 "members, which aren't allowed for move assignment.");
10774 // Build the move of this field.
10775 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10777 /*CopyingBaseSubobject=*/false,
10778 /*Copying=*/false);
10779 if (Move.isInvalid()) {
10780 Diag(CurrentLocation, diag::note_member_synthesized_at)
10781 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10782 MoveAssignOperator->setInvalidDecl();
10786 // Success! Record the copy.
10787 Statements.push_back(Move.getAs<Stmt>());
10791 // Add a "return *this;"
10792 ExprResult ThisObj =
10793 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10795 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10796 if (Return.isInvalid())
10799 Statements.push_back(Return.getAs<Stmt>());
10801 if (Trap.hasErrorOccurred()) {
10802 Diag(CurrentLocation, diag::note_member_synthesized_at)
10803 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10809 // The exception specification is needed because we are defining the
10811 ResolveExceptionSpec(CurrentLocation,
10812 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10815 MoveAssignOperator->setInvalidDecl();
10821 CompoundScopeRAII CompoundScope(*this);
10822 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10823 /*isStmtExpr=*/false);
10824 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10826 MoveAssignOperator->setBody(Body.getAs<Stmt>());
10828 if (ASTMutationListener *L = getASTMutationListener()) {
10829 L->CompletedImplicitDefinition(MoveAssignOperator);
10833 Sema::ImplicitExceptionSpecification
10834 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10835 CXXRecordDecl *ClassDecl = MD->getParent();
10837 ImplicitExceptionSpecification ExceptSpec(*this);
10838 if (ClassDecl->isInvalidDecl())
10841 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10842 assert(T->getNumParams() >= 1 && "not a copy ctor");
10843 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10845 // C++ [except.spec]p14:
10846 // An implicitly declared special member function (Clause 12) shall have an
10847 // exception-specification. [...]
10848 for (const auto &Base : ClassDecl->bases()) {
10849 // Virtual bases are handled below.
10850 if (Base.isVirtual())
10853 CXXRecordDecl *BaseClassDecl
10854 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10855 if (CXXConstructorDecl *CopyConstructor =
10856 LookupCopyingConstructor(BaseClassDecl, Quals))
10857 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10859 for (const auto &Base : ClassDecl->vbases()) {
10860 CXXRecordDecl *BaseClassDecl
10861 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10862 if (CXXConstructorDecl *CopyConstructor =
10863 LookupCopyingConstructor(BaseClassDecl, Quals))
10864 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10866 for (const auto *Field : ClassDecl->fields()) {
10867 QualType FieldType = Context.getBaseElementType(Field->getType());
10868 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10869 if (CXXConstructorDecl *CopyConstructor =
10870 LookupCopyingConstructor(FieldClassDecl,
10871 Quals | FieldType.getCVRQualifiers()))
10872 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10879 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10880 CXXRecordDecl *ClassDecl) {
10881 // C++ [class.copy]p4:
10882 // If the class definition does not explicitly declare a copy
10883 // constructor, one is declared implicitly.
10884 assert(ClassDecl->needsImplicitCopyConstructor());
10886 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10887 if (DSM.isAlreadyBeingDeclared())
10890 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10891 QualType ArgType = ClassType;
10892 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10894 ArgType = ArgType.withConst();
10895 ArgType = Context.getLValueReferenceType(ArgType);
10897 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10898 CXXCopyConstructor,
10901 DeclarationName Name
10902 = Context.DeclarationNames.getCXXConstructorName(
10903 Context.getCanonicalType(ClassType));
10904 SourceLocation ClassLoc = ClassDecl->getLocation();
10905 DeclarationNameInfo NameInfo(Name, ClassLoc);
10907 // An implicitly-declared copy constructor is an inline public
10908 // member of its class.
10909 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10910 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10911 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10913 CopyConstructor->setAccess(AS_public);
10914 CopyConstructor->setDefaulted();
10916 if (getLangOpts().CUDA) {
10917 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10919 /* ConstRHS */ Const,
10920 /* Diagnose */ false);
10923 // Build an exception specification pointing back at this member.
10924 FunctionProtoType::ExtProtoInfo EPI =
10925 getImplicitMethodEPI(*this, CopyConstructor);
10926 CopyConstructor->setType(
10927 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10929 // Add the parameter to the constructor.
10930 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10931 ClassLoc, ClassLoc,
10932 /*IdentifierInfo=*/nullptr,
10933 ArgType, /*TInfo=*/nullptr,
10935 CopyConstructor->setParams(FromParam);
10937 CopyConstructor->setTrivial(
10938 ClassDecl->needsOverloadResolutionForCopyConstructor()
10939 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10940 : ClassDecl->hasTrivialCopyConstructor());
10942 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10943 SetDeclDeleted(CopyConstructor, ClassLoc);
10945 // Note that we have declared this constructor.
10946 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10948 if (Scope *S = getScopeForContext(ClassDecl))
10949 PushOnScopeChains(CopyConstructor, S, false);
10950 ClassDecl->addDecl(CopyConstructor);
10952 return CopyConstructor;
10955 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10956 CXXConstructorDecl *CopyConstructor) {
10957 assert((CopyConstructor->isDefaulted() &&
10958 CopyConstructor->isCopyConstructor() &&
10959 !CopyConstructor->doesThisDeclarationHaveABody() &&
10960 !CopyConstructor->isDeleted()) &&
10961 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10963 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10964 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10966 // C++11 [class.copy]p7:
10967 // The [definition of an implicitly declared copy constructor] is
10968 // deprecated if the class has a user-declared copy assignment operator
10969 // or a user-declared destructor.
10970 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10971 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10973 SynthesizedFunctionScope Scope(*this, CopyConstructor);
10974 DiagnosticErrorTrap Trap(Diags);
10976 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10977 Trap.hasErrorOccurred()) {
10978 Diag(CurrentLocation, diag::note_member_synthesized_at)
10979 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10980 CopyConstructor->setInvalidDecl();
10982 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10983 ? CopyConstructor->getLocEnd()
10984 : CopyConstructor->getLocation();
10985 Sema::CompoundScopeRAII CompoundScope(*this);
10986 CopyConstructor->setBody(
10987 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10990 // The exception specification is needed because we are defining the
10992 ResolveExceptionSpec(CurrentLocation,
10993 CopyConstructor->getType()->castAs<FunctionProtoType>());
10995 CopyConstructor->markUsed(Context);
10996 MarkVTableUsed(CurrentLocation, ClassDecl);
10998 if (ASTMutationListener *L = getASTMutationListener()) {
10999 L->CompletedImplicitDefinition(CopyConstructor);
11003 Sema::ImplicitExceptionSpecification
11004 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11005 CXXRecordDecl *ClassDecl = MD->getParent();
11007 // C++ [except.spec]p14:
11008 // An implicitly declared special member function (Clause 12) shall have an
11009 // exception-specification. [...]
11010 ImplicitExceptionSpecification ExceptSpec(*this);
11011 if (ClassDecl->isInvalidDecl())
11014 // Direct base-class constructors.
11015 for (const auto &B : ClassDecl->bases()) {
11016 if (B.isVirtual()) // Handled below.
11019 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11020 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11021 CXXConstructorDecl *Constructor =
11022 LookupMovingConstructor(BaseClassDecl, 0);
11023 // If this is a deleted function, add it anyway. This might be conformant
11024 // with the standard. This might not. I'm not sure. It might not matter.
11026 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11030 // Virtual base-class constructors.
11031 for (const auto &B : ClassDecl->vbases()) {
11032 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11033 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11034 CXXConstructorDecl *Constructor =
11035 LookupMovingConstructor(BaseClassDecl, 0);
11036 // If this is a deleted function, add it anyway. This might be conformant
11037 // with the standard. This might not. I'm not sure. It might not matter.
11039 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11043 // Field constructors.
11044 for (const auto *F : ClassDecl->fields()) {
11045 QualType FieldType = Context.getBaseElementType(F->getType());
11046 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11047 CXXConstructorDecl *Constructor =
11048 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11049 // If this is a deleted function, add it anyway. This might be conformant
11050 // with the standard. This might not. I'm not sure. It might not matter.
11051 // In particular, the problem is that this function never gets called. It
11052 // might just be ill-formed because this function attempts to refer to
11053 // a deleted function here.
11055 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11062 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11063 CXXRecordDecl *ClassDecl) {
11064 assert(ClassDecl->needsImplicitMoveConstructor());
11066 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11067 if (DSM.isAlreadyBeingDeclared())
11070 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11071 QualType ArgType = Context.getRValueReferenceType(ClassType);
11073 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11074 CXXMoveConstructor,
11077 DeclarationName Name
11078 = Context.DeclarationNames.getCXXConstructorName(
11079 Context.getCanonicalType(ClassType));
11080 SourceLocation ClassLoc = ClassDecl->getLocation();
11081 DeclarationNameInfo NameInfo(Name, ClassLoc);
11083 // C++11 [class.copy]p11:
11084 // An implicitly-declared copy/move constructor is an inline public
11085 // member of its class.
11086 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11087 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11088 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11090 MoveConstructor->setAccess(AS_public);
11091 MoveConstructor->setDefaulted();
11093 if (getLangOpts().CUDA) {
11094 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11096 /* ConstRHS */ false,
11097 /* Diagnose */ false);
11100 // Build an exception specification pointing back at this member.
11101 FunctionProtoType::ExtProtoInfo EPI =
11102 getImplicitMethodEPI(*this, MoveConstructor);
11103 MoveConstructor->setType(
11104 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11106 // Add the parameter to the constructor.
11107 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11108 ClassLoc, ClassLoc,
11109 /*IdentifierInfo=*/nullptr,
11110 ArgType, /*TInfo=*/nullptr,
11112 MoveConstructor->setParams(FromParam);
11114 MoveConstructor->setTrivial(
11115 ClassDecl->needsOverloadResolutionForMoveConstructor()
11116 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11117 : ClassDecl->hasTrivialMoveConstructor());
11119 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11120 ClassDecl->setImplicitMoveConstructorIsDeleted();
11121 SetDeclDeleted(MoveConstructor, ClassLoc);
11124 // Note that we have declared this constructor.
11125 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11127 if (Scope *S = getScopeForContext(ClassDecl))
11128 PushOnScopeChains(MoveConstructor, S, false);
11129 ClassDecl->addDecl(MoveConstructor);
11131 return MoveConstructor;
11134 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11135 CXXConstructorDecl *MoveConstructor) {
11136 assert((MoveConstructor->isDefaulted() &&
11137 MoveConstructor->isMoveConstructor() &&
11138 !MoveConstructor->doesThisDeclarationHaveABody() &&
11139 !MoveConstructor->isDeleted()) &&
11140 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11142 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11143 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11145 SynthesizedFunctionScope Scope(*this, MoveConstructor);
11146 DiagnosticErrorTrap Trap(Diags);
11148 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11149 Trap.hasErrorOccurred()) {
11150 Diag(CurrentLocation, diag::note_member_synthesized_at)
11151 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11152 MoveConstructor->setInvalidDecl();
11154 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11155 ? MoveConstructor->getLocEnd()
11156 : MoveConstructor->getLocation();
11157 Sema::CompoundScopeRAII CompoundScope(*this);
11158 MoveConstructor->setBody(ActOnCompoundStmt(
11159 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11162 // The exception specification is needed because we are defining the
11164 ResolveExceptionSpec(CurrentLocation,
11165 MoveConstructor->getType()->castAs<FunctionProtoType>());
11167 MoveConstructor->markUsed(Context);
11168 MarkVTableUsed(CurrentLocation, ClassDecl);
11170 if (ASTMutationListener *L = getASTMutationListener()) {
11171 L->CompletedImplicitDefinition(MoveConstructor);
11175 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11176 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11179 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11180 SourceLocation CurrentLocation,
11181 CXXConversionDecl *Conv) {
11182 CXXRecordDecl *Lambda = Conv->getParent();
11183 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11184 // If we are defining a specialization of a conversion to function-ptr
11185 // cache the deduced template arguments for this specialization
11186 // so that we can use them to retrieve the corresponding call-operator
11187 // and static-invoker.
11188 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11190 // Retrieve the corresponding call-operator specialization.
11191 if (Lambda->isGenericLambda()) {
11192 assert(Conv->isFunctionTemplateSpecialization());
11193 FunctionTemplateDecl *CallOpTemplate =
11194 CallOp->getDescribedFunctionTemplate();
11195 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11196 void *InsertPos = nullptr;
11197 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11198 DeducedTemplateArgs->asArray(),
11200 assert(CallOpSpec &&
11201 "Conversion operator must have a corresponding call operator");
11202 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11204 // Mark the call operator referenced (and add to pending instantiations
11206 // For both the conversion and static-invoker template specializations
11207 // we construct their body's in this function, so no need to add them
11208 // to the PendingInstantiations.
11209 MarkFunctionReferenced(CurrentLocation, CallOp);
11211 SynthesizedFunctionScope Scope(*this, Conv);
11212 DiagnosticErrorTrap Trap(Diags);
11214 // Retrieve the static invoker...
11215 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11216 // ... and get the corresponding specialization for a generic lambda.
11217 if (Lambda->isGenericLambda()) {
11218 assert(DeducedTemplateArgs &&
11219 "Must have deduced template arguments from Conversion Operator");
11220 FunctionTemplateDecl *InvokeTemplate =
11221 Invoker->getDescribedFunctionTemplate();
11222 void *InsertPos = nullptr;
11223 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11224 DeducedTemplateArgs->asArray(),
11226 assert(InvokeSpec &&
11227 "Must have a corresponding static invoker specialization");
11228 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11230 // Construct the body of the conversion function { return __invoke; }.
11231 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11232 VK_LValue, Conv->getLocation()).get();
11233 assert(FunctionRef && "Can't refer to __invoke function?");
11234 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11235 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11236 Conv->getLocation(),
11237 Conv->getLocation()));
11239 Conv->markUsed(Context);
11240 Conv->setReferenced();
11242 // Fill in the __invoke function with a dummy implementation. IR generation
11243 // will fill in the actual details.
11244 Invoker->markUsed(Context);
11245 Invoker->setReferenced();
11246 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11248 if (ASTMutationListener *L = getASTMutationListener()) {
11249 L->CompletedImplicitDefinition(Conv);
11250 L->CompletedImplicitDefinition(Invoker);
11256 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11257 SourceLocation CurrentLocation,
11258 CXXConversionDecl *Conv)
11260 assert(!Conv->getParent()->isGenericLambda());
11262 Conv->markUsed(Context);
11264 SynthesizedFunctionScope Scope(*this, Conv);
11265 DiagnosticErrorTrap Trap(Diags);
11267 // Copy-initialize the lambda object as needed to capture it.
11268 Expr *This = ActOnCXXThis(CurrentLocation).get();
11269 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11271 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11272 Conv->getLocation(),
11275 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11276 // behavior. Note that only the general conversion function does this
11277 // (since it's unusable otherwise); in the case where we inline the
11278 // block literal, it has block literal lifetime semantics.
11279 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11280 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11281 CK_CopyAndAutoreleaseBlockObject,
11282 BuildBlock.get(), nullptr, VK_RValue);
11284 if (BuildBlock.isInvalid()) {
11285 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11286 Conv->setInvalidDecl();
11290 // Create the return statement that returns the block from the conversion
11292 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11293 if (Return.isInvalid()) {
11294 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11295 Conv->setInvalidDecl();
11299 // Set the body of the conversion function.
11300 Stmt *ReturnS = Return.get();
11301 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11302 Conv->getLocation(),
11303 Conv->getLocation()));
11305 // We're done; notify the mutation listener, if any.
11306 if (ASTMutationListener *L = getASTMutationListener()) {
11307 L->CompletedImplicitDefinition(Conv);
11311 /// \brief Determine whether the given list arguments contains exactly one
11312 /// "real" (non-default) argument.
11313 static bool hasOneRealArgument(MultiExprArg Args) {
11314 switch (Args.size()) {
11319 if (!Args[1]->isDefaultArgument())
11324 return !Args[0]->isDefaultArgument();
11331 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11332 CXXConstructorDecl *Constructor,
11333 MultiExprArg ExprArgs,
11334 bool HadMultipleCandidates,
11335 bool IsListInitialization,
11336 bool IsStdInitListInitialization,
11337 bool RequiresZeroInit,
11338 unsigned ConstructKind,
11339 SourceRange ParenRange) {
11340 bool Elidable = false;
11342 // C++0x [class.copy]p34:
11343 // When certain criteria are met, an implementation is allowed to
11344 // omit the copy/move construction of a class object, even if the
11345 // copy/move constructor and/or destructor for the object have
11346 // side effects. [...]
11347 // - when a temporary class object that has not been bound to a
11348 // reference (12.2) would be copied/moved to a class object
11349 // with the same cv-unqualified type, the copy/move operation
11350 // can be omitted by constructing the temporary object
11351 // directly into the target of the omitted copy/move
11352 if (ConstructKind == CXXConstructExpr::CK_Complete &&
11353 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11354 Expr *SubExpr = ExprArgs[0];
11355 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11358 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11359 Elidable, ExprArgs, HadMultipleCandidates,
11360 IsListInitialization,
11361 IsStdInitListInitialization, RequiresZeroInit,
11362 ConstructKind, ParenRange);
11365 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11366 /// including handling of its default argument expressions.
11368 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11369 CXXConstructorDecl *Constructor, bool Elidable,
11370 MultiExprArg ExprArgs,
11371 bool HadMultipleCandidates,
11372 bool IsListInitialization,
11373 bool IsStdInitListInitialization,
11374 bool RequiresZeroInit,
11375 unsigned ConstructKind,
11376 SourceRange ParenRange) {
11377 MarkFunctionReferenced(ConstructLoc, Constructor);
11378 return CXXConstructExpr::Create(
11379 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11380 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11382 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11386 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11387 assert(Field->hasInClassInitializer());
11389 // If we already have the in-class initializer nothing needs to be done.
11390 if (Field->getInClassInitializer())
11391 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11393 // Maybe we haven't instantiated the in-class initializer. Go check the
11394 // pattern FieldDecl to see if it has one.
11395 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11397 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11398 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11399 DeclContext::lookup_result Lookup =
11400 ClassPattern->lookup(Field->getDeclName());
11401 assert(Lookup.size() == 1);
11402 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11403 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11404 getTemplateInstantiationArgs(Field)))
11405 return ExprError();
11406 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11410 // If the brace-or-equal-initializer of a non-static data member
11411 // invokes a defaulted default constructor of its class or of an
11412 // enclosing class in a potentially evaluated subexpression, the
11413 // program is ill-formed.
11415 // This resolution is unworkable: the exception specification of the
11416 // default constructor can be needed in an unevaluated context, in
11417 // particular, in the operand of a noexcept-expression, and we can be
11418 // unable to compute an exception specification for an enclosed class.
11420 // Any attempt to resolve the exception specification of a defaulted default
11421 // constructor before the initializer is lexically complete will ultimately
11422 // come here at which point we can diagnose it.
11423 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11424 if (OutermostClass == ParentRD) {
11425 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11426 << ParentRD << Field;
11428 Diag(Field->getLocEnd(),
11429 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11430 << ParentRD << OutermostClass << Field;
11433 return ExprError();
11436 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11437 if (VD->isInvalidDecl()) return;
11439 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11440 if (ClassDecl->isInvalidDecl()) return;
11441 if (ClassDecl->hasIrrelevantDestructor()) return;
11442 if (ClassDecl->isDependentContext()) return;
11444 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11445 MarkFunctionReferenced(VD->getLocation(), Destructor);
11446 CheckDestructorAccess(VD->getLocation(), Destructor,
11447 PDiag(diag::err_access_dtor_var)
11448 << VD->getDeclName()
11450 DiagnoseUseOfDecl(Destructor, VD->getLocation());
11452 if (Destructor->isTrivial()) return;
11453 if (!VD->hasGlobalStorage()) return;
11455 // Emit warning for non-trivial dtor in global scope (a real global,
11456 // class-static, function-static).
11457 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11459 // TODO: this should be re-enabled for static locals by !CXAAtExit
11460 if (!VD->isStaticLocal())
11461 Diag(VD->getLocation(), diag::warn_global_destructor);
11464 /// \brief Given a constructor and the set of arguments provided for the
11465 /// constructor, convert the arguments and add any required default arguments
11466 /// to form a proper call to this constructor.
11468 /// \returns true if an error occurred, false otherwise.
11470 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11471 MultiExprArg ArgsPtr,
11472 SourceLocation Loc,
11473 SmallVectorImpl<Expr*> &ConvertedArgs,
11474 bool AllowExplicit,
11475 bool IsListInitialization) {
11476 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11477 unsigned NumArgs = ArgsPtr.size();
11478 Expr **Args = ArgsPtr.data();
11480 const FunctionProtoType *Proto
11481 = Constructor->getType()->getAs<FunctionProtoType>();
11482 assert(Proto && "Constructor without a prototype?");
11483 unsigned NumParams = Proto->getNumParams();
11485 // If too few arguments are available, we'll fill in the rest with defaults.
11486 if (NumArgs < NumParams)
11487 ConvertedArgs.reserve(NumParams);
11489 ConvertedArgs.reserve(NumArgs);
11491 VariadicCallType CallType =
11492 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11493 SmallVector<Expr *, 8> AllArgs;
11494 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11496 llvm::makeArrayRef(Args, NumArgs),
11498 CallType, AllowExplicit,
11499 IsListInitialization);
11500 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11502 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11504 CheckConstructorCall(Constructor,
11505 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11512 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11513 const FunctionDecl *FnDecl) {
11514 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11515 if (isa<NamespaceDecl>(DC)) {
11516 return SemaRef.Diag(FnDecl->getLocation(),
11517 diag::err_operator_new_delete_declared_in_namespace)
11518 << FnDecl->getDeclName();
11521 if (isa<TranslationUnitDecl>(DC) &&
11522 FnDecl->getStorageClass() == SC_Static) {
11523 return SemaRef.Diag(FnDecl->getLocation(),
11524 diag::err_operator_new_delete_declared_static)
11525 << FnDecl->getDeclName();
11532 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11533 CanQualType ExpectedResultType,
11534 CanQualType ExpectedFirstParamType,
11535 unsigned DependentParamTypeDiag,
11536 unsigned InvalidParamTypeDiag) {
11537 QualType ResultType =
11538 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11540 // Check that the result type is not dependent.
11541 if (ResultType->isDependentType())
11542 return SemaRef.Diag(FnDecl->getLocation(),
11543 diag::err_operator_new_delete_dependent_result_type)
11544 << FnDecl->getDeclName() << ExpectedResultType;
11546 // Check that the result type is what we expect.
11547 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11548 return SemaRef.Diag(FnDecl->getLocation(),
11549 diag::err_operator_new_delete_invalid_result_type)
11550 << FnDecl->getDeclName() << ExpectedResultType;
11552 // A function template must have at least 2 parameters.
11553 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11554 return SemaRef.Diag(FnDecl->getLocation(),
11555 diag::err_operator_new_delete_template_too_few_parameters)
11556 << FnDecl->getDeclName();
11558 // The function decl must have at least 1 parameter.
11559 if (FnDecl->getNumParams() == 0)
11560 return SemaRef.Diag(FnDecl->getLocation(),
11561 diag::err_operator_new_delete_too_few_parameters)
11562 << FnDecl->getDeclName();
11564 // Check the first parameter type is not dependent.
11565 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11566 if (FirstParamType->isDependentType())
11567 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11568 << FnDecl->getDeclName() << ExpectedFirstParamType;
11570 // Check that the first parameter type is what we expect.
11571 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11572 ExpectedFirstParamType)
11573 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11574 << FnDecl->getDeclName() << ExpectedFirstParamType;
11580 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11581 // C++ [basic.stc.dynamic.allocation]p1:
11582 // A program is ill-formed if an allocation function is declared in a
11583 // namespace scope other than global scope or declared static in global
11585 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11588 CanQualType SizeTy =
11589 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11591 // C++ [basic.stc.dynamic.allocation]p1:
11592 // The return type shall be void*. The first parameter shall have type
11594 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11596 diag::err_operator_new_dependent_param_type,
11597 diag::err_operator_new_param_type))
11600 // C++ [basic.stc.dynamic.allocation]p1:
11601 // The first parameter shall not have an associated default argument.
11602 if (FnDecl->getParamDecl(0)->hasDefaultArg())
11603 return SemaRef.Diag(FnDecl->getLocation(),
11604 diag::err_operator_new_default_arg)
11605 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11611 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11612 // C++ [basic.stc.dynamic.deallocation]p1:
11613 // A program is ill-formed if deallocation functions are declared in a
11614 // namespace scope other than global scope or declared static in global
11616 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11619 // C++ [basic.stc.dynamic.deallocation]p2:
11620 // Each deallocation function shall return void and its first parameter
11622 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11623 SemaRef.Context.VoidPtrTy,
11624 diag::err_operator_delete_dependent_param_type,
11625 diag::err_operator_delete_param_type))
11631 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11632 /// of this overloaded operator is well-formed. If so, returns false;
11633 /// otherwise, emits appropriate diagnostics and returns true.
11634 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11635 assert(FnDecl && FnDecl->isOverloadedOperator() &&
11636 "Expected an overloaded operator declaration");
11638 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11640 // C++ [over.oper]p5:
11641 // The allocation and deallocation functions, operator new,
11642 // operator new[], operator delete and operator delete[], are
11643 // described completely in 3.7.3. The attributes and restrictions
11644 // found in the rest of this subclause do not apply to them unless
11645 // explicitly stated in 3.7.3.
11646 if (Op == OO_Delete || Op == OO_Array_Delete)
11647 return CheckOperatorDeleteDeclaration(*this, FnDecl);
11649 if (Op == OO_New || Op == OO_Array_New)
11650 return CheckOperatorNewDeclaration(*this, FnDecl);
11652 // C++ [over.oper]p6:
11653 // An operator function shall either be a non-static member
11654 // function or be a non-member function and have at least one
11655 // parameter whose type is a class, a reference to a class, an
11656 // enumeration, or a reference to an enumeration.
11657 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11658 if (MethodDecl->isStatic())
11659 return Diag(FnDecl->getLocation(),
11660 diag::err_operator_overload_static) << FnDecl->getDeclName();
11662 bool ClassOrEnumParam = false;
11663 for (auto Param : FnDecl->params()) {
11664 QualType ParamType = Param->getType().getNonReferenceType();
11665 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11666 ParamType->isEnumeralType()) {
11667 ClassOrEnumParam = true;
11672 if (!ClassOrEnumParam)
11673 return Diag(FnDecl->getLocation(),
11674 diag::err_operator_overload_needs_class_or_enum)
11675 << FnDecl->getDeclName();
11678 // C++ [over.oper]p8:
11679 // An operator function cannot have default arguments (8.3.6),
11680 // except where explicitly stated below.
11682 // Only the function-call operator allows default arguments
11683 // (C++ [over.call]p1).
11684 if (Op != OO_Call) {
11685 for (auto Param : FnDecl->params()) {
11686 if (Param->hasDefaultArg())
11687 return Diag(Param->getLocation(),
11688 diag::err_operator_overload_default_arg)
11689 << FnDecl->getDeclName() << Param->getDefaultArgRange();
11693 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11694 { false, false, false }
11695 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11696 , { Unary, Binary, MemberOnly }
11697 #include "clang/Basic/OperatorKinds.def"
11700 bool CanBeUnaryOperator = OperatorUses[Op][0];
11701 bool CanBeBinaryOperator = OperatorUses[Op][1];
11702 bool MustBeMemberOperator = OperatorUses[Op][2];
11704 // C++ [over.oper]p8:
11705 // [...] Operator functions cannot have more or fewer parameters
11706 // than the number required for the corresponding operator, as
11707 // described in the rest of this subclause.
11708 unsigned NumParams = FnDecl->getNumParams()
11709 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11710 if (Op != OO_Call &&
11711 ((NumParams == 1 && !CanBeUnaryOperator) ||
11712 (NumParams == 2 && !CanBeBinaryOperator) ||
11713 (NumParams < 1) || (NumParams > 2))) {
11714 // We have the wrong number of parameters.
11715 unsigned ErrorKind;
11716 if (CanBeUnaryOperator && CanBeBinaryOperator) {
11717 ErrorKind = 2; // 2 -> unary or binary.
11718 } else if (CanBeUnaryOperator) {
11719 ErrorKind = 0; // 0 -> unary
11721 assert(CanBeBinaryOperator &&
11722 "All non-call overloaded operators are unary or binary!");
11723 ErrorKind = 1; // 1 -> binary
11726 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11727 << FnDecl->getDeclName() << NumParams << ErrorKind;
11730 // Overloaded operators other than operator() cannot be variadic.
11731 if (Op != OO_Call &&
11732 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11733 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11734 << FnDecl->getDeclName();
11737 // Some operators must be non-static member functions.
11738 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11739 return Diag(FnDecl->getLocation(),
11740 diag::err_operator_overload_must_be_member)
11741 << FnDecl->getDeclName();
11744 // C++ [over.inc]p1:
11745 // The user-defined function called operator++ implements the
11746 // prefix and postfix ++ operator. If this function is a member
11747 // function with no parameters, or a non-member function with one
11748 // parameter of class or enumeration type, it defines the prefix
11749 // increment operator ++ for objects of that type. If the function
11750 // is a member function with one parameter (which shall be of type
11751 // int) or a non-member function with two parameters (the second
11752 // of which shall be of type int), it defines the postfix
11753 // increment operator ++ for objects of that type.
11754 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11755 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11756 QualType ParamType = LastParam->getType();
11758 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11759 !ParamType->isDependentType())
11760 return Diag(LastParam->getLocation(),
11761 diag::err_operator_overload_post_incdec_must_be_int)
11762 << LastParam->getType() << (Op == OO_MinusMinus);
11768 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11769 /// of this literal operator function is well-formed. If so, returns
11770 /// false; otherwise, emits appropriate diagnostics and returns true.
11771 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11772 if (isa<CXXMethodDecl>(FnDecl)) {
11773 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11774 << FnDecl->getDeclName();
11778 if (FnDecl->isExternC()) {
11779 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11783 bool Valid = false;
11785 // This might be the definition of a literal operator template.
11786 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11787 // This might be a specialization of a literal operator template.
11789 TpDecl = FnDecl->getPrimaryTemplate();
11791 // template <char...> type operator "" name() and
11792 // template <class T, T...> type operator "" name() are the only valid
11793 // template signatures, and the only valid signatures with no parameters.
11795 if (FnDecl->param_size() == 0) {
11796 // Must have one or two template parameters
11797 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11798 if (Params->size() == 1) {
11799 NonTypeTemplateParmDecl *PmDecl =
11800 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11802 // The template parameter must be a char parameter pack.
11803 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11804 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11806 } else if (Params->size() == 2) {
11807 TemplateTypeParmDecl *PmType =
11808 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11809 NonTypeTemplateParmDecl *PmArgs =
11810 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11812 // The second template parameter must be a parameter pack with the
11813 // first template parameter as its type.
11814 if (PmType && PmArgs &&
11815 !PmType->isTemplateParameterPack() &&
11816 PmArgs->isTemplateParameterPack()) {
11817 const TemplateTypeParmType *TArgs =
11818 PmArgs->getType()->getAs<TemplateTypeParmType>();
11819 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11820 TArgs->getIndex() == PmType->getIndex()) {
11822 if (ActiveTemplateInstantiations.empty())
11823 Diag(FnDecl->getLocation(),
11824 diag::ext_string_literal_operator_template);
11829 } else if (FnDecl->param_size()) {
11830 // Check the first parameter
11831 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11833 QualType T = (*Param)->getType().getUnqualifiedType();
11835 // unsigned long long int, long double, and any character type are allowed
11836 // as the only parameters.
11837 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11838 Context.hasSameType(T, Context.LongDoubleTy) ||
11839 Context.hasSameType(T, Context.CharTy) ||
11840 Context.hasSameType(T, Context.WideCharTy) ||
11841 Context.hasSameType(T, Context.Char16Ty) ||
11842 Context.hasSameType(T, Context.Char32Ty)) {
11843 if (++Param == FnDecl->param_end())
11845 goto FinishedParams;
11848 // Otherwise it must be a pointer to const; let's strip those qualifiers.
11849 const PointerType *PT = T->getAs<PointerType>();
11851 goto FinishedParams;
11852 T = PT->getPointeeType();
11853 if (!T.isConstQualified() || T.isVolatileQualified())
11854 goto FinishedParams;
11855 T = T.getUnqualifiedType();
11857 // Move on to the second parameter;
11860 // If there is no second parameter, the first must be a const char *
11861 if (Param == FnDecl->param_end()) {
11862 if (Context.hasSameType(T, Context.CharTy))
11864 goto FinishedParams;
11867 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11868 // are allowed as the first parameter to a two-parameter function
11869 if (!(Context.hasSameType(T, Context.CharTy) ||
11870 Context.hasSameType(T, Context.WideCharTy) ||
11871 Context.hasSameType(T, Context.Char16Ty) ||
11872 Context.hasSameType(T, Context.Char32Ty)))
11873 goto FinishedParams;
11875 // The second and final parameter must be an std::size_t
11876 T = (*Param)->getType().getUnqualifiedType();
11877 if (Context.hasSameType(T, Context.getSizeType()) &&
11878 ++Param == FnDecl->param_end())
11882 // FIXME: This diagnostic is absolutely terrible.
11885 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11886 << FnDecl->getDeclName();
11890 // A parameter-declaration-clause containing a default argument is not
11891 // equivalent to any of the permitted forms.
11892 for (auto Param : FnDecl->params()) {
11893 if (Param->hasDefaultArg()) {
11894 Diag(Param->getDefaultArgRange().getBegin(),
11895 diag::err_literal_operator_default_argument)
11896 << Param->getDefaultArgRange();
11901 StringRef LiteralName
11902 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11903 if (LiteralName[0] != '_') {
11904 // C++11 [usrlit.suffix]p1:
11905 // Literal suffix identifiers that do not start with an underscore
11906 // are reserved for future standardization.
11907 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11908 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11914 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11915 /// linkage specification, including the language and (if present)
11916 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11917 /// language string literal. LBraceLoc, if valid, provides the location of
11918 /// the '{' brace. Otherwise, this linkage specification does not
11919 /// have any braces.
11920 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11922 SourceLocation LBraceLoc) {
11923 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11924 if (!Lit->isAscii()) {
11925 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11926 << LangStr->getSourceRange();
11930 StringRef Lang = Lit->getString();
11931 LinkageSpecDecl::LanguageIDs Language;
11933 Language = LinkageSpecDecl::lang_c;
11934 else if (Lang == "C++")
11935 Language = LinkageSpecDecl::lang_cxx;
11937 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11938 << LangStr->getSourceRange();
11942 // FIXME: Add all the various semantics of linkage specifications
11944 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11945 LangStr->getExprLoc(), Language,
11946 LBraceLoc.isValid());
11947 CurContext->addDecl(D);
11948 PushDeclContext(S, D);
11952 /// ActOnFinishLinkageSpecification - Complete the definition of
11953 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11954 /// valid, it's the position of the closing '}' brace in a linkage
11955 /// specification that uses braces.
11956 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11958 SourceLocation RBraceLoc) {
11959 if (RBraceLoc.isValid()) {
11960 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11961 LSDecl->setRBraceLoc(RBraceLoc);
11964 return LinkageSpec;
11967 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11968 AttributeList *AttrList,
11969 SourceLocation SemiLoc) {
11970 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11971 // Attribute declarations appertain to empty declaration so we handle
11974 ProcessDeclAttributeList(S, ED, AttrList);
11976 CurContext->addDecl(ED);
11980 /// \brief Perform semantic analysis for the variable declaration that
11981 /// occurs within a C++ catch clause, returning the newly-created
11983 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11984 TypeSourceInfo *TInfo,
11985 SourceLocation StartLoc,
11986 SourceLocation Loc,
11987 IdentifierInfo *Name) {
11988 bool Invalid = false;
11989 QualType ExDeclType = TInfo->getType();
11991 // Arrays and functions decay.
11992 if (ExDeclType->isArrayType())
11993 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11994 else if (ExDeclType->isFunctionType())
11995 ExDeclType = Context.getPointerType(ExDeclType);
11997 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11998 // The exception-declaration shall not denote a pointer or reference to an
11999 // incomplete type, other than [cv] void*.
12000 // N2844 forbids rvalue references.
12001 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12002 Diag(Loc, diag::err_catch_rvalue_ref);
12006 QualType BaseType = ExDeclType;
12007 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12008 unsigned DK = diag::err_catch_incomplete;
12009 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12010 BaseType = Ptr->getPointeeType();
12012 DK = diag::err_catch_incomplete_ptr;
12013 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12014 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12015 BaseType = Ref->getPointeeType();
12017 DK = diag::err_catch_incomplete_ref;
12019 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12020 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12023 if (!Invalid && !ExDeclType->isDependentType() &&
12024 RequireNonAbstractType(Loc, ExDeclType,
12025 diag::err_abstract_type_in_decl,
12026 AbstractVariableType))
12029 // Only the non-fragile NeXT runtime currently supports C++ catches
12030 // of ObjC types, and no runtime supports catching ObjC types by value.
12031 if (!Invalid && getLangOpts().ObjC1) {
12032 QualType T = ExDeclType;
12033 if (const ReferenceType *RT = T->getAs<ReferenceType>())
12034 T = RT->getPointeeType();
12036 if (T->isObjCObjectType()) {
12037 Diag(Loc, diag::err_objc_object_catch);
12039 } else if (T->isObjCObjectPointerType()) {
12040 // FIXME: should this be a test for macosx-fragile specifically?
12041 if (getLangOpts().ObjCRuntime.isFragile())
12042 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12046 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12047 ExDeclType, TInfo, SC_None);
12048 ExDecl->setExceptionVariable(true);
12050 // In ARC, infer 'retaining' for variables of retainable type.
12051 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12054 if (!Invalid && !ExDeclType->isDependentType()) {
12055 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12056 // Insulate this from anything else we might currently be parsing.
12057 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12059 // C++ [except.handle]p16:
12060 // The object declared in an exception-declaration or, if the
12061 // exception-declaration does not specify a name, a temporary (12.2) is
12062 // copy-initialized (8.5) from the exception object. [...]
12063 // The object is destroyed when the handler exits, after the destruction
12064 // of any automatic objects initialized within the handler.
12066 // We just pretend to initialize the object with itself, then make sure
12067 // it can be destroyed later.
12068 QualType initType = Context.getExceptionObjectType(ExDeclType);
12070 InitializedEntity entity =
12071 InitializedEntity::InitializeVariable(ExDecl);
12072 InitializationKind initKind =
12073 InitializationKind::CreateCopy(Loc, SourceLocation());
12075 Expr *opaqueValue =
12076 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12077 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12078 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12079 if (result.isInvalid())
12082 // If the constructor used was non-trivial, set this as the
12084 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12085 if (!construct->getConstructor()->isTrivial()) {
12086 Expr *init = MaybeCreateExprWithCleanups(construct);
12087 ExDecl->setInit(init);
12090 // And make sure it's destructable.
12091 FinalizeVarWithDestructor(ExDecl, recordType);
12097 ExDecl->setInvalidDecl();
12102 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12104 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12105 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12106 bool Invalid = D.isInvalidType();
12108 // Check for unexpanded parameter packs.
12109 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12110 UPPC_ExceptionType)) {
12111 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12112 D.getIdentifierLoc());
12116 IdentifierInfo *II = D.getIdentifier();
12117 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12118 LookupOrdinaryName,
12119 ForRedeclaration)) {
12120 // The scope should be freshly made just for us. There is just no way
12121 // it contains any previous declaration, except for function parameters in
12122 // a function-try-block's catch statement.
12123 assert(!S->isDeclScope(PrevDecl));
12124 if (isDeclInScope(PrevDecl, CurContext, S)) {
12125 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12126 << D.getIdentifier();
12127 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12129 } else if (PrevDecl->isTemplateParameter())
12130 // Maybe we will complain about the shadowed template parameter.
12131 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12134 if (D.getCXXScopeSpec().isSet() && !Invalid) {
12135 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12136 << D.getCXXScopeSpec().getRange();
12140 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12142 D.getIdentifierLoc(),
12143 D.getIdentifier());
12145 ExDecl->setInvalidDecl();
12147 // Add the exception declaration into this scope.
12149 PushOnScopeChains(ExDecl, S);
12151 CurContext->addDecl(ExDecl);
12153 ProcessDeclAttributes(S, ExDecl, D);
12157 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12159 Expr *AssertMessageExpr,
12160 SourceLocation RParenLoc) {
12161 StringLiteral *AssertMessage =
12162 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12164 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12167 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12168 AssertMessage, RParenLoc, false);
12171 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12173 StringLiteral *AssertMessage,
12174 SourceLocation RParenLoc,
12176 assert(AssertExpr != nullptr && "Expected non-null condition");
12177 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12179 // In a static_assert-declaration, the constant-expression shall be a
12180 // constant expression that can be contextually converted to bool.
12181 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12182 if (Converted.isInvalid())
12186 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12187 diag::err_static_assert_expression_is_not_constant,
12188 /*AllowFold=*/false).isInvalid())
12191 if (!Failed && !Cond) {
12192 SmallString<256> MsgBuffer;
12193 llvm::raw_svector_ostream Msg(MsgBuffer);
12195 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12196 Diag(StaticAssertLoc, diag::err_static_assert_failed)
12197 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12202 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12203 AssertExpr, AssertMessage, RParenLoc,
12206 CurContext->addDecl(Decl);
12210 /// \brief Perform semantic analysis of the given friend type declaration.
12212 /// \returns A friend declaration that.
12213 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12214 SourceLocation FriendLoc,
12215 TypeSourceInfo *TSInfo) {
12216 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12218 QualType T = TSInfo->getType();
12219 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12221 // C++03 [class.friend]p2:
12222 // An elaborated-type-specifier shall be used in a friend declaration
12225 // * The class-key of the elaborated-type-specifier is required.
12226 if (!ActiveTemplateInstantiations.empty()) {
12227 // Do not complain about the form of friend template types during
12228 // template instantiation; we will already have complained when the
12229 // template was declared.
12231 if (!T->isElaboratedTypeSpecifier()) {
12232 // If we evaluated the type to a record type, suggest putting
12234 if (const RecordType *RT = T->getAs<RecordType>()) {
12235 RecordDecl *RD = RT->getDecl();
12237 SmallString<16> InsertionText(" ");
12238 InsertionText += RD->getKindName();
12240 Diag(TypeRange.getBegin(),
12241 getLangOpts().CPlusPlus11 ?
12242 diag::warn_cxx98_compat_unelaborated_friend_type :
12243 diag::ext_unelaborated_friend_type)
12244 << (unsigned) RD->getTagKind()
12246 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
12250 getLangOpts().CPlusPlus11 ?
12251 diag::warn_cxx98_compat_nonclass_type_friend :
12252 diag::ext_nonclass_type_friend)
12256 } else if (T->getAs<EnumType>()) {
12258 getLangOpts().CPlusPlus11 ?
12259 diag::warn_cxx98_compat_enum_friend :
12260 diag::ext_enum_friend)
12265 // C++11 [class.friend]p3:
12266 // A friend declaration that does not declare a function shall have one
12267 // of the following forms:
12268 // friend elaborated-type-specifier ;
12269 // friend simple-type-specifier ;
12270 // friend typename-specifier ;
12271 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12272 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12275 // If the type specifier in a friend declaration designates a (possibly
12276 // cv-qualified) class type, that class is declared as a friend; otherwise,
12277 // the friend declaration is ignored.
12278 return FriendDecl::Create(Context, CurContext,
12279 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12283 /// Handle a friend tag declaration where the scope specifier was
12285 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12286 unsigned TagSpec, SourceLocation TagLoc,
12288 IdentifierInfo *Name,
12289 SourceLocation NameLoc,
12290 AttributeList *Attr,
12291 MultiTemplateParamsArg TempParamLists) {
12292 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12294 bool isExplicitSpecialization = false;
12295 bool Invalid = false;
12297 if (TemplateParameterList *TemplateParams =
12298 MatchTemplateParametersToScopeSpecifier(
12299 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12300 isExplicitSpecialization, Invalid)) {
12301 if (TemplateParams->size() > 0) {
12302 // This is a declaration of a class template.
12306 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12307 NameLoc, Attr, TemplateParams, AS_public,
12308 /*ModulePrivateLoc=*/SourceLocation(),
12309 FriendLoc, TempParamLists.size() - 1,
12310 TempParamLists.data()).get();
12312 // The "template<>" header is extraneous.
12313 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12314 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12315 isExplicitSpecialization = true;
12319 if (Invalid) return nullptr;
12321 bool isAllExplicitSpecializations = true;
12322 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12323 if (TempParamLists[I]->size()) {
12324 isAllExplicitSpecializations = false;
12329 // FIXME: don't ignore attributes.
12331 // If it's explicit specializations all the way down, just forget
12332 // about the template header and build an appropriate non-templated
12333 // friend. TODO: for source fidelity, remember the headers.
12334 if (isAllExplicitSpecializations) {
12335 if (SS.isEmpty()) {
12336 bool Owned = false;
12337 bool IsDependent = false;
12338 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12340 /*ModulePrivateLoc=*/SourceLocation(),
12341 MultiTemplateParamsArg(), Owned, IsDependent,
12342 /*ScopedEnumKWLoc=*/SourceLocation(),
12343 /*ScopedEnumUsesClassTag=*/false,
12344 /*UnderlyingType=*/TypeResult(),
12345 /*IsTypeSpecifier=*/false);
12348 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12349 ElaboratedTypeKeyword Keyword
12350 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12351 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12356 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12357 if (isa<DependentNameType>(T)) {
12358 DependentNameTypeLoc TL =
12359 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12360 TL.setElaboratedKeywordLoc(TagLoc);
12361 TL.setQualifierLoc(QualifierLoc);
12362 TL.setNameLoc(NameLoc);
12364 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12365 TL.setElaboratedKeywordLoc(TagLoc);
12366 TL.setQualifierLoc(QualifierLoc);
12367 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12370 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12371 TSI, FriendLoc, TempParamLists);
12372 Friend->setAccess(AS_public);
12373 CurContext->addDecl(Friend);
12377 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12381 // Handle the case of a templated-scope friend class. e.g.
12382 // template <class T> class A<T>::B;
12383 // FIXME: we don't support these right now.
12384 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12385 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12386 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12387 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12388 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12389 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12390 TL.setElaboratedKeywordLoc(TagLoc);
12391 TL.setQualifierLoc(SS.getWithLocInContext(Context));
12392 TL.setNameLoc(NameLoc);
12394 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12395 TSI, FriendLoc, TempParamLists);
12396 Friend->setAccess(AS_public);
12397 Friend->setUnsupportedFriend(true);
12398 CurContext->addDecl(Friend);
12403 /// Handle a friend type declaration. This works in tandem with
12406 /// Notes on friend class templates:
12408 /// We generally treat friend class declarations as if they were
12409 /// declaring a class. So, for example, the elaborated type specifier
12410 /// in a friend declaration is required to obey the restrictions of a
12411 /// class-head (i.e. no typedefs in the scope chain), template
12412 /// parameters are required to match up with simple template-ids, &c.
12413 /// However, unlike when declaring a template specialization, it's
12414 /// okay to refer to a template specialization without an empty
12415 /// template parameter declaration, e.g.
12416 /// friend class A<T>::B<unsigned>;
12417 /// We permit this as a special case; if there are any template
12418 /// parameters present at all, require proper matching, i.e.
12419 /// template <> template \<class T> friend class A<int>::B;
12420 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12421 MultiTemplateParamsArg TempParams) {
12422 SourceLocation Loc = DS.getLocStart();
12424 assert(DS.isFriendSpecified());
12425 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12427 // Try to convert the decl specifier to a type. This works for
12428 // friend templates because ActOnTag never produces a ClassTemplateDecl
12429 // for a TUK_Friend.
12430 Declarator TheDeclarator(DS, Declarator::MemberContext);
12431 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12432 QualType T = TSI->getType();
12433 if (TheDeclarator.isInvalidType())
12436 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12439 // This is definitely an error in C++98. It's probably meant to
12440 // be forbidden in C++0x, too, but the specification is just
12443 // The problem is with declarations like the following:
12444 // template <T> friend A<T>::foo;
12445 // where deciding whether a class C is a friend or not now hinges
12446 // on whether there exists an instantiation of A that causes
12447 // 'foo' to equal C. There are restrictions on class-heads
12448 // (which we declare (by fiat) elaborated friend declarations to
12449 // be) that makes this tractable.
12451 // FIXME: handle "template <> friend class A<T>;", which
12452 // is possibly well-formed? Who even knows?
12453 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12454 Diag(Loc, diag::err_tagless_friend_type_template)
12455 << DS.getSourceRange();
12459 // C++98 [class.friend]p1: A friend of a class is a function
12460 // or class that is not a member of the class . . .
12461 // This is fixed in DR77, which just barely didn't make the C++03
12462 // deadline. It's also a very silly restriction that seriously
12463 // affects inner classes and which nobody else seems to implement;
12464 // thus we never diagnose it, not even in -pedantic.
12466 // But note that we could warn about it: it's always useless to
12467 // friend one of your own members (it's not, however, worthless to
12468 // friend a member of an arbitrary specialization of your template).
12471 if (unsigned NumTempParamLists = TempParams.size())
12472 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12476 DS.getFriendSpecLoc());
12478 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12483 D->setAccess(AS_public);
12484 CurContext->addDecl(D);
12489 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12490 MultiTemplateParamsArg TemplateParams) {
12491 const DeclSpec &DS = D.getDeclSpec();
12493 assert(DS.isFriendSpecified());
12494 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12496 SourceLocation Loc = D.getIdentifierLoc();
12497 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12499 // C++ [class.friend]p1
12500 // A friend of a class is a function or class....
12501 // Note that this sees through typedefs, which is intended.
12502 // It *doesn't* see through dependent types, which is correct
12503 // according to [temp.arg.type]p3:
12504 // If a declaration acquires a function type through a
12505 // type dependent on a template-parameter and this causes
12506 // a declaration that does not use the syntactic form of a
12507 // function declarator to have a function type, the program
12509 if (!TInfo->getType()->isFunctionType()) {
12510 Diag(Loc, diag::err_unexpected_friend);
12512 // It might be worthwhile to try to recover by creating an
12513 // appropriate declaration.
12517 // C++ [namespace.memdef]p3
12518 // - If a friend declaration in a non-local class first declares a
12519 // class or function, the friend class or function is a member
12520 // of the innermost enclosing namespace.
12521 // - The name of the friend is not found by simple name lookup
12522 // until a matching declaration is provided in that namespace
12523 // scope (either before or after the class declaration granting
12525 // - If a friend function is called, its name may be found by the
12526 // name lookup that considers functions from namespaces and
12527 // classes associated with the types of the function arguments.
12528 // - When looking for a prior declaration of a class or a function
12529 // declared as a friend, scopes outside the innermost enclosing
12530 // namespace scope are not considered.
12532 CXXScopeSpec &SS = D.getCXXScopeSpec();
12533 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12534 DeclarationName Name = NameInfo.getName();
12537 // Check for unexpanded parameter packs.
12538 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12539 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12540 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12543 // The context we found the declaration in, or in which we should
12544 // create the declaration.
12546 Scope *DCScope = S;
12547 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12550 // There are five cases here.
12551 // - There's no scope specifier and we're in a local class. Only look
12552 // for functions declared in the immediately-enclosing block scope.
12553 // We recover from invalid scope qualifiers as if they just weren't there.
12554 FunctionDecl *FunctionContainingLocalClass = nullptr;
12555 if ((SS.isInvalid() || !SS.isSet()) &&
12556 (FunctionContainingLocalClass =
12557 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12558 // C++11 [class.friend]p11:
12559 // If a friend declaration appears in a local class and the name
12560 // specified is an unqualified name, a prior declaration is
12561 // looked up without considering scopes that are outside the
12562 // innermost enclosing non-class scope. For a friend function
12563 // declaration, if there is no prior declaration, the program is
12566 // Find the innermost enclosing non-class scope. This is the block
12567 // scope containing the local class definition (or for a nested class,
12568 // the outer local class).
12569 DCScope = S->getFnParent();
12571 // Look up the function name in the scope.
12572 Previous.clear(LookupLocalFriendName);
12573 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12575 if (!Previous.empty()) {
12576 // All possible previous declarations must have the same context:
12577 // either they were declared at block scope or they are members of
12578 // one of the enclosing local classes.
12579 DC = Previous.getRepresentativeDecl()->getDeclContext();
12581 // This is ill-formed, but provide the context that we would have
12582 // declared the function in, if we were permitted to, for error recovery.
12583 DC = FunctionContainingLocalClass;
12585 adjustContextForLocalExternDecl(DC);
12587 // C++ [class.friend]p6:
12588 // A function can be defined in a friend declaration of a class if and
12589 // only if the class is a non-local class (9.8), the function name is
12590 // unqualified, and the function has namespace scope.
12591 if (D.isFunctionDefinition()) {
12592 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12595 // - There's no scope specifier, in which case we just go to the
12596 // appropriate scope and look for a function or function template
12597 // there as appropriate.
12598 } else if (SS.isInvalid() || !SS.isSet()) {
12599 // C++11 [namespace.memdef]p3:
12600 // If the name in a friend declaration is neither qualified nor
12601 // a template-id and the declaration is a function or an
12602 // elaborated-type-specifier, the lookup to determine whether
12603 // the entity has been previously declared shall not consider
12604 // any scopes outside the innermost enclosing namespace.
12605 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12607 // Find the appropriate context according to the above.
12610 // Skip class contexts. If someone can cite chapter and verse
12611 // for this behavior, that would be nice --- it's what GCC and
12612 // EDG do, and it seems like a reasonable intent, but the spec
12613 // really only says that checks for unqualified existing
12614 // declarations should stop at the nearest enclosing namespace,
12615 // not that they should only consider the nearest enclosing
12617 while (DC->isRecord())
12618 DC = DC->getParent();
12620 DeclContext *LookupDC = DC;
12621 while (LookupDC->isTransparentContext())
12622 LookupDC = LookupDC->getParent();
12625 LookupQualifiedName(Previous, LookupDC);
12627 if (!Previous.empty()) {
12632 if (isTemplateId) {
12633 if (isa<TranslationUnitDecl>(LookupDC)) break;
12635 if (LookupDC->isFileContext()) break;
12637 LookupDC = LookupDC->getParent();
12640 DCScope = getScopeForDeclContext(S, DC);
12642 // - There's a non-dependent scope specifier, in which case we
12643 // compute it and do a previous lookup there for a function
12644 // or function template.
12645 } else if (!SS.getScopeRep()->isDependent()) {
12646 DC = computeDeclContext(SS);
12647 if (!DC) return nullptr;
12649 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12651 LookupQualifiedName(Previous, DC);
12653 // Ignore things found implicitly in the wrong scope.
12654 // TODO: better diagnostics for this case. Suggesting the right
12655 // qualified scope would be nice...
12656 LookupResult::Filter F = Previous.makeFilter();
12657 while (F.hasNext()) {
12658 NamedDecl *D = F.next();
12659 if (!DC->InEnclosingNamespaceSetOf(
12660 D->getDeclContext()->getRedeclContext()))
12665 if (Previous.empty()) {
12666 D.setInvalidType();
12667 Diag(Loc, diag::err_qualified_friend_not_found)
12668 << Name << TInfo->getType();
12672 // C++ [class.friend]p1: A friend of a class is a function or
12673 // class that is not a member of the class . . .
12674 if (DC->Equals(CurContext))
12675 Diag(DS.getFriendSpecLoc(),
12676 getLangOpts().CPlusPlus11 ?
12677 diag::warn_cxx98_compat_friend_is_member :
12678 diag::err_friend_is_member);
12680 if (D.isFunctionDefinition()) {
12681 // C++ [class.friend]p6:
12682 // A function can be defined in a friend declaration of a class if and
12683 // only if the class is a non-local class (9.8), the function name is
12684 // unqualified, and the function has namespace scope.
12685 SemaDiagnosticBuilder DB
12686 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12688 DB << SS.getScopeRep();
12689 if (DC->isFileContext())
12690 DB << FixItHint::CreateRemoval(SS.getRange());
12694 // - There's a scope specifier that does not match any template
12695 // parameter lists, in which case we use some arbitrary context,
12696 // create a method or method template, and wait for instantiation.
12697 // - There's a scope specifier that does match some template
12698 // parameter lists, which we don't handle right now.
12700 if (D.isFunctionDefinition()) {
12701 // C++ [class.friend]p6:
12702 // A function can be defined in a friend declaration of a class if and
12703 // only if the class is a non-local class (9.8), the function name is
12704 // unqualified, and the function has namespace scope.
12705 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12706 << SS.getScopeRep();
12710 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12713 if (!DC->isRecord()) {
12715 switch (D.getName().getKind()) {
12716 case UnqualifiedId::IK_ConstructorTemplateId:
12717 case UnqualifiedId::IK_ConstructorName:
12720 case UnqualifiedId::IK_DestructorName:
12723 case UnqualifiedId::IK_ConversionFunctionId:
12726 case UnqualifiedId::IK_Identifier:
12727 case UnqualifiedId::IK_ImplicitSelfParam:
12728 case UnqualifiedId::IK_LiteralOperatorId:
12729 case UnqualifiedId::IK_OperatorFunctionId:
12730 case UnqualifiedId::IK_TemplateId:
12733 // This implies that it has to be an operator or function.
12734 if (DiagArg >= 0) {
12735 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
12740 // FIXME: This is an egregious hack to cope with cases where the scope stack
12741 // does not contain the declaration context, i.e., in an out-of-line
12742 // definition of a class.
12743 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12745 FakeDCScope.setEntity(DC);
12746 DCScope = &FakeDCScope;
12749 bool AddToScope = true;
12750 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12751 TemplateParams, AddToScope);
12752 if (!ND) return nullptr;
12754 assert(ND->getLexicalDeclContext() == CurContext);
12756 // If we performed typo correction, we might have added a scope specifier
12757 // and changed the decl context.
12758 DC = ND->getDeclContext();
12760 // Add the function declaration to the appropriate lookup tables,
12761 // adjusting the redeclarations list as necessary. We don't
12762 // want to do this yet if the friending class is dependent.
12764 // Also update the scope-based lookup if the target context's
12765 // lookup context is in lexical scope.
12766 if (!CurContext->isDependentContext()) {
12767 DC = DC->getRedeclContext();
12768 DC->makeDeclVisibleInContext(ND);
12769 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12770 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12773 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12774 D.getIdentifierLoc(), ND,
12775 DS.getFriendSpecLoc());
12776 FrD->setAccess(AS_public);
12777 CurContext->addDecl(FrD);
12779 if (ND->isInvalidDecl()) {
12780 FrD->setInvalidDecl();
12782 if (DC->isRecord()) CheckFriendAccess(ND);
12785 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12786 FD = FTD->getTemplatedDecl();
12788 FD = cast<FunctionDecl>(ND);
12790 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12791 // default argument expression, that declaration shall be a definition
12792 // and shall be the only declaration of the function or function
12793 // template in the translation unit.
12794 if (functionDeclHasDefaultArgument(FD)) {
12795 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12796 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12797 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12798 } else if (!D.isFunctionDefinition())
12799 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12802 // Mark templated-scope function declarations as unsupported.
12803 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12804 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12805 << SS.getScopeRep() << SS.getRange()
12806 << cast<CXXRecordDecl>(CurContext);
12807 FrD->setUnsupportedFriend(true);
12814 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12815 AdjustDeclIfTemplate(Dcl);
12817 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12819 Diag(DelLoc, diag::err_deleted_non_function);
12823 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12824 // Don't consider the implicit declaration we generate for explicit
12825 // specializations. FIXME: Do not generate these implicit declarations.
12826 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12827 Prev->getPreviousDecl()) &&
12828 !Prev->isDefined()) {
12829 Diag(DelLoc, diag::err_deleted_decl_not_first);
12830 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12831 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12832 : diag::note_previous_declaration);
12834 // If the declaration wasn't the first, we delete the function anyway for
12836 Fn = Fn->getCanonicalDecl();
12839 // dllimport/dllexport cannot be deleted.
12840 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12841 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12842 Fn->setInvalidDecl();
12845 if (Fn->isDeleted())
12848 // See if we're deleting a function which is already known to override a
12849 // non-deleted virtual function.
12850 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12851 bool IssuedDiagnostic = false;
12852 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12853 E = MD->end_overridden_methods();
12855 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12856 if (!IssuedDiagnostic) {
12857 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12858 IssuedDiagnostic = true;
12860 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12865 // C++11 [basic.start.main]p3:
12866 // A program that defines main as deleted [...] is ill-formed.
12868 Diag(DelLoc, diag::err_deleted_main);
12870 Fn->setDeletedAsWritten();
12873 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12874 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12877 if (MD->getParent()->isDependentType()) {
12878 MD->setDefaulted();
12879 MD->setExplicitlyDefaulted();
12883 CXXSpecialMember Member = getSpecialMember(MD);
12884 if (Member == CXXInvalid) {
12885 if (!MD->isInvalidDecl())
12886 Diag(DefaultLoc, diag::err_default_special_members);
12890 MD->setDefaulted();
12891 MD->setExplicitlyDefaulted();
12893 // If this definition appears within the record, do the checking when
12894 // the record is complete.
12895 const FunctionDecl *Primary = MD;
12896 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12897 // Find the uninstantiated declaration that actually had the '= default'
12899 Pattern->isDefined(Primary);
12901 // If the method was defaulted on its first declaration, we will have
12902 // already performed the checking in CheckCompletedCXXClass. Such a
12903 // declaration doesn't trigger an implicit definition.
12904 if (Primary == Primary->getCanonicalDecl())
12907 CheckExplicitlyDefaultedSpecialMember(MD);
12909 if (MD->isInvalidDecl())
12913 case CXXDefaultConstructor:
12914 DefineImplicitDefaultConstructor(DefaultLoc,
12915 cast<CXXConstructorDecl>(MD));
12917 case CXXCopyConstructor:
12918 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12920 case CXXCopyAssignment:
12921 DefineImplicitCopyAssignment(DefaultLoc, MD);
12923 case CXXDestructor:
12924 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12926 case CXXMoveConstructor:
12927 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12929 case CXXMoveAssignment:
12930 DefineImplicitMoveAssignment(DefaultLoc, MD);
12933 llvm_unreachable("Invalid special member.");
12936 Diag(DefaultLoc, diag::err_default_special_members);
12940 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12941 for (Stmt *SubStmt : S->children()) {
12944 if (isa<ReturnStmt>(SubStmt))
12945 Self.Diag(SubStmt->getLocStart(),
12946 diag::err_return_in_constructor_handler);
12947 if (!isa<Expr>(SubStmt))
12948 SearchForReturnInStmt(Self, SubStmt);
12952 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12953 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12954 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12955 SearchForReturnInStmt(*this, Handler);
12959 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12960 const CXXMethodDecl *Old) {
12961 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12962 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12964 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12966 // If the calling conventions match, everything is fine
12967 if (NewCC == OldCC)
12970 // If the calling conventions mismatch because the new function is static,
12971 // suppress the calling convention mismatch error; the error about static
12972 // function override (err_static_overrides_virtual from
12973 // Sema::CheckFunctionDeclaration) is more clear.
12974 if (New->getStorageClass() == SC_Static)
12977 Diag(New->getLocation(),
12978 diag::err_conflicting_overriding_cc_attributes)
12979 << New->getDeclName() << New->getType() << Old->getType();
12980 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12984 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12985 const CXXMethodDecl *Old) {
12986 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12987 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12989 if (Context.hasSameType(NewTy, OldTy) ||
12990 NewTy->isDependentType() || OldTy->isDependentType())
12993 // Check if the return types are covariant
12994 QualType NewClassTy, OldClassTy;
12996 /// Both types must be pointers or references to classes.
12997 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12998 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12999 NewClassTy = NewPT->getPointeeType();
13000 OldClassTy = OldPT->getPointeeType();
13002 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13003 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13004 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13005 NewClassTy = NewRT->getPointeeType();
13006 OldClassTy = OldRT->getPointeeType();
13011 // The return types aren't either both pointers or references to a class type.
13012 if (NewClassTy.isNull()) {
13013 Diag(New->getLocation(),
13014 diag::err_different_return_type_for_overriding_virtual_function)
13015 << New->getDeclName() << NewTy << OldTy
13016 << New->getReturnTypeSourceRange();
13017 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13018 << Old->getReturnTypeSourceRange();
13023 // C++ [class.virtual]p6:
13024 // If the return type of D::f differs from the return type of B::f, the
13025 // class type in the return type of D::f shall be complete at the point of
13026 // declaration of D::f or shall be the class type D.
13027 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13028 if (!RT->isBeingDefined() &&
13029 RequireCompleteType(New->getLocation(), NewClassTy,
13030 diag::err_covariant_return_incomplete,
13031 New->getDeclName()))
13035 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13036 // Check if the new class derives from the old class.
13037 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13038 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13039 << New->getDeclName() << NewTy << OldTy
13040 << New->getReturnTypeSourceRange();
13041 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13042 << Old->getReturnTypeSourceRange();
13046 // Check if we the conversion from derived to base is valid.
13047 if (CheckDerivedToBaseConversion(
13048 NewClassTy, OldClassTy,
13049 diag::err_covariant_return_inaccessible_base,
13050 diag::err_covariant_return_ambiguous_derived_to_base_conv,
13051 New->getLocation(), New->getReturnTypeSourceRange(),
13052 New->getDeclName(), nullptr)) {
13053 // FIXME: this note won't trigger for delayed access control
13054 // diagnostics, and it's impossible to get an undelayed error
13055 // here from access control during the original parse because
13056 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13057 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13058 << Old->getReturnTypeSourceRange();
13063 // The qualifiers of the return types must be the same.
13064 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13065 Diag(New->getLocation(),
13066 diag::err_covariant_return_type_different_qualifications)
13067 << New->getDeclName() << NewTy << OldTy
13068 << New->getReturnTypeSourceRange();
13069 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13070 << Old->getReturnTypeSourceRange();
13075 // The new class type must have the same or less qualifiers as the old type.
13076 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13077 Diag(New->getLocation(),
13078 diag::err_covariant_return_type_class_type_more_qualified)
13079 << New->getDeclName() << NewTy << OldTy
13080 << New->getReturnTypeSourceRange();
13081 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13082 << Old->getReturnTypeSourceRange();
13089 /// \brief Mark the given method pure.
13091 /// \param Method the method to be marked pure.
13093 /// \param InitRange the source range that covers the "0" initializer.
13094 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13095 SourceLocation EndLoc = InitRange.getEnd();
13096 if (EndLoc.isValid())
13097 Method->setRangeEnd(EndLoc);
13099 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13104 if (!Method->isInvalidDecl())
13105 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13106 << Method->getDeclName() << InitRange;
13110 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13111 if (D->getFriendObjectKind())
13112 Diag(D->getLocation(), diag::err_pure_friend);
13113 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13114 CheckPureMethod(M, ZeroLoc);
13116 Diag(D->getLocation(), diag::err_illegal_initializer);
13119 /// \brief Determine whether the given declaration is a static data member.
13120 static bool isStaticDataMember(const Decl *D) {
13121 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13122 return Var->isStaticDataMember();
13127 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13128 /// an initializer for the out-of-line declaration 'Dcl'. The scope
13129 /// is a fresh scope pushed for just this purpose.
13131 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13132 /// static data member of class X, names should be looked up in the scope of
13134 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13135 // If there is no declaration, there was an error parsing it.
13136 if (!D || D->isInvalidDecl())
13139 // We will always have a nested name specifier here, but this declaration
13140 // might not be out of line if the specifier names the current namespace:
13143 if (D->isOutOfLine())
13144 EnterDeclaratorContext(S, D->getDeclContext());
13146 // If we are parsing the initializer for a static data member, push a
13147 // new expression evaluation context that is associated with this static
13149 if (isStaticDataMember(D))
13150 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13153 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13154 /// initializer for the out-of-line declaration 'D'.
13155 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13156 // If there is no declaration, there was an error parsing it.
13157 if (!D || D->isInvalidDecl())
13160 if (isStaticDataMember(D))
13161 PopExpressionEvaluationContext();
13163 if (D->isOutOfLine())
13164 ExitDeclaratorContext(S);
13167 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13168 /// C++ if/switch/while/for statement.
13169 /// e.g: "if (int x = f()) {...}"
13170 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13172 // The declarator shall not specify a function or an array.
13173 // The type-specifier-seq shall not contain typedef and shall not declare a
13174 // new class or enumeration.
13175 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13176 "Parser allowed 'typedef' as storage class of condition decl.");
13178 Decl *Dcl = ActOnDeclarator(S, D);
13182 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13183 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13184 << D.getSourceRange();
13191 void Sema::LoadExternalVTableUses() {
13192 if (!ExternalSource)
13195 SmallVector<ExternalVTableUse, 4> VTables;
13196 ExternalSource->ReadUsedVTables(VTables);
13197 SmallVector<VTableUse, 4> NewUses;
13198 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13199 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13200 = VTablesUsed.find(VTables[I].Record);
13201 // Even if a definition wasn't required before, it may be required now.
13202 if (Pos != VTablesUsed.end()) {
13203 if (!Pos->second && VTables[I].DefinitionRequired)
13204 Pos->second = true;
13208 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13209 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13212 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13215 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13216 bool DefinitionRequired) {
13217 // Ignore any vtable uses in unevaluated operands or for classes that do
13218 // not have a vtable.
13219 if (!Class->isDynamicClass() || Class->isDependentContext() ||
13220 CurContext->isDependentContext() || isUnevaluatedContext())
13223 // Try to insert this class into the map.
13224 LoadExternalVTableUses();
13225 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13226 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13227 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13229 // If we already had an entry, check to see if we are promoting this vtable
13230 // to require a definition. If so, we need to reappend to the VTableUses
13231 // list, since we may have already processed the first entry.
13232 if (DefinitionRequired && !Pos.first->second) {
13233 Pos.first->second = true;
13235 // Otherwise, we can early exit.
13239 // The Microsoft ABI requires that we perform the destructor body
13240 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13241 // the deleting destructor is emitted with the vtable, not with the
13242 // destructor definition as in the Itanium ABI.
13243 // If it has a definition, we do the check at that point instead.
13244 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13245 Class->hasUserDeclaredDestructor() &&
13246 !Class->getDestructor()->isDefined() &&
13247 !Class->getDestructor()->isDeleted()) {
13248 CXXDestructorDecl *DD = Class->getDestructor();
13249 ContextRAII SavedContext(*this, DD);
13250 CheckDestructor(DD);
13254 // Local classes need to have their virtual members marked
13255 // immediately. For all other classes, we mark their virtual members
13256 // at the end of the translation unit.
13257 if (Class->isLocalClass())
13258 MarkVirtualMembersReferenced(Loc, Class);
13260 VTableUses.push_back(std::make_pair(Class, Loc));
13263 bool Sema::DefineUsedVTables() {
13264 LoadExternalVTableUses();
13265 if (VTableUses.empty())
13268 // Note: The VTableUses vector could grow as a result of marking
13269 // the members of a class as "used", so we check the size each
13270 // time through the loop and prefer indices (which are stable) to
13271 // iterators (which are not).
13272 bool DefinedAnything = false;
13273 for (unsigned I = 0; I != VTableUses.size(); ++I) {
13274 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13278 SourceLocation Loc = VTableUses[I].second;
13280 bool DefineVTable = true;
13282 // If this class has a key function, but that key function is
13283 // defined in another translation unit, we don't need to emit the
13284 // vtable even though we're using it.
13285 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13286 if (KeyFunction && !KeyFunction->hasBody()) {
13287 // The key function is in another translation unit.
13288 DefineVTable = false;
13289 TemplateSpecializationKind TSK =
13290 KeyFunction->getTemplateSpecializationKind();
13291 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13292 TSK != TSK_ImplicitInstantiation &&
13293 "Instantiations don't have key functions");
13295 } else if (!KeyFunction) {
13296 // If we have a class with no key function that is the subject
13297 // of an explicit instantiation declaration, suppress the
13298 // vtable; it will live with the explicit instantiation
13300 bool IsExplicitInstantiationDeclaration
13301 = Class->getTemplateSpecializationKind()
13302 == TSK_ExplicitInstantiationDeclaration;
13303 for (auto R : Class->redecls()) {
13304 TemplateSpecializationKind TSK
13305 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13306 if (TSK == TSK_ExplicitInstantiationDeclaration)
13307 IsExplicitInstantiationDeclaration = true;
13308 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13309 IsExplicitInstantiationDeclaration = false;
13314 if (IsExplicitInstantiationDeclaration)
13315 DefineVTable = false;
13318 // The exception specifications for all virtual members may be needed even
13319 // if we are not providing an authoritative form of the vtable in this TU.
13320 // We may choose to emit it available_externally anyway.
13321 if (!DefineVTable) {
13322 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13326 // Mark all of the virtual members of this class as referenced, so
13327 // that we can build a vtable. Then, tell the AST consumer that a
13328 // vtable for this class is required.
13329 DefinedAnything = true;
13330 MarkVirtualMembersReferenced(Loc, Class);
13331 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13332 if (VTablesUsed[Canonical])
13333 Consumer.HandleVTable(Class);
13335 // Optionally warn if we're emitting a weak vtable.
13336 if (Class->isExternallyVisible() &&
13337 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13338 const FunctionDecl *KeyFunctionDef = nullptr;
13339 if (!KeyFunction ||
13340 (KeyFunction->hasBody(KeyFunctionDef) &&
13341 KeyFunctionDef->isInlined()))
13342 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13343 TSK_ExplicitInstantiationDefinition
13344 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13348 VTableUses.clear();
13350 return DefinedAnything;
13353 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13354 const CXXRecordDecl *RD) {
13355 for (const auto *I : RD->methods())
13356 if (I->isVirtual() && !I->isPure())
13357 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13360 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13361 const CXXRecordDecl *RD) {
13362 // Mark all functions which will appear in RD's vtable as used.
13363 CXXFinalOverriderMap FinalOverriders;
13364 RD->getFinalOverriders(FinalOverriders);
13365 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13366 E = FinalOverriders.end();
13368 for (OverridingMethods::const_iterator OI = I->second.begin(),
13369 OE = I->second.end();
13371 assert(OI->second.size() > 0 && "no final overrider");
13372 CXXMethodDecl *Overrider = OI->second.front().Method;
13374 // C++ [basic.def.odr]p2:
13375 // [...] A virtual member function is used if it is not pure. [...]
13376 if (!Overrider->isPure())
13377 MarkFunctionReferenced(Loc, Overrider);
13381 // Only classes that have virtual bases need a VTT.
13382 if (RD->getNumVBases() == 0)
13385 for (const auto &I : RD->bases()) {
13386 const CXXRecordDecl *Base =
13387 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13388 if (Base->getNumVBases() == 0)
13390 MarkVirtualMembersReferenced(Loc, Base);
13394 /// SetIvarInitializers - This routine builds initialization ASTs for the
13395 /// Objective-C implementation whose ivars need be initialized.
13396 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13397 if (!getLangOpts().CPlusPlus)
13399 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13400 SmallVector<ObjCIvarDecl*, 8> ivars;
13401 CollectIvarsToConstructOrDestruct(OID, ivars);
13404 SmallVector<CXXCtorInitializer*, 32> AllToInit;
13405 for (unsigned i = 0; i < ivars.size(); i++) {
13406 FieldDecl *Field = ivars[i];
13407 if (Field->isInvalidDecl())
13410 CXXCtorInitializer *Member;
13411 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13412 InitializationKind InitKind =
13413 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13415 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13416 ExprResult MemberInit =
13417 InitSeq.Perform(*this, InitEntity, InitKind, None);
13418 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13419 // Note, MemberInit could actually come back empty if no initialization
13420 // is required (e.g., because it would call a trivial default constructor)
13421 if (!MemberInit.get() || MemberInit.isInvalid())
13425 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13427 MemberInit.getAs<Expr>(),
13429 AllToInit.push_back(Member);
13431 // Be sure that the destructor is accessible and is marked as referenced.
13432 if (const RecordType *RecordTy =
13433 Context.getBaseElementType(Field->getType())
13434 ->getAs<RecordType>()) {
13435 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13436 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13437 MarkFunctionReferenced(Field->getLocation(), Destructor);
13438 CheckDestructorAccess(Field->getLocation(), Destructor,
13439 PDiag(diag::err_access_dtor_ivar)
13440 << Context.getBaseElementType(Field->getType()));
13444 ObjCImplementation->setIvarInitializers(Context,
13445 AllToInit.data(), AllToInit.size());
13450 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13451 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13452 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13453 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13455 if (Ctor->isInvalidDecl())
13458 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13460 // Target may not be determinable yet, for instance if this is a dependent
13461 // call in an uninstantiated template.
13463 const FunctionDecl *FNTarget = nullptr;
13464 (void)Target->hasBody(FNTarget);
13465 Target = const_cast<CXXConstructorDecl*>(
13466 cast_or_null<CXXConstructorDecl>(FNTarget));
13469 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13470 // Avoid dereferencing a null pointer here.
13471 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13473 if (!Current.insert(Canonical).second)
13476 // We know that beyond here, we aren't chaining into a cycle.
13477 if (!Target || !Target->isDelegatingConstructor() ||
13478 Target->isInvalidDecl() || Valid.count(TCanonical)) {
13479 Valid.insert(Current.begin(), Current.end());
13481 // We've hit a cycle.
13482 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13483 Current.count(TCanonical)) {
13484 // If we haven't diagnosed this cycle yet, do so now.
13485 if (!Invalid.count(TCanonical)) {
13486 S.Diag((*Ctor->init_begin())->getSourceLocation(),
13487 diag::warn_delegating_ctor_cycle)
13490 // Don't add a note for a function delegating directly to itself.
13491 if (TCanonical != Canonical)
13492 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13494 CXXConstructorDecl *C = Target;
13495 while (C->getCanonicalDecl() != Canonical) {
13496 const FunctionDecl *FNTarget = nullptr;
13497 (void)C->getTargetConstructor()->hasBody(FNTarget);
13498 assert(FNTarget && "Ctor cycle through bodiless function");
13500 C = const_cast<CXXConstructorDecl*>(
13501 cast<CXXConstructorDecl>(FNTarget));
13502 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13506 Invalid.insert(Current.begin(), Current.end());
13509 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13514 void Sema::CheckDelegatingCtorCycles() {
13515 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13517 for (DelegatingCtorDeclsType::iterator
13518 I = DelegatingCtorDecls.begin(ExternalSource),
13519 E = DelegatingCtorDecls.end();
13521 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13523 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13524 CE = Invalid.end();
13526 (*CI)->setInvalidDecl();
13530 /// \brief AST visitor that finds references to the 'this' expression.
13531 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13535 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13537 bool VisitCXXThisExpr(CXXThisExpr *E) {
13538 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13539 << E->isImplicit();
13545 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13546 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13550 TypeLoc TL = TSInfo->getTypeLoc();
13551 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13555 // C++11 [expr.prim.general]p3:
13556 // [The expression this] shall not appear before the optional
13557 // cv-qualifier-seq and it shall not appear within the declaration of a
13558 // static member function (although its type and value category are defined
13559 // within a static member function as they are within a non-static member
13560 // function). [ Note: this is because declaration matching does not occur
13561 // until the complete declarator is known. - end note ]
13562 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13563 FindCXXThisExpr Finder(*this);
13565 // If the return type came after the cv-qualifier-seq, check it now.
13566 if (Proto->hasTrailingReturn() &&
13567 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13570 // Check the exception specification.
13571 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13574 return checkThisInStaticMemberFunctionAttributes(Method);
13577 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13578 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13582 TypeLoc TL = TSInfo->getTypeLoc();
13583 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13587 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13588 FindCXXThisExpr Finder(*this);
13590 switch (Proto->getExceptionSpecType()) {
13592 case EST_Uninstantiated:
13593 case EST_Unevaluated:
13594 case EST_BasicNoexcept:
13595 case EST_DynamicNone:
13600 case EST_ComputedNoexcept:
13601 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13605 for (const auto &E : Proto->exceptions()) {
13606 if (!Finder.TraverseType(E))
13615 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13616 FindCXXThisExpr Finder(*this);
13618 // Check attributes.
13619 for (const auto *A : Method->attrs()) {
13620 // FIXME: This should be emitted by tblgen.
13621 Expr *Arg = nullptr;
13622 ArrayRef<Expr *> Args;
13623 if (const auto *G = dyn_cast<GuardedByAttr>(A))
13625 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13627 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13628 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13629 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13630 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13631 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13632 Arg = ETLF->getSuccessValue();
13633 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13634 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13635 Arg = STLF->getSuccessValue();
13636 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13637 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13638 Arg = LR->getArg();
13639 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13640 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13641 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13642 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13643 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13644 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13645 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13646 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13647 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13648 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13650 if (Arg && !Finder.TraverseStmt(Arg))
13653 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13654 if (!Finder.TraverseStmt(Args[I]))
13662 void Sema::checkExceptionSpecification(
13663 bool IsTopLevel, ExceptionSpecificationType EST,
13664 ArrayRef<ParsedType> DynamicExceptions,
13665 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13666 SmallVectorImpl<QualType> &Exceptions,
13667 FunctionProtoType::ExceptionSpecInfo &ESI) {
13668 Exceptions.clear();
13670 if (EST == EST_Dynamic) {
13671 Exceptions.reserve(DynamicExceptions.size());
13672 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13673 // FIXME: Preserve type source info.
13674 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13677 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13678 collectUnexpandedParameterPacks(ET, Unexpanded);
13679 if (!Unexpanded.empty()) {
13680 DiagnoseUnexpandedParameterPacks(
13681 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13687 // Check that the type is valid for an exception spec, and
13689 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13690 Exceptions.push_back(ET);
13692 ESI.Exceptions = Exceptions;
13696 if (EST == EST_ComputedNoexcept) {
13697 // If an error occurred, there's no expression here.
13698 if (NoexceptExpr) {
13699 assert((NoexceptExpr->isTypeDependent() ||
13700 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13702 "Parser should have made sure that the expression is boolean");
13703 if (IsTopLevel && NoexceptExpr &&
13704 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13705 ESI.Type = EST_BasicNoexcept;
13709 if (!NoexceptExpr->isValueDependent())
13710 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13711 diag::err_noexcept_needs_constant_expression,
13712 /*AllowFold*/ false).get();
13713 ESI.NoexceptExpr = NoexceptExpr;
13719 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13720 ExceptionSpecificationType EST,
13721 SourceRange SpecificationRange,
13722 ArrayRef<ParsedType> DynamicExceptions,
13723 ArrayRef<SourceRange> DynamicExceptionRanges,
13724 Expr *NoexceptExpr) {
13728 // Dig out the method we're referring to.
13729 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13730 MethodD = FunTmpl->getTemplatedDecl();
13732 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13736 // Check the exception specification.
13737 llvm::SmallVector<QualType, 4> Exceptions;
13738 FunctionProtoType::ExceptionSpecInfo ESI;
13739 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13740 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13743 // Update the exception specification on the function type.
13744 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13746 if (Method->isStatic())
13747 checkThisInStaticMemberFunctionExceptionSpec(Method);
13749 if (Method->isVirtual()) {
13750 // Check overrides, which we previously had to delay.
13751 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13752 OEnd = Method->end_overridden_methods();
13754 CheckOverridingFunctionExceptionSpec(Method, *O);
13758 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13760 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13761 SourceLocation DeclStart,
13762 Declarator &D, Expr *BitWidth,
13763 InClassInitStyle InitStyle,
13764 AccessSpecifier AS,
13765 AttributeList *MSPropertyAttr) {
13766 IdentifierInfo *II = D.getIdentifier();
13768 Diag(DeclStart, diag::err_anonymous_property);
13771 SourceLocation Loc = D.getIdentifierLoc();
13773 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13774 QualType T = TInfo->getType();
13775 if (getLangOpts().CPlusPlus) {
13776 CheckExtraCXXDefaultArguments(D);
13778 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13779 UPPC_DataMemberType)) {
13780 D.setInvalidType();
13782 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13786 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13788 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13789 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13790 diag::err_invalid_thread)
13791 << DeclSpec::getSpecifierName(TSCS);
13793 // Check to see if this name was declared as a member previously
13794 NamedDecl *PrevDecl = nullptr;
13795 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13796 LookupName(Previous, S);
13797 switch (Previous.getResultKind()) {
13798 case LookupResult::Found:
13799 case LookupResult::FoundUnresolvedValue:
13800 PrevDecl = Previous.getAsSingle<NamedDecl>();
13803 case LookupResult::FoundOverloaded:
13804 PrevDecl = Previous.getRepresentativeDecl();
13807 case LookupResult::NotFound:
13808 case LookupResult::NotFoundInCurrentInstantiation:
13809 case LookupResult::Ambiguous:
13813 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13814 // Maybe we will complain about the shadowed template parameter.
13815 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13816 // Just pretend that we didn't see the previous declaration.
13817 PrevDecl = nullptr;
13820 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13821 PrevDecl = nullptr;
13823 SourceLocation TSSL = D.getLocStart();
13824 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13825 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13826 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13827 ProcessDeclAttributes(TUScope, NewPD, D);
13828 NewPD->setAccess(AS);
13830 if (NewPD->isInvalidDecl())
13831 Record->setInvalidDecl();
13833 if (D.getDeclSpec().isModulePrivateSpecified())
13834 NewPD->setModulePrivate();
13836 if (NewPD->isInvalidDecl() && PrevDecl) {
13837 // Don't introduce NewFD into scope; there's already something
13838 // with the same name in the same scope.
13840 PushOnScopeChains(NewPD, S);
13842 Record->addDecl(NewPD);