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/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/ComparisonCategories.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/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
47 using namespace clang;
49 //===----------------------------------------------------------------------===//
50 // CheckDefaultArgumentVisitor
51 //===----------------------------------------------------------------------===//
54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55 /// the default argument of a parameter to determine whether it
56 /// contains any ill-formed subexpressions. For example, this will
57 /// diagnose the use of local variables or parameters within the
58 /// default argument expression.
59 class CheckDefaultArgumentVisitor
60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66 : DefaultArg(defarg), S(s) {}
68 bool VisitExpr(Expr *Node);
69 bool VisitDeclRefExpr(DeclRefExpr *DRE);
70 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71 bool VisitLambdaExpr(LambdaExpr *Lambda);
72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
75 /// VisitExpr - Visit all of the children of this expression.
76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77 bool IsInvalid = false;
78 for (Stmt *SubStmt : Node->children())
79 IsInvalid |= Visit(SubStmt);
83 /// VisitDeclRefExpr - Visit a reference to a declaration, to
84 /// determine whether this declaration can be used in the default
85 /// argument expression.
86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87 NamedDecl *Decl = DRE->getDecl();
88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89 // C++ [dcl.fct.default]p9
90 // Default arguments are evaluated each time the function is
91 // called. The order of evaluation of function arguments is
92 // unspecified. Consequently, parameters of a function shall not
93 // be used in default argument expressions, even if they are not
94 // evaluated. Parameters of a function declared before a default
95 // argument expression are in scope and can hide namespace and
96 // class member names.
97 return S->Diag(DRE->getBeginLoc(),
98 diag::err_param_default_argument_references_param)
99 << Param->getDeclName() << DefaultArg->getSourceRange();
100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101 // C++ [dcl.fct.default]p7
102 // Local variables shall not be used in default argument
104 if (VDecl->isLocalVarDecl())
105 return S->Diag(DRE->getBeginLoc(),
106 diag::err_param_default_argument_references_local)
107 << VDecl->getDeclName() << DefaultArg->getSourceRange();
113 /// VisitCXXThisExpr - Visit a C++ "this" expression.
114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115 // C++ [dcl.fct.default]p8:
116 // The keyword this shall not be used in a default argument of a
118 return S->Diag(ThisE->getBeginLoc(),
119 diag::err_param_default_argument_references_this)
120 << ThisE->getSourceRange();
123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124 bool Invalid = false;
125 for (PseudoObjectExpr::semantics_iterator
126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
129 // Look through bindings.
130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131 E = OVE->getSourceExpr();
132 assert(E && "pseudo-object binding without source expression?");
140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141 // C++11 [expr.lambda.prim]p13:
142 // A lambda-expression appearing in a default argument shall not
143 // implicitly or explicitly capture any entity.
144 if (Lambda->capture_begin() == Lambda->capture_end())
147 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171 EST = EST_BasicNoexcept;
175 case EST_Uninstantiated:
176 case EST_Unevaluated:
177 llvm_unreachable("should not see unresolved exception specs here");
179 // If this function can throw any exceptions, make a note of that.
182 // FIXME: Whichever we see last of MSAny and None determines our result.
183 // We should make a consistent, order-independent choice here.
187 case EST_NoexceptFalse:
189 ComputedEST = EST_None;
191 // FIXME: If the call to this decl is using any of its default arguments, we
192 // need to search them for potentially-throwing calls.
193 // If this function has a basic noexcept, it doesn't affect the outcome.
194 case EST_BasicNoexcept:
195 case EST_NoexceptTrue:
197 // If we're still at noexcept(true) and there's a throw() callee,
198 // change to that specification.
199 case EST_DynamicNone:
200 if (ComputedEST == EST_BasicNoexcept)
201 ComputedEST = EST_DynamicNone;
203 case EST_DependentNoexcept:
205 "should not generate implicit declarations for dependent cases");
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216 Exceptions.push_back(E);
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220 if (!E || ComputedEST == EST_MSAny)
225 // C++0x [except.spec]p14:
226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
244 if (Self->canThrow(E))
245 ComputedEST = EST_None;
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250 SourceLocation EqualLoc) {
251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269 if (Result.isInvalid())
271 Arg = Result.getAs<Expr>();
273 CheckCompletedExpr(Arg, EqualLoc);
274 Arg = MaybeCreateExprWithCleanups(Arg);
276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300 if (!param || !DefaultArg)
303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
304 UnparsedDefaultArgLocs.erase(Param);
306 // Default arguments are only permitted in C++
307 if (!getLangOpts().CPlusPlus) {
308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
310 Param->setInvalidDecl();
314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
320 // C++11 [dcl.fct.default]p3
321 // A default argument expression [...] shall not be specified for a
323 if (Param->isParameterPack()) {
324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325 << DefaultArg->getSourceRange();
329 // Check that the default argument is well-formed
330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331 if (DefaultArgChecker.Visit(DefaultArg)) {
332 Param->setInvalidDecl();
336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344 SourceLocation EqualLoc,
345 SourceLocation ArgLoc) {
349 ParmVarDecl *Param = cast<ParmVarDecl>(param);
350 Param->setUnparsedDefaultArg();
351 UnparsedDefaultArgLocs[Param] = ArgLoc;
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357 SourceLocation EqualLoc) {
361 ParmVarDecl *Param = cast<ParmVarDecl>(param);
362 Param->setInvalidDecl();
363 UnparsedDefaultArgLocs.erase(Param);
364 Param->setDefaultArg(new(Context)
365 OpaqueValueExpr(EqualLoc,
366 Param->getType().getNonReferenceType(),
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376 // C++ [dcl.fct.default]p3
377 // A default argument expression shall be specified only in the
378 // parameter-declaration-clause of a function declaration or in a
379 // template-parameter (14.1). It shall not be specified for a
380 // parameter pack. If it is specified in a
381 // parameter-declaration-clause, it shall not occur within a
382 // declarator or abstract-declarator of a parameter-declaration.
383 bool MightBeFunction = D.isFunctionDeclarationContext();
384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385 DeclaratorChunk &chunk = D.getTypeObject(i);
386 if (chunk.Kind == DeclaratorChunk::Function) {
387 if (MightBeFunction) {
388 // This is a function declaration. It can have default arguments, but
389 // keep looking in case its return type is a function type with default
391 MightBeFunction = false;
394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397 if (Param->hasUnparsedDefaultArg()) {
398 std::unique_ptr<CachedTokens> Toks =
399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
405 SR = UnparsedDefaultArgLocs[Param];
406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
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 // sufficient, and if neither is local, then they are in the same scope.)
474 // We found the right previous declaration.
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 unless the new
551 // function is a friend declaration in a template class. In the latter
552 // case the default arguments will be inherited when the friend
553 // declaration will be instantiated.
554 if (New->getFriendObjectKind() == Decl::FOK_None ||
555 !New->getLexicalDeclContext()->isDependentContext()) {
556 // It's important to use getInit() here; getDefaultArg()
557 // strips off any top-level ExprWithCleanups.
558 NewParam->setHasInheritedDefaultArg();
559 if (OldParam->hasUnparsedDefaultArg())
560 NewParam->setUnparsedDefaultArg();
561 else if (OldParam->hasUninstantiatedDefaultArg())
562 NewParam->setUninstantiatedDefaultArg(
563 OldParam->getUninstantiatedDefaultArg());
565 NewParam->setDefaultArg(OldParam->getInit());
567 } else if (NewParamHasDfl) {
568 if (New->getDescribedFunctionTemplate()) {
569 // Paragraph 4, quoted above, only applies to non-template functions.
570 Diag(NewParam->getLocation(),
571 diag::err_param_default_argument_template_redecl)
572 << NewParam->getDefaultArgRange();
573 Diag(PrevForDefaultArgs->getLocation(),
574 diag::note_template_prev_declaration)
576 } else if (New->getTemplateSpecializationKind()
577 != TSK_ImplicitInstantiation &&
578 New->getTemplateSpecializationKind() != TSK_Undeclared) {
579 // C++ [temp.expr.spec]p21:
580 // Default function arguments shall not be specified in a declaration
581 // or a definition for one of the following explicit specializations:
582 // - the explicit specialization of a function template;
583 // - the explicit specialization of a member function template;
584 // - the explicit specialization of a member function of a class
585 // template where the class template specialization to which the
586 // member function specialization belongs is implicitly
588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590 << New->getDeclName()
591 << NewParam->getDefaultArgRange();
592 } else if (New->getDeclContext()->isDependentContext()) {
593 // C++ [dcl.fct.default]p6 (DR217):
594 // Default arguments for a member function of a class template shall
595 // be specified on the initial declaration of the member function
596 // within the class template.
598 // Reading the tea leaves a bit in DR217 and its reference to DR205
599 // leads me to the conclusion that one cannot add default function
600 // arguments for an out-of-line definition of a member function of a
603 if (CXXRecordDecl *Record
604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605 if (Record->getDescribedClassTemplate())
607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
613 Diag(NewParam->getLocation(),
614 diag::err_param_default_argument_member_template_redecl)
616 << NewParam->getDefaultArgRange();
621 // DR1344: If a default argument is added outside a class definition and that
622 // default argument makes the function a special member function, the program
623 // is ill-formed. This can only happen for constructors.
624 if (isa<CXXConstructorDecl>(New) &&
625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628 if (NewSM != OldSM) {
629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630 assert(NewParam->hasDefaultArg());
631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632 << NewParam->getDefaultArgRange() << NewSM;
633 Diag(Old->getLocation(), diag::note_previous_declaration);
637 const FunctionDecl *Def;
638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639 // template has a constexpr specifier then all its declarations shall
640 // contain the constexpr specifier.
641 if (New->isConstexpr() != Old->isConstexpr()) {
642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643 << New << New->isConstexpr();
644 Diag(Old->getLocation(), diag::note_previous_declaration);
646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647 Old->isDefined(Def) &&
648 // If a friend function is inlined but does not have 'inline'
649 // specifier, it is a definition. Do not report attribute conflict
650 // in this case, redefinition will be diagnosed later.
651 (New->isInlineSpecified() ||
652 New->getFriendObjectKind() == Decl::FOK_None)) {
653 // C++11 [dcl.fcn.spec]p4:
654 // If the definition of a function appears in a translation unit before its
655 // first declaration as inline, the program is ill-formed.
656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657 Diag(Def->getLocation(), diag::note_previous_definition);
661 // FIXME: It's not clear what should happen if multiple declarations of a
662 // deduction guide have different explicitness. For now at least we simply
663 // reject any case where the explicitness changes.
664 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
665 if (NewGuide && NewGuide->isExplicitSpecified() !=
666 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
667 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
668 << NewGuide->isExplicitSpecified();
669 Diag(Old->getLocation(), diag::note_previous_declaration);
672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673 // argument expression, that declaration shall be a definition and shall be
674 // the only declaration of the function or function template in the
676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
677 functionDeclHasDefaultArgument(Old)) {
678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679 Diag(Old->getLocation(), diag::note_previous_declaration);
687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
688 MultiTemplateParamsArg TemplateParamLists) {
689 assert(D.isDecompositionDeclarator());
690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
692 // The syntax only allows a decomposition declarator as a simple-declaration,
693 // a for-range-declaration, or a condition in Clang, but we parse it in more
695 if (!D.mayHaveDecompositionDeclarator()) {
696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
697 << Decomp.getSourceRange();
701 if (!TemplateParamLists.empty()) {
702 // FIXME: There's no rule against this, but there are also no rules that
703 // would actually make it usable, so we reject it for now.
704 Diag(TemplateParamLists.front()->getTemplateLoc(),
705 diag::err_decomp_decl_template);
709 Diag(Decomp.getLSquareLoc(),
710 !getLangOpts().CPlusPlus17
711 ? diag::ext_decomp_decl
712 : D.getContext() == DeclaratorContext::ConditionContext
713 ? diag::ext_decomp_decl_cond
714 : diag::warn_cxx14_compat_decomp_decl)
715 << Decomp.getSourceRange();
717 // The semantic context is always just the current context.
718 DeclContext *const DC = CurContext;
720 // C++1z [dcl.dcl]/8:
721 // The decl-specifier-seq shall contain only the type-specifier auto
722 // and cv-qualifiers.
723 auto &DS = D.getDeclSpec();
725 SmallVector<StringRef, 8> BadSpecifiers;
726 SmallVector<SourceLocation, 8> BadSpecifierLocs;
727 if (auto SCS = DS.getStorageClassSpec()) {
728 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
729 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
731 if (auto TSCS = DS.getThreadStorageClassSpec()) {
732 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
733 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
735 if (DS.isConstexprSpecified()) {
736 BadSpecifiers.push_back("constexpr");
737 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
739 if (DS.isInlineSpecified()) {
740 BadSpecifiers.push_back("inline");
741 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
743 if (!BadSpecifiers.empty()) {
744 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
745 Err << (int)BadSpecifiers.size()
746 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
747 // Don't add FixItHints to remove the specifiers; we do still respect
748 // them when building the underlying variable.
749 for (auto Loc : BadSpecifierLocs)
750 Err << SourceRange(Loc, Loc);
752 // We can't recover from it being declared as a typedef.
753 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
757 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
758 QualType R = TInfo->getType();
760 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
761 UPPC_DeclarationType))
764 // The syntax only allows a single ref-qualifier prior to the decomposition
765 // declarator. No other declarator chunks are permitted. Also check the type
767 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
768 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
769 (D.getNumTypeObjects() == 1 &&
770 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
771 Diag(Decomp.getLSquareLoc(),
772 (D.hasGroupingParens() ||
773 (D.getNumTypeObjects() &&
774 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
775 ? diag::err_decomp_decl_parens
776 : diag::err_decomp_decl_type)
779 // In most cases, there's no actual problem with an explicitly-specified
780 // type, but a function type won't work here, and ActOnVariableDeclarator
781 // shouldn't be called for such a type.
782 if (R->isFunctionType())
786 // Build the BindingDecls.
787 SmallVector<BindingDecl*, 8> Bindings;
789 // Build the BindingDecls.
790 for (auto &B : D.getDecompositionDeclarator().bindings()) {
791 // Check for name conflicts.
792 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
793 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
794 ForVisibleRedeclaration);
795 LookupName(Previous, S,
796 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
798 // It's not permitted to shadow a template parameter name.
799 if (Previous.isSingleResult() &&
800 Previous.getFoundDecl()->isTemplateParameter()) {
801 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
802 Previous.getFoundDecl());
806 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
807 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
808 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
809 /*AllowInlineNamespace*/false);
810 if (!Previous.empty()) {
811 auto *Old = Previous.getRepresentativeDecl();
812 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
813 Diag(Old->getLocation(), diag::note_previous_definition);
816 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
817 PushOnScopeChains(BD, S, true);
818 Bindings.push_back(BD);
819 ParsingInitForAutoVars.insert(BD);
822 // There are no prior lookup results for the variable itself, because it
824 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
825 Decomp.getLSquareLoc());
826 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
827 ForVisibleRedeclaration);
829 // Build the variable that holds the non-decomposed object.
830 bool AddToScope = true;
832 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
833 MultiTemplateParamsArg(), AddToScope, Bindings);
836 CurContext->addHiddenDecl(New);
839 if (isInOpenMPDeclareTargetContext())
840 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
845 static bool checkSimpleDecomposition(
846 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
847 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
848 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
849 if ((int64_t)Bindings.size() != NumElems) {
850 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
851 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
852 << (NumElems < Bindings.size());
857 for (auto *B : Bindings) {
858 SourceLocation Loc = B->getLocation();
859 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
862 E = GetInit(Loc, E.get(), I++);
865 B->setBinding(ElemType, E.get());
871 static bool checkArrayLikeDecomposition(Sema &S,
872 ArrayRef<BindingDecl *> Bindings,
873 ValueDecl *Src, QualType DecompType,
874 const llvm::APSInt &NumElems,
876 return checkSimpleDecomposition(
877 S, Bindings, Src, DecompType, NumElems, ElemType,
878 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
879 ExprResult E = S.ActOnIntegerConstant(Loc, I);
882 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
886 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
887 ValueDecl *Src, QualType DecompType,
888 const ConstantArrayType *CAT) {
889 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
890 llvm::APSInt(CAT->getSize()),
891 CAT->getElementType());
894 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
895 ValueDecl *Src, QualType DecompType,
896 const VectorType *VT) {
897 return checkArrayLikeDecomposition(
898 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
899 S.Context.getQualifiedType(VT->getElementType(),
900 DecompType.getQualifiers()));
903 static bool checkComplexDecomposition(Sema &S,
904 ArrayRef<BindingDecl *> Bindings,
905 ValueDecl *Src, QualType DecompType,
906 const ComplexType *CT) {
907 return checkSimpleDecomposition(
908 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
909 S.Context.getQualifiedType(CT->getElementType(),
910 DecompType.getQualifiers()),
911 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
912 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
916 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
917 TemplateArgumentListInfo &Args) {
919 llvm::raw_svector_ostream OS(SS);
921 for (auto &Arg : Args.arguments()) {
924 Arg.getArgument().print(PrintingPolicy, OS);
930 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
931 SourceLocation Loc, StringRef Trait,
932 TemplateArgumentListInfo &Args,
934 auto DiagnoseMissing = [&] {
936 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
941 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
942 NamespaceDecl *Std = S.getStdNamespace();
944 return DiagnoseMissing();
946 // Look up the trait itself, within namespace std. We can diagnose various
947 // problems with this lookup even if we've been asked to not diagnose a
948 // missing specialization, because this can only fail if the user has been
949 // declaring their own names in namespace std or we don't support the
950 // standard library implementation in use.
951 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
952 Loc, Sema::LookupOrdinaryName);
953 if (!S.LookupQualifiedName(Result, Std))
954 return DiagnoseMissing();
955 if (Result.isAmbiguous())
958 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
960 Result.suppressDiagnostics();
961 NamedDecl *Found = *Result.begin();
962 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
963 S.Diag(Found->getLocation(), diag::note_declared_at);
967 // Build the template-id.
968 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
969 if (TraitTy.isNull())
971 if (!S.isCompleteType(Loc, TraitTy)) {
973 S.RequireCompleteType(
974 Loc, TraitTy, DiagID,
975 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
979 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
980 assert(RD && "specialization of class template is not a class?");
982 // Look up the member of the trait type.
983 S.LookupQualifiedName(TraitMemberLookup, RD);
984 return TraitMemberLookup.isAmbiguous();
987 static TemplateArgumentLoc
988 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
990 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
991 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
994 static TemplateArgumentLoc
995 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
996 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
999 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1001 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1002 llvm::APSInt &Size) {
1003 EnterExpressionEvaluationContext ContextRAII(
1004 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1006 DeclarationName Value = S.PP.getIdentifierInfo("value");
1007 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1009 // Form template argument list for tuple_size<T>.
1010 TemplateArgumentListInfo Args(Loc, Loc);
1011 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1013 // If there's no tuple_size specialization, it's not tuple-like.
1014 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1015 return IsTupleLike::NotTupleLike;
1017 // If we get this far, we've committed to the tuple interpretation, but
1018 // we can still fail if there actually isn't a usable ::value.
1020 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1022 TemplateArgumentListInfo &Args;
1023 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1024 : R(R), Args(Args) {}
1025 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1026 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1027 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1029 } Diagnoser(R, Args);
1032 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1033 return IsTupleLike::Error;
1037 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1039 return IsTupleLike::Error;
1041 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1043 return IsTupleLike::Error;
1045 return IsTupleLike::TupleLike;
1048 /// \return std::tuple_element<I, T>::type.
1049 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1050 unsigned I, QualType T) {
1051 // Form template argument list for tuple_element<I, T>.
1052 TemplateArgumentListInfo Args(Loc, Loc);
1054 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1055 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1057 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1058 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1059 if (lookupStdTypeTraitMember(
1060 S, R, Loc, "tuple_element", Args,
1061 diag::err_decomp_decl_std_tuple_element_not_specialized))
1064 auto *TD = R.getAsSingle<TypeDecl>();
1066 R.suppressDiagnostics();
1067 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1068 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1070 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1074 return S.Context.getTypeDeclType(TD);
1078 struct BindingDiagnosticTrap {
1080 DiagnosticErrorTrap Trap;
1083 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1084 : S(S), Trap(S.Diags), BD(BD) {}
1085 ~BindingDiagnosticTrap() {
1086 if (Trap.hasErrorOccurred())
1087 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1092 static bool checkTupleLikeDecomposition(Sema &S,
1093 ArrayRef<BindingDecl *> Bindings,
1094 VarDecl *Src, QualType DecompType,
1095 const llvm::APSInt &TupleSize) {
1096 if ((int64_t)Bindings.size() != TupleSize) {
1097 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1098 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1099 << (TupleSize < Bindings.size());
1103 if (Bindings.empty())
1106 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1109 // The unqualified-id get is looked up in the scope of E by class member
1110 // access lookup ...
1111 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1112 bool UseMemberGet = false;
1113 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1114 if (auto *RD = DecompType->getAsCXXRecordDecl())
1115 S.LookupQualifiedName(MemberGet, RD);
1116 if (MemberGet.isAmbiguous())
1118 // ... and if that finds at least one declaration that is a function
1119 // template whose first template parameter is a non-type parameter ...
1120 for (NamedDecl *D : MemberGet) {
1121 if (FunctionTemplateDecl *FTD =
1122 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1123 TemplateParameterList *TPL = FTD->getTemplateParameters();
1124 if (TPL->size() != 0 &&
1125 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1126 // ... the initializer is e.get<i>().
1127 UseMemberGet = true;
1132 S.FilterAcceptableTemplateNames(MemberGet);
1136 for (auto *B : Bindings) {
1137 BindingDiagnosticTrap Trap(S, B);
1138 SourceLocation Loc = B->getLocation();
1140 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1144 // e is an lvalue if the type of the entity is an lvalue reference and
1145 // an xvalue otherwise
1146 if (!Src->getType()->isLValueReferenceType())
1147 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1148 E.get(), nullptr, VK_XValue);
1150 TemplateArgumentListInfo Args(Loc, Loc);
1152 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1155 // if [lookup of member get] finds at least one declaration, the
1156 // initializer is e.get<i-1>().
1157 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1158 CXXScopeSpec(), SourceLocation(), nullptr,
1159 MemberGet, &Args, nullptr);
1163 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1165 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1166 // in the associated namespaces.
1167 Expr *Get = UnresolvedLookupExpr::Create(
1168 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1169 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1170 UnresolvedSetIterator(), UnresolvedSetIterator());
1172 Expr *Arg = E.get();
1173 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1177 Expr *Init = E.get();
1179 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1180 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1184 // each vi is a variable of type "reference to T" initialized with the
1185 // initializer, where the reference is an lvalue reference if the
1186 // initializer is an lvalue and an rvalue reference otherwise
1188 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1189 if (RefType.isNull())
1191 auto *RefVD = VarDecl::Create(
1192 S.Context, Src->getDeclContext(), Loc, Loc,
1193 B->getDeclName().getAsIdentifierInfo(), RefType,
1194 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1195 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1196 RefVD->setTSCSpec(Src->getTSCSpec());
1197 RefVD->setImplicit();
1198 if (Src->isInlineSpecified())
1199 RefVD->setInlineSpecified();
1200 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1202 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1203 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1204 InitializationSequence Seq(S, Entity, Kind, Init);
1205 E = Seq.Perform(S, Entity, Kind, Init);
1208 E = S.ActOnFinishFullExpr(E.get(), Loc);
1211 RefVD->setInit(E.get());
1212 RefVD->checkInitIsICE();
1214 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1215 DeclarationNameInfo(B->getDeclName(), Loc),
1220 B->setBinding(T, E.get());
1227 /// Find the base class to decompose in a built-in decomposition of a class type.
1228 /// This base class search is, unfortunately, not quite like any other that we
1229 /// perform anywhere else in C++.
1230 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1231 const CXXRecordDecl *RD,
1232 CXXCastPath &BasePath) {
1233 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1234 CXXBasePath &Path) {
1235 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1238 const CXXRecordDecl *ClassWithFields = nullptr;
1239 AccessSpecifier AS = AS_public;
1240 if (RD->hasDirectFields())
1242 // Otherwise, all of E's non-static data members shall be public direct
1244 ClassWithFields = RD;
1248 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1249 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1250 // If no classes have fields, just decompose RD itself. (This will work
1251 // if and only if zero bindings were provided.)
1252 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1255 CXXBasePath *BestPath = nullptr;
1256 for (auto &P : Paths) {
1259 else if (!S.Context.hasSameType(P.back().Base->getType(),
1260 BestPath->back().Base->getType())) {
1262 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1263 << false << RD << BestPath->back().Base->getType()
1264 << P.back().Base->getType();
1265 return DeclAccessPair();
1266 } else if (P.Access < BestPath->Access) {
1271 // ... unambiguous ...
1272 QualType BaseType = BestPath->back().Base->getType();
1273 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1274 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1275 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1276 return DeclAccessPair();
1279 // ... [accessible, implied by other rules] base class of E.
1280 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1281 *BestPath, diag::err_decomp_decl_inaccessible_base);
1282 AS = BestPath->Access;
1284 ClassWithFields = BaseType->getAsCXXRecordDecl();
1285 S.BuildBasePathArray(Paths, BasePath);
1288 // The above search did not check whether the selected class itself has base
1289 // classes with fields, so check that now.
1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293 << (ClassWithFields == RD) << RD << ClassWithFields
1294 << Paths.front().back().Base->getType();
1295 return DeclAccessPair();
1298 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1302 ValueDecl *Src, QualType DecompType,
1303 const CXXRecordDecl *OrigRD) {
1304 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1305 diag::err_incomplete_type))
1308 CXXCastPath BasePath;
1309 DeclAccessPair BasePair =
1310 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1311 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1314 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1315 DecompType.getQualifiers());
1317 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1318 unsigned NumFields =
1319 std::count_if(RD->field_begin(), RD->field_end(),
1320 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1321 assert(Bindings.size() != NumFields);
1322 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1323 << DecompType << (unsigned)Bindings.size() << NumFields
1324 << (NumFields < Bindings.size());
1328 // all of E's non-static data members shall be [...] well-formed
1329 // when named as e.name in the context of the structured binding,
1330 // E shall not have an anonymous union member, ...
1332 for (auto *FD : RD->fields()) {
1333 if (FD->isUnnamedBitfield())
1336 if (FD->isAnonymousStructOrUnion()) {
1337 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1338 << DecompType << FD->getType()->isUnionType();
1339 S.Diag(FD->getLocation(), diag::note_declared_at);
1343 // We have a real field to bind.
1344 if (I >= Bindings.size())
1345 return DiagnoseBadNumberOfBindings();
1346 auto *B = Bindings[I++];
1347 SourceLocation Loc = B->getLocation();
1349 // The field must be accessible in the context of the structured binding.
1350 // We already checked that the base class is accessible.
1351 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1353 S.CheckStructuredBindingMemberAccess(
1354 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1355 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1356 BasePair.getAccess(), FD->getAccess())));
1358 // Initialize the binding to Src.FD.
1359 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1362 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1363 VK_LValue, &BasePath);
1366 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1368 DeclAccessPair::make(FD, FD->getAccess()),
1369 DeclarationNameInfo(FD->getDeclName(), Loc));
1373 // If the type of the member is T, the referenced type is cv T, where cv is
1374 // the cv-qualification of the decomposition expression.
1376 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1377 // 'const' to the type of the field.
1378 Qualifiers Q = DecompType.getQualifiers();
1379 if (FD->isMutable())
1381 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1384 if (I != Bindings.size())
1385 return DiagnoseBadNumberOfBindings();
1390 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1391 QualType DecompType = DD->getType();
1393 // If the type of the decomposition is dependent, then so is the type of
1395 if (DecompType->isDependentType()) {
1396 for (auto *B : DD->bindings())
1397 B->setType(Context.DependentTy);
1401 DecompType = DecompType.getNonReferenceType();
1402 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1404 // C++1z [dcl.decomp]/2:
1405 // If E is an array type [...]
1406 // As an extension, we also support decomposition of built-in complex and
1408 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1409 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1410 DD->setInvalidDecl();
1413 if (auto *VT = DecompType->getAs<VectorType>()) {
1414 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1415 DD->setInvalidDecl();
1418 if (auto *CT = DecompType->getAs<ComplexType>()) {
1419 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1420 DD->setInvalidDecl();
1424 // C++1z [dcl.decomp]/3:
1425 // if the expression std::tuple_size<E>::value is a well-formed integral
1426 // constant expression, [...]
1427 llvm::APSInt TupleSize(32);
1428 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1429 case IsTupleLike::Error:
1430 DD->setInvalidDecl();
1433 case IsTupleLike::TupleLike:
1434 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1435 DD->setInvalidDecl();
1438 case IsTupleLike::NotTupleLike:
1442 // C++1z [dcl.dcl]/8:
1443 // [E shall be of array or non-union class type]
1444 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1445 if (!RD || RD->isUnion()) {
1446 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1447 << DD << !RD << DecompType;
1448 DD->setInvalidDecl();
1452 // C++1z [dcl.decomp]/4:
1453 // all of E's non-static data members shall be [...] direct members of
1454 // E or of the same unambiguous public base class of E, ...
1455 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1456 DD->setInvalidDecl();
1459 /// Merge the exception specifications of two variable declarations.
1461 /// This is called when there's a redeclaration of a VarDecl. The function
1462 /// checks if the redeclaration might have an exception specification and
1463 /// validates compatibility and merges the specs if necessary.
1464 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1465 // Shortcut if exceptions are disabled.
1466 if (!getLangOpts().CXXExceptions)
1469 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1470 "Should only be called if types are otherwise the same.");
1472 QualType NewType = New->getType();
1473 QualType OldType = Old->getType();
1475 // We're only interested in pointers and references to functions, as well
1476 // as pointers to member functions.
1477 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1478 NewType = R->getPointeeType();
1479 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1480 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1481 NewType = P->getPointeeType();
1482 OldType = OldType->getAs<PointerType>()->getPointeeType();
1483 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1484 NewType = M->getPointeeType();
1485 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1488 if (!NewType->isFunctionProtoType())
1491 // There's lots of special cases for functions. For function pointers, system
1492 // libraries are hopefully not as broken so that we don't need these
1494 if (CheckEquivalentExceptionSpec(
1495 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1496 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1497 New->setInvalidDecl();
1501 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1502 /// function declaration are well-formed according to C++
1503 /// [dcl.fct.default].
1504 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1505 unsigned NumParams = FD->getNumParams();
1508 // Find first parameter with a default argument
1509 for (p = 0; p < NumParams; ++p) {
1510 ParmVarDecl *Param = FD->getParamDecl(p);
1511 if (Param->hasDefaultArg())
1515 // C++11 [dcl.fct.default]p4:
1516 // In a given function declaration, each parameter subsequent to a parameter
1517 // with a default argument shall have a default argument supplied in this or
1518 // a previous declaration or shall be a function parameter pack. A default
1519 // argument shall not be redefined by a later declaration (not even to the
1521 unsigned LastMissingDefaultArg = 0;
1522 for (; p < NumParams; ++p) {
1523 ParmVarDecl *Param = FD->getParamDecl(p);
1524 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1525 if (Param->isInvalidDecl())
1526 /* We already complained about this parameter. */;
1527 else if (Param->getIdentifier())
1528 Diag(Param->getLocation(),
1529 diag::err_param_default_argument_missing_name)
1530 << Param->getIdentifier();
1532 Diag(Param->getLocation(),
1533 diag::err_param_default_argument_missing);
1535 LastMissingDefaultArg = p;
1539 if (LastMissingDefaultArg > 0) {
1540 // Some default arguments were missing. Clear out all of the
1541 // default arguments up to (and including) the last missing
1542 // default argument, so that we leave the function parameters
1543 // in a semantically valid state.
1544 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1545 ParmVarDecl *Param = FD->getParamDecl(p);
1546 if (Param->hasDefaultArg()) {
1547 Param->setDefaultArg(nullptr);
1553 // CheckConstexprParameterTypes - Check whether a function's parameter types
1554 // are all literal types. If so, return true. If not, produce a suitable
1555 // diagnostic and return false.
1556 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1557 const FunctionDecl *FD) {
1558 unsigned ArgIndex = 0;
1559 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1560 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1561 e = FT->param_type_end();
1562 i != e; ++i, ++ArgIndex) {
1563 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1564 SourceLocation ParamLoc = PD->getLocation();
1565 if (!(*i)->isDependentType() &&
1566 SemaRef.RequireLiteralType(ParamLoc, *i,
1567 diag::err_constexpr_non_literal_param,
1568 ArgIndex+1, PD->getSourceRange(),
1569 isa<CXXConstructorDecl>(FD)))
1575 /// Get diagnostic %select index for tag kind for
1576 /// record diagnostic message.
1577 /// WARNING: Indexes apply to particular diagnostics only!
1579 /// \returns diagnostic %select index.
1580 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1582 case TTK_Struct: return 0;
1583 case TTK_Interface: return 1;
1584 case TTK_Class: return 2;
1585 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1589 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1590 // the requirements of a constexpr function definition or a constexpr
1591 // constructor definition. If so, return true. If not, produce appropriate
1592 // diagnostics and return false.
1594 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1595 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1596 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1597 if (MD && MD->isInstance()) {
1598 // C++11 [dcl.constexpr]p4:
1599 // The definition of a constexpr constructor shall satisfy the following
1601 // - the class shall not have any virtual base classes;
1602 const CXXRecordDecl *RD = MD->getParent();
1603 if (RD->getNumVBases()) {
1604 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1605 << isa<CXXConstructorDecl>(NewFD)
1606 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1607 for (const auto &I : RD->vbases())
1608 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1609 << I.getSourceRange();
1614 if (!isa<CXXConstructorDecl>(NewFD)) {
1615 // C++11 [dcl.constexpr]p3:
1616 // The definition of a constexpr function shall satisfy the following
1618 // - it shall not be virtual;
1619 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1620 if (Method && Method->isVirtual()) {
1621 Method = Method->getCanonicalDecl();
1622 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1624 // If it's not obvious why this function is virtual, find an overridden
1625 // function which uses the 'virtual' keyword.
1626 const CXXMethodDecl *WrittenVirtual = Method;
1627 while (!WrittenVirtual->isVirtualAsWritten())
1628 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1629 if (WrittenVirtual != Method)
1630 Diag(WrittenVirtual->getLocation(),
1631 diag::note_overridden_virtual_function);
1635 // - its return type shall be a literal type;
1636 QualType RT = NewFD->getReturnType();
1637 if (!RT->isDependentType() &&
1638 RequireLiteralType(NewFD->getLocation(), RT,
1639 diag::err_constexpr_non_literal_return))
1643 // - each of its parameter types shall be a literal type;
1644 if (!CheckConstexprParameterTypes(*this, NewFD))
1650 /// Check the given declaration statement is legal within a constexpr function
1651 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1653 /// \return true if the body is OK (maybe only as an extension), false if we
1654 /// have diagnosed a problem.
1655 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1656 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1657 // C++11 [dcl.constexpr]p3 and p4:
1658 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1660 for (const auto *DclIt : DS->decls()) {
1661 switch (DclIt->getKind()) {
1662 case Decl::StaticAssert:
1664 case Decl::UsingShadow:
1665 case Decl::UsingDirective:
1666 case Decl::UnresolvedUsingTypename:
1667 case Decl::UnresolvedUsingValue:
1668 // - static_assert-declarations
1669 // - using-declarations,
1670 // - using-directives,
1674 case Decl::TypeAlias: {
1675 // - typedef declarations and alias-declarations that do not define
1676 // classes or enumerations,
1677 const auto *TN = cast<TypedefNameDecl>(DclIt);
1678 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1679 // Don't allow variably-modified types in constexpr functions.
1680 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1681 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1682 << TL.getSourceRange() << TL.getType()
1683 << isa<CXXConstructorDecl>(Dcl);
1690 case Decl::CXXRecord:
1691 // C++1y allows types to be defined, not just declared.
1692 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1693 SemaRef.Diag(DS->getBeginLoc(),
1694 SemaRef.getLangOpts().CPlusPlus14
1695 ? diag::warn_cxx11_compat_constexpr_type_definition
1696 : diag::ext_constexpr_type_definition)
1697 << isa<CXXConstructorDecl>(Dcl);
1700 case Decl::EnumConstant:
1701 case Decl::IndirectField:
1703 // These can only appear with other declarations which are banned in
1704 // C++11 and permitted in C++1y, so ignore them.
1708 case Decl::Decomposition: {
1709 // C++1y [dcl.constexpr]p3 allows anything except:
1710 // a definition of a variable of non-literal type or of static or
1711 // thread storage duration or for which no initialization is performed.
1712 const auto *VD = cast<VarDecl>(DclIt);
1713 if (VD->isThisDeclarationADefinition()) {
1714 if (VD->isStaticLocal()) {
1715 SemaRef.Diag(VD->getLocation(),
1716 diag::err_constexpr_local_var_static)
1717 << isa<CXXConstructorDecl>(Dcl)
1718 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1721 if (!VD->getType()->isDependentType() &&
1722 SemaRef.RequireLiteralType(
1723 VD->getLocation(), VD->getType(),
1724 diag::err_constexpr_local_var_non_literal_type,
1725 isa<CXXConstructorDecl>(Dcl)))
1727 if (!VD->getType()->isDependentType() &&
1728 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1729 SemaRef.Diag(VD->getLocation(),
1730 diag::err_constexpr_local_var_no_init)
1731 << isa<CXXConstructorDecl>(Dcl);
1735 SemaRef.Diag(VD->getLocation(),
1736 SemaRef.getLangOpts().CPlusPlus14
1737 ? diag::warn_cxx11_compat_constexpr_local_var
1738 : diag::ext_constexpr_local_var)
1739 << isa<CXXConstructorDecl>(Dcl);
1743 case Decl::NamespaceAlias:
1744 case Decl::Function:
1745 // These are disallowed in C++11 and permitted in C++1y. Allow them
1746 // everywhere as an extension.
1747 if (!Cxx1yLoc.isValid())
1748 Cxx1yLoc = DS->getBeginLoc();
1752 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1753 << isa<CXXConstructorDecl>(Dcl);
1761 /// Check that the given field is initialized within a constexpr constructor.
1763 /// \param Dcl The constexpr constructor being checked.
1764 /// \param Field The field being checked. This may be a member of an anonymous
1765 /// struct or union nested within the class being checked.
1766 /// \param Inits All declarations, including anonymous struct/union members and
1767 /// indirect members, for which any initialization was provided.
1768 /// \param Diagnosed Set to true if an error is produced.
1769 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1770 const FunctionDecl *Dcl,
1772 llvm::SmallSet<Decl*, 16> &Inits,
1774 if (Field->isInvalidDecl())
1777 if (Field->isUnnamedBitfield())
1780 // Anonymous unions with no variant members and empty anonymous structs do not
1781 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1782 // indirect fields don't need initializing.
1783 if (Field->isAnonymousStructOrUnion() &&
1784 (Field->getType()->isUnionType()
1785 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1786 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1789 if (!Inits.count(Field)) {
1791 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1794 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1795 } else if (Field->isAnonymousStructOrUnion()) {
1796 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1797 for (auto *I : RD->fields())
1798 // If an anonymous union contains an anonymous struct of which any member
1799 // is initialized, all members must be initialized.
1800 if (!RD->isUnion() || Inits.count(I))
1801 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1805 /// Check the provided statement is allowed in a constexpr function
1808 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1809 SmallVectorImpl<SourceLocation> &ReturnStmts,
1810 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1811 // - its function-body shall be [...] a compound-statement that contains only
1812 switch (S->getStmtClass()) {
1813 case Stmt::NullStmtClass:
1814 // - null statements,
1817 case Stmt::DeclStmtClass:
1818 // - static_assert-declarations
1819 // - using-declarations,
1820 // - using-directives,
1821 // - typedef declarations and alias-declarations that do not define
1822 // classes or enumerations,
1823 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1827 case Stmt::ReturnStmtClass:
1828 // - and exactly one return statement;
1829 if (isa<CXXConstructorDecl>(Dcl)) {
1830 // C++1y allows return statements in constexpr constructors.
1831 if (!Cxx1yLoc.isValid())
1832 Cxx1yLoc = S->getBeginLoc();
1836 ReturnStmts.push_back(S->getBeginLoc());
1839 case Stmt::CompoundStmtClass: {
1840 // C++1y allows compound-statements.
1841 if (!Cxx1yLoc.isValid())
1842 Cxx1yLoc = S->getBeginLoc();
1844 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1845 for (auto *BodyIt : CompStmt->body()) {
1846 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1847 Cxx1yLoc, Cxx2aLoc))
1853 case Stmt::AttributedStmtClass:
1854 if (!Cxx1yLoc.isValid())
1855 Cxx1yLoc = S->getBeginLoc();
1858 case Stmt::IfStmtClass: {
1859 // C++1y allows if-statements.
1860 if (!Cxx1yLoc.isValid())
1861 Cxx1yLoc = S->getBeginLoc();
1863 IfStmt *If = cast<IfStmt>(S);
1864 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1865 Cxx1yLoc, Cxx2aLoc))
1867 if (If->getElse() &&
1868 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1869 Cxx1yLoc, Cxx2aLoc))
1874 case Stmt::WhileStmtClass:
1875 case Stmt::DoStmtClass:
1876 case Stmt::ForStmtClass:
1877 case Stmt::CXXForRangeStmtClass:
1878 case Stmt::ContinueStmtClass:
1879 // C++1y allows all of these. We don't allow them as extensions in C++11,
1880 // because they don't make sense without variable mutation.
1881 if (!SemaRef.getLangOpts().CPlusPlus14)
1883 if (!Cxx1yLoc.isValid())
1884 Cxx1yLoc = S->getBeginLoc();
1885 for (Stmt *SubStmt : S->children())
1887 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1888 Cxx1yLoc, Cxx2aLoc))
1892 case Stmt::SwitchStmtClass:
1893 case Stmt::CaseStmtClass:
1894 case Stmt::DefaultStmtClass:
1895 case Stmt::BreakStmtClass:
1896 // C++1y allows switch-statements, and since they don't need variable
1897 // mutation, we can reasonably allow them in C++11 as an extension.
1898 if (!Cxx1yLoc.isValid())
1899 Cxx1yLoc = S->getBeginLoc();
1900 for (Stmt *SubStmt : S->children())
1902 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1903 Cxx1yLoc, Cxx2aLoc))
1907 case Stmt::CXXTryStmtClass:
1908 if (Cxx2aLoc.isInvalid())
1909 Cxx2aLoc = S->getBeginLoc();
1910 for (Stmt *SubStmt : S->children()) {
1912 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1913 Cxx1yLoc, Cxx2aLoc))
1918 case Stmt::CXXCatchStmtClass:
1919 // Do not bother checking the language mode (already covered by the
1920 // try block check).
1921 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1922 cast<CXXCatchStmt>(S)->getHandlerBlock(),
1923 ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1931 // C++1y allows expression-statements.
1932 if (!Cxx1yLoc.isValid())
1933 Cxx1yLoc = S->getBeginLoc();
1937 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1938 << isa<CXXConstructorDecl>(Dcl);
1942 /// Check the body for the given constexpr function declaration only contains
1943 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1945 /// \return true if the body is OK, false if we have diagnosed a problem.
1946 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1947 SmallVector<SourceLocation, 4> ReturnStmts;
1949 if (isa<CXXTryStmt>(Body)) {
1950 // C++11 [dcl.constexpr]p3:
1951 // The definition of a constexpr function shall satisfy the following
1952 // constraints: [...]
1953 // - its function-body shall be = delete, = default, or a
1954 // compound-statement
1956 // C++11 [dcl.constexpr]p4:
1957 // In the definition of a constexpr constructor, [...]
1958 // - its function-body shall not be a function-try-block;
1960 // This restriction is lifted in C++2a, as long as inner statements also
1961 // apply the general constexpr rules.
1962 Diag(Body->getBeginLoc(),
1963 !getLangOpts().CPlusPlus2a
1964 ? diag::ext_constexpr_function_try_block_cxx2a
1965 : diag::warn_cxx17_compat_constexpr_function_try_block)
1966 << isa<CXXConstructorDecl>(Dcl);
1969 // - its function-body shall be [...] a compound-statement that contains only
1970 // [... list of cases ...]
1972 // Note that walking the children here is enough to properly check for
1973 // CompoundStmt and CXXTryStmt body.
1974 SourceLocation Cxx1yLoc, Cxx2aLoc;
1975 for (Stmt *SubStmt : Body->children()) {
1977 !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1978 Cxx1yLoc, Cxx2aLoc))
1982 if (Cxx2aLoc.isValid())
1984 getLangOpts().CPlusPlus2a
1985 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1986 : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1987 << isa<CXXConstructorDecl>(Dcl);
1988 if (Cxx1yLoc.isValid())
1990 getLangOpts().CPlusPlus14
1991 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1992 : diag::ext_constexpr_body_invalid_stmt)
1993 << isa<CXXConstructorDecl>(Dcl);
1995 if (const CXXConstructorDecl *Constructor
1996 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1997 const CXXRecordDecl *RD = Constructor->getParent();
1999 // - every non-variant non-static data member and base class sub-object
2000 // shall be initialized;
2002 // - if the class is a union having variant members, exactly one of them
2003 // shall be initialized;
2004 if (RD->isUnion()) {
2005 if (Constructor->getNumCtorInitializers() == 0 &&
2006 RD->hasVariantMembers()) {
2007 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2010 } else if (!Constructor->isDependentContext() &&
2011 !Constructor->isDelegatingConstructor()) {
2012 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2014 // Skip detailed checking if we have enough initializers, and we would
2015 // allow at most one initializer per member.
2016 bool AnyAnonStructUnionMembers = false;
2017 unsigned Fields = 0;
2018 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2019 E = RD->field_end(); I != E; ++I, ++Fields) {
2020 if (I->isAnonymousStructOrUnion()) {
2021 AnyAnonStructUnionMembers = true;
2026 // - if the class is a union-like class, but is not a union, for each of
2027 // its anonymous union members having variant members, exactly one of
2028 // them shall be initialized;
2029 if (AnyAnonStructUnionMembers ||
2030 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2031 // Check initialization of non-static data members. Base classes are
2032 // always initialized so do not need to be checked. Dependent bases
2033 // might not have initializers in the member initializer list.
2034 llvm::SmallSet<Decl*, 16> Inits;
2035 for (const auto *I: Constructor->inits()) {
2036 if (FieldDecl *FD = I->getMember())
2038 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2039 Inits.insert(ID->chain_begin(), ID->chain_end());
2042 bool Diagnosed = false;
2043 for (auto *I : RD->fields())
2044 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2050 if (ReturnStmts.empty()) {
2051 // C++1y doesn't require constexpr functions to contain a 'return'
2052 // statement. We still do, unless the return type might be void, because
2053 // otherwise if there's no return statement, the function cannot
2054 // be used in a core constant expression.
2055 bool OK = getLangOpts().CPlusPlus14 &&
2056 (Dcl->getReturnType()->isVoidType() ||
2057 Dcl->getReturnType()->isDependentType());
2058 Diag(Dcl->getLocation(),
2059 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2060 : diag::err_constexpr_body_no_return);
2063 } else if (ReturnStmts.size() > 1) {
2064 Diag(ReturnStmts.back(),
2065 getLangOpts().CPlusPlus14
2066 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2067 : diag::ext_constexpr_body_multiple_return);
2068 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2069 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2073 // C++11 [dcl.constexpr]p5:
2074 // if no function argument values exist such that the function invocation
2075 // substitution would produce a constant expression, the program is
2076 // ill-formed; no diagnostic required.
2077 // C++11 [dcl.constexpr]p3:
2078 // - every constructor call and implicit conversion used in initializing the
2079 // return value shall be one of those allowed in a constant expression.
2080 // C++11 [dcl.constexpr]p4:
2081 // - every constructor involved in initializing non-static data members and
2082 // base class sub-objects shall be a constexpr constructor.
2083 SmallVector<PartialDiagnosticAt, 8> Diags;
2084 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2085 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2086 << isa<CXXConstructorDecl>(Dcl);
2087 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2088 Diag(Diags[I].first, Diags[I].second);
2089 // Don't return false here: we allow this for compatibility in
2096 /// Get the class that is directly named by the current context. This is the
2097 /// class for which an unqualified-id in this scope could name a constructor
2100 /// If the scope specifier denotes a class, this will be that class.
2101 /// If the scope specifier is empty, this will be the class whose
2102 /// member-specification we are currently within. Otherwise, there
2103 /// is no such class.
2104 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2105 assert(getLangOpts().CPlusPlus && "No class names in C!");
2107 if (SS && SS->isInvalid())
2110 if (SS && SS->isNotEmpty()) {
2111 DeclContext *DC = computeDeclContext(*SS, true);
2112 return dyn_cast_or_null<CXXRecordDecl>(DC);
2115 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2118 /// isCurrentClassName - Determine whether the identifier II is the
2119 /// name of the class type currently being defined. In the case of
2120 /// nested classes, this will only return true if II is the name of
2121 /// the innermost class.
2122 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2123 const CXXScopeSpec *SS) {
2124 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2125 return CurDecl && &II == CurDecl->getIdentifier();
2128 /// Determine whether the identifier II is a typo for the name of
2129 /// the class type currently being defined. If so, update it to the identifier
2130 /// that should have been used.
2131 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2132 assert(getLangOpts().CPlusPlus && "No class names in C!");
2134 if (!getLangOpts().SpellChecking)
2137 CXXRecordDecl *CurDecl;
2138 if (SS && SS->isSet() && !SS->isInvalid()) {
2139 DeclContext *DC = computeDeclContext(*SS, true);
2140 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2142 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2144 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2145 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2146 < II->getLength()) {
2147 II = CurDecl->getIdentifier();
2154 /// Determine whether the given class is a base class of the given
2155 /// class, including looking at dependent bases.
2156 static bool findCircularInheritance(const CXXRecordDecl *Class,
2157 const CXXRecordDecl *Current) {
2158 SmallVector<const CXXRecordDecl*, 8> Queue;
2160 Class = Class->getCanonicalDecl();
2162 for (const auto &I : Current->bases()) {
2163 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2167 Base = Base->getDefinition();
2171 if (Base->getCanonicalDecl() == Class)
2174 Queue.push_back(Base);
2180 Current = Queue.pop_back_val();
2186 /// Check the validity of a C++ base class specifier.
2188 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2189 /// and returns NULL otherwise.
2191 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2192 SourceRange SpecifierRange,
2193 bool Virtual, AccessSpecifier Access,
2194 TypeSourceInfo *TInfo,
2195 SourceLocation EllipsisLoc) {
2196 QualType BaseType = TInfo->getType();
2198 // C++ [class.union]p1:
2199 // A union shall not have base classes.
2200 if (Class->isUnion()) {
2201 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2206 if (EllipsisLoc.isValid() &&
2207 !TInfo->getType()->containsUnexpandedParameterPack()) {
2208 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2209 << TInfo->getTypeLoc().getSourceRange();
2210 EllipsisLoc = SourceLocation();
2213 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2215 if (BaseType->isDependentType()) {
2216 // Make sure that we don't have circular inheritance among our dependent
2217 // bases. For non-dependent bases, the check for completeness below handles
2219 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2220 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2221 ((BaseDecl = BaseDecl->getDefinition()) &&
2222 findCircularInheritance(Class, BaseDecl))) {
2223 Diag(BaseLoc, diag::err_circular_inheritance)
2224 << BaseType << Context.getTypeDeclType(Class);
2226 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2227 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2234 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2235 Class->getTagKind() == TTK_Class,
2236 Access, TInfo, EllipsisLoc);
2239 // Base specifiers must be record types.
2240 if (!BaseType->isRecordType()) {
2241 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2245 // C++ [class.union]p1:
2246 // A union shall not be used as a base class.
2247 if (BaseType->isUnionType()) {
2248 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2252 // For the MS ABI, propagate DLL attributes to base class templates.
2253 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2254 if (Attr *ClassAttr = getDLLAttr(Class)) {
2255 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2256 BaseType->getAsCXXRecordDecl())) {
2257 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2263 // C++ [class.derived]p2:
2264 // The class-name in a base-specifier shall not be an incompletely
2266 if (RequireCompleteType(BaseLoc, BaseType,
2267 diag::err_incomplete_base_class, SpecifierRange)) {
2268 Class->setInvalidDecl();
2272 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2273 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2274 assert(BaseDecl && "Record type has no declaration");
2275 BaseDecl = BaseDecl->getDefinition();
2276 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2277 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2278 assert(CXXBaseDecl && "Base type is not a C++ type");
2280 // Microsoft docs say:
2281 // "If a base-class has a code_seg attribute, derived classes must have the
2283 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2284 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2285 if ((DerivedCSA || BaseCSA) &&
2286 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2287 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2288 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2293 // A class which contains a flexible array member is not suitable for use as a
2295 // - If the layout determines that a base comes before another base,
2296 // the flexible array member would index into the subsequent base.
2297 // - If the layout determines that base comes before the derived class,
2298 // the flexible array member would index into the derived class.
2299 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2300 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2301 << CXXBaseDecl->getDeclName();
2306 // If a class is marked final and it appears as a base-type-specifier in
2307 // base-clause, the program is ill-formed.
2308 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2309 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2310 << CXXBaseDecl->getDeclName()
2311 << FA->isSpelledAsSealed();
2312 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2313 << CXXBaseDecl->getDeclName() << FA->getRange();
2317 if (BaseDecl->isInvalidDecl())
2318 Class->setInvalidDecl();
2320 // Create the base specifier.
2321 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2322 Class->getTagKind() == TTK_Class,
2323 Access, TInfo, EllipsisLoc);
2326 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2327 /// one entry in the base class list of a class specifier, for
2329 /// class foo : public bar, virtual private baz {
2330 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2332 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2333 ParsedAttributes &Attributes,
2334 bool Virtual, AccessSpecifier Access,
2335 ParsedType basetype, SourceLocation BaseLoc,
2336 SourceLocation EllipsisLoc) {
2340 AdjustDeclIfTemplate(classdecl);
2341 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2345 // We haven't yet attached the base specifiers.
2346 Class->setIsParsingBaseSpecifiers();
2348 // We do not support any C++11 attributes on base-specifiers yet.
2349 // Diagnose any attributes we see.
2350 for (const ParsedAttr &AL : Attributes) {
2351 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2353 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2354 ? (unsigned)diag::warn_unknown_attribute_ignored
2355 : (unsigned)diag::err_base_specifier_attribute)
2359 TypeSourceInfo *TInfo = nullptr;
2360 GetTypeFromParser(basetype, &TInfo);
2362 if (EllipsisLoc.isInvalid() &&
2363 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2367 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2368 Virtual, Access, TInfo,
2372 Class->setInvalidDecl();
2377 /// Use small set to collect indirect bases. As this is only used
2378 /// locally, there's no need to abstract the small size parameter.
2379 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2381 /// Recursively add the bases of Type. Don't add Type itself.
2383 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2384 const QualType &Type)
2386 // Even though the incoming type is a base, it might not be
2387 // a class -- it could be a template parm, for instance.
2388 if (auto Rec = Type->getAs<RecordType>()) {
2389 auto Decl = Rec->getAsCXXRecordDecl();
2391 // Iterate over its bases.
2392 for (const auto &BaseSpec : Decl->bases()) {
2393 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2394 .getUnqualifiedType();
2395 if (Set.insert(Base).second)
2396 // If we've not already seen it, recurse.
2397 NoteIndirectBases(Context, Set, Base);
2402 /// Performs the actual work of attaching the given base class
2403 /// specifiers to a C++ class.
2404 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2405 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2409 // Used to keep track of which base types we have already seen, so
2410 // that we can properly diagnose redundant direct base types. Note
2411 // that the key is always the unqualified canonical type of the base
2413 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2415 // Used to track indirect bases so we can see if a direct base is
2417 IndirectBaseSet IndirectBaseTypes;
2419 // Copy non-redundant base specifiers into permanent storage.
2420 unsigned NumGoodBases = 0;
2421 bool Invalid = false;
2422 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2423 QualType NewBaseType
2424 = Context.getCanonicalType(Bases[idx]->getType());
2425 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2427 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2429 // C++ [class.mi]p3:
2430 // A class shall not be specified as a direct base class of a
2431 // derived class more than once.
2432 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2433 << KnownBase->getType() << Bases[idx]->getSourceRange();
2435 // Delete the duplicate base class specifier; we're going to
2436 // overwrite its pointer later.
2437 Context.Deallocate(Bases[idx]);
2441 // Okay, add this new base class.
2442 KnownBase = Bases[idx];
2443 Bases[NumGoodBases++] = Bases[idx];
2445 // Note this base's direct & indirect bases, if there could be ambiguity.
2446 if (Bases.size() > 1)
2447 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2449 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2450 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2451 if (Class->isInterface() &&
2452 (!RD->isInterfaceLike() ||
2453 KnownBase->getAccessSpecifier() != AS_public)) {
2454 // The Microsoft extension __interface does not permit bases that
2455 // are not themselves public interfaces.
2456 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2457 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2458 << RD->getSourceRange();
2461 if (RD->hasAttr<WeakAttr>())
2462 Class->addAttr(WeakAttr::CreateImplicit(Context));
2467 // Attach the remaining base class specifiers to the derived class.
2468 Class->setBases(Bases.data(), NumGoodBases);
2470 // Check that the only base classes that are duplicate are virtual.
2471 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2472 // Check whether this direct base is inaccessible due to ambiguity.
2473 QualType BaseType = Bases[idx]->getType();
2475 // Skip all dependent types in templates being used as base specifiers.
2476 // Checks below assume that the base specifier is a CXXRecord.
2477 if (BaseType->isDependentType())
2480 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2481 .getUnqualifiedType();
2483 if (IndirectBaseTypes.count(CanonicalBase)) {
2484 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2485 /*DetectVirtual=*/true);
2487 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2491 if (Paths.isAmbiguous(CanonicalBase))
2492 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2493 << BaseType << getAmbiguousPathsDisplayString(Paths)
2494 << Bases[idx]->getSourceRange();
2496 assert(Bases[idx]->isVirtual());
2499 // Delete the base class specifier, since its data has been copied
2500 // into the CXXRecordDecl.
2501 Context.Deallocate(Bases[idx]);
2507 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2508 /// class, after checking whether there are any duplicate base
2510 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2511 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2512 if (!ClassDecl || Bases.empty())
2515 AdjustDeclIfTemplate(ClassDecl);
2516 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2519 /// Determine whether the type \p Derived is a C++ class that is
2520 /// derived from the type \p Base.
2521 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2522 if (!getLangOpts().CPlusPlus)
2525 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2529 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2533 // If either the base or the derived type is invalid, don't try to
2534 // check whether one is derived from the other.
2535 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2538 // FIXME: In a modules build, do we need the entire path to be visible for us
2539 // to be able to use the inheritance relationship?
2540 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2543 return DerivedRD->isDerivedFrom(BaseRD);
2546 /// Determine whether the type \p Derived is a C++ class that is
2547 /// derived from the type \p Base.
2548 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2549 CXXBasePaths &Paths) {
2550 if (!getLangOpts().CPlusPlus)
2553 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2557 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2561 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2564 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2567 static void BuildBasePathArray(const CXXBasePath &Path,
2568 CXXCastPath &BasePathArray) {
2569 // We first go backward and check if we have a virtual base.
2570 // FIXME: It would be better if CXXBasePath had the base specifier for
2571 // the nearest virtual base.
2573 for (unsigned I = Path.size(); I != 0; --I) {
2574 if (Path[I - 1].Base->isVirtual()) {
2580 // Now add all bases.
2581 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2582 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2586 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2587 CXXCastPath &BasePathArray) {
2588 assert(BasePathArray.empty() && "Base path array must be empty!");
2589 assert(Paths.isRecordingPaths() && "Must record paths!");
2590 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2592 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2593 /// conversion (where Derived and Base are class types) is
2594 /// well-formed, meaning that the conversion is unambiguous (and
2595 /// that all of the base classes are accessible). Returns true
2596 /// and emits a diagnostic if the code is ill-formed, returns false
2597 /// otherwise. Loc is the location where this routine should point to
2598 /// if there is an error, and Range is the source range to highlight
2599 /// if there is an error.
2601 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2602 /// diagnostic for the respective type of error will be suppressed, but the
2603 /// check for ill-formed code will still be performed.
2605 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2606 unsigned InaccessibleBaseID,
2607 unsigned AmbigiousBaseConvID,
2608 SourceLocation Loc, SourceRange Range,
2609 DeclarationName Name,
2610 CXXCastPath *BasePath,
2611 bool IgnoreAccess) {
2612 // First, determine whether the path from Derived to Base is
2613 // ambiguous. This is slightly more expensive than checking whether
2614 // the Derived to Base conversion exists, because here we need to
2615 // explore multiple paths to determine if there is an ambiguity.
2616 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2617 /*DetectVirtual=*/false);
2618 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2619 if (!DerivationOkay)
2622 const CXXBasePath *Path = nullptr;
2623 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2624 Path = &Paths.front();
2626 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2627 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2628 // user to access such bases.
2629 if (!Path && getLangOpts().MSVCCompat) {
2630 for (const CXXBasePath &PossiblePath : Paths) {
2631 if (PossiblePath.size() == 1) {
2632 Path = &PossiblePath;
2633 if (AmbigiousBaseConvID)
2634 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2635 << Base << Derived << Range;
2642 if (!IgnoreAccess) {
2643 // Check that the base class can be accessed.
2645 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2646 case AR_inaccessible:
2655 // Build a base path if necessary.
2657 ::BuildBasePathArray(*Path, *BasePath);
2661 if (AmbigiousBaseConvID) {
2662 // We know that the derived-to-base conversion is ambiguous, and
2663 // we're going to produce a diagnostic. Perform the derived-to-base
2664 // search just one more time to compute all of the possible paths so
2665 // that we can print them out. This is more expensive than any of
2666 // the previous derived-to-base checks we've done, but at this point
2667 // performance isn't as much of an issue.
2669 Paths.setRecordingPaths(true);
2670 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2671 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2674 // Build up a textual representation of the ambiguous paths, e.g.,
2675 // D -> B -> A, that will be used to illustrate the ambiguous
2676 // conversions in the diagnostic. We only print one of the paths
2677 // to each base class subobject.
2678 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2680 Diag(Loc, AmbigiousBaseConvID)
2681 << Derived << Base << PathDisplayStr << Range << Name;
2687 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2688 SourceLocation Loc, SourceRange Range,
2689 CXXCastPath *BasePath,
2690 bool IgnoreAccess) {
2691 return CheckDerivedToBaseConversion(
2692 Derived, Base, diag::err_upcast_to_inaccessible_base,
2693 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2694 BasePath, IgnoreAccess);
2698 /// Builds a string representing ambiguous paths from a
2699 /// specific derived class to different subobjects of the same base
2702 /// This function builds a string that can be used in error messages
2703 /// to show the different paths that one can take through the
2704 /// inheritance hierarchy to go from the derived class to different
2705 /// subobjects of a base class. The result looks something like this:
2707 /// struct D -> struct B -> struct A
2708 /// struct D -> struct C -> struct A
2710 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2711 std::string PathDisplayStr;
2712 std::set<unsigned> DisplayedPaths;
2713 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2714 Path != Paths.end(); ++Path) {
2715 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2716 // We haven't displayed a path to this particular base
2717 // class subobject yet.
2718 PathDisplayStr += "\n ";
2719 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2720 for (CXXBasePath::const_iterator Element = Path->begin();
2721 Element != Path->end(); ++Element)
2722 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2726 return PathDisplayStr;
2729 //===----------------------------------------------------------------------===//
2730 // C++ class member Handling
2731 //===----------------------------------------------------------------------===//
2733 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2734 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2735 SourceLocation ColonLoc,
2736 const ParsedAttributesView &Attrs) {
2737 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2738 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2740 CurContext->addHiddenDecl(ASDecl);
2741 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2744 /// CheckOverrideControl - Check C++11 override control semantics.
2745 void Sema::CheckOverrideControl(NamedDecl *D) {
2746 if (D->isInvalidDecl())
2749 // We only care about "override" and "final" declarations.
2750 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2753 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2755 // We can't check dependent instance methods.
2756 if (MD && MD->isInstance() &&
2757 (MD->getParent()->hasAnyDependentBases() ||
2758 MD->getType()->isDependentType()))
2761 if (MD && !MD->isVirtual()) {
2762 // If we have a non-virtual method, check if if hides a virtual method.
2763 // (In that case, it's most likely the method has the wrong type.)
2764 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2765 FindHiddenVirtualMethods(MD, OverloadedMethods);
2767 if (!OverloadedMethods.empty()) {
2768 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2769 Diag(OA->getLocation(),
2770 diag::override_keyword_hides_virtual_member_function)
2771 << "override" << (OverloadedMethods.size() > 1);
2772 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2773 Diag(FA->getLocation(),
2774 diag::override_keyword_hides_virtual_member_function)
2775 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2776 << (OverloadedMethods.size() > 1);
2778 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2779 MD->setInvalidDecl();
2782 // Fall through into the general case diagnostic.
2783 // FIXME: We might want to attempt typo correction here.
2786 if (!MD || !MD->isVirtual()) {
2787 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2788 Diag(OA->getLocation(),
2789 diag::override_keyword_only_allowed_on_virtual_member_functions)
2790 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2791 D->dropAttr<OverrideAttr>();
2793 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2794 Diag(FA->getLocation(),
2795 diag::override_keyword_only_allowed_on_virtual_member_functions)
2796 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2797 << FixItHint::CreateRemoval(FA->getLocation());
2798 D->dropAttr<FinalAttr>();
2803 // C++11 [class.virtual]p5:
2804 // If a function is marked with the virt-specifier override and
2805 // does not override a member function of a base class, the program is
2807 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2808 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2809 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2810 << MD->getDeclName();
2813 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2814 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2816 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2817 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2820 SourceLocation Loc = MD->getLocation();
2821 SourceLocation SpellingLoc = Loc;
2822 if (getSourceManager().isMacroArgExpansion(Loc))
2823 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2824 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2825 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2828 if (MD->size_overridden_methods() > 0) {
2829 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2830 ? diag::warn_destructor_marked_not_override_overriding
2831 : diag::warn_function_marked_not_override_overriding;
2832 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2833 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2834 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2838 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2839 /// function overrides a virtual member function marked 'final', according to
2840 /// C++11 [class.virtual]p4.
2841 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2842 const CXXMethodDecl *Old) {
2843 FinalAttr *FA = Old->getAttr<FinalAttr>();
2847 Diag(New->getLocation(), diag::err_final_function_overridden)
2848 << New->getDeclName()
2849 << FA->isSpelledAsSealed();
2850 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2854 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2855 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2856 // FIXME: Destruction of ObjC lifetime types has side-effects.
2857 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2858 return !RD->isCompleteDefinition() ||
2859 !RD->hasTrivialDefaultConstructor() ||
2860 !RD->hasTrivialDestructor();
2864 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2865 ParsedAttributesView::const_iterator Itr =
2866 llvm::find_if(list, [](const ParsedAttr &AL) {
2867 return AL.isDeclspecPropertyAttribute();
2869 if (Itr != list.end())
2874 // Check if there is a field shadowing.
2875 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2876 DeclarationName FieldName,
2877 const CXXRecordDecl *RD,
2879 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2882 // To record a shadowed field in a base
2883 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2884 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2885 CXXBasePath &Path) {
2886 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2887 // Record an ambiguous path directly
2888 if (Bases.find(Base) != Bases.end())
2890 for (const auto Field : Base->lookup(FieldName)) {
2891 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2892 Field->getAccess() != AS_private) {
2893 assert(Field->getAccess() != AS_none);
2894 assert(Bases.find(Base) == Bases.end());
2895 Bases[Base] = Field;
2902 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2903 /*DetectVirtual=*/true);
2904 if (!RD->lookupInBases(FieldShadowed, Paths))
2907 for (const auto &P : Paths) {
2908 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2909 auto It = Bases.find(Base);
2910 // Skip duplicated bases
2911 if (It == Bases.end())
2913 auto BaseField = It->second;
2914 assert(BaseField->getAccess() != AS_private);
2916 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2917 Diag(Loc, diag::warn_shadow_field)
2918 << FieldName << RD << Base << DeclIsField;
2919 Diag(BaseField->getLocation(), diag::note_shadow_field);
2925 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2926 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2927 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2928 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2929 /// present (but parsing it has been deferred).
2931 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2932 MultiTemplateParamsArg TemplateParameterLists,
2933 Expr *BW, const VirtSpecifiers &VS,
2934 InClassInitStyle InitStyle) {
2935 const DeclSpec &DS = D.getDeclSpec();
2936 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2937 DeclarationName Name = NameInfo.getName();
2938 SourceLocation Loc = NameInfo.getLoc();
2940 // For anonymous bitfields, the location should point to the type.
2941 if (Loc.isInvalid())
2942 Loc = D.getBeginLoc();
2944 Expr *BitWidth = static_cast<Expr*>(BW);
2946 assert(isa<CXXRecordDecl>(CurContext));
2947 assert(!DS.isFriendSpecified());
2949 bool isFunc = D.isDeclarationOfFunction();
2950 const ParsedAttr *MSPropertyAttr =
2951 getMSPropertyAttr(D.getDeclSpec().getAttributes());
2953 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2954 // The Microsoft extension __interface only permits public member functions
2955 // and prohibits constructors, destructors, operators, non-public member
2956 // functions, static methods and data members.
2957 unsigned InvalidDecl;
2958 bool ShowDeclName = true;
2960 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2964 else if (AS != AS_public)
2966 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2968 else switch (Name.getNameKind()) {
2969 case DeclarationName::CXXConstructorName:
2971 ShowDeclName = false;
2974 case DeclarationName::CXXDestructorName:
2976 ShowDeclName = false;
2979 case DeclarationName::CXXOperatorName:
2980 case DeclarationName::CXXConversionFunctionName:
2991 Diag(Loc, diag::err_invalid_member_in_interface)
2992 << (InvalidDecl-1) << Name;
2994 Diag(Loc, diag::err_invalid_member_in_interface)
2995 << (InvalidDecl-1) << "";
3000 // C++ 9.2p6: A member shall not be declared to have automatic storage
3001 // duration (auto, register) or with the extern storage-class-specifier.
3002 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3003 // data members and cannot be applied to names declared const or static,
3004 // and cannot be applied to reference members.
3005 switch (DS.getStorageClassSpec()) {
3006 case DeclSpec::SCS_unspecified:
3007 case DeclSpec::SCS_typedef:
3008 case DeclSpec::SCS_static:
3010 case DeclSpec::SCS_mutable:
3012 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3014 // FIXME: It would be nicer if the keyword was ignored only for this
3015 // declarator. Otherwise we could get follow-up errors.
3016 D.getMutableDeclSpec().ClearStorageClassSpecs();
3020 Diag(DS.getStorageClassSpecLoc(),
3021 diag::err_storageclass_invalid_for_member);
3022 D.getMutableDeclSpec().ClearStorageClassSpecs();
3026 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3027 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3030 if (DS.isConstexprSpecified() && isInstField) {
3031 SemaDiagnosticBuilder B =
3032 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3033 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3034 if (InitStyle == ICIS_NoInit) {
3036 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3037 B << FixItHint::CreateRemoval(ConstexprLoc);
3039 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3040 D.getMutableDeclSpec().ClearConstexprSpec();
3041 const char *PrevSpec;
3043 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3044 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3046 assert(!Failed && "Making a constexpr member const shouldn't fail");
3050 const char *PrevSpec;
3052 if (D.getMutableDeclSpec().SetStorageClassSpec(
3053 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3054 Context.getPrintingPolicy())) {
3055 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3056 "This is the only DeclSpec that should fail to be applied");
3059 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3060 isInstField = false;
3067 CXXScopeSpec &SS = D.getCXXScopeSpec();
3069 // Data members must have identifiers for names.
3070 if (!Name.isIdentifier()) {
3071 Diag(Loc, diag::err_bad_variable_name)
3076 IdentifierInfo *II = Name.getAsIdentifierInfo();
3078 // Member field could not be with "template" keyword.
3079 // So TemplateParameterLists should be empty in this case.
3080 if (TemplateParameterLists.size()) {
3081 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3082 if (TemplateParams->size()) {
3083 // There is no such thing as a member field template.
3084 Diag(D.getIdentifierLoc(), diag::err_template_member)
3086 << SourceRange(TemplateParams->getTemplateLoc(),
3087 TemplateParams->getRAngleLoc());
3089 // There is an extraneous 'template<>' for this member.
3090 Diag(TemplateParams->getTemplateLoc(),
3091 diag::err_template_member_noparams)
3093 << SourceRange(TemplateParams->getTemplateLoc(),
3094 TemplateParams->getRAngleLoc());
3099 if (SS.isSet() && !SS.isInvalid()) {
3100 // The user provided a superfluous scope specifier inside a class
3106 if (DeclContext *DC = computeDeclContext(SS, false))
3107 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3108 D.getName().getKind() ==
3109 UnqualifiedIdKind::IK_TemplateId);
3111 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3112 << Name << SS.getRange();
3117 if (MSPropertyAttr) {
3118 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3119 BitWidth, InitStyle, AS, *MSPropertyAttr);
3122 isInstField = false;
3124 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3125 BitWidth, InitStyle, AS);
3130 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3132 Member = HandleDeclarator(S, D, TemplateParameterLists);
3136 // Non-instance-fields can't have a bitfield.
3138 if (Member->isInvalidDecl()) {
3139 // don't emit another diagnostic.
3140 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3141 // C++ 9.6p3: A bit-field shall not be a static member.
3142 // "static member 'A' cannot be a bit-field"
3143 Diag(Loc, diag::err_static_not_bitfield)
3144 << Name << BitWidth->getSourceRange();
3145 } else if (isa<TypedefDecl>(Member)) {
3146 // "typedef member 'x' cannot be a bit-field"
3147 Diag(Loc, diag::err_typedef_not_bitfield)
3148 << Name << BitWidth->getSourceRange();
3150 // A function typedef ("typedef int f(); f a;").
3151 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3152 Diag(Loc, diag::err_not_integral_type_bitfield)
3153 << Name << cast<ValueDecl>(Member)->getType()
3154 << BitWidth->getSourceRange();
3158 Member->setInvalidDecl();
3161 NamedDecl *NonTemplateMember = Member;
3162 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3163 NonTemplateMember = FunTmpl->getTemplatedDecl();
3164 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3165 NonTemplateMember = VarTmpl->getTemplatedDecl();
3167 Member->setAccess(AS);
3169 // If we have declared a member function template or static data member
3170 // template, set the access of the templated declaration as well.
3171 if (NonTemplateMember != Member)
3172 NonTemplateMember->setAccess(AS);
3174 // C++ [temp.deduct.guide]p3:
3175 // A deduction guide [...] for a member class template [shall be
3176 // declared] with the same access [as the template].
3177 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3178 auto *TD = DG->getDeducedTemplate();
3179 if (AS != TD->getAccess()) {
3180 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3181 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3183 const AccessSpecDecl *LastAccessSpec = nullptr;
3184 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3185 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3186 LastAccessSpec = AccessSpec;
3188 assert(LastAccessSpec && "differing access with no access specifier");
3189 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3195 if (VS.isOverrideSpecified())
3196 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3197 if (VS.isFinalSpecified())
3198 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3199 VS.isFinalSpelledSealed()));
3201 if (VS.getLastLocation().isValid()) {
3202 // Update the end location of a method that has a virt-specifiers.
3203 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3204 MD->setRangeEnd(VS.getLastLocation());
3207 CheckOverrideControl(Member);
3209 assert((Name || isInstField) && "No identifier for non-field ?");
3212 FieldDecl *FD = cast<FieldDecl>(Member);
3213 FieldCollector->Add(FD);
3215 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3216 // Remember all explicit private FieldDecls that have a name, no side
3217 // effects and are not part of a dependent type declaration.
3218 if (!FD->isImplicit() && FD->getDeclName() &&
3219 FD->getAccess() == AS_private &&
3220 !FD->hasAttr<UnusedAttr>() &&
3221 !FD->getParent()->isDependentContext() &&
3222 !InitializationHasSideEffects(*FD))
3223 UnusedPrivateFields.insert(FD);
3231 class UninitializedFieldVisitor
3232 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3234 // List of Decls to generate a warning on. Also remove Decls that become
3236 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3237 // List of base classes of the record. Classes are removed after their
3239 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3240 // Vector of decls to be removed from the Decl set prior to visiting the
3241 // nodes. These Decls may have been initialized in the prior initializer.
3242 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3243 // If non-null, add a note to the warning pointing back to the constructor.
3244 const CXXConstructorDecl *Constructor;
3245 // Variables to hold state when processing an initializer list. When
3246 // InitList is true, special case initialization of FieldDecls matching
3247 // InitListFieldDecl.
3249 FieldDecl *InitListFieldDecl;
3250 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3253 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3254 UninitializedFieldVisitor(Sema &S,
3255 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3256 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3257 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3258 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3260 // Returns true if the use of ME is not an uninitialized use.
3261 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3262 bool CheckReferenceOnly) {
3263 llvm::SmallVector<FieldDecl*, 4> Fields;
3264 bool ReferenceField = false;
3266 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3269 Fields.push_back(FD);
3270 if (FD->getType()->isReferenceType())
3271 ReferenceField = true;
3272 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3275 // Binding a reference to an uninitialized field is not an
3276 // uninitialized use.
3277 if (CheckReferenceOnly && !ReferenceField)
3280 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3281 // Discard the first field since it is the field decl that is being
3283 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3284 UsedFieldIndex.push_back((*I)->getFieldIndex());
3287 for (auto UsedIter = UsedFieldIndex.begin(),
3288 UsedEnd = UsedFieldIndex.end(),
3289 OrigIter = InitFieldIndex.begin(),
3290 OrigEnd = InitFieldIndex.end();
3291 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3292 if (*UsedIter < *OrigIter)
3294 if (*UsedIter > *OrigIter)
3301 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3303 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3306 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3308 MemberExpr *FieldME = ME;
3310 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3313 while (MemberExpr *SubME =
3314 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3316 if (isa<VarDecl>(SubME->getMemberDecl()))
3319 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3320 if (!FD->isAnonymousStructOrUnion())
3323 if (!FieldME->getType().isPODType(S.Context))
3324 AllPODFields = false;
3326 Base = SubME->getBase();
3329 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3332 if (AddressOf && AllPODFields)
3335 ValueDecl* FoundVD = FieldME->getMemberDecl();
3337 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3338 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3339 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3342 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3343 QualType T = BaseCast->getType();
3344 if (T->isPointerType() &&
3345 BaseClasses.count(T->getPointeeType())) {
3346 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3347 << T->getPointeeType() << FoundVD;
3352 if (!Decls.count(FoundVD))
3355 const bool IsReference = FoundVD->getType()->isReferenceType();
3357 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3358 // Special checking for initializer lists.
3359 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3363 // Prevent double warnings on use of unbounded references.
3364 if (CheckReferenceOnly && !IsReference)
3368 unsigned diag = IsReference
3369 ? diag::warn_reference_field_is_uninit
3370 : diag::warn_field_is_uninit;
3371 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3373 S.Diag(Constructor->getLocation(),
3374 diag::note_uninit_in_this_constructor)
3375 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3379 void HandleValue(Expr *E, bool AddressOf) {
3380 E = E->IgnoreParens();
3382 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3383 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3384 AddressOf /*AddressOf*/);
3388 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3389 Visit(CO->getCond());
3390 HandleValue(CO->getTrueExpr(), AddressOf);
3391 HandleValue(CO->getFalseExpr(), AddressOf);
3395 if (BinaryConditionalOperator *BCO =
3396 dyn_cast<BinaryConditionalOperator>(E)) {
3397 Visit(BCO->getCond());
3398 HandleValue(BCO->getFalseExpr(), AddressOf);
3402 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3403 HandleValue(OVE->getSourceExpr(), AddressOf);
3407 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3408 switch (BO->getOpcode()) {
3413 HandleValue(BO->getLHS(), AddressOf);
3414 Visit(BO->getRHS());
3417 Visit(BO->getLHS());
3418 HandleValue(BO->getRHS(), AddressOf);
3426 void CheckInitListExpr(InitListExpr *ILE) {
3427 InitFieldIndex.push_back(0);
3428 for (auto Child : ILE->children()) {
3429 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3430 CheckInitListExpr(SubList);
3434 ++InitFieldIndex.back();
3436 InitFieldIndex.pop_back();
3439 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3440 FieldDecl *Field, const Type *BaseClass) {
3441 // Remove Decls that may have been initialized in the previous
3443 for (ValueDecl* VD : DeclsToRemove)
3445 DeclsToRemove.clear();
3447 Constructor = FieldConstructor;
3448 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3452 InitListFieldDecl = Field;
3453 InitFieldIndex.clear();
3454 CheckInitListExpr(ILE);
3463 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3466 void VisitMemberExpr(MemberExpr *ME) {
3467 // All uses of unbounded reference fields will warn.
3468 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3471 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3472 if (E->getCastKind() == CK_LValueToRValue) {
3473 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3477 Inherited::VisitImplicitCastExpr(E);
3480 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3481 if (E->getConstructor()->isCopyConstructor()) {
3482 Expr *ArgExpr = E->getArg(0);
3483 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3484 if (ILE->getNumInits() == 1)
3485 ArgExpr = ILE->getInit(0);
3486 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3487 if (ICE->getCastKind() == CK_NoOp)
3488 ArgExpr = ICE->getSubExpr();
3489 HandleValue(ArgExpr, false /*AddressOf*/);
3492 Inherited::VisitCXXConstructExpr(E);
3495 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3496 Expr *Callee = E->getCallee();
3497 if (isa<MemberExpr>(Callee)) {
3498 HandleValue(Callee, false /*AddressOf*/);
3499 for (auto Arg : E->arguments())
3504 Inherited::VisitCXXMemberCallExpr(E);
3507 void VisitCallExpr(CallExpr *E) {
3508 // Treat std::move as a use.
3509 if (E->isCallToStdMove()) {
3510 HandleValue(E->getArg(0), /*AddressOf=*/false);
3514 Inherited::VisitCallExpr(E);
3517 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3518 Expr *Callee = E->getCallee();
3520 if (isa<UnresolvedLookupExpr>(Callee))
3521 return Inherited::VisitCXXOperatorCallExpr(E);
3524 for (auto Arg : E->arguments())
3525 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3528 void VisitBinaryOperator(BinaryOperator *E) {
3529 // If a field assignment is detected, remove the field from the
3530 // uninitiailized field set.
3531 if (E->getOpcode() == BO_Assign)
3532 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3533 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3534 if (!FD->getType()->isReferenceType())
3535 DeclsToRemove.push_back(FD);
3537 if (E->isCompoundAssignmentOp()) {
3538 HandleValue(E->getLHS(), false /*AddressOf*/);
3543 Inherited::VisitBinaryOperator(E);
3546 void VisitUnaryOperator(UnaryOperator *E) {
3547 if (E->isIncrementDecrementOp()) {
3548 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3551 if (E->getOpcode() == UO_AddrOf) {
3552 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3553 HandleValue(ME->getBase(), true /*AddressOf*/);
3558 Inherited::VisitUnaryOperator(E);
3562 // Diagnose value-uses of fields to initialize themselves, e.g.
3564 // where foo is not also a parameter to the constructor.
3565 // Also diagnose across field uninitialized use such as
3567 // TODO: implement -Wuninitialized and fold this into that framework.
3568 static void DiagnoseUninitializedFields(
3569 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3571 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3572 Constructor->getLocation())) {
3576 if (Constructor->isInvalidDecl())
3579 const CXXRecordDecl *RD = Constructor->getParent();
3581 if (RD->getDescribedClassTemplate())
3584 // Holds fields that are uninitialized.
3585 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3587 // At the beginning, all fields are uninitialized.
3588 for (auto *I : RD->decls()) {
3589 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3590 UninitializedFields.insert(FD);
3591 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3592 UninitializedFields.insert(IFD->getAnonField());
3596 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3597 for (auto I : RD->bases())
3598 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3600 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3603 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3604 UninitializedFields,
3605 UninitializedBaseClasses);
3607 for (const auto *FieldInit : Constructor->inits()) {
3608 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3611 Expr *InitExpr = FieldInit->getInit();
3615 if (CXXDefaultInitExpr *Default =
3616 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3617 InitExpr = Default->getExpr();
3620 // In class initializers will point to the constructor.
3621 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3622 FieldInit->getAnyMember(),
3623 FieldInit->getBaseClass());
3625 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3626 FieldInit->getAnyMember(),
3627 FieldInit->getBaseClass());
3633 /// Enter a new C++ default initializer scope. After calling this, the
3634 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3635 /// parsing or instantiating the initializer failed.
3636 void Sema::ActOnStartCXXInClassMemberInitializer() {
3637 // Create a synthetic function scope to represent the call to the constructor
3638 // that notionally surrounds a use of this initializer.
3639 PushFunctionScope();
3642 /// This is invoked after parsing an in-class initializer for a
3643 /// non-static C++ class member, and after instantiating an in-class initializer
3644 /// in a class template. Such actions are deferred until the class is complete.
3645 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3646 SourceLocation InitLoc,
3648 // Pop the notional constructor scope we created earlier.
3649 PopFunctionScopeInfo(nullptr, D);
3651 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3652 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3653 "must set init style when field is created");
3656 D->setInvalidDecl();
3658 FD->removeInClassInitializer();
3662 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3663 FD->setInvalidDecl();
3664 FD->removeInClassInitializer();
3668 ExprResult Init = InitExpr;
3669 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3670 InitializedEntity Entity =
3671 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3672 InitializationKind Kind =
3673 FD->getInClassInitStyle() == ICIS_ListInit
3674 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3675 InitExpr->getBeginLoc(),
3676 InitExpr->getEndLoc())
3677 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3678 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3679 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3680 if (Init.isInvalid()) {
3681 FD->setInvalidDecl();
3686 // C++11 [class.base.init]p7:
3687 // The initialization of each base and member constitutes a
3689 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3690 if (Init.isInvalid()) {
3691 FD->setInvalidDecl();
3695 InitExpr = Init.get();
3697 FD->setInClassInitializer(InitExpr);
3700 /// Find the direct and/or virtual base specifiers that
3701 /// correspond to the given base type, for use in base initialization
3702 /// within a constructor.
3703 static bool FindBaseInitializer(Sema &SemaRef,
3704 CXXRecordDecl *ClassDecl,
3706 const CXXBaseSpecifier *&DirectBaseSpec,
3707 const CXXBaseSpecifier *&VirtualBaseSpec) {
3708 // First, check for a direct base class.
3709 DirectBaseSpec = nullptr;
3710 for (const auto &Base : ClassDecl->bases()) {
3711 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3712 // We found a direct base of this type. That's what we're
3714 DirectBaseSpec = &Base;
3719 // Check for a virtual base class.
3720 // FIXME: We might be able to short-circuit this if we know in advance that
3721 // there are no virtual bases.
3722 VirtualBaseSpec = nullptr;
3723 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3724 // We haven't found a base yet; search the class hierarchy for a
3725 // virtual base class.
3726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3727 /*DetectVirtual=*/false);
3728 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3729 SemaRef.Context.getTypeDeclType(ClassDecl),
3731 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3732 Path != Paths.end(); ++Path) {
3733 if (Path->back().Base->isVirtual()) {
3734 VirtualBaseSpec = Path->back().Base;
3741 return DirectBaseSpec || VirtualBaseSpec;
3744 /// Handle a C++ member initializer using braced-init-list syntax.
3746 Sema::ActOnMemInitializer(Decl *ConstructorD,
3749 IdentifierInfo *MemberOrBase,
3750 ParsedType TemplateTypeTy,
3752 SourceLocation IdLoc,
3754 SourceLocation EllipsisLoc) {
3755 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3756 DS, IdLoc, InitList,
3760 /// Handle a C++ member initializer using parentheses syntax.
3762 Sema::ActOnMemInitializer(Decl *ConstructorD,
3765 IdentifierInfo *MemberOrBase,
3766 ParsedType TemplateTypeTy,
3768 SourceLocation IdLoc,
3769 SourceLocation LParenLoc,
3770 ArrayRef<Expr *> Args,
3771 SourceLocation RParenLoc,
3772 SourceLocation EllipsisLoc) {
3773 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3774 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3775 DS, IdLoc, List, EllipsisLoc);
3780 // Callback to only accept typo corrections that can be a valid C++ member
3781 // intializer: either a non-static field member or a base class.
3782 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3784 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3785 : ClassDecl(ClassDecl) {}
3787 bool ValidateCandidate(const TypoCorrection &candidate) override {
3788 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3789 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3790 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3791 return isa<TypeDecl>(ND);
3797 CXXRecordDecl *ClassDecl;
3802 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3804 ParsedType TemplateTypeTy,
3805 IdentifierInfo *MemberOrBase) {
3806 if (SS.getScopeRep() || TemplateTypeTy)
3808 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3812 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3813 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3818 /// Handle a C++ member initializer.
3820 Sema::BuildMemInitializer(Decl *ConstructorD,
3823 IdentifierInfo *MemberOrBase,
3824 ParsedType TemplateTypeTy,
3826 SourceLocation IdLoc,
3828 SourceLocation EllipsisLoc) {
3829 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3830 if (!Res.isUsable())
3837 AdjustDeclIfTemplate(ConstructorD);
3839 CXXConstructorDecl *Constructor
3840 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3842 // The user wrote a constructor initializer on a function that is
3843 // not a C++ constructor. Ignore the error for now, because we may
3844 // have more member initializers coming; we'll diagnose it just
3845 // once in ActOnMemInitializers.
3849 CXXRecordDecl *ClassDecl = Constructor->getParent();
3851 // C++ [class.base.init]p2:
3852 // Names in a mem-initializer-id are looked up in the scope of the
3853 // constructor's class and, if not found in that scope, are looked
3854 // up in the scope containing the constructor's definition.
3855 // [Note: if the constructor's class contains a member with the
3856 // same name as a direct or virtual base class of the class, a
3857 // mem-initializer-id naming the member or base class and composed
3858 // of a single identifier refers to the class member. A
3859 // mem-initializer-id for the hidden base class may be specified
3860 // using a qualified name. ]
3862 // Look for a member, first.
3863 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3864 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3865 if (EllipsisLoc.isValid())
3866 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3868 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3870 return BuildMemberInitializer(Member, Init, IdLoc);
3872 // It didn't name a member, so see if it names a class.
3874 TypeSourceInfo *TInfo = nullptr;
3876 if (TemplateTypeTy) {
3877 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3878 } else if (DS.getTypeSpecType() == TST_decltype) {
3879 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3880 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3881 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3884 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3885 LookupParsedName(R, S, &SS);
3887 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3889 if (R.isAmbiguous()) return true;
3891 // We don't want access-control diagnostics here.
3892 R.suppressDiagnostics();
3894 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3895 bool NotUnknownSpecialization = false;
3896 DeclContext *DC = computeDeclContext(SS, false);
3897 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3898 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3900 if (!NotUnknownSpecialization) {
3901 // When the scope specifier can refer to a member of an unknown
3902 // specialization, we take it as a type name.
3903 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3904 SS.getWithLocInContext(Context),
3905 *MemberOrBase, IdLoc);
3906 if (BaseType.isNull())
3909 TInfo = Context.CreateTypeSourceInfo(BaseType);
3910 DependentNameTypeLoc TL =
3911 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3913 TL.setNameLoc(IdLoc);
3914 TL.setElaboratedKeywordLoc(SourceLocation());
3915 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3919 R.setLookupName(MemberOrBase);
3923 // If no results were found, try to correct typos.
3924 TypoCorrection Corr;
3925 if (R.empty() && BaseType.isNull() &&
3926 (Corr = CorrectTypo(
3927 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3928 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3929 CTK_ErrorRecovery, ClassDecl))) {
3930 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3931 // We have found a non-static data member with a similar
3932 // name to what was typed; complain and initialize that
3935 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3936 << MemberOrBase << true);
3937 return BuildMemberInitializer(Member, Init, IdLoc);
3938 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3939 const CXXBaseSpecifier *DirectBaseSpec;
3940 const CXXBaseSpecifier *VirtualBaseSpec;
3941 if (FindBaseInitializer(*this, ClassDecl,
3942 Context.getTypeDeclType(Type),
3943 DirectBaseSpec, VirtualBaseSpec)) {
3944 // We have found a direct or virtual base class with a
3945 // similar name to what was typed; complain and initialize
3948 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3949 << MemberOrBase << false,
3950 PDiag() /*Suppress note, we provide our own.*/);
3952 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3954 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3955 << BaseSpec->getType() << BaseSpec->getSourceRange();
3962 if (!TyD && BaseType.isNull()) {
3963 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3964 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3969 if (BaseType.isNull()) {
3970 BaseType = Context.getTypeDeclType(TyD);
3971 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3973 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3975 TInfo = Context.CreateTypeSourceInfo(BaseType);
3976 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3977 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3978 TL.setElaboratedKeywordLoc(SourceLocation());
3979 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3985 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3987 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3991 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3992 SourceLocation IdLoc) {
3993 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3994 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3995 assert((DirectMember || IndirectMember) &&
3996 "Member must be a FieldDecl or IndirectFieldDecl");
3998 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4001 if (Member->isInvalidDecl())
4005 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4006 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4007 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4008 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4010 // Template instantiation doesn't reconstruct ParenListExprs for us.
4014 SourceRange InitRange = Init->getSourceRange();
4016 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4017 // Can't check initialization for a member of dependent type or when
4018 // any of the arguments are type-dependent expressions.
4019 DiscardCleanupsInEvaluationContext();
4021 bool InitList = false;
4022 if (isa<InitListExpr>(Init)) {
4027 // Initialize the member.
4028 InitializedEntity MemberEntity =
4029 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4030 : InitializedEntity::InitializeMember(IndirectMember,
4032 InitializationKind Kind =
4033 InitList ? InitializationKind::CreateDirectList(
4034 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4035 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4036 InitRange.getEnd());
4038 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4039 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4041 if (MemberInit.isInvalid())
4044 // C++11 [class.base.init]p7:
4045 // The initialization of each base and member constitutes a
4047 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4048 if (MemberInit.isInvalid())
4051 Init = MemberInit.get();
4055 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4056 InitRange.getBegin(), Init,
4057 InitRange.getEnd());
4059 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4060 InitRange.getBegin(), Init,
4061 InitRange.getEnd());
4066 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4067 CXXRecordDecl *ClassDecl) {
4068 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4069 if (!LangOpts.CPlusPlus11)
4070 return Diag(NameLoc, diag::err_delegating_ctor)
4071 << TInfo->getTypeLoc().getLocalSourceRange();
4072 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4074 bool InitList = true;
4075 MultiExprArg Args = Init;
4076 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4078 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4081 SourceRange InitRange = Init->getSourceRange();
4082 // Initialize the object.
4083 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4084 QualType(ClassDecl->getTypeForDecl(), 0));
4085 InitializationKind Kind =
4086 InitList ? InitializationKind::CreateDirectList(
4087 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4088 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4089 InitRange.getEnd());
4090 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4091 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4093 if (DelegationInit.isInvalid())
4096 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4097 "Delegating constructor with no target?");
4099 // C++11 [class.base.init]p7:
4100 // The initialization of each base and member constitutes a
4102 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4103 InitRange.getBegin());
4104 if (DelegationInit.isInvalid())
4107 // If we are in a dependent context, template instantiation will
4108 // perform this type-checking again. Just save the arguments that we
4109 // received in a ParenListExpr.
4110 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4111 // of the information that we have about the base
4112 // initializer. However, deconstructing the ASTs is a dicey process,
4113 // and this approach is far more likely to get the corner cases right.
4114 if (CurContext->isDependentContext())
4115 DelegationInit = Init;
4117 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4118 DelegationInit.getAs<Expr>(),
4119 InitRange.getEnd());
4123 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4124 Expr *Init, CXXRecordDecl *ClassDecl,
4125 SourceLocation EllipsisLoc) {
4126 SourceLocation BaseLoc
4127 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4129 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4130 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4131 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4133 // C++ [class.base.init]p2:
4134 // [...] Unless the mem-initializer-id names a nonstatic data
4135 // member of the constructor's class or a direct or virtual base
4136 // of that class, the mem-initializer is ill-formed. A
4137 // mem-initializer-list can initialize a base class using any
4138 // name that denotes that base class type.
4139 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4141 SourceRange InitRange = Init->getSourceRange();
4142 if (EllipsisLoc.isValid()) {
4143 // This is a pack expansion.
4144 if (!BaseType->containsUnexpandedParameterPack()) {
4145 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4146 << SourceRange(BaseLoc, InitRange.getEnd());
4148 EllipsisLoc = SourceLocation();
4151 // Check for any unexpanded parameter packs.
4152 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4155 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4159 // Check for direct and virtual base classes.
4160 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4161 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4163 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4165 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4167 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4170 // C++ [base.class.init]p2:
4171 // Unless the mem-initializer-id names a nonstatic data member of the
4172 // constructor's class or a direct or virtual base of that class, the
4173 // mem-initializer is ill-formed.
4174 if (!DirectBaseSpec && !VirtualBaseSpec) {
4175 // If the class has any dependent bases, then it's possible that
4176 // one of those types will resolve to the same type as
4177 // BaseType. Therefore, just treat this as a dependent base
4178 // class initialization. FIXME: Should we try to check the
4179 // initialization anyway? It seems odd.
4180 if (ClassDecl->hasAnyDependentBases())
4183 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4184 << BaseType << Context.getTypeDeclType(ClassDecl)
4185 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4190 DiscardCleanupsInEvaluationContext();
4192 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4193 /*IsVirtual=*/false,
4194 InitRange.getBegin(), Init,
4195 InitRange.getEnd(), EllipsisLoc);
4198 // C++ [base.class.init]p2:
4199 // If a mem-initializer-id is ambiguous because it designates both
4200 // a direct non-virtual base class and an inherited virtual base
4201 // class, the mem-initializer is ill-formed.
4202 if (DirectBaseSpec && VirtualBaseSpec)
4203 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4204 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4206 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4208 BaseSpec = VirtualBaseSpec;
4210 // Initialize the base.
4211 bool InitList = true;
4212 MultiExprArg Args = Init;
4213 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4215 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4218 InitializedEntity BaseEntity =
4219 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4220 InitializationKind Kind =
4221 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4222 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4223 InitRange.getEnd());
4224 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4225 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4226 if (BaseInit.isInvalid())
4229 // C++11 [class.base.init]p7:
4230 // The initialization of each base and member constitutes a
4232 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4233 if (BaseInit.isInvalid())
4236 // If we are in a dependent context, template instantiation will
4237 // perform this type-checking again. Just save the arguments that we
4238 // received in a ParenListExpr.
4239 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4240 // of the information that we have about the base
4241 // initializer. However, deconstructing the ASTs is a dicey process,
4242 // and this approach is far more likely to get the corner cases right.
4243 if (CurContext->isDependentContext())
4246 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4247 BaseSpec->isVirtual(),
4248 InitRange.getBegin(),
4249 BaseInit.getAs<Expr>(),
4250 InitRange.getEnd(), EllipsisLoc);
4253 // Create a static_cast\<T&&>(expr).
4254 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4255 if (T.isNull()) T = E->getType();
4256 QualType TargetType = SemaRef.BuildReferenceType(
4257 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4258 SourceLocation ExprLoc = E->getBeginLoc();
4259 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4260 TargetType, ExprLoc);
4262 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4263 SourceRange(ExprLoc, ExprLoc),
4264 E->getSourceRange()).get();
4267 /// ImplicitInitializerKind - How an implicit base or member initializer should
4268 /// initialize its base or member.
4269 enum ImplicitInitializerKind {
4277 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4278 ImplicitInitializerKind ImplicitInitKind,
4279 CXXBaseSpecifier *BaseSpec,
4280 bool IsInheritedVirtualBase,
4281 CXXCtorInitializer *&CXXBaseInit) {
4282 InitializedEntity InitEntity
4283 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4284 IsInheritedVirtualBase);
4286 ExprResult BaseInit;
4288 switch (ImplicitInitKind) {
4291 InitializationKind InitKind
4292 = InitializationKind::CreateDefault(Constructor->getLocation());
4293 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4294 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4300 bool Moving = ImplicitInitKind == IIK_Move;
4301 ParmVarDecl *Param = Constructor->getParamDecl(0);
4302 QualType ParamType = Param->getType().getNonReferenceType();
4305 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4306 SourceLocation(), Param, false,
4307 Constructor->getLocation(), ParamType,
4308 VK_LValue, nullptr);
4310 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4312 // Cast to the base class to avoid ambiguities.
4314 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4315 ParamType.getQualifiers());
4318 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4321 CXXCastPath BasePath;
4322 BasePath.push_back(BaseSpec);
4323 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4324 CK_UncheckedDerivedToBase,
4325 Moving ? VK_XValue : VK_LValue,
4328 InitializationKind InitKind
4329 = InitializationKind::CreateDirect(Constructor->getLocation(),
4330 SourceLocation(), SourceLocation());
4331 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4332 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4337 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4338 if (BaseInit.isInvalid())
4342 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4343 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4345 BaseSpec->isVirtual(),
4347 BaseInit.getAs<Expr>(),
4354 static bool RefersToRValueRef(Expr *MemRef) {
4355 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4356 return Referenced->getType()->isRValueReferenceType();
4360 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4361 ImplicitInitializerKind ImplicitInitKind,
4362 FieldDecl *Field, IndirectFieldDecl *Indirect,
4363 CXXCtorInitializer *&CXXMemberInit) {
4364 if (Field->isInvalidDecl())
4367 SourceLocation Loc = Constructor->getLocation();
4369 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4370 bool Moving = ImplicitInitKind == IIK_Move;
4371 ParmVarDecl *Param = Constructor->getParamDecl(0);
4372 QualType ParamType = Param->getType().getNonReferenceType();
4374 // Suppress copying zero-width bitfields.
4375 if (Field->isZeroLengthBitField(SemaRef.Context))
4378 Expr *MemberExprBase =
4379 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4380 SourceLocation(), Param, false,
4381 Loc, ParamType, VK_LValue, nullptr);
4383 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4386 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4389 // Build a reference to this field within the parameter.
4391 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4392 Sema::LookupMemberName);
4393 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4394 : cast<ValueDecl>(Field), AS_public);
4395 MemberLookup.resolveKind();
4397 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4401 /*TemplateKWLoc=*/SourceLocation(),
4402 /*FirstQualifierInScope=*/nullptr,
4404 /*TemplateArgs=*/nullptr,
4406 if (CtorArg.isInvalid())
4409 // C++11 [class.copy]p15:
4410 // - if a member m has rvalue reference type T&&, it is direct-initialized
4411 // with static_cast<T&&>(x.m);
4412 if (RefersToRValueRef(CtorArg.get())) {
4413 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4416 InitializedEntity Entity =
4417 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4419 : InitializedEntity::InitializeMember(Field, nullptr,
4422 // Direct-initialize to use the copy constructor.
4423 InitializationKind InitKind =
4424 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4426 Expr *CtorArgE = CtorArg.getAs<Expr>();
4427 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4428 ExprResult MemberInit =
4429 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4430 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4431 if (MemberInit.isInvalid())
4435 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4436 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4438 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4439 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4443 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4444 "Unhandled implicit init kind!");
4446 QualType FieldBaseElementType =
4447 SemaRef.Context.getBaseElementType(Field->getType());
4449 if (FieldBaseElementType->isRecordType()) {
4450 InitializedEntity InitEntity =
4451 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4453 : InitializedEntity::InitializeMember(Field, nullptr,
4455 InitializationKind InitKind =
4456 InitializationKind::CreateDefault(Loc);
4458 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4459 ExprResult MemberInit =
4460 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4462 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4463 if (MemberInit.isInvalid())
4467 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4473 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4480 if (!Field->getParent()->isUnion()) {
4481 if (FieldBaseElementType->isReferenceType()) {
4482 SemaRef.Diag(Constructor->getLocation(),
4483 diag::err_uninitialized_member_in_ctor)
4484 << (int)Constructor->isImplicit()
4485 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4486 << 0 << Field->getDeclName();
4487 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4491 if (FieldBaseElementType.isConstQualified()) {
4492 SemaRef.Diag(Constructor->getLocation(),
4493 diag::err_uninitialized_member_in_ctor)
4494 << (int)Constructor->isImplicit()
4495 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4496 << 1 << Field->getDeclName();
4497 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4502 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4504 // Default-initialize Objective-C pointers to NULL.
4506 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4508 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4513 // Nothing to initialize.
4514 CXXMemberInit = nullptr;
4519 struct BaseAndFieldInfo {
4521 CXXConstructorDecl *Ctor;
4522 bool AnyErrorsInInits;
4523 ImplicitInitializerKind IIK;
4524 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4525 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4526 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4528 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4529 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4530 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4531 if (Ctor->getInheritedConstructor())
4533 else if (Generated && Ctor->isCopyConstructor())
4535 else if (Generated && Ctor->isMoveConstructor())
4541 bool isImplicitCopyOrMove() const {
4552 llvm_unreachable("Invalid ImplicitInitializerKind!");
4555 bool addFieldInitializer(CXXCtorInitializer *Init) {
4556 AllToInit.push_back(Init);
4558 // Check whether this initializer makes the field "used".
4559 if (Init->getInit()->HasSideEffects(S.Context))
4560 S.UnusedPrivateFields.remove(Init->getAnyMember());
4565 bool isInactiveUnionMember(FieldDecl *Field) {
4566 RecordDecl *Record = Field->getParent();
4567 if (!Record->isUnion())
4570 if (FieldDecl *Active =
4571 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4572 return Active != Field->getCanonicalDecl();
4574 // In an implicit copy or move constructor, ignore any in-class initializer.
4575 if (isImplicitCopyOrMove())
4578 // If there's no explicit initialization, the field is active only if it
4579 // has an in-class initializer...
4580 if (Field->hasInClassInitializer())
4582 // ... or it's an anonymous struct or union whose class has an in-class
4584 if (!Field->isAnonymousStructOrUnion())
4586 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4587 return !FieldRD->hasInClassInitializer();
4590 /// Determine whether the given field is, or is within, a union member
4591 /// that is inactive (because there was an initializer given for a different
4592 /// member of the union, or because the union was not initialized at all).
4593 bool isWithinInactiveUnionMember(FieldDecl *Field,
4594 IndirectFieldDecl *Indirect) {
4596 return isInactiveUnionMember(Field);
4598 for (auto *C : Indirect->chain()) {
4599 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4600 if (Field && isInactiveUnionMember(Field))
4608 /// Determine whether the given type is an incomplete or zero-lenfgth
4610 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4611 if (T->isIncompleteArrayType())
4614 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4615 if (!ArrayT->getSize())
4618 T = ArrayT->getElementType();
4624 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4626 IndirectFieldDecl *Indirect = nullptr) {
4627 if (Field->isInvalidDecl())
4630 // Overwhelmingly common case: we have a direct initializer for this field.
4631 if (CXXCtorInitializer *Init =
4632 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4633 return Info.addFieldInitializer(Init);
4635 // C++11 [class.base.init]p8:
4636 // if the entity is a non-static data member that has a
4637 // brace-or-equal-initializer and either
4638 // -- the constructor's class is a union and no other variant member of that
4639 // union is designated by a mem-initializer-id or
4640 // -- the constructor's class is not a union, and, if the entity is a member
4641 // of an anonymous union, no other member of that union is designated by
4642 // a mem-initializer-id,
4643 // the entity is initialized as specified in [dcl.init].
4645 // We also apply the same rules to handle anonymous structs within anonymous
4647 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4650 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4652 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4653 if (DIE.isInvalid())
4656 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4657 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4659 CXXCtorInitializer *Init;
4661 Init = new (SemaRef.Context)
4662 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4663 SourceLocation(), DIE.get(), SourceLocation());
4665 Init = new (SemaRef.Context)
4666 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4667 SourceLocation(), DIE.get(), SourceLocation());
4668 return Info.addFieldInitializer(Init);
4671 // Don't initialize incomplete or zero-length arrays.
4672 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4675 // Don't try to build an implicit initializer if there were semantic
4676 // errors in any of the initializers (and therefore we might be
4677 // missing some that the user actually wrote).
4678 if (Info.AnyErrorsInInits)
4681 CXXCtorInitializer *Init = nullptr;
4682 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4689 return Info.addFieldInitializer(Init);
4693 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4694 CXXCtorInitializer *Initializer) {
4695 assert(Initializer->isDelegatingInitializer());
4696 Constructor->setNumCtorInitializers(1);
4697 CXXCtorInitializer **initializer =
4698 new (Context) CXXCtorInitializer*[1];
4699 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4700 Constructor->setCtorInitializers(initializer);
4702 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4703 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4704 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4707 DelegatingCtorDecls.push_back(Constructor);
4709 DiagnoseUninitializedFields(*this, Constructor);
4714 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4715 ArrayRef<CXXCtorInitializer *> Initializers) {
4716 if (Constructor->isDependentContext()) {
4717 // Just store the initializers as written, they will be checked during
4719 if (!Initializers.empty()) {
4720 Constructor->setNumCtorInitializers(Initializers.size());
4721 CXXCtorInitializer **baseOrMemberInitializers =
4722 new (Context) CXXCtorInitializer*[Initializers.size()];
4723 memcpy(baseOrMemberInitializers, Initializers.data(),
4724 Initializers.size() * sizeof(CXXCtorInitializer*));
4725 Constructor->setCtorInitializers(baseOrMemberInitializers);
4728 // Let template instantiation know whether we had errors.
4730 Constructor->setInvalidDecl();
4735 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4737 // We need to build the initializer AST according to order of construction
4738 // and not what user specified in the Initializers list.
4739 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4743 bool HadError = false;
4745 for (unsigned i = 0; i < Initializers.size(); i++) {
4746 CXXCtorInitializer *Member = Initializers[i];
4748 if (Member->isBaseInitializer())
4749 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4751 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4753 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4754 for (auto *C : F->chain()) {
4755 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4756 if (FD && FD->getParent()->isUnion())
4757 Info.ActiveUnionMember.insert(std::make_pair(
4758 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4760 } else if (FieldDecl *FD = Member->getMember()) {
4761 if (FD->getParent()->isUnion())
4762 Info.ActiveUnionMember.insert(std::make_pair(
4763 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4768 // Keep track of the direct virtual bases.
4769 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4770 for (auto &I : ClassDecl->bases()) {
4772 DirectVBases.insert(&I);
4775 // Push virtual bases before others.
4776 for (auto &VBase : ClassDecl->vbases()) {
4777 if (CXXCtorInitializer *Value
4778 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4779 // [class.base.init]p7, per DR257:
4780 // A mem-initializer where the mem-initializer-id names a virtual base
4781 // class is ignored during execution of a constructor of any class that
4782 // is not the most derived class.
4783 if (ClassDecl->isAbstract()) {
4784 // FIXME: Provide a fixit to remove the base specifier. This requires
4785 // tracking the location of the associated comma for a base specifier.
4786 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4787 << VBase.getType() << ClassDecl;
4788 DiagnoseAbstractType(ClassDecl);
4791 Info.AllToInit.push_back(Value);
4792 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4793 // [class.base.init]p8, per DR257:
4794 // If a given [...] base class is not named by a mem-initializer-id
4795 // [...] and the entity is not a virtual base class of an abstract
4796 // class, then [...] the entity is default-initialized.
4797 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4798 CXXCtorInitializer *CXXBaseInit;
4799 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4800 &VBase, IsInheritedVirtualBase,
4806 Info.AllToInit.push_back(CXXBaseInit);
4810 // Non-virtual bases.
4811 for (auto &Base : ClassDecl->bases()) {
4812 // Virtuals are in the virtual base list and already constructed.
4813 if (Base.isVirtual())
4816 if (CXXCtorInitializer *Value
4817 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4818 Info.AllToInit.push_back(Value);
4819 } else if (!AnyErrors) {
4820 CXXCtorInitializer *CXXBaseInit;
4821 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4822 &Base, /*IsInheritedVirtualBase=*/false,
4828 Info.AllToInit.push_back(CXXBaseInit);
4833 for (auto *Mem : ClassDecl->decls()) {
4834 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4835 // C++ [class.bit]p2:
4836 // A declaration for a bit-field that omits the identifier declares an
4837 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4839 if (F->isUnnamedBitfield())
4842 // If we're not generating the implicit copy/move constructor, then we'll
4843 // handle anonymous struct/union fields based on their individual
4845 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4848 if (CollectFieldInitializer(*this, Info, F))
4853 // Beyond this point, we only consider default initialization.
4854 if (Info.isImplicitCopyOrMove())
4857 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4858 if (F->getType()->isIncompleteArrayType()) {
4859 assert(ClassDecl->hasFlexibleArrayMember() &&
4860 "Incomplete array type is not valid");
4864 // Initialize each field of an anonymous struct individually.
4865 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4872 unsigned NumInitializers = Info.AllToInit.size();
4873 if (NumInitializers > 0) {
4874 Constructor->setNumCtorInitializers(NumInitializers);
4875 CXXCtorInitializer **baseOrMemberInitializers =
4876 new (Context) CXXCtorInitializer*[NumInitializers];
4877 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4878 NumInitializers * sizeof(CXXCtorInitializer*));
4879 Constructor->setCtorInitializers(baseOrMemberInitializers);
4881 // Constructors implicitly reference the base and member
4883 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4884 Constructor->getParent());
4890 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4891 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4892 const RecordDecl *RD = RT->getDecl();
4893 if (RD->isAnonymousStructOrUnion()) {
4894 for (auto *Field : RD->fields())
4895 PopulateKeysForFields(Field, IdealInits);
4899 IdealInits.push_back(Field->getCanonicalDecl());
4902 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4903 return Context.getCanonicalType(BaseType).getTypePtr();
4906 static const void *GetKeyForMember(ASTContext &Context,
4907 CXXCtorInitializer *Member) {
4908 if (!Member->isAnyMemberInitializer())
4909 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4911 return Member->getAnyMember()->getCanonicalDecl();
4914 static void DiagnoseBaseOrMemInitializerOrder(
4915 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4916 ArrayRef<CXXCtorInitializer *> Inits) {
4917 if (Constructor->getDeclContext()->isDependentContext())
4920 // Don't check initializers order unless the warning is enabled at the
4921 // location of at least one initializer.
4922 bool ShouldCheckOrder = false;
4923 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4924 CXXCtorInitializer *Init = Inits[InitIndex];
4925 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4926 Init->getSourceLocation())) {
4927 ShouldCheckOrder = true;
4931 if (!ShouldCheckOrder)
4934 // Build the list of bases and members in the order that they'll
4935 // actually be initialized. The explicit initializers should be in
4936 // this same order but may be missing things.
4937 SmallVector<const void*, 32> IdealInitKeys;
4939 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4941 // 1. Virtual bases.
4942 for (const auto &VBase : ClassDecl->vbases())
4943 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4945 // 2. Non-virtual bases.
4946 for (const auto &Base : ClassDecl->bases()) {
4947 if (Base.isVirtual())
4949 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4952 // 3. Direct fields.
4953 for (auto *Field : ClassDecl->fields()) {
4954 if (Field->isUnnamedBitfield())
4957 PopulateKeysForFields(Field, IdealInitKeys);
4960 unsigned NumIdealInits = IdealInitKeys.size();
4961 unsigned IdealIndex = 0;
4963 CXXCtorInitializer *PrevInit = nullptr;
4964 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4965 CXXCtorInitializer *Init = Inits[InitIndex];
4966 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4968 // Scan forward to try to find this initializer in the idealized
4969 // initializers list.
4970 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4971 if (InitKey == IdealInitKeys[IdealIndex])
4974 // If we didn't find this initializer, it must be because we
4975 // scanned past it on a previous iteration. That can only
4976 // happen if we're out of order; emit a warning.
4977 if (IdealIndex == NumIdealInits && PrevInit) {
4978 Sema::SemaDiagnosticBuilder D =
4979 SemaRef.Diag(PrevInit->getSourceLocation(),
4980 diag::warn_initializer_out_of_order);
4982 if (PrevInit->isAnyMemberInitializer())
4983 D << 0 << PrevInit->getAnyMember()->getDeclName();
4985 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4987 if (Init->isAnyMemberInitializer())
4988 D << 0 << Init->getAnyMember()->getDeclName();
4990 D << 1 << Init->getTypeSourceInfo()->getType();
4992 // Move back to the initializer's location in the ideal list.
4993 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4994 if (InitKey == IdealInitKeys[IdealIndex])
4997 assert(IdealIndex < NumIdealInits &&
4998 "initializer not found in initializer list");
5006 bool CheckRedundantInit(Sema &S,
5007 CXXCtorInitializer *Init,
5008 CXXCtorInitializer *&PrevInit) {
5014 if (FieldDecl *Field = Init->getAnyMember())
5015 S.Diag(Init->getSourceLocation(),
5016 diag::err_multiple_mem_initialization)
5017 << Field->getDeclName()
5018 << Init->getSourceRange();
5020 const Type *BaseClass = Init->getBaseClass();
5021 assert(BaseClass && "neither field nor base");
5022 S.Diag(Init->getSourceLocation(),
5023 diag::err_multiple_base_initialization)
5024 << QualType(BaseClass, 0)
5025 << Init->getSourceRange();
5027 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5028 << 0 << PrevInit->getSourceRange();
5033 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5034 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5036 bool CheckRedundantUnionInit(Sema &S,
5037 CXXCtorInitializer *Init,
5038 RedundantUnionMap &Unions) {
5039 FieldDecl *Field = Init->getAnyMember();
5040 RecordDecl *Parent = Field->getParent();
5041 NamedDecl *Child = Field;
5043 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5044 if (Parent->isUnion()) {
5045 UnionEntry &En = Unions[Parent];
5046 if (En.first && En.first != Child) {
5047 S.Diag(Init->getSourceLocation(),
5048 diag::err_multiple_mem_union_initialization)
5049 << Field->getDeclName()
5050 << Init->getSourceRange();
5051 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5052 << 0 << En.second->getSourceRange();
5059 if (!Parent->isAnonymousStructOrUnion())
5064 Parent = cast<RecordDecl>(Parent->getDeclContext());
5071 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5072 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5073 SourceLocation ColonLoc,
5074 ArrayRef<CXXCtorInitializer*> MemInits,
5076 if (!ConstructorDecl)
5079 AdjustDeclIfTemplate(ConstructorDecl);
5081 CXXConstructorDecl *Constructor
5082 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5085 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5089 // Mapping for the duplicate initializers check.
5090 // For member initializers, this is keyed with a FieldDecl*.
5091 // For base initializers, this is keyed with a Type*.
5092 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5094 // Mapping for the inconsistent anonymous-union initializers check.
5095 RedundantUnionMap MemberUnions;
5097 bool HadError = false;
5098 for (unsigned i = 0; i < MemInits.size(); i++) {
5099 CXXCtorInitializer *Init = MemInits[i];
5101 // Set the source order index.
5102 Init->setSourceOrder(i);
5104 if (Init->isAnyMemberInitializer()) {
5105 const void *Key = GetKeyForMember(Context, Init);
5106 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5107 CheckRedundantUnionInit(*this, Init, MemberUnions))
5109 } else if (Init->isBaseInitializer()) {
5110 const void *Key = GetKeyForMember(Context, Init);
5111 if (CheckRedundantInit(*this, Init, Members[Key]))
5114 assert(Init->isDelegatingInitializer());
5115 // This must be the only initializer
5116 if (MemInits.size() != 1) {
5117 Diag(Init->getSourceLocation(),
5118 diag::err_delegating_initializer_alone)
5119 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5120 // We will treat this as being the only initializer.
5122 SetDelegatingInitializer(Constructor, MemInits[i]);
5123 // Return immediately as the initializer is set.
5131 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5133 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5135 DiagnoseUninitializedFields(*this, Constructor);
5139 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5140 CXXRecordDecl *ClassDecl) {
5141 // Ignore dependent contexts. Also ignore unions, since their members never
5142 // have destructors implicitly called.
5143 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5146 // FIXME: all the access-control diagnostics are positioned on the
5147 // field/base declaration. That's probably good; that said, the
5148 // user might reasonably want to know why the destructor is being
5149 // emitted, and we currently don't say.
5151 // Non-static data members.
5152 for (auto *Field : ClassDecl->fields()) {
5153 if (Field->isInvalidDecl())
5156 // Don't destroy incomplete or zero-length arrays.
5157 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5160 QualType FieldType = Context.getBaseElementType(Field->getType());
5162 const RecordType* RT = FieldType->getAs<RecordType>();
5166 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5167 if (FieldClassDecl->isInvalidDecl())
5169 if (FieldClassDecl->hasIrrelevantDestructor())
5171 // The destructor for an implicit anonymous union member is never invoked.
5172 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5175 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5176 assert(Dtor && "No dtor found for FieldClassDecl!");
5177 CheckDestructorAccess(Field->getLocation(), Dtor,
5178 PDiag(diag::err_access_dtor_field)
5179 << Field->getDeclName()
5182 MarkFunctionReferenced(Location, Dtor);
5183 DiagnoseUseOfDecl(Dtor, Location);
5186 // We only potentially invoke the destructors of potentially constructed
5188 bool VisitVirtualBases = !ClassDecl->isAbstract();
5190 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5193 for (const auto &Base : ClassDecl->bases()) {
5194 // Bases are always records in a well-formed non-dependent class.
5195 const RecordType *RT = Base.getType()->getAs<RecordType>();
5197 // Remember direct virtual bases.
5198 if (Base.isVirtual()) {
5199 if (!VisitVirtualBases)
5201 DirectVirtualBases.insert(RT);
5204 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5205 // If our base class is invalid, we probably can't get its dtor anyway.
5206 if (BaseClassDecl->isInvalidDecl())
5208 if (BaseClassDecl->hasIrrelevantDestructor())
5211 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5212 assert(Dtor && "No dtor found for BaseClassDecl!");
5214 // FIXME: caret should be on the start of the class name
5215 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5216 PDiag(diag::err_access_dtor_base)
5217 << Base.getType() << Base.getSourceRange(),
5218 Context.getTypeDeclType(ClassDecl));
5220 MarkFunctionReferenced(Location, Dtor);
5221 DiagnoseUseOfDecl(Dtor, Location);
5224 if (!VisitVirtualBases)
5228 for (const auto &VBase : ClassDecl->vbases()) {
5229 // Bases are always records in a well-formed non-dependent class.
5230 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5232 // Ignore direct virtual bases.
5233 if (DirectVirtualBases.count(RT))
5236 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5237 // If our base class is invalid, we probably can't get its dtor anyway.
5238 if (BaseClassDecl->isInvalidDecl())
5240 if (BaseClassDecl->hasIrrelevantDestructor())
5243 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5244 assert(Dtor && "No dtor found for BaseClassDecl!");
5245 if (CheckDestructorAccess(
5246 ClassDecl->getLocation(), Dtor,
5247 PDiag(diag::err_access_dtor_vbase)
5248 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5249 Context.getTypeDeclType(ClassDecl)) ==
5251 CheckDerivedToBaseConversion(
5252 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5253 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5254 SourceRange(), DeclarationName(), nullptr);
5257 MarkFunctionReferenced(Location, Dtor);
5258 DiagnoseUseOfDecl(Dtor, Location);
5262 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5266 if (CXXConstructorDecl *Constructor
5267 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5268 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5269 DiagnoseUninitializedFields(*this, Constructor);
5273 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5274 if (!getLangOpts().CPlusPlus)
5277 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5281 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5282 // class template specialization here, but doing so breaks a lot of code.
5284 // We can't answer whether something is abstract until it has a
5285 // definition. If it's currently being defined, we'll walk back
5286 // over all the declarations when we have a full definition.
5287 const CXXRecordDecl *Def = RD->getDefinition();
5288 if (!Def || Def->isBeingDefined())
5291 return RD->isAbstract();
5294 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5295 TypeDiagnoser &Diagnoser) {
5296 if (!isAbstractType(Loc, T))
5299 T = Context.getBaseElementType(T);
5300 Diagnoser.diagnose(*this, Loc, T);
5301 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5305 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5306 // Check if we've already emitted the list of pure virtual functions
5308 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5311 // If the diagnostic is suppressed, don't emit the notes. We're only
5312 // going to emit them once, so try to attach them to a diagnostic we're
5313 // actually going to show.
5314 if (Diags.isLastDiagnosticIgnored())
5317 CXXFinalOverriderMap FinalOverriders;
5318 RD->getFinalOverriders(FinalOverriders);
5320 // Keep a set of seen pure methods so we won't diagnose the same method
5322 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5324 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5325 MEnd = FinalOverriders.end();
5328 for (OverridingMethods::iterator SO = M->second.begin(),
5329 SOEnd = M->second.end();
5330 SO != SOEnd; ++SO) {
5331 // C++ [class.abstract]p4:
5332 // A class is abstract if it contains or inherits at least one
5333 // pure virtual function for which the final overrider is pure
5337 if (SO->second.size() != 1)
5340 if (!SO->second.front().Method->isPure())
5343 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5346 Diag(SO->second.front().Method->getLocation(),
5347 diag::note_pure_virtual_function)
5348 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5352 if (!PureVirtualClassDiagSet)
5353 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5354 PureVirtualClassDiagSet->insert(RD);
5358 struct AbstractUsageInfo {
5360 CXXRecordDecl *Record;
5361 CanQualType AbstractType;
5364 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5365 : S(S), Record(Record),
5366 AbstractType(S.Context.getCanonicalType(
5367 S.Context.getTypeDeclType(Record))),
5370 void DiagnoseAbstractType() {
5371 if (Invalid) return;
5372 S.DiagnoseAbstractType(Record);
5376 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5379 struct CheckAbstractUsage {
5380 AbstractUsageInfo &Info;
5381 const NamedDecl *Ctx;
5383 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5384 : Info(Info), Ctx(Ctx) {}
5386 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5387 switch (TL.getTypeLocClass()) {
5388 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5389 #define TYPELOC(CLASS, PARENT) \
5390 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5391 #include "clang/AST/TypeLocNodes.def"
5395 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5396 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5397 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5398 if (!TL.getParam(I))
5401 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5402 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5406 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5407 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5410 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5411 // Visit the type parameters from a permissive context.
5412 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5413 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5414 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5415 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5416 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5417 // TODO: other template argument types?
5421 // Visit pointee types from a permissive context.
5422 #define CheckPolymorphic(Type) \
5423 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5424 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5426 CheckPolymorphic(PointerTypeLoc)
5427 CheckPolymorphic(ReferenceTypeLoc)
5428 CheckPolymorphic(MemberPointerTypeLoc)
5429 CheckPolymorphic(BlockPointerTypeLoc)
5430 CheckPolymorphic(AtomicTypeLoc)
5432 /// Handle all the types we haven't given a more specific
5433 /// implementation for above.
5434 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5435 // Every other kind of type that we haven't called out already
5436 // that has an inner type is either (1) sugar or (2) contains that
5437 // inner type in some way as a subobject.
5438 if (TypeLoc Next = TL.getNextTypeLoc())
5439 return Visit(Next, Sel);
5441 // If there's no inner type and we're in a permissive context,
5443 if (Sel == Sema::AbstractNone) return;
5445 // Check whether the type matches the abstract type.
5446 QualType T = TL.getType();
5447 if (T->isArrayType()) {
5448 Sel = Sema::AbstractArrayType;
5449 T = Info.S.Context.getBaseElementType(T);
5451 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5452 if (CT != Info.AbstractType) return;
5454 // It matched; do some magic.
5455 if (Sel == Sema::AbstractArrayType) {
5456 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5457 << T << TL.getSourceRange();
5459 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5460 << Sel << T << TL.getSourceRange();
5462 Info.DiagnoseAbstractType();
5466 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5467 Sema::AbstractDiagSelID Sel) {
5468 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5473 /// Check for invalid uses of an abstract type in a method declaration.
5474 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5475 CXXMethodDecl *MD) {
5476 // No need to do the check on definitions, which require that
5477 // the return/param types be complete.
5478 if (MD->doesThisDeclarationHaveABody())
5481 // For safety's sake, just ignore it if we don't have type source
5482 // information. This should never happen for non-implicit methods,
5484 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5485 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5488 /// Check for invalid uses of an abstract type within a class definition.
5489 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5490 CXXRecordDecl *RD) {
5491 for (auto *D : RD->decls()) {
5492 if (D->isImplicit()) continue;
5494 // Methods and method templates.
5495 if (isa<CXXMethodDecl>(D)) {
5496 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5497 } else if (isa<FunctionTemplateDecl>(D)) {
5498 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5499 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5501 // Fields and static variables.
5502 } else if (isa<FieldDecl>(D)) {
5503 FieldDecl *FD = cast<FieldDecl>(D);
5504 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5505 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5506 } else if (isa<VarDecl>(D)) {
5507 VarDecl *VD = cast<VarDecl>(D);
5508 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5509 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5511 // Nested classes and class templates.
5512 } else if (isa<CXXRecordDecl>(D)) {
5513 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5514 } else if (isa<ClassTemplateDecl>(D)) {
5515 CheckAbstractClassUsage(Info,
5516 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5521 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5522 Attr *ClassAttr = getDLLAttr(Class);
5526 assert(ClassAttr->getKind() == attr::DLLExport);
5528 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5530 if (TSK == TSK_ExplicitInstantiationDeclaration)
5531 // Don't go any further if this is just an explicit instantiation
5535 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5536 S.MarkVTableUsed(Class->getLocation(), Class, true);
5538 for (Decl *Member : Class->decls()) {
5539 // Defined static variables that are members of an exported base
5540 // class must be marked export too.
5541 auto *VD = dyn_cast<VarDecl>(Member);
5542 if (VD && Member->getAttr<DLLExportAttr>() &&
5543 VD->getStorageClass() == SC_Static &&
5544 TSK == TSK_ImplicitInstantiation)
5545 S.MarkVariableReferenced(VD->getLocation(), VD);
5547 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5551 if (Member->getAttr<DLLExportAttr>()) {
5552 if (MD->isUserProvided()) {
5553 // Instantiate non-default class member functions ...
5555 // .. except for certain kinds of template specializations.
5556 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5559 S.MarkFunctionReferenced(Class->getLocation(), MD);
5561 // The function will be passed to the consumer when its definition is
5563 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5564 MD->isCopyAssignmentOperator() ||
5565 MD->isMoveAssignmentOperator()) {
5566 // Synthesize and instantiate non-trivial implicit methods, explicitly
5567 // defaulted methods, and the copy and move assignment operators. The
5568 // latter are exported even if they are trivial, because the address of
5569 // an operator can be taken and should compare equal across libraries.
5570 DiagnosticErrorTrap Trap(S.Diags);
5571 S.MarkFunctionReferenced(Class->getLocation(), MD);
5572 if (Trap.hasErrorOccurred()) {
5573 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5574 << Class << !S.getLangOpts().CPlusPlus11;
5578 // There is no later point when we will see the definition of this
5579 // function, so pass it to the consumer now.
5580 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5586 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5587 CXXRecordDecl *Class) {
5588 // Only the MS ABI has default constructor closures, so we don't need to do
5589 // this semantic checking anywhere else.
5590 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5593 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5594 for (Decl *Member : Class->decls()) {
5595 // Look for exported default constructors.
5596 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5597 if (!CD || !CD->isDefaultConstructor())
5599 auto *Attr = CD->getAttr<DLLExportAttr>();
5603 // If the class is non-dependent, mark the default arguments as ODR-used so
5604 // that we can properly codegen the constructor closure.
5605 if (!Class->isDependentContext()) {
5606 for (ParmVarDecl *PD : CD->parameters()) {
5607 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5608 S.DiscardCleanupsInEvaluationContext();
5612 if (LastExportedDefaultCtor) {
5613 S.Diag(LastExportedDefaultCtor->getLocation(),
5614 diag::err_attribute_dll_ambiguous_default_ctor)
5616 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5617 << CD->getDeclName();
5620 LastExportedDefaultCtor = CD;
5624 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5625 // Mark any compiler-generated routines with the implicit code_seg attribute.
5626 for (auto *Method : Class->methods()) {
5627 if (Method->isUserProvided())
5629 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5634 /// Check class-level dllimport/dllexport attribute.
5635 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5636 Attr *ClassAttr = getDLLAttr(Class);
5638 // MSVC inherits DLL attributes to partial class template specializations.
5639 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5640 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5641 if (Attr *TemplateAttr =
5642 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5643 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5644 A->setInherited(true);
5653 if (!Class->isExternallyVisible()) {
5654 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5655 << Class << ClassAttr;
5659 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5660 !ClassAttr->isInherited()) {
5661 // Diagnose dll attributes on members of class with dll attribute.
5662 for (Decl *Member : Class->decls()) {
5663 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5665 InheritableAttr *MemberAttr = getDLLAttr(Member);
5666 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5669 Diag(MemberAttr->getLocation(),
5670 diag::err_attribute_dll_member_of_dll_class)
5671 << MemberAttr << ClassAttr;
5672 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5673 Member->setInvalidDecl();
5677 if (Class->getDescribedClassTemplate())
5678 // Don't inherit dll attribute until the template is instantiated.
5681 // The class is either imported or exported.
5682 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5684 // Check if this was a dllimport attribute propagated from a derived class to
5685 // a base class template specialization. We don't apply these attributes to
5686 // static data members.
5687 const bool PropagatedImport =
5689 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5691 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5693 // Ignore explicit dllexport on explicit class template instantiation declarations.
5694 if (ClassExported && !ClassAttr->isInherited() &&
5695 TSK == TSK_ExplicitInstantiationDeclaration) {
5696 Class->dropAttr<DLLExportAttr>();
5700 // Force declaration of implicit members so they can inherit the attribute.
5701 ForceDeclarationOfImplicitMembers(Class);
5703 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5704 // seem to be true in practice?
5706 for (Decl *Member : Class->decls()) {
5707 VarDecl *VD = dyn_cast<VarDecl>(Member);
5708 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5710 // Only methods and static fields inherit the attributes.
5715 // Don't process deleted methods.
5716 if (MD->isDeleted())
5719 if (MD->isInlined()) {
5720 // MinGW does not import or export inline methods.
5721 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5722 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5725 // MSVC versions before 2015 don't export the move assignment operators
5726 // and move constructor, so don't attempt to import/export them if
5727 // we have a definition.
5728 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5729 if ((MD->isMoveAssignmentOperator() ||
5730 (Ctor && Ctor->isMoveConstructor())) &&
5731 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5734 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5735 // operator is exported anyway.
5736 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5737 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5742 // Don't apply dllimport attributes to static data members of class template
5743 // instantiations when the attribute is propagated from a derived class.
5744 if (VD && PropagatedImport)
5747 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5750 if (!getDLLAttr(Member)) {
5751 InheritableAttr *NewAttr = nullptr;
5753 // Do not export/import inline function when -fno-dllexport-inlines is
5754 // passed. But add attribute for later local static var check.
5755 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5756 TSK != TSK_ExplicitInstantiationDeclaration &&
5757 TSK != TSK_ExplicitInstantiationDefinition) {
5758 if (ClassExported) {
5759 NewAttr = ::new (getASTContext())
5760 DLLExportStaticLocalAttr(ClassAttr->getRange(),
5762 ClassAttr->getSpellingListIndex());
5764 NewAttr = ::new (getASTContext())
5765 DLLImportStaticLocalAttr(ClassAttr->getRange(),
5767 ClassAttr->getSpellingListIndex());
5770 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5773 NewAttr->setInherited(true);
5774 Member->addAttr(NewAttr);
5777 // Propagate DLLAttr to friend re-declarations of MD that have already
5778 // been constructed.
5779 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5780 FD = FD->getPreviousDecl()) {
5781 if (FD->getFriendObjectKind() == Decl::FOK_None)
5783 assert(!getDLLAttr(FD) &&
5784 "friend re-decl should not already have a DLLAttr");
5785 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5786 NewAttr->setInherited(true);
5787 FD->addAttr(NewAttr);
5794 DelayedDllExportClasses.push_back(Class);
5797 /// Perform propagation of DLL attributes from a derived class to a
5798 /// templated base class for MS compatibility.
5799 void Sema::propagateDLLAttrToBaseClassTemplate(
5800 CXXRecordDecl *Class, Attr *ClassAttr,
5801 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5803 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5804 // If the base class template has a DLL attribute, don't try to change it.
5808 auto TSK = BaseTemplateSpec->getSpecializationKind();
5809 if (!getDLLAttr(BaseTemplateSpec) &&
5810 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5811 TSK == TSK_ImplicitInstantiation)) {
5812 // The template hasn't been instantiated yet (or it has, but only as an
5813 // explicit instantiation declaration or implicit instantiation, which means
5814 // we haven't codegenned any members yet), so propagate the attribute.
5815 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5816 NewAttr->setInherited(true);
5817 BaseTemplateSpec->addAttr(NewAttr);
5819 // If this was an import, mark that we propagated it from a derived class to
5820 // a base class template specialization.
5821 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5822 ImportAttr->setPropagatedToBaseTemplate();
5824 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5825 // needs to be run again to work see the new attribute. Otherwise this will
5826 // get run whenever the template is instantiated.
5827 if (TSK != TSK_Undeclared)
5828 checkClassLevelDLLAttribute(BaseTemplateSpec);
5833 if (getDLLAttr(BaseTemplateSpec)) {
5834 // The template has already been specialized or instantiated with an
5835 // attribute, explicitly or through propagation. We should not try to change
5840 // The template was previously instantiated or explicitly specialized without
5841 // a dll attribute, It's too late for us to add an attribute, so warn that
5842 // this is unsupported.
5843 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5844 << BaseTemplateSpec->isExplicitSpecialization();
5845 Diag(ClassAttr->getLocation(), diag::note_attribute);
5846 if (BaseTemplateSpec->isExplicitSpecialization()) {
5847 Diag(BaseTemplateSpec->getLocation(),
5848 diag::note_template_class_explicit_specialization_was_here)
5849 << BaseTemplateSpec;
5851 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5852 diag::note_template_class_instantiation_was_here)
5853 << BaseTemplateSpec;
5857 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5858 SourceLocation DefaultLoc) {
5859 switch (S.getSpecialMember(MD)) {
5860 case Sema::CXXDefaultConstructor:
5861 S.DefineImplicitDefaultConstructor(DefaultLoc,
5862 cast<CXXConstructorDecl>(MD));
5864 case Sema::CXXCopyConstructor:
5865 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5867 case Sema::CXXCopyAssignment:
5868 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5870 case Sema::CXXDestructor:
5871 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5873 case Sema::CXXMoveConstructor:
5874 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5876 case Sema::CXXMoveAssignment:
5877 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5879 case Sema::CXXInvalid:
5880 llvm_unreachable("Invalid special member.");
5884 /// Determine whether a type is permitted to be passed or returned in
5885 /// registers, per C++ [class.temporary]p3.
5886 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5887 TargetInfo::CallingConvKind CCK) {
5888 if (D->isDependentType() || D->isInvalidDecl())
5891 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5892 // The PS4 platform ABI follows the behavior of Clang 3.2.
5893 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5894 return !D->hasNonTrivialDestructorForCall() &&
5895 !D->hasNonTrivialCopyConstructorForCall();
5897 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5898 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5899 bool DtorIsTrivialForCall = false;
5901 // If a class has at least one non-deleted, trivial copy constructor, it
5902 // is passed according to the C ABI. Otherwise, it is passed indirectly.
5904 // Note: This permits classes with non-trivial copy or move ctors to be
5905 // passed in registers, so long as they *also* have a trivial copy ctor,
5906 // which is non-conforming.
5907 if (D->needsImplicitCopyConstructor()) {
5908 if (!D->defaultedCopyConstructorIsDeleted()) {
5909 if (D->hasTrivialCopyConstructor())
5910 CopyCtorIsTrivial = true;
5911 if (D->hasTrivialCopyConstructorForCall())
5912 CopyCtorIsTrivialForCall = true;
5915 for (const CXXConstructorDecl *CD : D->ctors()) {
5916 if (CD->isCopyConstructor() && !CD->isDeleted()) {
5917 if (CD->isTrivial())
5918 CopyCtorIsTrivial = true;
5919 if (CD->isTrivialForCall())
5920 CopyCtorIsTrivialForCall = true;
5925 if (D->needsImplicitDestructor()) {
5926 if (!D->defaultedDestructorIsDeleted() &&
5927 D->hasTrivialDestructorForCall())
5928 DtorIsTrivialForCall = true;
5929 } else if (const auto *DD = D->getDestructor()) {
5930 if (!DD->isDeleted() && DD->isTrivialForCall())
5931 DtorIsTrivialForCall = true;
5934 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5935 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5938 // If a class has a destructor, we'd really like to pass it indirectly
5939 // because it allows us to elide copies. Unfortunately, MSVC makes that
5940 // impossible for small types, which it will pass in a single register or
5941 // stack slot. Most objects with dtors are large-ish, so handle that early.
5942 // We can't call out all large objects as being indirect because there are
5943 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5944 // how we pass large POD types.
5946 // Note: This permits small classes with nontrivial destructors to be
5947 // passed in registers, which is non-conforming.
5948 if (CopyCtorIsTrivial &&
5949 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5954 // Per C++ [class.temporary]p3, the relevant condition is:
5955 // each copy constructor, move constructor, and destructor of X is
5956 // either trivial or deleted, and X has at least one non-deleted copy
5957 // or move constructor
5958 bool HasNonDeletedCopyOrMove = false;
5960 if (D->needsImplicitCopyConstructor() &&
5961 !D->defaultedCopyConstructorIsDeleted()) {
5962 if (!D->hasTrivialCopyConstructorForCall())
5964 HasNonDeletedCopyOrMove = true;
5967 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5968 !D->defaultedMoveConstructorIsDeleted()) {
5969 if (!D->hasTrivialMoveConstructorForCall())
5971 HasNonDeletedCopyOrMove = true;
5974 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5975 !D->hasTrivialDestructorForCall())
5978 for (const CXXMethodDecl *MD : D->methods()) {
5979 if (MD->isDeleted())
5982 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5983 if (CD && CD->isCopyOrMoveConstructor())
5984 HasNonDeletedCopyOrMove = true;
5985 else if (!isa<CXXDestructorDecl>(MD))
5988 if (!MD->isTrivialForCall())
5992 return HasNonDeletedCopyOrMove;
5995 /// Perform semantic checks on a class definition that has been
5996 /// completing, introducing implicitly-declared members, checking for
5997 /// abstract types, etc.
5998 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6002 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6003 AbstractUsageInfo Info(*this, Record);
6004 CheckAbstractClassUsage(Info, Record);
6007 // If this is not an aggregate type and has no user-declared constructor,
6008 // complain about any non-static data members of reference or const scalar
6009 // type, since they will never get initializers.
6010 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6011 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6012 !Record->isLambda()) {
6013 bool Complained = false;
6014 for (const auto *F : Record->fields()) {
6015 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6018 if (F->getType()->isReferenceType() ||
6019 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6021 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6022 << Record->getTagKind() << Record;
6026 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6027 << F->getType()->isReferenceType()
6028 << F->getDeclName();
6033 if (Record->getIdentifier()) {
6034 // C++ [class.mem]p13:
6035 // If T is the name of a class, then each of the following shall have a
6036 // name different from T:
6037 // - every member of every anonymous union that is a member of class T.
6039 // C++ [class.mem]p14:
6040 // In addition, if class T has a user-declared constructor (12.1), every
6041 // non-static data member of class T shall have a name different from T.
6042 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6043 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6045 NamedDecl *D = (*I)->getUnderlyingDecl();
6046 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6047 Record->hasUserDeclaredConstructor()) ||
6048 isa<IndirectFieldDecl>(D)) {
6049 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6050 << D->getDeclName();
6056 // Warn if the class has virtual methods but non-virtual public destructor.
6057 if (Record->isPolymorphic() && !Record->isDependentType()) {
6058 CXXDestructorDecl *dtor = Record->getDestructor();
6059 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6060 !Record->hasAttr<FinalAttr>())
6061 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6062 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6065 if (Record->isAbstract()) {
6066 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6067 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6068 << FA->isSpelledAsSealed();
6069 DiagnoseAbstractType(Record);
6073 // See if trivial_abi has to be dropped.
6074 if (Record->hasAttr<TrivialABIAttr>())
6075 checkIllFormedTrivialABIStruct(*Record);
6077 // Set HasTrivialSpecialMemberForCall if the record has attribute
6079 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6082 Record->setHasTrivialSpecialMemberForCall();
6084 bool HasMethodWithOverrideControl = false,
6085 HasOverridingMethodWithoutOverrideControl = false;
6086 if (!Record->isDependentType()) {
6087 for (auto *M : Record->methods()) {
6088 // See if a method overloads virtual methods in a base
6089 // class without overriding any.
6091 DiagnoseHiddenVirtualMethods(M);
6092 if (M->hasAttr<OverrideAttr>())
6093 HasMethodWithOverrideControl = true;
6094 else if (M->size_overridden_methods() > 0)
6095 HasOverridingMethodWithoutOverrideControl = true;
6096 // Check whether the explicitly-defaulted special members are valid.
6097 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6098 CheckExplicitlyDefaultedSpecialMember(M);
6100 // For an explicitly defaulted or deleted special member, we defer
6101 // determining triviality until the class is complete. That time is now!
6102 CXXSpecialMember CSM = getSpecialMember(M);
6103 if (!M->isImplicit() && !M->isUserProvided()) {
6104 if (CSM != CXXInvalid) {
6105 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6106 // Inform the class that we've finished declaring this member.
6107 Record->finishedDefaultedOrDeletedMember(M);
6108 M->setTrivialForCall(
6110 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6111 Record->setTrivialForCallFlags(M);
6115 // Set triviality for the purpose of calls if this is a user-provided
6116 // copy/move constructor or destructor.
6117 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6118 CSM == CXXDestructor) && M->isUserProvided()) {
6119 M->setTrivialForCall(HasTrivialABI);
6120 Record->setTrivialForCallFlags(M);
6123 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6124 M->hasAttr<DLLExportAttr>()) {
6125 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6127 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6128 CSM == CXXDestructor))
6129 M->dropAttr<DLLExportAttr>();
6131 if (M->hasAttr<DLLExportAttr>()) {
6132 DefineImplicitSpecialMember(*this, M, M->getLocation());
6133 ActOnFinishInlineFunctionDef(M);
6139 if (HasMethodWithOverrideControl &&
6140 HasOverridingMethodWithoutOverrideControl) {
6141 // At least one method has the 'override' control declared.
6142 // Diagnose all other overridden methods which do not have 'override' specified on them.
6143 for (auto *M : Record->methods())
6144 DiagnoseAbsenceOfOverrideControl(M);
6147 // ms_struct is a request to use the same ABI rules as MSVC. Check
6148 // whether this class uses any C++ features that are implemented
6149 // completely differently in MSVC, and if so, emit a diagnostic.
6150 // That diagnostic defaults to an error, but we allow projects to
6151 // map it down to a warning (or ignore it). It's a fairly common
6152 // practice among users of the ms_struct pragma to mass-annotate
6153 // headers, sweeping up a bunch of types that the project doesn't
6154 // really rely on MSVC-compatible layout for. We must therefore
6155 // support "ms_struct except for C++ stuff" as a secondary ABI.
6156 if (Record->isMsStruct(Context) &&
6157 (Record->isPolymorphic() || Record->getNumBases())) {
6158 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6161 checkClassLevelDLLAttribute(Record);
6162 checkClassLevelCodeSegAttribute(Record);
6164 bool ClangABICompat4 =
6165 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6166 TargetInfo::CallingConvKind CCK =
6167 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6168 bool CanPass = canPassInRegisters(*this, Record, CCK);
6170 // Do not change ArgPassingRestrictions if it has already been set to
6171 // APK_CanNeverPassInRegs.
6172 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6173 Record->setArgPassingRestrictions(CanPass
6174 ? RecordDecl::APK_CanPassInRegs
6175 : RecordDecl::APK_CannotPassInRegs);
6177 // If canPassInRegisters returns true despite the record having a non-trivial
6178 // destructor, the record is destructed in the callee. This happens only when
6179 // the record or one of its subobjects has a field annotated with trivial_abi
6180 // or a field qualified with ObjC __strong/__weak.
6181 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6182 Record->setParamDestroyedInCallee(true);
6183 else if (Record->hasNonTrivialDestructor())
6184 Record->setParamDestroyedInCallee(CanPass);
6186 if (getLangOpts().ForceEmitVTables) {
6187 // If we want to emit all the vtables, we need to mark it as used. This
6188 // is especially required for cases like vtable assumption loads.
6189 MarkVTableUsed(Record->getInnerLocStart(), Record);
6193 /// Look up the special member function that would be called by a special
6194 /// member function for a subobject of class type.
6196 /// \param Class The class type of the subobject.
6197 /// \param CSM The kind of special member function.
6198 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6199 /// \param ConstRHS True if this is a copy operation with a const object
6200 /// on its RHS, that is, if the argument to the outer special member
6201 /// function is 'const' and this is not a field marked 'mutable'.
6202 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6203 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6204 unsigned FieldQuals, bool ConstRHS) {
6205 unsigned LHSQuals = 0;
6206 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6207 LHSQuals = FieldQuals;
6209 unsigned RHSQuals = FieldQuals;
6210 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6213 RHSQuals |= Qualifiers::Const;
6215 return S.LookupSpecialMember(Class, CSM,
6216 RHSQuals & Qualifiers::Const,
6217 RHSQuals & Qualifiers::Volatile,
6219 LHSQuals & Qualifiers::Const,
6220 LHSQuals & Qualifiers::Volatile);
6223 class Sema::InheritedConstructorInfo {
6225 SourceLocation UseLoc;
6227 /// A mapping from the base classes through which the constructor was
6228 /// inherited to the using shadow declaration in that base class (or a null
6229 /// pointer if the constructor was declared in that base class).
6230 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6234 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6235 ConstructorUsingShadowDecl *Shadow)
6236 : S(S), UseLoc(UseLoc) {
6237 bool DiagnosedMultipleConstructedBases = false;
6238 CXXRecordDecl *ConstructedBase = nullptr;
6239 UsingDecl *ConstructedBaseUsing = nullptr;
6241 // Find the set of such base class subobjects and check that there's a
6242 // unique constructed subobject.
6243 for (auto *D : Shadow->redecls()) {
6244 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6245 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6246 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6248 InheritedFromBases.insert(
6249 std::make_pair(DNominatedBase->getCanonicalDecl(),
6250 DShadow->getNominatedBaseClassShadowDecl()));
6251 if (DShadow->constructsVirtualBase())
6252 InheritedFromBases.insert(
6253 std::make_pair(DConstructedBase->getCanonicalDecl(),
6254 DShadow->getConstructedBaseClassShadowDecl()));
6256 assert(DNominatedBase == DConstructedBase);
6258 // [class.inhctor.init]p2:
6259 // If the constructor was inherited from multiple base class subobjects
6260 // of type B, the program is ill-formed.
6261 if (!ConstructedBase) {
6262 ConstructedBase = DConstructedBase;
6263 ConstructedBaseUsing = D->getUsingDecl();
6264 } else if (ConstructedBase != DConstructedBase &&
6265 !Shadow->isInvalidDecl()) {
6266 if (!DiagnosedMultipleConstructedBases) {
6267 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6268 << Shadow->getTargetDecl();
6269 S.Diag(ConstructedBaseUsing->getLocation(),
6270 diag::note_ambiguous_inherited_constructor_using)
6272 DiagnosedMultipleConstructedBases = true;
6274 S.Diag(D->getUsingDecl()->getLocation(),
6275 diag::note_ambiguous_inherited_constructor_using)
6276 << DConstructedBase;
6280 if (DiagnosedMultipleConstructedBases)
6281 Shadow->setInvalidDecl();
6284 /// Find the constructor to use for inherited construction of a base class,
6285 /// and whether that base class constructor inherits the constructor from a
6286 /// virtual base class (in which case it won't actually invoke it).
6287 std::pair<CXXConstructorDecl *, bool>
6288 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6289 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6290 if (It == InheritedFromBases.end())
6291 return std::make_pair(nullptr, false);
6293 // This is an intermediary class.
6295 return std::make_pair(
6296 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6297 It->second->constructsVirtualBase());
6299 // This is the base class from which the constructor was inherited.
6300 return std::make_pair(Ctor, false);
6304 /// Is the special member function which would be selected to perform the
6305 /// specified operation on the specified class type a constexpr constructor?
6307 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6308 Sema::CXXSpecialMember CSM, unsigned Quals,
6310 CXXConstructorDecl *InheritedCtor = nullptr,
6311 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6312 // If we're inheriting a constructor, see if we need to call it for this base
6314 if (InheritedCtor) {
6315 assert(CSM == Sema::CXXDefaultConstructor);
6317 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6319 return BaseCtor->isConstexpr();
6322 if (CSM == Sema::CXXDefaultConstructor)
6323 return ClassDecl->hasConstexprDefaultConstructor();
6325 Sema::SpecialMemberOverloadResult SMOR =
6326 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6327 if (!SMOR.getMethod())
6328 // A constructor we wouldn't select can't be "involved in initializing"
6331 return SMOR.getMethod()->isConstexpr();
6334 /// Determine whether the specified special member function would be constexpr
6335 /// if it were implicitly defined.
6336 static bool defaultedSpecialMemberIsConstexpr(
6337 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6338 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6339 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6340 if (!S.getLangOpts().CPlusPlus11)
6343 // C++11 [dcl.constexpr]p4:
6344 // In the definition of a constexpr constructor [...]
6347 case Sema::CXXDefaultConstructor:
6350 // Since default constructor lookup is essentially trivial (and cannot
6351 // involve, for instance, template instantiation), we compute whether a
6352 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6354 // This is important for performance; we need to know whether the default
6355 // constructor is constexpr to determine whether the type is a literal type.
6356 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6358 case Sema::CXXCopyConstructor:
6359 case Sema::CXXMoveConstructor:
6360 // For copy or move constructors, we need to perform overload resolution.
6363 case Sema::CXXCopyAssignment:
6364 case Sema::CXXMoveAssignment:
6365 if (!S.getLangOpts().CPlusPlus14)
6367 // In C++1y, we need to perform overload resolution.
6371 case Sema::CXXDestructor:
6372 case Sema::CXXInvalid:
6376 // -- if the class is a non-empty union, or for each non-empty anonymous
6377 // union member of a non-union class, exactly one non-static data member
6378 // shall be initialized; [DR1359]
6380 // If we squint, this is guaranteed, since exactly one non-static data member
6381 // will be initialized (if the constructor isn't deleted), we just don't know
6383 if (Ctor && ClassDecl->isUnion())
6384 return CSM == Sema::CXXDefaultConstructor
6385 ? ClassDecl->hasInClassInitializer() ||
6386 !ClassDecl->hasVariantMembers()
6389 // -- the class shall not have any virtual base classes;
6390 if (Ctor && ClassDecl->getNumVBases())
6393 // C++1y [class.copy]p26:
6394 // -- [the class] is a literal type, and
6395 if (!Ctor && !ClassDecl->isLiteral())
6398 // -- every constructor involved in initializing [...] base class
6399 // sub-objects shall be a constexpr constructor;
6400 // -- the assignment operator selected to copy/move each direct base
6401 // class is a constexpr function, and
6402 for (const auto &B : ClassDecl->bases()) {
6403 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6404 if (!BaseType) continue;
6406 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6407 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6408 InheritedCtor, Inherited))
6412 // -- every constructor involved in initializing non-static data members
6413 // [...] shall be a constexpr constructor;
6414 // -- every non-static data member and base class sub-object shall be
6416 // -- for each non-static data member of X that is of class type (or array
6417 // thereof), the assignment operator selected to copy/move that member is
6418 // a constexpr function
6419 for (const auto *F : ClassDecl->fields()) {
6420 if (F->isInvalidDecl())
6422 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6424 QualType BaseType = S.Context.getBaseElementType(F->getType());
6425 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6426 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6427 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6428 BaseType.getCVRQualifiers(),
6429 ConstArg && !F->isMutable()))
6431 } else if (CSM == Sema::CXXDefaultConstructor) {
6436 // All OK, it's constexpr!
6440 static Sema::ImplicitExceptionSpecification
6441 ComputeDefaultedSpecialMemberExceptionSpec(
6442 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6443 Sema::InheritedConstructorInfo *ICI);
6445 static Sema::ImplicitExceptionSpecification
6446 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6447 auto CSM = S.getSpecialMember(MD);
6448 if (CSM != Sema::CXXInvalid)
6449 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6451 auto *CD = cast<CXXConstructorDecl>(MD);
6452 assert(CD->getInheritedConstructor() &&
6453 "only special members have implicit exception specs");
6454 Sema::InheritedConstructorInfo ICI(
6455 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6456 return ComputeDefaultedSpecialMemberExceptionSpec(
6457 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6460 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6461 CXXMethodDecl *MD) {
6462 FunctionProtoType::ExtProtoInfo EPI;
6464 // Build an exception specification pointing back at this member.
6465 EPI.ExceptionSpec.Type = EST_Unevaluated;
6466 EPI.ExceptionSpec.SourceDecl = MD;
6468 // Set the calling convention to the default for C++ instance methods.
6469 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6470 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6471 /*IsCXXMethod=*/true));
6475 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6476 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6477 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6480 // Evaluate the exception specification.
6481 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6482 auto ESI = IES.getExceptionSpec();
6484 // Update the type of the special member to use it.
6485 UpdateExceptionSpec(MD, ESI);
6487 // A user-provided destructor can be defined outside the class. When that
6488 // happens, be sure to update the exception specification on both
6490 const FunctionProtoType *CanonicalFPT =
6491 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6492 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6493 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6496 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6497 CXXRecordDecl *RD = MD->getParent();
6498 CXXSpecialMember CSM = getSpecialMember(MD);
6500 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6501 "not an explicitly-defaulted special member");
6503 // Whether this was the first-declared instance of the constructor.
6504 // This affects whether we implicitly add an exception spec and constexpr.
6505 bool First = MD == MD->getCanonicalDecl();
6507 bool HadError = false;
6509 // C++11 [dcl.fct.def.default]p1:
6510 // A function that is explicitly defaulted shall
6511 // -- be a special member function (checked elsewhere),
6512 // -- have the same type (except for ref-qualifiers, and except that a
6513 // copy operation can take a non-const reference) as an implicit
6515 // -- not have default arguments.
6516 // C++2a changes the second bullet to instead delete the function if it's
6517 // defaulted on its first declaration, unless it's "an assignment operator,
6518 // and its return type differs or its parameter type is not a reference".
6519 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6520 bool ShouldDeleteForTypeMismatch = false;
6521 unsigned ExpectedParams = 1;
6522 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6524 if (MD->getNumParams() != ExpectedParams) {
6525 // This checks for default arguments: a copy or move constructor with a
6526 // default argument is classified as a default constructor, and assignment
6527 // operations and destructors can't have default arguments.
6528 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6529 << CSM << MD->getSourceRange();
6531 } else if (MD->isVariadic()) {
6532 if (DeleteOnTypeMismatch)
6533 ShouldDeleteForTypeMismatch = true;
6535 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6536 << CSM << MD->getSourceRange();
6541 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6543 bool CanHaveConstParam = false;
6544 if (CSM == CXXCopyConstructor)
6545 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6546 else if (CSM == CXXCopyAssignment)
6547 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6549 QualType ReturnType = Context.VoidTy;
6550 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6551 // Check for return type matching.
6552 ReturnType = Type->getReturnType();
6554 QualType DeclType = Context.getTypeDeclType(RD);
6555 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getTypeQualifiers().getAddressSpace());
6556 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6558 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6559 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6560 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6564 // A defaulted special member cannot have cv-qualifiers.
6565 if (Type->getTypeQuals().hasConst() || Type->getTypeQuals().hasVolatile()) {
6566 if (DeleteOnTypeMismatch)
6567 ShouldDeleteForTypeMismatch = true;
6569 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6570 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6576 // Check for parameter type matching.
6577 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6578 bool HasConstParam = false;
6579 if (ExpectedParams && ArgType->isReferenceType()) {
6580 // Argument must be reference to possibly-const T.
6581 QualType ReferentType = ArgType->getPointeeType();
6582 HasConstParam = ReferentType.isConstQualified();
6584 if (ReferentType.isVolatileQualified()) {
6585 if (DeleteOnTypeMismatch)
6586 ShouldDeleteForTypeMismatch = true;
6588 Diag(MD->getLocation(),
6589 diag::err_defaulted_special_member_volatile_param) << CSM;
6594 if (HasConstParam && !CanHaveConstParam) {
6595 if (DeleteOnTypeMismatch)
6596 ShouldDeleteForTypeMismatch = true;
6597 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6598 Diag(MD->getLocation(),
6599 diag::err_defaulted_special_member_copy_const_param)
6600 << (CSM == CXXCopyAssignment);
6601 // FIXME: Explain why this special member can't be const.
6604 Diag(MD->getLocation(),
6605 diag::err_defaulted_special_member_move_const_param)
6606 << (CSM == CXXMoveAssignment);
6610 } else if (ExpectedParams) {
6611 // A copy assignment operator can take its argument by value, but a
6612 // defaulted one cannot.
6613 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6614 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6618 // C++11 [dcl.fct.def.default]p2:
6619 // An explicitly-defaulted function may be declared constexpr only if it
6620 // would have been implicitly declared as constexpr,
6621 // Do not apply this rule to members of class templates, since core issue 1358
6622 // makes such functions always instantiate to constexpr functions. For
6623 // functions which cannot be constexpr (for non-constructors in C++11 and for
6624 // destructors in C++1y), this is checked elsewhere.
6625 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6627 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6628 : isa<CXXConstructorDecl>(MD)) &&
6629 MD->isConstexpr() && !Constexpr &&
6630 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6631 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6632 // FIXME: Explain why the special member can't be constexpr.
6636 // and may have an explicit exception-specification only if it is compatible
6637 // with the exception-specification on the implicit declaration.
6638 if (Type->hasExceptionSpec()) {
6639 // Delay the check if this is the first declaration of the special member,
6640 // since we may not have parsed some necessary in-class initializers yet.
6642 // If the exception specification needs to be instantiated, do so now,
6643 // before we clobber it with an EST_Unevaluated specification below.
6644 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6645 InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6646 Type = MD->getType()->getAs<FunctionProtoType>();
6648 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6650 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6653 // If a function is explicitly defaulted on its first declaration,
6655 // -- it is implicitly considered to be constexpr if the implicit
6656 // definition would be,
6657 MD->setConstexpr(Constexpr);
6659 // -- it is implicitly considered to have the same exception-specification
6660 // as if it had been implicitly declared,
6661 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6662 EPI.ExceptionSpec.Type = EST_Unevaluated;
6663 EPI.ExceptionSpec.SourceDecl = MD;
6664 MD->setType(Context.getFunctionType(ReturnType,
6665 llvm::makeArrayRef(&ArgType,
6670 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6672 SetDeclDeleted(MD, MD->getLocation());
6673 if (!inTemplateInstantiation() && !HadError) {
6674 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6675 if (ShouldDeleteForTypeMismatch) {
6676 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6678 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6681 if (ShouldDeleteForTypeMismatch && !HadError) {
6682 Diag(MD->getLocation(),
6683 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6686 // C++11 [dcl.fct.def.default]p4:
6687 // [For a] user-provided explicitly-defaulted function [...] if such a
6688 // function is implicitly defined as deleted, the program is ill-formed.
6689 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6690 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6691 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6697 MD->setInvalidDecl();
6700 /// Check whether the exception specification provided for an
6701 /// explicitly-defaulted special member matches the exception specification
6702 /// that would have been generated for an implicit special member, per
6703 /// C++11 [dcl.fct.def.default]p2.
6704 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6705 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6706 // If the exception specification was explicitly specified but hadn't been
6707 // parsed when the method was defaulted, grab it now.
6708 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6710 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6712 // Compute the implicit exception specification.
6713 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6714 /*IsCXXMethod=*/true);
6715 FunctionProtoType::ExtProtoInfo EPI(CC);
6716 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6717 EPI.ExceptionSpec = IES.getExceptionSpec();
6718 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6719 Context.getFunctionType(Context.VoidTy, None, EPI));
6721 // Ensure that it matches.
6722 CheckEquivalentExceptionSpec(
6723 PDiag(diag::err_incorrect_defaulted_exception_spec)
6724 << getSpecialMember(MD), PDiag(),
6725 ImplicitType, SourceLocation(),
6726 SpecifiedType, MD->getLocation());
6729 void Sema::CheckDelayedMemberExceptionSpecs() {
6730 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6731 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6732 decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6734 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6735 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6736 std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6738 // Perform any deferred checking of exception specifications for virtual
6740 for (auto &Check : Overriding)
6741 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6743 // Perform any deferred checking of exception specifications for befriended
6745 for (auto &Check : Equivalent)
6746 CheckEquivalentExceptionSpec(Check.second, Check.first);
6748 // Check that any explicitly-defaulted methods have exception specifications
6749 // compatible with their implicit exception specifications.
6750 for (auto &Spec : Defaulted)
6751 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6755 /// CRTP base class for visiting operations performed by a special member
6756 /// function (or inherited constructor).
6757 template<typename Derived>
6758 struct SpecialMemberVisitor {
6761 Sema::CXXSpecialMember CSM;
6762 Sema::InheritedConstructorInfo *ICI;
6764 // Properties of the special member, computed for convenience.
6765 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6767 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6768 Sema::InheritedConstructorInfo *ICI)
6769 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6771 case Sema::CXXDefaultConstructor:
6772 case Sema::CXXCopyConstructor:
6773 case Sema::CXXMoveConstructor:
6774 IsConstructor = true;
6776 case Sema::CXXCopyAssignment:
6777 case Sema::CXXMoveAssignment:
6778 IsAssignment = true;
6780 case Sema::CXXDestructor:
6782 case Sema::CXXInvalid:
6783 llvm_unreachable("invalid special member kind");
6786 if (MD->getNumParams()) {
6787 if (const ReferenceType *RT =
6788 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6789 ConstArg = RT->getPointeeType().isConstQualified();
6793 Derived &getDerived() { return static_cast<Derived&>(*this); }
6795 /// Is this a "move" special member?
6796 bool isMove() const {
6797 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6800 /// Look up the corresponding special member in the given class.
6801 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6802 unsigned Quals, bool IsMutable) {
6803 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6804 ConstArg && !IsMutable);
6807 /// Look up the constructor for the specified base class to see if it's
6808 /// overridden due to this being an inherited constructor.
6809 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6812 assert(CSM == Sema::CXXDefaultConstructor);
6814 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6815 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6820 /// A base or member subobject.
6821 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6823 /// Get the location to use for a subobject in diagnostics.
6824 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6825 // FIXME: For an indirect virtual base, the direct base leading to
6826 // the indirect virtual base would be a more useful choice.
6827 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6828 return B->getBaseTypeLoc();
6830 return Subobj.get<FieldDecl*>()->getLocation();
6834 /// Visit all non-virtual (direct) bases.
6835 VisitNonVirtualBases,
6836 /// Visit all direct bases, virtual or not.
6838 /// Visit all non-virtual bases, and all virtual bases if the class
6839 /// is not abstract.
6840 VisitPotentiallyConstructedBases,
6841 /// Visit all direct or virtual bases.
6845 // Visit the bases and members of the class.
6846 bool visit(BasesToVisit Bases) {
6847 CXXRecordDecl *RD = MD->getParent();
6849 if (Bases == VisitPotentiallyConstructedBases)
6850 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6852 for (auto &B : RD->bases())
6853 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6854 getDerived().visitBase(&B))
6857 if (Bases == VisitAllBases)
6858 for (auto &B : RD->vbases())
6859 if (getDerived().visitBase(&B))
6862 for (auto *F : RD->fields())
6863 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6864 getDerived().visitField(F))
6873 struct SpecialMemberDeletionInfo
6874 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6879 bool AllFieldsAreConst;
6881 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6882 Sema::CXXSpecialMember CSM,
6883 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6884 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6885 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6887 bool inUnion() const { return MD->getParent()->isUnion(); }
6889 Sema::CXXSpecialMember getEffectiveCSM() {
6890 return ICI ? Sema::CXXInvalid : CSM;
6893 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6894 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6896 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6897 bool shouldDeleteForField(FieldDecl *FD);
6898 bool shouldDeleteForAllConstMembers();
6900 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6902 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6903 Sema::SpecialMemberOverloadResult SMOR,
6904 bool IsDtorCallInCtor);
6906 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6910 /// Is the given special member inaccessible when used on the given
6912 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6913 CXXMethodDecl *target) {
6914 /// If we're operating on a base class, the object type is the
6915 /// type of this special member.
6917 AccessSpecifier access = target->getAccess();
6918 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6919 objectTy = S.Context.getTypeDeclType(MD->getParent());
6920 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6922 // If we're operating on a field, the object type is the type of the field.
6924 objectTy = S.Context.getTypeDeclType(target->getParent());
6927 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6930 /// Check whether we should delete a special member due to the implicit
6931 /// definition containing a call to a special member of a subobject.
6932 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6933 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6934 bool IsDtorCallInCtor) {
6935 CXXMethodDecl *Decl = SMOR.getMethod();
6936 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6940 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6941 DiagKind = !Decl ? 0 : 1;
6942 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6944 else if (!isAccessible(Subobj, Decl))
6946 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6947 !Decl->isTrivial()) {
6948 // A member of a union must have a trivial corresponding special member.
6949 // As a weird special case, a destructor call from a union's constructor
6950 // must be accessible and non-deleted, but need not be trivial. Such a
6951 // destructor is never actually called, but is semantically checked as
6961 S.Diag(Field->getLocation(),
6962 diag::note_deleted_special_member_class_subobject)
6963 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6964 << Field << DiagKind << IsDtorCallInCtor;
6966 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6967 S.Diag(Base->getBeginLoc(),
6968 diag::note_deleted_special_member_class_subobject)
6969 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6970 << Base->getType() << DiagKind << IsDtorCallInCtor;
6974 S.NoteDeletedFunction(Decl);
6975 // FIXME: Explain inaccessibility if DiagKind == 3.
6981 /// Check whether we should delete a special member function due to having a
6982 /// direct or virtual base class or non-static data member of class type M.
6983 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6984 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6985 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6986 bool IsMutable = Field && Field->isMutable();
6988 // C++11 [class.ctor]p5:
6989 // -- any direct or virtual base class, or non-static data member with no
6990 // brace-or-equal-initializer, has class type M (or array thereof) and
6991 // either M has no default constructor or overload resolution as applied
6992 // to M's default constructor results in an ambiguity or in a function
6993 // that is deleted or inaccessible
6994 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6995 // -- a direct or virtual base class B that cannot be copied/moved because
6996 // overload resolution, as applied to B's corresponding special member,
6997 // results in an ambiguity or a function that is deleted or inaccessible
6998 // from the defaulted special member
6999 // C++11 [class.dtor]p5:
7000 // -- any direct or virtual base class [...] has a type with a destructor
7001 // that is deleted or inaccessible
7002 if (!(CSM == Sema::CXXDefaultConstructor &&
7003 Field && Field->hasInClassInitializer()) &&
7004 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7008 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7009 // -- any direct or virtual base class or non-static data member has a
7010 // type with a destructor that is deleted or inaccessible
7011 if (IsConstructor) {
7012 Sema::SpecialMemberOverloadResult SMOR =
7013 S.LookupSpecialMember(Class, Sema::CXXDestructor,
7014 false, false, false, false, false);
7015 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7022 /// Check whether we should delete a special member function due to the class
7023 /// having a particular direct or virtual base class.
7024 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7025 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7026 // If program is correct, BaseClass cannot be null, but if it is, the error
7027 // must be reported elsewhere.
7030 // If we have an inheriting constructor, check whether we're calling an
7031 // inherited constructor instead of a default constructor.
7032 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7033 if (auto *BaseCtor = SMOR.getMethod()) {
7034 // Note that we do not check access along this path; other than that,
7035 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7036 // FIXME: Check that the base has a usable destructor! Sink this into
7037 // shouldDeleteForClassSubobject.
7038 if (BaseCtor->isDeleted() && Diagnose) {
7039 S.Diag(Base->getBeginLoc(),
7040 diag::note_deleted_special_member_class_subobject)
7041 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7042 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
7043 S.NoteDeletedFunction(BaseCtor);
7045 return BaseCtor->isDeleted();
7047 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7050 /// Check whether we should delete a special member function due to the class
7051 /// having a particular non-static data member.
7052 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7053 QualType FieldType = S.Context.getBaseElementType(FD->getType());
7054 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7056 if (CSM == Sema::CXXDefaultConstructor) {
7057 // For a default constructor, all references must be initialized in-class
7058 // and, if a union, it must have a non-const member.
7059 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7061 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7062 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7065 // C++11 [class.ctor]p5: any non-variant non-static data member of
7066 // const-qualified type (or array thereof) with no
7067 // brace-or-equal-initializer does not have a user-provided default
7069 if (!inUnion() && FieldType.isConstQualified() &&
7070 !FD->hasInClassInitializer() &&
7071 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7073 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7074 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7078 if (inUnion() && !FieldType.isConstQualified())
7079 AllFieldsAreConst = false;
7080 } else if (CSM == Sema::CXXCopyConstructor) {
7081 // For a copy constructor, data members must not be of rvalue reference
7083 if (FieldType->isRValueReferenceType()) {
7085 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7086 << MD->getParent() << FD << FieldType;
7089 } else if (IsAssignment) {
7090 // For an assignment operator, data members must not be of reference type.
7091 if (FieldType->isReferenceType()) {
7093 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7094 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7097 if (!FieldRecord && FieldType.isConstQualified()) {
7098 // C++11 [class.copy]p23:
7099 // -- a non-static data member of const non-class type (or array thereof)
7101 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7102 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7108 // Some additional restrictions exist on the variant members.
7109 if (!inUnion() && FieldRecord->isUnion() &&
7110 FieldRecord->isAnonymousStructOrUnion()) {
7111 bool AllVariantFieldsAreConst = true;
7113 // FIXME: Handle anonymous unions declared within anonymous unions.
7114 for (auto *UI : FieldRecord->fields()) {
7115 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7117 if (!UnionFieldType.isConstQualified())
7118 AllVariantFieldsAreConst = false;
7120 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7121 if (UnionFieldRecord &&
7122 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7123 UnionFieldType.getCVRQualifiers()))
7127 // At least one member in each anonymous union must be non-const
7128 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7129 !FieldRecord->field_empty()) {
7131 S.Diag(FieldRecord->getLocation(),
7132 diag::note_deleted_default_ctor_all_const)
7133 << !!ICI << MD->getParent() << /*anonymous union*/1;
7137 // Don't check the implicit member of the anonymous union type.
7138 // This is technically non-conformant, but sanity demands it.
7142 if (shouldDeleteForClassSubobject(FieldRecord, FD,
7143 FieldType.getCVRQualifiers()))
7150 /// C++11 [class.ctor] p5:
7151 /// A defaulted default constructor for a class X is defined as deleted if
7152 /// X is a union and all of its variant members are of const-qualified type.
7153 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7154 // This is a silly definition, because it gives an empty union a deleted
7155 // default constructor. Don't do that.
7156 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7157 bool AnyFields = false;
7158 for (auto *F : MD->getParent()->fields())
7159 if ((AnyFields = !F->isUnnamedBitfield()))
7164 S.Diag(MD->getParent()->getLocation(),
7165 diag::note_deleted_default_ctor_all_const)
7166 << !!ICI << MD->getParent() << /*not anonymous union*/0;
7172 /// Determine whether a defaulted special member function should be defined as
7173 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7174 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7175 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7176 InheritedConstructorInfo *ICI,
7178 if (MD->isInvalidDecl())
7180 CXXRecordDecl *RD = MD->getParent();
7181 assert(!RD->isDependentType() && "do deletion after instantiation");
7182 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7185 // C++11 [expr.lambda.prim]p19:
7186 // The closure type associated with a lambda-expression has a
7187 // deleted (8.4.3) default constructor and a deleted copy
7188 // assignment operator.
7189 // C++2a adds back these operators if the lambda has no capture-default.
7190 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7191 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7193 Diag(RD->getLocation(), diag::note_lambda_decl);
7197 // For an anonymous struct or union, the copy and assignment special members
7198 // will never be used, so skip the check. For an anonymous union declared at
7199 // namespace scope, the constructor and destructor are used.
7200 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7201 RD->isAnonymousStructOrUnion())
7204 // C++11 [class.copy]p7, p18:
7205 // If the class definition declares a move constructor or move assignment
7206 // operator, an implicitly declared copy constructor or copy assignment
7207 // operator is defined as deleted.
7208 if (MD->isImplicit() &&
7209 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7210 CXXMethodDecl *UserDeclaredMove = nullptr;
7212 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7213 // deletion of the corresponding copy operation, not both copy operations.
7214 // MSVC 2015 has adopted the standards conforming behavior.
7215 bool DeletesOnlyMatchingCopy =
7216 getLangOpts().MSVCCompat &&
7217 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7219 if (RD->hasUserDeclaredMoveConstructor() &&
7220 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7221 if (!Diagnose) return true;
7223 // Find any user-declared move constructor.
7224 for (auto *I : RD->ctors()) {
7225 if (I->isMoveConstructor()) {
7226 UserDeclaredMove = I;
7230 assert(UserDeclaredMove);
7231 } else if (RD->hasUserDeclaredMoveAssignment() &&
7232 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7233 if (!Diagnose) return true;
7235 // Find any user-declared move assignment operator.
7236 for (auto *I : RD->methods()) {
7237 if (I->isMoveAssignmentOperator()) {
7238 UserDeclaredMove = I;
7242 assert(UserDeclaredMove);
7245 if (UserDeclaredMove) {
7246 Diag(UserDeclaredMove->getLocation(),
7247 diag::note_deleted_copy_user_declared_move)
7248 << (CSM == CXXCopyAssignment) << RD
7249 << UserDeclaredMove->isMoveAssignmentOperator();
7254 // Do access control from the special member function
7255 ContextRAII MethodContext(*this, MD);
7257 // C++11 [class.dtor]p5:
7258 // -- for a virtual destructor, lookup of the non-array deallocation function
7259 // results in an ambiguity or in a function that is deleted or inaccessible
7260 if (CSM == CXXDestructor && MD->isVirtual()) {
7261 FunctionDecl *OperatorDelete = nullptr;
7262 DeclarationName Name =
7263 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7264 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7265 OperatorDelete, /*Diagnose*/false)) {
7267 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7272 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7274 // Per DR1611, do not consider virtual bases of constructors of abstract
7275 // classes, since we are not going to construct them.
7276 // Per DR1658, do not consider virtual bases of destructors of abstract
7278 // Per DR2180, for assignment operators we only assign (and thus only
7279 // consider) direct bases.
7280 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7281 : SMI.VisitPotentiallyConstructedBases))
7284 if (SMI.shouldDeleteForAllConstMembers())
7287 if (getLangOpts().CUDA) {
7288 // We should delete the special member in CUDA mode if target inference
7290 // For inherited constructors (non-null ICI), CSM may be passed so that MD
7291 // is treated as certain special member, which may not reflect what special
7292 // member MD really is. However inferCUDATargetForImplicitSpecialMember
7293 // expects CSM to match MD, therefore recalculate CSM.
7294 assert(ICI || CSM == getSpecialMember(MD));
7297 RealCSM = getSpecialMember(MD);
7299 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7300 SMI.ConstArg, Diagnose);
7306 /// Perform lookup for a special member of the specified kind, and determine
7307 /// whether it is trivial. If the triviality can be determined without the
7308 /// lookup, skip it. This is intended for use when determining whether a
7309 /// special member of a containing object is trivial, and thus does not ever
7310 /// perform overload resolution for default constructors.
7312 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7313 /// member that was most likely to be intended to be trivial, if any.
7315 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7316 /// determine whether the special member is trivial.
7317 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7318 Sema::CXXSpecialMember CSM, unsigned Quals,
7320 Sema::TrivialABIHandling TAH,
7321 CXXMethodDecl **Selected) {
7323 *Selected = nullptr;
7326 case Sema::CXXInvalid:
7327 llvm_unreachable("not a special member");
7329 case Sema::CXXDefaultConstructor:
7330 // C++11 [class.ctor]p5:
7331 // A default constructor is trivial if:
7332 // - all the [direct subobjects] have trivial default constructors
7334 // Note, no overload resolution is performed in this case.
7335 if (RD->hasTrivialDefaultConstructor())
7339 // If there's a default constructor which could have been trivial, dig it
7340 // out. Otherwise, if there's any user-provided default constructor, point
7341 // to that as an example of why there's not a trivial one.
7342 CXXConstructorDecl *DefCtor = nullptr;
7343 if (RD->needsImplicitDefaultConstructor())
7344 S.DeclareImplicitDefaultConstructor(RD);
7345 for (auto *CI : RD->ctors()) {
7346 if (!CI->isDefaultConstructor())
7349 if (!DefCtor->isUserProvided())
7353 *Selected = DefCtor;
7358 case Sema::CXXDestructor:
7359 // C++11 [class.dtor]p5:
7360 // A destructor is trivial if:
7361 // - all the direct [subobjects] have trivial destructors
7362 if (RD->hasTrivialDestructor() ||
7363 (TAH == Sema::TAH_ConsiderTrivialABI &&
7364 RD->hasTrivialDestructorForCall()))
7368 if (RD->needsImplicitDestructor())
7369 S.DeclareImplicitDestructor(RD);
7370 *Selected = RD->getDestructor();
7375 case Sema::CXXCopyConstructor:
7376 // C++11 [class.copy]p12:
7377 // A copy constructor is trivial if:
7378 // - the constructor selected to copy each direct [subobject] is trivial
7379 if (RD->hasTrivialCopyConstructor() ||
7380 (TAH == Sema::TAH_ConsiderTrivialABI &&
7381 RD->hasTrivialCopyConstructorForCall())) {
7382 if (Quals == Qualifiers::Const)
7383 // We must either select the trivial copy constructor or reach an
7384 // ambiguity; no need to actually perform overload resolution.
7386 } else if (!Selected) {
7389 // In C++98, we are not supposed to perform overload resolution here, but we
7390 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7391 // cases like B as having a non-trivial copy constructor:
7392 // struct A { template<typename T> A(T&); };
7393 // struct B { mutable A a; };
7394 goto NeedOverloadResolution;
7396 case Sema::CXXCopyAssignment:
7397 // C++11 [class.copy]p25:
7398 // A copy assignment operator is trivial if:
7399 // - the assignment operator selected to copy each direct [subobject] is
7401 if (RD->hasTrivialCopyAssignment()) {
7402 if (Quals == Qualifiers::Const)
7404 } else if (!Selected) {
7407 // In C++98, we are not supposed to perform overload resolution here, but we
7408 // treat that as a language defect.
7409 goto NeedOverloadResolution;
7411 case Sema::CXXMoveConstructor:
7412 case Sema::CXXMoveAssignment:
7413 NeedOverloadResolution:
7414 Sema::SpecialMemberOverloadResult SMOR =
7415 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7417 // The standard doesn't describe how to behave if the lookup is ambiguous.
7418 // We treat it as not making the member non-trivial, just like the standard
7419 // mandates for the default constructor. This should rarely matter, because
7420 // the member will also be deleted.
7421 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7424 if (!SMOR.getMethod()) {
7425 assert(SMOR.getKind() ==
7426 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7430 // We deliberately don't check if we found a deleted special member. We're
7433 *Selected = SMOR.getMethod();
7435 if (TAH == Sema::TAH_ConsiderTrivialABI &&
7436 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7437 return SMOR.getMethod()->isTrivialForCall();
7438 return SMOR.getMethod()->isTrivial();
7441 llvm_unreachable("unknown special method kind");
7444 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7445 for (auto *CI : RD->ctors())
7446 if (!CI->isImplicit())
7449 // Look for constructor templates.
7450 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7451 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7452 if (CXXConstructorDecl *CD =
7453 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7460 /// The kind of subobject we are checking for triviality. The values of this
7461 /// enumeration are used in diagnostics.
7462 enum TrivialSubobjectKind {
7463 /// The subobject is a base class.
7465 /// The subobject is a non-static data member.
7467 /// The object is actually the complete object.
7471 /// Check whether the special member selected for a given type would be trivial.
7472 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7473 QualType SubType, bool ConstRHS,
7474 Sema::CXXSpecialMember CSM,
7475 TrivialSubobjectKind Kind,
7476 Sema::TrivialABIHandling TAH, bool Diagnose) {
7477 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7481 CXXMethodDecl *Selected;
7482 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7483 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7490 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7491 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7492 << Kind << SubType.getUnqualifiedType();
7493 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7494 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7495 } else if (!Selected)
7496 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7497 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7498 else if (Selected->isUserProvided()) {
7499 if (Kind == TSK_CompleteObject)
7500 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7501 << Kind << SubType.getUnqualifiedType() << CSM;
7503 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7504 << Kind << SubType.getUnqualifiedType() << CSM;
7505 S.Diag(Selected->getLocation(), diag::note_declared_at);
7508 if (Kind != TSK_CompleteObject)
7509 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7510 << Kind << SubType.getUnqualifiedType() << CSM;
7512 // Explain why the defaulted or deleted special member isn't trivial.
7513 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7521 /// Check whether the members of a class type allow a special member to be
7523 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7524 Sema::CXXSpecialMember CSM,
7526 Sema::TrivialABIHandling TAH,
7528 for (const auto *FI : RD->fields()) {
7529 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7532 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7534 // Pretend anonymous struct or union members are members of this class.
7535 if (FI->isAnonymousStructOrUnion()) {
7536 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7537 CSM, ConstArg, TAH, Diagnose))
7542 // C++11 [class.ctor]p5:
7543 // A default constructor is trivial if [...]
7544 // -- no non-static data member of its class has a
7545 // brace-or-equal-initializer
7546 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7548 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7552 // Objective C ARC 4.3.5:
7553 // [...] nontrivally ownership-qualified types are [...] not trivially
7554 // default constructible, copy constructible, move constructible, copy
7555 // assignable, move assignable, or destructible [...]
7556 if (FieldType.hasNonTrivialObjCLifetime()) {
7558 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7559 << RD << FieldType.getObjCLifetime();
7563 bool ConstRHS = ConstArg && !FI->isMutable();
7564 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7565 CSM, TSK_Field, TAH, Diagnose))
7572 /// Diagnose why the specified class does not have a trivial special member of
7574 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7575 QualType Ty = Context.getRecordType(RD);
7577 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7578 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7579 TSK_CompleteObject, TAH_IgnoreTrivialABI,
7583 /// Determine whether a defaulted or deleted special member function is trivial,
7584 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7585 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7586 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7587 TrivialABIHandling TAH, bool Diagnose) {
7588 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7590 CXXRecordDecl *RD = MD->getParent();
7592 bool ConstArg = false;
7594 // C++11 [class.copy]p12, p25: [DR1593]
7595 // A [special member] is trivial if [...] its parameter-type-list is
7596 // equivalent to the parameter-type-list of an implicit declaration [...]
7598 case CXXDefaultConstructor:
7600 // Trivial default constructors and destructors cannot have parameters.
7603 case CXXCopyConstructor:
7604 case CXXCopyAssignment: {
7605 // Trivial copy operations always have const, non-volatile parameter types.
7607 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7608 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7609 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7611 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7612 << Param0->getSourceRange() << Param0->getType()
7613 << Context.getLValueReferenceType(
7614 Context.getRecordType(RD).withConst());
7620 case CXXMoveConstructor:
7621 case CXXMoveAssignment: {
7622 // Trivial move operations always have non-cv-qualified parameters.
7623 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7624 const RValueReferenceType *RT =
7625 Param0->getType()->getAs<RValueReferenceType>();
7626 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7628 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7629 << Param0->getSourceRange() << Param0->getType()
7630 << Context.getRValueReferenceType(Context.getRecordType(RD));
7637 llvm_unreachable("not a special member");
7640 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7642 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7643 diag::note_nontrivial_default_arg)
7644 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7647 if (MD->isVariadic()) {
7649 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7653 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7654 // A copy/move [constructor or assignment operator] is trivial if
7655 // -- the [member] selected to copy/move each direct base class subobject
7658 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7659 // A [default constructor or destructor] is trivial if
7660 // -- all the direct base classes have trivial [default constructors or
7662 for (const auto &BI : RD->bases())
7663 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7664 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7667 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7668 // A copy/move [constructor or assignment operator] for a class X is
7670 // -- for each non-static data member of X that is of class type (or array
7671 // thereof), the constructor selected to copy/move that member is
7674 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7675 // A [default constructor or destructor] is trivial if
7676 // -- for all of the non-static data members of its class that are of class
7677 // type (or array thereof), each such class has a trivial [default
7678 // constructor or destructor]
7679 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7682 // C++11 [class.dtor]p5:
7683 // A destructor is trivial if [...]
7684 // -- the destructor is not virtual
7685 if (CSM == CXXDestructor && MD->isVirtual()) {
7687 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7691 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7692 // A [special member] for class X is trivial if [...]
7693 // -- class X has no virtual functions and no virtual base classes
7694 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7698 if (RD->getNumVBases()) {
7699 // Check for virtual bases. We already know that the corresponding
7700 // member in all bases is trivial, so vbases must all be direct.
7701 CXXBaseSpecifier &BS = *RD->vbases_begin();
7702 assert(BS.isVirtual());
7703 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7707 // Must have a virtual method.
7708 for (const auto *MI : RD->methods()) {
7709 if (MI->isVirtual()) {
7710 SourceLocation MLoc = MI->getBeginLoc();
7711 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7716 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7719 // Looks like it's trivial!
7724 struct FindHiddenVirtualMethod {
7726 CXXMethodDecl *Method;
7727 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7728 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7731 /// Check whether any most overridden method from MD in Methods
7732 static bool CheckMostOverridenMethods(
7733 const CXXMethodDecl *MD,
7734 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7735 if (MD->size_overridden_methods() == 0)
7736 return Methods.count(MD->getCanonicalDecl());
7737 for (const CXXMethodDecl *O : MD->overridden_methods())
7738 if (CheckMostOverridenMethods(O, Methods))
7744 /// Member lookup function that determines whether a given C++
7745 /// method overloads virtual methods in a base class without overriding any,
7746 /// to be used with CXXRecordDecl::lookupInBases().
7747 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7748 RecordDecl *BaseRecord =
7749 Specifier->getType()->getAs<RecordType>()->getDecl();
7751 DeclarationName Name = Method->getDeclName();
7752 assert(Name.getNameKind() == DeclarationName::Identifier);
7754 bool foundSameNameMethod = false;
7755 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7756 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7757 Path.Decls = Path.Decls.slice(1)) {
7758 NamedDecl *D = Path.Decls.front();
7759 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7760 MD = MD->getCanonicalDecl();
7761 foundSameNameMethod = true;
7762 // Interested only in hidden virtual methods.
7763 if (!MD->isVirtual())
7765 // If the method we are checking overrides a method from its base
7766 // don't warn about the other overloaded methods. Clang deviates from
7767 // GCC by only diagnosing overloads of inherited virtual functions that
7768 // do not override any other virtual functions in the base. GCC's
7769 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7770 // function from a base class. These cases may be better served by a
7771 // warning (not specific to virtual functions) on call sites when the
7772 // call would select a different function from the base class, were it
7774 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7775 if (!S->IsOverload(Method, MD, false))
7777 // Collect the overload only if its hidden.
7778 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7779 overloadedMethods.push_back(MD);
7783 if (foundSameNameMethod)
7784 OverloadedMethods.append(overloadedMethods.begin(),
7785 overloadedMethods.end());
7786 return foundSameNameMethod;
7789 } // end anonymous namespace
7791 /// Add the most overriden methods from MD to Methods
7792 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7793 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7794 if (MD->size_overridden_methods() == 0)
7795 Methods.insert(MD->getCanonicalDecl());
7797 for (const CXXMethodDecl *O : MD->overridden_methods())
7798 AddMostOverridenMethods(O, Methods);
7801 /// Check if a method overloads virtual methods in a base class without
7803 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7804 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7805 if (!MD->getDeclName().isIdentifier())
7808 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7809 /*bool RecordPaths=*/false,
7810 /*bool DetectVirtual=*/false);
7811 FindHiddenVirtualMethod FHVM;
7815 // Keep the base methods that were overridden or introduced in the subclass
7816 // by 'using' in a set. A base method not in this set is hidden.
7817 CXXRecordDecl *DC = MD->getParent();
7818 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7819 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7821 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7822 ND = shad->getTargetDecl();
7823 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7824 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7827 if (DC->lookupInBases(FHVM, Paths))
7828 OverloadedMethods = FHVM.OverloadedMethods;
7831 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7832 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7833 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7834 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7835 PartialDiagnostic PD = PDiag(
7836 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7837 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7838 Diag(overloadedMD->getLocation(), PD);
7842 /// Diagnose methods which overload virtual methods in a base class
7843 /// without overriding any.
7844 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7845 if (MD->isInvalidDecl())
7848 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7851 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7852 FindHiddenVirtualMethods(MD, OverloadedMethods);
7853 if (!OverloadedMethods.empty()) {
7854 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7855 << MD << (OverloadedMethods.size() > 1);
7857 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7861 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7862 auto PrintDiagAndRemoveAttr = [&]() {
7863 // No diagnostics if this is a template instantiation.
7864 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7865 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7866 diag::ext_cannot_use_trivial_abi) << &RD;
7867 RD.dropAttr<TrivialABIAttr>();
7870 // Ill-formed if the struct has virtual functions.
7871 if (RD.isPolymorphic()) {
7872 PrintDiagAndRemoveAttr();
7876 for (const auto &B : RD.bases()) {
7877 // Ill-formed if the base class is non-trivial for the purpose of calls or a
7879 if ((!B.getType()->isDependentType() &&
7880 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7882 PrintDiagAndRemoveAttr();
7887 for (const auto *FD : RD.fields()) {
7888 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7889 // non-trivial for the purpose of calls.
7890 QualType FT = FD->getType();
7891 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7892 PrintDiagAndRemoveAttr();
7896 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7897 if (!RT->isDependentType() &&
7898 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7899 PrintDiagAndRemoveAttr();
7905 void Sema::ActOnFinishCXXMemberSpecification(
7906 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7907 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7911 AdjustDeclIfTemplate(TagDecl);
7913 for (const ParsedAttr &AL : AttrList) {
7914 if (AL.getKind() != ParsedAttr::AT_Visibility)
7917 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7921 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7922 // strict aliasing violation!
7923 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7924 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7926 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7929 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7930 /// special functions, such as the default constructor, copy
7931 /// constructor, or destructor, to the given C++ class (C++
7932 /// [special]p1). This routine can only be executed just before the
7933 /// definition of the class is complete.
7934 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7935 if (ClassDecl->needsImplicitDefaultConstructor()) {
7936 ++ASTContext::NumImplicitDefaultConstructors;
7938 if (ClassDecl->hasInheritedConstructor())
7939 DeclareImplicitDefaultConstructor(ClassDecl);
7942 if (ClassDecl->needsImplicitCopyConstructor()) {
7943 ++ASTContext::NumImplicitCopyConstructors;
7945 // If the properties or semantics of the copy constructor couldn't be
7946 // determined while the class was being declared, force a declaration
7948 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7949 ClassDecl->hasInheritedConstructor())
7950 DeclareImplicitCopyConstructor(ClassDecl);
7951 // For the MS ABI we need to know whether the copy ctor is deleted. A
7952 // prerequisite for deleting the implicit copy ctor is that the class has a
7953 // move ctor or move assignment that is either user-declared or whose
7954 // semantics are inherited from a subobject. FIXME: We should provide a more
7955 // direct way for CodeGen to ask whether the constructor was deleted.
7956 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7957 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7958 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7959 ClassDecl->hasUserDeclaredMoveAssignment() ||
7960 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7961 DeclareImplicitCopyConstructor(ClassDecl);
7964 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7965 ++ASTContext::NumImplicitMoveConstructors;
7967 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7968 ClassDecl->hasInheritedConstructor())
7969 DeclareImplicitMoveConstructor(ClassDecl);
7972 if (ClassDecl->needsImplicitCopyAssignment()) {
7973 ++ASTContext::NumImplicitCopyAssignmentOperators;
7975 // If we have a dynamic class, then the copy assignment operator may be
7976 // virtual, so we have to declare it immediately. This ensures that, e.g.,
7977 // it shows up in the right place in the vtable and that we diagnose
7978 // problems with the implicit exception specification.
7979 if (ClassDecl->isDynamicClass() ||
7980 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7981 ClassDecl->hasInheritedAssignment())
7982 DeclareImplicitCopyAssignment(ClassDecl);
7985 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7986 ++ASTContext::NumImplicitMoveAssignmentOperators;
7988 // Likewise for the move assignment operator.
7989 if (ClassDecl->isDynamicClass() ||
7990 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7991 ClassDecl->hasInheritedAssignment())
7992 DeclareImplicitMoveAssignment(ClassDecl);
7995 if (ClassDecl->needsImplicitDestructor()) {
7996 ++ASTContext::NumImplicitDestructors;
7998 // If we have a dynamic class, then the destructor may be virtual, so we
7999 // have to declare the destructor immediately. This ensures that, e.g., it
8000 // shows up in the right place in the vtable and that we diagnose problems
8001 // with the implicit exception specification.
8002 if (ClassDecl->isDynamicClass() ||
8003 ClassDecl->needsOverloadResolutionForDestructor())
8004 DeclareImplicitDestructor(ClassDecl);
8008 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8012 // The order of template parameters is not important here. All names
8013 // get added to the same scope.
8014 SmallVector<TemplateParameterList *, 4> ParameterLists;
8016 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8017 D = TD->getTemplatedDecl();
8019 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8020 ParameterLists.push_back(PSD->getTemplateParameters());
8022 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8023 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8024 ParameterLists.push_back(DD->getTemplateParameterList(i));
8026 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8027 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8028 ParameterLists.push_back(FTD->getTemplateParameters());
8032 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8033 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8034 ParameterLists.push_back(TD->getTemplateParameterList(i));
8036 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8037 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8038 ParameterLists.push_back(CTD->getTemplateParameters());
8043 for (TemplateParameterList *Params : ParameterLists) {
8044 if (Params->size() > 0)
8045 // Ignore explicit specializations; they don't contribute to the template
8048 for (NamedDecl *Param : *Params) {
8049 if (Param->getDeclName()) {
8051 IdResolver.AddDecl(Param);
8059 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8060 if (!RecordD) return;
8061 AdjustDeclIfTemplate(RecordD);
8062 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8063 PushDeclContext(S, Record);
8066 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8067 if (!RecordD) return;
8071 /// This is used to implement the constant expression evaluation part of the
8072 /// attribute enable_if extension. There is nothing in standard C++ which would
8073 /// require reentering parameters.
8074 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8079 if (Param->getDeclName())
8080 IdResolver.AddDecl(Param);
8083 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8084 /// parsing a top-level (non-nested) C++ class, and we are now
8085 /// parsing those parts of the given Method declaration that could
8086 /// not be parsed earlier (C++ [class.mem]p2), such as default
8087 /// arguments. This action should enter the scope of the given
8088 /// Method declaration as if we had just parsed the qualified method
8089 /// name. However, it should not bring the parameters into scope;
8090 /// that will be performed by ActOnDelayedCXXMethodParameter.
8091 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8094 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8095 /// C++ method declaration. We're (re-)introducing the given
8096 /// function parameter into scope for use in parsing later parts of
8097 /// the method declaration. For example, we could see an
8098 /// ActOnParamDefaultArgument event for this parameter.
8099 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8103 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8105 // If this parameter has an unparsed default argument, clear it out
8106 // to make way for the parsed default argument.
8107 if (Param->hasUnparsedDefaultArg())
8108 Param->setDefaultArg(nullptr);
8111 if (Param->getDeclName())
8112 IdResolver.AddDecl(Param);
8115 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8116 /// processing the delayed method declaration for Method. The method
8117 /// declaration is now considered finished. There may be a separate
8118 /// ActOnStartOfFunctionDef action later (not necessarily
8119 /// immediately!) for this method, if it was also defined inside the
8121 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8125 AdjustDeclIfTemplate(MethodD);
8127 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8129 // Now that we have our default arguments, check the constructor
8130 // again. It could produce additional diagnostics or affect whether
8131 // the class has implicitly-declared destructors, among other
8133 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8134 CheckConstructor(Constructor);
8136 // Check the default arguments, which we may have added.
8137 if (!Method->isInvalidDecl())
8138 CheckCXXDefaultArguments(Method);
8141 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8142 /// the well-formedness of the constructor declarator @p D with type @p
8143 /// R. If there are any errors in the declarator, this routine will
8144 /// emit diagnostics and set the invalid bit to true. In any case, the type
8145 /// will be updated to reflect a well-formed type for the constructor and
8147 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8149 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8151 // C++ [class.ctor]p3:
8152 // A constructor shall not be virtual (10.3) or static (9.4). A
8153 // constructor can be invoked for a const, volatile or const
8154 // volatile object. A constructor shall not be declared const,
8155 // volatile, or const volatile (9.3.2).
8157 if (!D.isInvalidType())
8158 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8159 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8160 << SourceRange(D.getIdentifierLoc());
8163 if (SC == SC_Static) {
8164 if (!D.isInvalidType())
8165 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8166 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8167 << SourceRange(D.getIdentifierLoc());
8172 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8173 diagnoseIgnoredQualifiers(
8174 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8175 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8176 D.getDeclSpec().getRestrictSpecLoc(),
8177 D.getDeclSpec().getAtomicSpecLoc());
8181 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8182 if (FTI.hasMethodTypeQualifiers()) {
8183 FTI.MethodQualifiers->forEachQualifier(
8184 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8185 Diag(SL, diag::err_invalid_qualified_constructor)
8186 << QualName << SourceRange(SL);
8191 // C++0x [class.ctor]p4:
8192 // A constructor shall not be declared with a ref-qualifier.
8193 if (FTI.hasRefQualifier()) {
8194 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8195 << FTI.RefQualifierIsLValueRef
8196 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8200 // Rebuild the function type "R" without any type qualifiers (in
8201 // case any of the errors above fired) and with "void" as the
8202 // return type, since constructors don't have return types.
8203 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8204 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8207 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8208 EPI.TypeQuals = Qualifiers();
8209 EPI.RefQualifier = RQ_None;
8211 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8214 /// CheckConstructor - Checks a fully-formed constructor for
8215 /// well-formedness, issuing any diagnostics required. Returns true if
8216 /// the constructor declarator is invalid.
8217 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8218 CXXRecordDecl *ClassDecl
8219 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8221 return Constructor->setInvalidDecl();
8223 // C++ [class.copy]p3:
8224 // A declaration of a constructor for a class X is ill-formed if
8225 // its first parameter is of type (optionally cv-qualified) X and
8226 // either there are no other parameters or else all other
8227 // parameters have default arguments.
8228 if (!Constructor->isInvalidDecl() &&
8229 ((Constructor->getNumParams() == 1) ||
8230 (Constructor->getNumParams() > 1 &&
8231 Constructor->getParamDecl(1)->hasDefaultArg())) &&
8232 Constructor->getTemplateSpecializationKind()
8233 != TSK_ImplicitInstantiation) {
8234 QualType ParamType = Constructor->getParamDecl(0)->getType();
8235 QualType ClassTy = Context.getTagDeclType(ClassDecl);
8236 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8237 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8238 const char *ConstRef
8239 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8241 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8242 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8244 // FIXME: Rather that making the constructor invalid, we should endeavor
8246 Constructor->setInvalidDecl();
8251 /// CheckDestructor - Checks a fully-formed destructor definition for
8252 /// well-formedness, issuing any diagnostics required. Returns true
8254 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8255 CXXRecordDecl *RD = Destructor->getParent();
8257 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8260 if (!Destructor->isImplicit())
8261 Loc = Destructor->getLocation();
8263 Loc = RD->getLocation();
8265 // If we have a virtual destructor, look up the deallocation function
8266 if (FunctionDecl *OperatorDelete =
8267 FindDeallocationFunctionForDestructor(Loc, RD)) {
8268 Expr *ThisArg = nullptr;
8270 // If the notional 'delete this' expression requires a non-trivial
8271 // conversion from 'this' to the type of a destroying operator delete's
8272 // first parameter, perform that conversion now.
8273 if (OperatorDelete->isDestroyingOperatorDelete()) {
8274 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8275 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8276 // C++ [class.dtor]p13:
8277 // ... as if for the expression 'delete this' appearing in a
8278 // non-virtual destructor of the destructor's class.
8279 ContextRAII SwitchContext(*this, Destructor);
8281 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8282 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8283 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8284 if (This.isInvalid()) {
8285 // FIXME: Register this as a context note so that it comes out
8286 // in the right order.
8287 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8290 ThisArg = This.get();
8294 DiagnoseUseOfDecl(OperatorDelete, Loc);
8295 MarkFunctionReferenced(Loc, OperatorDelete);
8296 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8303 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8304 /// the well-formednes of the destructor declarator @p D with type @p
8305 /// R. If there are any errors in the declarator, this routine will
8306 /// emit diagnostics and set the declarator to invalid. Even if this happens,
8307 /// will be updated to reflect a well-formed type for the destructor and
8309 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8311 // C++ [class.dtor]p1:
8312 // [...] A typedef-name that names a class is a class-name
8313 // (7.1.3); however, a typedef-name that names a class shall not
8314 // be used as the identifier in the declarator for a destructor
8316 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8317 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8318 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8319 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8320 else if (const TemplateSpecializationType *TST =
8321 DeclaratorType->getAs<TemplateSpecializationType>())
8322 if (TST->isTypeAlias())
8323 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8324 << DeclaratorType << 1;
8326 // C++ [class.dtor]p2:
8327 // A destructor is used to destroy objects of its class type. A
8328 // destructor takes no parameters, and no return type can be
8329 // specified for it (not even void). The address of a destructor
8330 // shall not be taken. A destructor shall not be static. A
8331 // destructor can be invoked for a const, volatile or const
8332 // volatile object. A destructor shall not be declared const,
8333 // volatile or const volatile (9.3.2).
8334 if (SC == SC_Static) {
8335 if (!D.isInvalidType())
8336 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8337 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8338 << SourceRange(D.getIdentifierLoc())
8339 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8343 if (!D.isInvalidType()) {
8344 // Destructors don't have return types, but the parser will
8345 // happily parse something like:
8351 // The return type will be eliminated later.
8352 if (D.getDeclSpec().hasTypeSpecifier())
8353 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8354 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8355 << SourceRange(D.getIdentifierLoc());
8356 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8357 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8359 D.getDeclSpec().getConstSpecLoc(),
8360 D.getDeclSpec().getVolatileSpecLoc(),
8361 D.getDeclSpec().getRestrictSpecLoc(),
8362 D.getDeclSpec().getAtomicSpecLoc());
8367 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8368 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8369 FTI.MethodQualifiers->forEachQualifier(
8370 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8371 Diag(SL, diag::err_invalid_qualified_destructor)
8372 << QualName << SourceRange(SL);
8377 // C++0x [class.dtor]p2:
8378 // A destructor shall not be declared with a ref-qualifier.
8379 if (FTI.hasRefQualifier()) {
8380 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8381 << FTI.RefQualifierIsLValueRef
8382 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8386 // Make sure we don't have any parameters.
8387 if (FTIHasNonVoidParameters(FTI)) {
8388 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8390 // Delete the parameters.
8395 // Make sure the destructor isn't variadic.
8396 if (FTI.isVariadic) {
8397 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8401 // Rebuild the function type "R" without any type qualifiers or
8402 // parameters (in case any of the errors above fired) and with
8403 // "void" as the return type, since destructors don't have return
8405 if (!D.isInvalidType())
8408 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8409 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8410 EPI.Variadic = false;
8411 EPI.TypeQuals = Qualifiers();
8412 EPI.RefQualifier = RQ_None;
8413 return Context.getFunctionType(Context.VoidTy, None, EPI);
8416 static void extendLeft(SourceRange &R, SourceRange Before) {
8417 if (Before.isInvalid())
8419 R.setBegin(Before.getBegin());
8420 if (R.getEnd().isInvalid())
8421 R.setEnd(Before.getEnd());
8424 static void extendRight(SourceRange &R, SourceRange After) {
8425 if (After.isInvalid())
8427 if (R.getBegin().isInvalid())
8428 R.setBegin(After.getBegin());
8429 R.setEnd(After.getEnd());
8432 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8433 /// well-formednes of the conversion function declarator @p D with
8434 /// type @p R. If there are any errors in the declarator, this routine
8435 /// will emit diagnostics and return true. Otherwise, it will return
8436 /// false. Either way, the type @p R will be updated to reflect a
8437 /// well-formed type for the conversion operator.
8438 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8440 // C++ [class.conv.fct]p1:
8441 // Neither parameter types nor return type can be specified. The
8442 // type of a conversion function (8.3.5) is "function taking no
8443 // parameter returning conversion-type-id."
8444 if (SC == SC_Static) {
8445 if (!D.isInvalidType())
8446 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8447 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8448 << D.getName().getSourceRange();
8453 TypeSourceInfo *ConvTSI = nullptr;
8455 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8457 const DeclSpec &DS = D.getDeclSpec();
8458 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8459 // Conversion functions don't have return types, but the parser will
8460 // happily parse something like:
8463 // float operator bool();
8466 // The return type will be changed later anyway.
8467 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8468 << SourceRange(DS.getTypeSpecTypeLoc())
8469 << SourceRange(D.getIdentifierLoc());
8471 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8472 // It's also plausible that the user writes type qualifiers in the wrong
8474 // struct S { const operator int(); };
8475 // FIXME: we could provide a fixit to move the qualifiers onto the
8477 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8478 << SourceRange(D.getIdentifierLoc()) << 0;
8482 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8484 // Make sure we don't have any parameters.
8485 if (Proto->getNumParams() > 0) {
8486 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8488 // Delete the parameters.
8489 D.getFunctionTypeInfo().freeParams();
8491 } else if (Proto->isVariadic()) {
8492 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8496 // Diagnose "&operator bool()" and other such nonsense. This
8497 // is actually a gcc extension which we don't support.
8498 if (Proto->getReturnType() != ConvType) {
8499 bool NeedsTypedef = false;
8500 SourceRange Before, After;
8502 // Walk the chunks and extract information on them for our diagnostic.
8503 bool PastFunctionChunk = false;
8504 for (auto &Chunk : D.type_objects()) {
8505 switch (Chunk.Kind) {
8506 case DeclaratorChunk::Function:
8507 if (!PastFunctionChunk) {
8508 if (Chunk.Fun.HasTrailingReturnType) {
8509 TypeSourceInfo *TRT = nullptr;
8510 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8511 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8513 PastFunctionChunk = true;
8517 case DeclaratorChunk::Array:
8518 NeedsTypedef = true;
8519 extendRight(After, Chunk.getSourceRange());
8522 case DeclaratorChunk::Pointer:
8523 case DeclaratorChunk::BlockPointer:
8524 case DeclaratorChunk::Reference:
8525 case DeclaratorChunk::MemberPointer:
8526 case DeclaratorChunk::Pipe:
8527 extendLeft(Before, Chunk.getSourceRange());
8530 case DeclaratorChunk::Paren:
8531 extendLeft(Before, Chunk.Loc);
8532 extendRight(After, Chunk.EndLoc);
8537 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8538 After.isValid() ? After.getBegin() :
8539 D.getIdentifierLoc();
8540 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8541 DB << Before << After;
8543 if (!NeedsTypedef) {
8544 DB << /*don't need a typedef*/0;
8546 // If we can provide a correct fix-it hint, do so.
8547 if (After.isInvalid() && ConvTSI) {
8548 SourceLocation InsertLoc =
8549 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8550 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8551 << FixItHint::CreateInsertionFromRange(
8552 InsertLoc, CharSourceRange::getTokenRange(Before))
8553 << FixItHint::CreateRemoval(Before);
8555 } else if (!Proto->getReturnType()->isDependentType()) {
8556 DB << /*typedef*/1 << Proto->getReturnType();
8557 } else if (getLangOpts().CPlusPlus11) {
8558 DB << /*alias template*/2 << Proto->getReturnType();
8560 DB << /*might not be fixable*/3;
8563 // Recover by incorporating the other type chunks into the result type.
8564 // Note, this does *not* change the name of the function. This is compatible
8565 // with the GCC extension:
8566 // struct S { &operator int(); } s;
8567 // int &r = s.operator int(); // ok in GCC
8568 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8569 ConvType = Proto->getReturnType();
8572 // C++ [class.conv.fct]p4:
8573 // The conversion-type-id shall not represent a function type nor
8575 if (ConvType->isArrayType()) {
8576 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8577 ConvType = Context.getPointerType(ConvType);
8579 } else if (ConvType->isFunctionType()) {
8580 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8581 ConvType = Context.getPointerType(ConvType);
8585 // Rebuild the function type "R" without any parameters (in case any
8586 // of the errors above fired) and with the conversion type as the
8588 if (D.isInvalidType())
8589 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8591 // C++0x explicit conversion operators.
8592 if (DS.isExplicitSpecified())
8593 Diag(DS.getExplicitSpecLoc(),
8594 getLangOpts().CPlusPlus11
8595 ? diag::warn_cxx98_compat_explicit_conversion_functions
8596 : diag::ext_explicit_conversion_functions)
8597 << SourceRange(DS.getExplicitSpecLoc());
8600 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8601 /// the declaration of the given C++ conversion function. This routine
8602 /// is responsible for recording the conversion function in the C++
8603 /// class, if possible.
8604 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8605 assert(Conversion && "Expected to receive a conversion function declaration");
8607 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8609 // Make sure we aren't redeclaring the conversion function.
8610 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8612 // C++ [class.conv.fct]p1:
8613 // [...] A conversion function is never used to convert a
8614 // (possibly cv-qualified) object to the (possibly cv-qualified)
8615 // same object type (or a reference to it), to a (possibly
8616 // cv-qualified) base class of that type (or a reference to it),
8617 // or to (possibly cv-qualified) void.
8618 // FIXME: Suppress this warning if the conversion function ends up being a
8619 // virtual function that overrides a virtual function in a base class.
8621 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8622 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8623 ConvType = ConvTypeRef->getPointeeType();
8624 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8625 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8626 /* Suppress diagnostics for instantiations. */;
8627 else if (ConvType->isRecordType()) {
8628 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8629 if (ConvType == ClassType)
8630 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8632 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8633 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8634 << ClassType << ConvType;
8635 } else if (ConvType->isVoidType()) {
8636 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8637 << ClassType << ConvType;
8640 if (FunctionTemplateDecl *ConversionTemplate
8641 = Conversion->getDescribedFunctionTemplate())
8642 return ConversionTemplate;
8648 /// Utility class to accumulate and print a diagnostic listing the invalid
8649 /// specifier(s) on a declaration.
8650 struct BadSpecifierDiagnoser {
8651 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8652 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8653 ~BadSpecifierDiagnoser() {
8654 Diagnostic << Specifiers;
8657 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8658 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8660 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8661 return check(SpecLoc,
8662 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8664 void check(SourceLocation SpecLoc, const char *Spec) {
8665 if (SpecLoc.isInvalid()) return;
8666 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8667 if (!Specifiers.empty()) Specifiers += " ";
8672 Sema::SemaDiagnosticBuilder Diagnostic;
8673 std::string Specifiers;
8677 /// Check the validity of a declarator that we parsed for a deduction-guide.
8678 /// These aren't actually declarators in the grammar, so we need to check that
8679 /// the user didn't specify any pieces that are not part of the deduction-guide
8681 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8683 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8684 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8685 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8687 // C++ [temp.deduct.guide]p3:
8688 // A deduction-gide shall be declared in the same scope as the
8689 // corresponding class template.
8690 if (!CurContext->getRedeclContext()->Equals(
8691 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8692 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8693 << GuidedTemplateDecl;
8694 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8697 auto &DS = D.getMutableDeclSpec();
8698 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8699 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8700 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8701 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8702 BadSpecifierDiagnoser Diagnoser(
8703 *this, D.getIdentifierLoc(),
8704 diag::err_deduction_guide_invalid_specifier);
8706 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8707 DS.ClearStorageClassSpecs();
8710 // 'explicit' is permitted.
8711 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8712 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8713 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8714 DS.ClearConstexprSpec();
8716 Diagnoser.check(DS.getConstSpecLoc(), "const");
8717 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8718 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8719 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8720 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8721 DS.ClearTypeQualifiers();
8723 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8724 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8725 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8726 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8727 DS.ClearTypeSpecType();
8730 if (D.isInvalidType())
8733 // Check the declarator is simple enough.
8734 bool FoundFunction = false;
8735 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8736 if (Chunk.Kind == DeclaratorChunk::Paren)
8738 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8739 Diag(D.getDeclSpec().getBeginLoc(),
8740 diag::err_deduction_guide_with_complex_decl)
8741 << D.getSourceRange();
8744 if (!Chunk.Fun.hasTrailingReturnType()) {
8745 Diag(D.getName().getBeginLoc(),
8746 diag::err_deduction_guide_no_trailing_return_type);
8750 // Check that the return type is written as a specialization of
8751 // the template specified as the deduction-guide's name.
8752 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8753 TypeSourceInfo *TSI = nullptr;
8754 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8755 assert(TSI && "deduction guide has valid type but invalid return type?");
8756 bool AcceptableReturnType = false;
8757 bool MightInstantiateToSpecialization = false;
8759 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8760 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8761 bool TemplateMatches =
8762 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8763 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8764 AcceptableReturnType = true;
8766 // This could still instantiate to the right type, unless we know it
8767 // names the wrong class template.
8768 auto *TD = SpecifiedName.getAsTemplateDecl();
8769 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8772 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8773 MightInstantiateToSpecialization = true;
8776 if (!AcceptableReturnType) {
8777 Diag(TSI->getTypeLoc().getBeginLoc(),
8778 diag::err_deduction_guide_bad_trailing_return_type)
8779 << GuidedTemplate << TSI->getType()
8780 << MightInstantiateToSpecialization
8781 << TSI->getTypeLoc().getSourceRange();
8784 // Keep going to check that we don't have any inner declarator pieces (we
8785 // could still have a function returning a pointer to a function).
8786 FoundFunction = true;
8789 if (D.isFunctionDefinition())
8790 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8793 //===----------------------------------------------------------------------===//
8794 // Namespace Handling
8795 //===----------------------------------------------------------------------===//
8797 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8799 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8801 IdentifierInfo *II, bool *IsInline,
8802 NamespaceDecl *PrevNS) {
8803 assert(*IsInline != PrevNS->isInline());
8805 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8806 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8807 // inline namespaces, with the intention of bringing names into namespace std.
8809 // We support this just well enough to get that case working; this is not
8810 // sufficient to support reopening namespaces as inline in general.
8811 if (*IsInline && II && II->getName().startswith("__atomic") &&
8812 S.getSourceManager().isInSystemHeader(Loc)) {
8813 // Mark all prior declarations of the namespace as inline.
8814 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8815 NS = NS->getPreviousDecl())
8816 NS->setInline(*IsInline);
8817 // Patch up the lookup table for the containing namespace. This isn't really
8818 // correct, but it's good enough for this particular case.
8819 for (auto *I : PrevNS->decls())
8820 if (auto *ND = dyn_cast<NamedDecl>(I))
8821 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8825 if (PrevNS->isInline())
8826 // The user probably just forgot the 'inline', so suggest that it
8828 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8829 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8831 S.Diag(Loc, diag::err_inline_namespace_mismatch);
8833 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8834 *IsInline = PrevNS->isInline();
8837 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8839 Decl *Sema::ActOnStartNamespaceDef(
8840 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8841 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8842 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8843 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8844 // For anonymous namespace, take the location of the left brace.
8845 SourceLocation Loc = II ? IdentLoc : LBrace;
8846 bool IsInline = InlineLoc.isValid();
8847 bool IsInvalid = false;
8849 bool AddToKnown = false;
8850 Scope *DeclRegionScope = NamespcScope->getParent();
8852 NamespaceDecl *PrevNS = nullptr;
8854 // C++ [namespace.def]p2:
8855 // The identifier in an original-namespace-definition shall not
8856 // have been previously defined in the declarative region in
8857 // which the original-namespace-definition appears. The
8858 // identifier in an original-namespace-definition is the name of
8859 // the namespace. Subsequently in that declarative region, it is
8860 // treated as an original-namespace-name.
8862 // Since namespace names are unique in their scope, and we don't
8863 // look through using directives, just look for any ordinary names
8864 // as if by qualified name lookup.
8865 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8866 ForExternalRedeclaration);
8867 LookupQualifiedName(R, CurContext->getRedeclContext());
8868 NamedDecl *PrevDecl =
8869 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8870 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8873 // This is an extended namespace definition.
8874 if (IsInline != PrevNS->isInline())
8875 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8877 } else if (PrevDecl) {
8878 // This is an invalid name redefinition.
8879 Diag(Loc, diag::err_redefinition_different_kind)
8881 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8883 // Continue on to push Namespc as current DeclContext and return it.
8884 } else if (II->isStr("std") &&
8885 CurContext->getRedeclContext()->isTranslationUnit()) {
8886 // This is the first "real" definition of the namespace "std", so update
8887 // our cache of the "std" namespace to point at this definition.
8888 PrevNS = getStdNamespace();
8890 AddToKnown = !IsInline;
8892 // We've seen this namespace for the first time.
8893 AddToKnown = !IsInline;
8896 // Anonymous namespaces.
8898 // Determine whether the parent already has an anonymous namespace.
8899 DeclContext *Parent = CurContext->getRedeclContext();
8900 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8901 PrevNS = TU->getAnonymousNamespace();
8903 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8904 PrevNS = ND->getAnonymousNamespace();
8907 if (PrevNS && IsInline != PrevNS->isInline())
8908 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8912 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8913 StartLoc, Loc, II, PrevNS);
8915 Namespc->setInvalidDecl();
8917 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8918 AddPragmaAttributes(DeclRegionScope, Namespc);
8920 // FIXME: Should we be merging attributes?
8921 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8922 PushNamespaceVisibilityAttr(Attr, Loc);
8925 StdNamespace = Namespc;
8927 KnownNamespaces[Namespc] = false;
8930 PushOnScopeChains(Namespc, DeclRegionScope);
8932 // Link the anonymous namespace into its parent.
8933 DeclContext *Parent = CurContext->getRedeclContext();
8934 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8935 TU->setAnonymousNamespace(Namespc);
8937 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8940 CurContext->addDecl(Namespc);
8942 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8943 // behaves as if it were replaced by
8944 // namespace unique { /* empty body */ }
8945 // using namespace unique;
8946 // namespace unique { namespace-body }
8947 // where all occurrences of 'unique' in a translation unit are
8948 // replaced by the same identifier and this identifier differs
8949 // from all other identifiers in the entire program.
8951 // We just create the namespace with an empty name and then add an
8952 // implicit using declaration, just like the standard suggests.
8954 // CodeGen enforces the "universally unique" aspect by giving all
8955 // declarations semantically contained within an anonymous
8956 // namespace internal linkage.
8959 UD = UsingDirectiveDecl::Create(Context, Parent,
8960 /* 'using' */ LBrace,
8961 /* 'namespace' */ SourceLocation(),
8962 /* qualifier */ NestedNameSpecifierLoc(),
8963 /* identifier */ SourceLocation(),
8965 /* Ancestor */ Parent);
8967 Parent->addDecl(UD);
8971 ActOnDocumentableDecl(Namespc);
8973 // Although we could have an invalid decl (i.e. the namespace name is a
8974 // redefinition), push it as current DeclContext and try to continue parsing.
8975 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8976 // for the namespace has the declarations that showed up in that particular
8977 // namespace definition.
8978 PushDeclContext(NamespcScope, Namespc);
8982 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8983 /// is a namespace alias, returns the namespace it points to.
8984 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8985 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8986 return AD->getNamespace();
8987 return dyn_cast_or_null<NamespaceDecl>(D);
8990 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8991 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8992 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8993 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8994 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8995 Namespc->setRBraceLoc(RBrace);
8997 if (Namespc->hasAttr<VisibilityAttr>())
8998 PopPragmaVisibility(true, RBrace);
9001 CXXRecordDecl *Sema::getStdBadAlloc() const {
9002 return cast_or_null<CXXRecordDecl>(
9003 StdBadAlloc.get(Context.getExternalSource()));
9006 EnumDecl *Sema::getStdAlignValT() const {
9007 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9010 NamespaceDecl *Sema::getStdNamespace() const {
9011 return cast_or_null<NamespaceDecl>(
9012 StdNamespace.get(Context.getExternalSource()));
9015 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9016 if (!StdExperimentalNamespaceCache) {
9017 if (auto Std = getStdNamespace()) {
9018 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9019 SourceLocation(), LookupNamespaceName);
9020 if (!LookupQualifiedName(Result, Std) ||
9021 !(StdExperimentalNamespaceCache =
9022 Result.getAsSingle<NamespaceDecl>()))
9023 Result.suppressDiagnostics();
9026 return StdExperimentalNamespaceCache;
9031 enum UnsupportedSTLSelect {
9038 struct InvalidSTLDiagnoser {
9041 QualType TyForDiags;
9043 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9044 const VarDecl *VD = nullptr) {
9046 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9047 << TyForDiags << ((int)Sel);
9048 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9049 assert(!Name.empty());
9053 if (Sel == USS_InvalidMember) {
9054 S.Diag(VD->getLocation(), diag::note_var_declared_here)
9055 << VD << VD->getSourceRange();
9062 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9063 SourceLocation Loc) {
9064 assert(getLangOpts().CPlusPlus &&
9065 "Looking for comparison category type outside of C++.");
9067 // Check if we've already successfully checked the comparison category type
9068 // before. If so, skip checking it again.
9069 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9070 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9071 return Info->getType();
9075 std::string NameForDiags = "std::";
9076 NameForDiags += ComparisonCategories::getCategoryString(Kind);
9077 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9082 assert(Info->Kind == Kind);
9083 assert(Info->Record);
9085 // Update the Record decl in case we encountered a forward declaration on our
9086 // first pass. FIXME: This is a bit of a hack.
9087 if (Info->Record->hasDefinition())
9088 Info->Record = Info->Record->getDefinition();
9090 // Use an elaborated type for diagnostics which has a name containing the
9091 // prepended 'std' namespace but not any inline namespace names.
9092 QualType TyForDiags = [&]() {
9094 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9095 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9098 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9101 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9103 if (!Info->Record->isTriviallyCopyable())
9104 return UnsupportedSTLError(USS_NonTrivial);
9106 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9107 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9108 // Tolerate empty base classes.
9109 if (Base->isEmpty())
9111 // Reject STL implementations which have at least one non-empty base.
9112 return UnsupportedSTLError();
9115 // Check that the STL has implemented the types using a single integer field.
9116 // This expectation allows better codegen for builtin operators. We require:
9117 // (1) The class has exactly one field.
9118 // (2) The field is an integral or enumeration type.
9119 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9120 if (std::distance(FIt, FEnd) != 1 ||
9121 !FIt->getType()->isIntegralOrEnumerationType()) {
9122 return UnsupportedSTLError();
9125 // Build each of the require values and store them in Info.
9126 for (ComparisonCategoryResult CCR :
9127 ComparisonCategories::getPossibleResultsForType(Kind)) {
9128 StringRef MemName = ComparisonCategories::getResultString(CCR);
9129 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9132 return UnsupportedSTLError(USS_MissingMember, MemName);
9134 VarDecl *VD = ValInfo->VD;
9135 assert(VD && "should not be null!");
9137 // Attempt to diagnose reasons why the STL definition of this type
9138 // might be foobar, including it failing to be a constant expression.
9139 // TODO Handle more ways the lookup or result can be invalid.
9140 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9141 !VD->checkInitIsICE())
9142 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9144 // Attempt to evaluate the var decl as a constant expression and extract
9145 // the value of its first field as a ICE. If this fails, the STL
9146 // implementation is not supported.
9147 if (!ValInfo->hasValidIntValue())
9148 return UnsupportedSTLError();
9150 MarkVariableReferenced(Loc, VD);
9153 // We've successfully built the required types and expressions. Update
9154 // the cache and return the newly cached value.
9155 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9156 return Info->getType();
9159 /// Retrieve the special "std" namespace, which may require us to
9160 /// implicitly define the namespace.
9161 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9162 if (!StdNamespace) {
9163 // The "std" namespace has not yet been defined, so build one implicitly.
9164 StdNamespace = NamespaceDecl::Create(Context,
9165 Context.getTranslationUnitDecl(),
9167 SourceLocation(), SourceLocation(),
9168 &PP.getIdentifierTable().get("std"),
9169 /*PrevDecl=*/nullptr);
9170 getStdNamespace()->setImplicit(true);
9173 return getStdNamespace();
9176 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9177 assert(getLangOpts().CPlusPlus &&
9178 "Looking for std::initializer_list outside of C++.");
9180 // We're looking for implicit instantiations of
9181 // template <typename E> class std::initializer_list.
9183 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9186 ClassTemplateDecl *Template = nullptr;
9187 const TemplateArgument *Arguments = nullptr;
9189 if (const RecordType *RT = Ty->getAs<RecordType>()) {
9191 ClassTemplateSpecializationDecl *Specialization =
9192 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9193 if (!Specialization)
9196 Template = Specialization->getSpecializedTemplate();
9197 Arguments = Specialization->getTemplateArgs().data();
9198 } else if (const TemplateSpecializationType *TST =
9199 Ty->getAs<TemplateSpecializationType>()) {
9200 Template = dyn_cast_or_null<ClassTemplateDecl>(
9201 TST->getTemplateName().getAsTemplateDecl());
9202 Arguments = TST->getArgs();
9207 if (!StdInitializerList) {
9208 // Haven't recognized std::initializer_list yet, maybe this is it.
9209 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9210 if (TemplateClass->getIdentifier() !=
9211 &PP.getIdentifierTable().get("initializer_list") ||
9212 !getStdNamespace()->InEnclosingNamespaceSetOf(
9213 TemplateClass->getDeclContext()))
9215 // This is a template called std::initializer_list, but is it the right
9217 TemplateParameterList *Params = Template->getTemplateParameters();
9218 if (Params->getMinRequiredArguments() != 1)
9220 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9223 // It's the right template.
9224 StdInitializerList = Template;
9227 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9230 // This is an instance of std::initializer_list. Find the argument type.
9232 *Element = Arguments[0].getAsType();
9236 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9237 NamespaceDecl *Std = S.getStdNamespace();
9239 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9243 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9244 Loc, Sema::LookupOrdinaryName);
9245 if (!S.LookupQualifiedName(Result, Std)) {
9246 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9249 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9251 Result.suppressDiagnostics();
9252 // We found something weird. Complain about the first thing we found.
9253 NamedDecl *Found = *Result.begin();
9254 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9258 // We found some template called std::initializer_list. Now verify that it's
9260 TemplateParameterList *Params = Template->getTemplateParameters();
9261 if (Params->getMinRequiredArguments() != 1 ||
9262 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9263 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9270 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9271 if (!StdInitializerList) {
9272 StdInitializerList = LookupStdInitializerList(*this, Loc);
9273 if (!StdInitializerList)
9277 TemplateArgumentListInfo Args(Loc, Loc);
9278 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9279 Context.getTrivialTypeSourceInfo(Element,
9281 return Context.getCanonicalType(
9282 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9285 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9286 // C++ [dcl.init.list]p2:
9287 // A constructor is an initializer-list constructor if its first parameter
9288 // is of type std::initializer_list<E> or reference to possibly cv-qualified
9289 // std::initializer_list<E> for some type E, and either there are no other
9290 // parameters or else all other parameters have default arguments.
9291 if (Ctor->getNumParams() < 1 ||
9292 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9295 QualType ArgType = Ctor->getParamDecl(0)->getType();
9296 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9297 ArgType = RT->getPointeeType().getUnqualifiedType();
9299 return isStdInitializerList(ArgType, nullptr);
9302 /// Determine whether a using statement is in a context where it will be
9303 /// apply in all contexts.
9304 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9305 switch (CurContext->getDeclKind()) {
9306 case Decl::TranslationUnit:
9308 case Decl::LinkageSpec:
9309 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9317 // Callback to only accept typo corrections that are namespaces.
9318 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9320 bool ValidateCandidate(const TypoCorrection &candidate) override {
9321 if (NamedDecl *ND = candidate.getCorrectionDecl())
9322 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9329 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9331 SourceLocation IdentLoc,
9332 IdentifierInfo *Ident) {
9334 if (TypoCorrection Corrected =
9335 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9336 llvm::make_unique<NamespaceValidatorCCC>(),
9337 Sema::CTK_ErrorRecovery)) {
9338 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9339 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9340 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9341 Ident->getName().equals(CorrectedStr);
9342 S.diagnoseTypo(Corrected,
9343 S.PDiag(diag::err_using_directive_member_suggest)
9344 << Ident << DC << DroppedSpecifier << SS.getRange(),
9345 S.PDiag(diag::note_namespace_defined_here));
9347 S.diagnoseTypo(Corrected,
9348 S.PDiag(diag::err_using_directive_suggest) << Ident,
9349 S.PDiag(diag::note_namespace_defined_here));
9351 R.addDecl(Corrected.getFoundDecl());
9357 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9358 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9359 SourceLocation IdentLoc,
9360 IdentifierInfo *NamespcName,
9361 const ParsedAttributesView &AttrList) {
9362 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9363 assert(NamespcName && "Invalid NamespcName.");
9364 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9366 // This can only happen along a recovery path.
9367 while (S->isTemplateParamScope())
9369 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9371 UsingDirectiveDecl *UDir = nullptr;
9372 NestedNameSpecifier *Qualifier = nullptr;
9374 Qualifier = SS.getScopeRep();
9376 // Lookup namespace name.
9377 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9378 LookupParsedName(R, S, &SS);
9379 if (R.isAmbiguous())
9384 // Allow "using namespace std;" or "using namespace ::std;" even if
9385 // "std" hasn't been defined yet, for GCC compatibility.
9386 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9387 NamespcName->isStr("std")) {
9388 Diag(IdentLoc, diag::ext_using_undefined_std);
9389 R.addDecl(getOrCreateStdNamespace());
9392 // Otherwise, attempt typo correction.
9393 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9397 NamedDecl *Named = R.getRepresentativeDecl();
9398 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9399 assert(NS && "expected namespace decl");
9401 // The use of a nested name specifier may trigger deprecation warnings.
9402 DiagnoseUseOfDecl(Named, IdentLoc);
9404 // C++ [namespace.udir]p1:
9405 // A using-directive specifies that the names in the nominated
9406 // namespace can be used in the scope in which the
9407 // using-directive appears after the using-directive. During
9408 // unqualified name lookup (3.4.1), the names appear as if they
9409 // were declared in the nearest enclosing namespace which
9410 // contains both the using-directive and the nominated
9411 // namespace. [Note: in this context, "contains" means "contains
9412 // directly or indirectly". ]
9414 // Find enclosing context containing both using-directive and
9415 // nominated namespace.
9416 DeclContext *CommonAncestor = NS;
9417 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9418 CommonAncestor = CommonAncestor->getParent();
9420 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9421 SS.getWithLocInContext(Context),
9422 IdentLoc, Named, CommonAncestor);
9424 if (IsUsingDirectiveInToplevelContext(CurContext) &&
9425 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9426 Diag(IdentLoc, diag::warn_using_directive_in_header);
9429 PushUsingDirective(S, UDir);
9431 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9435 ProcessDeclAttributeList(S, UDir, AttrList);
9440 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9441 // If the scope has an associated entity and the using directive is at
9442 // namespace or translation unit scope, add the UsingDirectiveDecl into
9443 // its lookup structure so qualified name lookup can find it.
9444 DeclContext *Ctx = S->getEntity();
9445 if (Ctx && !Ctx->isFunctionOrMethod())
9448 // Otherwise, it is at block scope. The using-directives will affect lookup
9449 // only to the end of the scope.
9450 S->PushUsingDirective(UDir);
9453 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9454 SourceLocation UsingLoc,
9455 SourceLocation TypenameLoc, CXXScopeSpec &SS,
9456 UnqualifiedId &Name,
9457 SourceLocation EllipsisLoc,
9458 const ParsedAttributesView &AttrList) {
9459 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9462 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9466 switch (Name.getKind()) {
9467 case UnqualifiedIdKind::IK_ImplicitSelfParam:
9468 case UnqualifiedIdKind::IK_Identifier:
9469 case UnqualifiedIdKind::IK_OperatorFunctionId:
9470 case UnqualifiedIdKind::IK_LiteralOperatorId:
9471 case UnqualifiedIdKind::IK_ConversionFunctionId:
9474 case UnqualifiedIdKind::IK_ConstructorName:
9475 case UnqualifiedIdKind::IK_ConstructorTemplateId:
9476 // C++11 inheriting constructors.
9477 Diag(Name.getBeginLoc(),
9478 getLangOpts().CPlusPlus11
9479 ? diag::warn_cxx98_compat_using_decl_constructor
9480 : diag::err_using_decl_constructor)
9483 if (getLangOpts().CPlusPlus11) break;
9487 case UnqualifiedIdKind::IK_DestructorName:
9488 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9491 case UnqualifiedIdKind::IK_TemplateId:
9492 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9493 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9496 case UnqualifiedIdKind::IK_DeductionGuideName:
9497 llvm_unreachable("cannot parse qualified deduction guide name");
9500 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9501 DeclarationName TargetName = TargetNameInfo.getName();
9505 // Warn about access declarations.
9506 if (UsingLoc.isInvalid()) {
9507 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9508 ? diag::err_access_decl
9509 : diag::warn_access_decl_deprecated)
9510 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9513 if (EllipsisLoc.isInvalid()) {
9514 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9515 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9518 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9519 !TargetNameInfo.containsUnexpandedParameterPack()) {
9520 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9521 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9522 EllipsisLoc = SourceLocation();
9527 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9528 SS, TargetNameInfo, EllipsisLoc, AttrList,
9529 /*IsInstantiation*/false);
9531 PushOnScopeChains(UD, S, /*AddToContext*/ false);
9536 /// Determine whether a using declaration considers the given
9537 /// declarations as "equivalent", e.g., if they are redeclarations of
9538 /// the same entity or are both typedefs of the same type.
9540 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9541 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9544 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9545 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9546 return Context.hasSameType(TD1->getUnderlyingType(),
9547 TD2->getUnderlyingType());
9553 /// Determines whether to create a using shadow decl for a particular
9554 /// decl, given the set of decls existing prior to this using lookup.
9555 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9556 const LookupResult &Previous,
9557 UsingShadowDecl *&PrevShadow) {
9558 // Diagnose finding a decl which is not from a base class of the
9559 // current class. We do this now because there are cases where this
9560 // function will silently decide not to build a shadow decl, which
9561 // will pre-empt further diagnostics.
9563 // We don't need to do this in C++11 because we do the check once on
9566 // FIXME: diagnose the following if we care enough:
9567 // struct A { int foo; };
9568 // struct B : A { using A::foo; };
9569 // template <class T> struct C : A {};
9570 // template <class T> struct D : C<T> { using B::foo; } // <---
9571 // This is invalid (during instantiation) in C++03 because B::foo
9572 // resolves to the using decl in B, which is not a base class of D<T>.
9573 // We can't diagnose it immediately because C<T> is an unknown
9574 // specialization. The UsingShadowDecl in D<T> then points directly
9575 // to A::foo, which will look well-formed when we instantiate.
9576 // The right solution is to not collapse the shadow-decl chain.
9577 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9578 DeclContext *OrigDC = Orig->getDeclContext();
9580 // Handle enums and anonymous structs.
9581 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9582 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9583 while (OrigRec->isAnonymousStructOrUnion())
9584 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9586 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9587 if (OrigDC == CurContext) {
9588 Diag(Using->getLocation(),
9589 diag::err_using_decl_nested_name_specifier_is_current_class)
9590 << Using->getQualifierLoc().getSourceRange();
9591 Diag(Orig->getLocation(), diag::note_using_decl_target);
9592 Using->setInvalidDecl();
9596 Diag(Using->getQualifierLoc().getBeginLoc(),
9597 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9598 << Using->getQualifier()
9599 << cast<CXXRecordDecl>(CurContext)
9600 << Using->getQualifierLoc().getSourceRange();
9601 Diag(Orig->getLocation(), diag::note_using_decl_target);
9602 Using->setInvalidDecl();
9607 if (Previous.empty()) return false;
9609 NamedDecl *Target = Orig;
9610 if (isa<UsingShadowDecl>(Target))
9611 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9613 // If the target happens to be one of the previous declarations, we
9614 // don't have a conflict.
9616 // FIXME: but we might be increasing its access, in which case we
9617 // should redeclare it.
9618 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9619 bool FoundEquivalentDecl = false;
9620 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9622 NamedDecl *D = (*I)->getUnderlyingDecl();
9623 // We can have UsingDecls in our Previous results because we use the same
9624 // LookupResult for checking whether the UsingDecl itself is a valid
9626 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9629 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9630 // C++ [class.mem]p19:
9631 // If T is the name of a class, then [every named member other than
9632 // a non-static data member] shall have a name different from T
9633 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9634 !isa<IndirectFieldDecl>(Target) &&
9635 !isa<UnresolvedUsingValueDecl>(Target) &&
9636 DiagnoseClassNameShadow(
9638 DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9642 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9643 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9644 PrevShadow = Shadow;
9645 FoundEquivalentDecl = true;
9646 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9647 // We don't conflict with an existing using shadow decl of an equivalent
9648 // declaration, but we're not a redeclaration of it.
9649 FoundEquivalentDecl = true;
9653 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9656 if (FoundEquivalentDecl)
9659 if (FunctionDecl *FD = Target->getAsFunction()) {
9660 NamedDecl *OldDecl = nullptr;
9661 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9662 /*IsForUsingDecl*/ true)) {
9666 case Ovl_NonFunction:
9667 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9670 // We found a decl with the exact signature.
9672 // If we're in a record, we want to hide the target, so we
9673 // return true (without a diagnostic) to tell the caller not to
9674 // build a shadow decl.
9675 if (CurContext->isRecord())
9678 // If we're not in a record, this is an error.
9679 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9683 Diag(Target->getLocation(), diag::note_using_decl_target);
9684 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9685 Using->setInvalidDecl();
9689 // Target is not a function.
9691 if (isa<TagDecl>(Target)) {
9692 // No conflict between a tag and a non-tag.
9693 if (!Tag) return false;
9695 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9696 Diag(Target->getLocation(), diag::note_using_decl_target);
9697 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9698 Using->setInvalidDecl();
9702 // No conflict between a tag and a non-tag.
9703 if (!NonTag) return false;
9705 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9706 Diag(Target->getLocation(), diag::note_using_decl_target);
9707 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9708 Using->setInvalidDecl();
9712 /// Determine whether a direct base class is a virtual base class.
9713 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9714 if (!Derived->getNumVBases())
9716 for (auto &B : Derived->bases())
9717 if (B.getType()->getAsCXXRecordDecl() == Base)
9718 return B.isVirtual();
9719 llvm_unreachable("not a direct base class");
9722 /// Builds a shadow declaration corresponding to a 'using' declaration.
9723 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9726 UsingShadowDecl *PrevDecl) {
9727 // If we resolved to another shadow declaration, just coalesce them.
9728 NamedDecl *Target = Orig;
9729 if (isa<UsingShadowDecl>(Target)) {
9730 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9731 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9734 NamedDecl *NonTemplateTarget = Target;
9735 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9736 NonTemplateTarget = TargetTD->getTemplatedDecl();
9738 UsingShadowDecl *Shadow;
9739 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9740 bool IsVirtualBase =
9741 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9742 UD->getQualifier()->getAsRecordDecl());
9743 Shadow = ConstructorUsingShadowDecl::Create(
9744 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9746 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9749 UD->addShadowDecl(Shadow);
9751 Shadow->setAccess(UD->getAccess());
9752 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9753 Shadow->setInvalidDecl();
9755 Shadow->setPreviousDecl(PrevDecl);
9758 PushOnScopeChains(Shadow, S);
9760 CurContext->addDecl(Shadow);
9766 /// Hides a using shadow declaration. This is required by the current
9767 /// using-decl implementation when a resolvable using declaration in a
9768 /// class is followed by a declaration which would hide or override
9769 /// one or more of the using decl's targets; for example:
9771 /// struct Base { void foo(int); };
9772 /// struct Derived : Base {
9773 /// using Base::foo;
9777 /// The governing language is C++03 [namespace.udecl]p12:
9779 /// When a using-declaration brings names from a base class into a
9780 /// derived class scope, member functions in the derived class
9781 /// override and/or hide member functions with the same name and
9782 /// parameter types in a base class (rather than conflicting).
9784 /// There are two ways to implement this:
9785 /// (1) optimistically create shadow decls when they're not hidden
9786 /// by existing declarations, or
9787 /// (2) don't create any shadow decls (or at least don't make them
9788 /// visible) until we've fully parsed/instantiated the class.
9789 /// The problem with (1) is that we might have to retroactively remove
9790 /// a shadow decl, which requires several O(n) operations because the
9791 /// decl structures are (very reasonably) not designed for removal.
9792 /// (2) avoids this but is very fiddly and phase-dependent.
9793 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9794 if (Shadow->getDeclName().getNameKind() ==
9795 DeclarationName::CXXConversionFunctionName)
9796 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9798 // Remove it from the DeclContext...
9799 Shadow->getDeclContext()->removeDecl(Shadow);
9801 // ...and the scope, if applicable...
9803 S->RemoveDecl(Shadow);
9804 IdResolver.RemoveDecl(Shadow);
9807 // ...and the using decl.
9808 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9810 // TODO: complain somehow if Shadow was used. It shouldn't
9811 // be possible for this to happen, because...?
9814 /// Find the base specifier for a base class with the given type.
9815 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9816 QualType DesiredBase,
9817 bool &AnyDependentBases) {
9818 // Check whether the named type is a direct base class.
9819 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9820 for (auto &Base : Derived->bases()) {
9821 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9822 if (CanonicalDesiredBase == BaseType)
9824 if (BaseType->isDependentType())
9825 AnyDependentBases = true;
9831 class UsingValidatorCCC : public CorrectionCandidateCallback {
9833 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9834 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9835 : HasTypenameKeyword(HasTypenameKeyword),
9836 IsInstantiation(IsInstantiation), OldNNS(NNS),
9837 RequireMemberOf(RequireMemberOf) {}
9839 bool ValidateCandidate(const TypoCorrection &Candidate) override {
9840 NamedDecl *ND = Candidate.getCorrectionDecl();
9842 // Keywords are not valid here.
9843 if (!ND || isa<NamespaceDecl>(ND))
9846 // Completely unqualified names are invalid for a 'using' declaration.
9847 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9850 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9853 if (RequireMemberOf) {
9854 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9855 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9856 // No-one ever wants a using-declaration to name an injected-class-name
9857 // of a base class, unless they're declaring an inheriting constructor.
9858 ASTContext &Ctx = ND->getASTContext();
9859 if (!Ctx.getLangOpts().CPlusPlus11)
9861 QualType FoundType = Ctx.getRecordType(FoundRecord);
9863 // Check that the injected-class-name is named as a member of its own
9864 // type; we don't want to suggest 'using Derived::Base;', since that
9865 // means something else.
9866 NestedNameSpecifier *Specifier =
9867 Candidate.WillReplaceSpecifier()
9868 ? Candidate.getCorrectionSpecifier()
9870 if (!Specifier->getAsType() ||
9871 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9874 // Check that this inheriting constructor declaration actually names a
9875 // direct base class of the current class.
9876 bool AnyDependentBases = false;
9877 if (!findDirectBaseWithType(RequireMemberOf,
9878 Ctx.getRecordType(FoundRecord),
9879 AnyDependentBases) &&
9883 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9884 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9887 // FIXME: Check that the base class member is accessible?
9890 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9891 if (FoundRecord && FoundRecord->isInjectedClassName())
9895 if (isa<TypeDecl>(ND))
9896 return HasTypenameKeyword || !IsInstantiation;
9898 return !HasTypenameKeyword;
9902 bool HasTypenameKeyword;
9903 bool IsInstantiation;
9904 NestedNameSpecifier *OldNNS;
9905 CXXRecordDecl *RequireMemberOf;
9907 } // end anonymous namespace
9909 /// Builds a using declaration.
9911 /// \param IsInstantiation - Whether this call arises from an
9912 /// instantiation of an unresolved using declaration. We treat
9913 /// the lookup differently for these declarations.
9914 NamedDecl *Sema::BuildUsingDeclaration(
9915 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9916 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9917 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9918 const ParsedAttributesView &AttrList, bool IsInstantiation) {
9919 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9920 SourceLocation IdentLoc = NameInfo.getLoc();
9921 assert(IdentLoc.isValid() && "Invalid TargetName location.");
9923 // FIXME: We ignore attributes for now.
9925 // For an inheriting constructor declaration, the name of the using
9926 // declaration is the name of a constructor in this class, not in the
9928 DeclarationNameInfo UsingName = NameInfo;
9929 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9930 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9931 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9932 Context.getCanonicalType(Context.getRecordType(RD))));
9934 // Do the redeclaration lookup in the current scope.
9935 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9936 ForVisibleRedeclaration);
9937 Previous.setHideTags(false);
9939 LookupName(Previous, S);
9941 // It is really dumb that we have to do this.
9942 LookupResult::Filter F = Previous.makeFilter();
9943 while (F.hasNext()) {
9944 NamedDecl *D = F.next();
9945 if (!isDeclInScope(D, CurContext, S))
9947 // If we found a local extern declaration that's not ordinarily visible,
9948 // and this declaration is being added to a non-block scope, ignore it.
9949 // We're only checking for scope conflicts here, not also for violations
9950 // of the linkage rules.
9951 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9952 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9957 assert(IsInstantiation && "no scope in non-instantiation");
9958 if (CurContext->isRecord())
9959 LookupQualifiedName(Previous, CurContext);
9961 // No redeclaration check is needed here; in non-member contexts we
9962 // diagnosed all possible conflicts with other using-declarations when
9963 // building the template:
9965 // For a dependent non-type using declaration, the only valid case is
9966 // if we instantiate to a single enumerator. We check for conflicts
9967 // between shadow declarations we introduce, and we check in the template
9968 // definition for conflicts between a non-type using declaration and any
9969 // other declaration, which together covers all cases.
9971 // A dependent typename using declaration will never successfully
9972 // instantiate, since it will always name a class member, so we reject
9973 // that in the template definition.
9977 // Check for invalid redeclarations.
9978 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9979 SS, IdentLoc, Previous))
9982 // Check for bad qualifiers.
9983 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9987 DeclContext *LookupContext = computeDeclContext(SS);
9989 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9990 if (!LookupContext || EllipsisLoc.isValid()) {
9991 if (HasTypenameKeyword) {
9992 // FIXME: not all declaration name kinds are legal here
9993 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9994 UsingLoc, TypenameLoc,
9996 IdentLoc, NameInfo.getName(),
9999 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10000 QualifierLoc, NameInfo, EllipsisLoc);
10003 CurContext->addDecl(D);
10007 auto Build = [&](bool Invalid) {
10009 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10010 UsingName, HasTypenameKeyword);
10012 CurContext->addDecl(UD);
10013 UD->setInvalidDecl(Invalid);
10016 auto BuildInvalid = [&]{ return Build(true); };
10017 auto BuildValid = [&]{ return Build(false); };
10019 if (RequireCompleteDeclContext(SS, LookupContext))
10020 return BuildInvalid();
10022 // Look up the target name.
10023 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10025 // Unlike most lookups, we don't always want to hide tag
10026 // declarations: tag names are visible through the using declaration
10027 // even if hidden by ordinary names, *except* in a dependent context
10028 // where it's important for the sanity of two-phase lookup.
10029 if (!IsInstantiation)
10030 R.setHideTags(false);
10032 // For the purposes of this lookup, we have a base object type
10033 // equal to that of the current context.
10034 if (CurContext->isRecord()) {
10035 R.setBaseObjectType(
10036 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10039 LookupQualifiedName(R, LookupContext);
10041 // Try to correct typos if possible. If constructor name lookup finds no
10042 // results, that means the named class has no explicit constructors, and we
10043 // suppressed declaring implicit ones (probably because it's dependent or
10046 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10047 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10048 // it will believe that glibc provides a ::gets in cases where it does not,
10049 // and will try to pull it into namespace std with a using-declaration.
10050 // Just ignore the using-declaration in that case.
10051 auto *II = NameInfo.getName().getAsIdentifierInfo();
10052 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10053 CurContext->isStdNamespace() &&
10054 isa<TranslationUnitDecl>(LookupContext) &&
10055 getSourceManager().isInSystemHeader(UsingLoc))
10057 if (TypoCorrection Corrected = CorrectTypo(
10058 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
10059 llvm::make_unique<UsingValidatorCCC>(
10060 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10061 dyn_cast<CXXRecordDecl>(CurContext)),
10062 CTK_ErrorRecovery)) {
10063 // We reject candidates where DroppedSpecifier == true, hence the
10064 // literal '0' below.
10065 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10066 << NameInfo.getName() << LookupContext << 0
10069 // If we picked a correction with no attached Decl we can't do anything
10070 // useful with it, bail out.
10071 NamedDecl *ND = Corrected.getCorrectionDecl();
10073 return BuildInvalid();
10075 // If we corrected to an inheriting constructor, handle it as one.
10076 auto *RD = dyn_cast<CXXRecordDecl>(ND);
10077 if (RD && RD->isInjectedClassName()) {
10078 // The parent of the injected class name is the class itself.
10079 RD = cast<CXXRecordDecl>(RD->getParent());
10081 // Fix up the information we'll use to build the using declaration.
10082 if (Corrected.WillReplaceSpecifier()) {
10083 NestedNameSpecifierLocBuilder Builder;
10084 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10085 QualifierLoc.getSourceRange());
10086 QualifierLoc = Builder.getWithLocInContext(Context);
10089 // In this case, the name we introduce is the name of a derived class
10091 auto *CurClass = cast<CXXRecordDecl>(CurContext);
10092 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10093 Context.getCanonicalType(Context.getRecordType(CurClass))));
10094 UsingName.setNamedTypeInfo(nullptr);
10095 for (auto *Ctor : LookupConstructors(RD))
10099 // FIXME: Pick up all the declarations if we found an overloaded
10101 UsingName.setName(ND->getDeclName());
10105 Diag(IdentLoc, diag::err_no_member)
10106 << NameInfo.getName() << LookupContext << SS.getRange();
10107 return BuildInvalid();
10111 if (R.isAmbiguous())
10112 return BuildInvalid();
10114 if (HasTypenameKeyword) {
10115 // If we asked for a typename and got a non-type decl, error out.
10116 if (!R.getAsSingle<TypeDecl>()) {
10117 Diag(IdentLoc, diag::err_using_typename_non_type);
10118 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10119 Diag((*I)->getUnderlyingDecl()->getLocation(),
10120 diag::note_using_decl_target);
10121 return BuildInvalid();
10124 // If we asked for a non-typename and we got a type, error out,
10125 // but only if this is an instantiation of an unresolved using
10126 // decl. Otherwise just silently find the type name.
10127 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10128 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10129 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10130 return BuildInvalid();
10134 // C++14 [namespace.udecl]p6:
10135 // A using-declaration shall not name a namespace.
10136 if (R.getAsSingle<NamespaceDecl>()) {
10137 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10139 return BuildInvalid();
10142 // C++14 [namespace.udecl]p7:
10143 // A using-declaration shall not name a scoped enumerator.
10144 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10145 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10146 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10148 return BuildInvalid();
10152 UsingDecl *UD = BuildValid();
10154 // Some additional rules apply to inheriting constructors.
10155 if (UsingName.getName().getNameKind() ==
10156 DeclarationName::CXXConstructorName) {
10157 // Suppress access diagnostics; the access check is instead performed at the
10158 // point of use for an inheriting constructor.
10159 R.suppressDiagnostics();
10160 if (CheckInheritingConstructorUsingDecl(UD))
10164 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10165 UsingShadowDecl *PrevDecl = nullptr;
10166 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10167 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10173 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10174 ArrayRef<NamedDecl *> Expansions) {
10175 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10176 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10177 isa<UsingPackDecl>(InstantiatedFrom));
10180 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10181 UPD->setAccess(InstantiatedFrom->getAccess());
10182 CurContext->addDecl(UPD);
10186 /// Additional checks for a using declaration referring to a constructor name.
10187 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10188 assert(!UD->hasTypename() && "expecting a constructor name");
10190 const Type *SourceType = UD->getQualifier()->getAsType();
10191 assert(SourceType &&
10192 "Using decl naming constructor doesn't have type in scope spec.");
10193 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10195 // Check whether the named type is a direct base class.
10196 bool AnyDependentBases = false;
10197 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10198 AnyDependentBases);
10199 if (!Base && !AnyDependentBases) {
10200 Diag(UD->getUsingLoc(),
10201 diag::err_using_decl_constructor_not_in_direct_base)
10202 << UD->getNameInfo().getSourceRange()
10203 << QualType(SourceType, 0) << TargetClass;
10204 UD->setInvalidDecl();
10209 Base->setInheritConstructors();
10214 /// Checks that the given using declaration is not an invalid
10215 /// redeclaration. Note that this is checking only for the using decl
10216 /// itself, not for any ill-formedness among the UsingShadowDecls.
10217 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10218 bool HasTypenameKeyword,
10219 const CXXScopeSpec &SS,
10220 SourceLocation NameLoc,
10221 const LookupResult &Prev) {
10222 NestedNameSpecifier *Qual = SS.getScopeRep();
10224 // C++03 [namespace.udecl]p8:
10225 // C++0x [namespace.udecl]p10:
10226 // A using-declaration is a declaration and can therefore be used
10227 // repeatedly where (and only where) multiple declarations are
10230 // That's in non-member contexts.
10231 if (!CurContext->getRedeclContext()->isRecord()) {
10232 // A dependent qualifier outside a class can only ever resolve to an
10233 // enumeration type. Therefore it conflicts with any other non-type
10234 // declaration in the same scope.
10235 // FIXME: How should we check for dependent type-type conflicts at block
10237 if (Qual->isDependent() && !HasTypenameKeyword) {
10238 for (auto *D : Prev) {
10239 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10240 bool OldCouldBeEnumerator =
10241 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10243 OldCouldBeEnumerator ? diag::err_redefinition
10244 : diag::err_redefinition_different_kind)
10245 << Prev.getLookupName();
10246 Diag(D->getLocation(), diag::note_previous_definition);
10254 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10258 NestedNameSpecifier *DQual;
10259 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10260 DTypename = UD->hasTypename();
10261 DQual = UD->getQualifier();
10262 } else if (UnresolvedUsingValueDecl *UD
10263 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10265 DQual = UD->getQualifier();
10266 } else if (UnresolvedUsingTypenameDecl *UD
10267 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10269 DQual = UD->getQualifier();
10272 // using decls differ if one says 'typename' and the other doesn't.
10273 // FIXME: non-dependent using decls?
10274 if (HasTypenameKeyword != DTypename) continue;
10276 // using decls differ if they name different scopes (but note that
10277 // template instantiation can cause this check to trigger when it
10278 // didn't before instantiation).
10279 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10280 Context.getCanonicalNestedNameSpecifier(DQual))
10283 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10284 Diag(D->getLocation(), diag::note_using_decl) << 1;
10292 /// Checks that the given nested-name qualifier used in a using decl
10293 /// in the current context is appropriately related to the current
10294 /// scope. If an error is found, diagnoses it and returns true.
10295 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10297 const CXXScopeSpec &SS,
10298 const DeclarationNameInfo &NameInfo,
10299 SourceLocation NameLoc) {
10300 DeclContext *NamedContext = computeDeclContext(SS);
10302 if (!CurContext->isRecord()) {
10303 // C++03 [namespace.udecl]p3:
10304 // C++0x [namespace.udecl]p8:
10305 // A using-declaration for a class member shall be a member-declaration.
10307 // If we weren't able to compute a valid scope, it might validly be a
10308 // dependent class scope or a dependent enumeration unscoped scope. If
10309 // we have a 'typename' keyword, the scope must resolve to a class type.
10310 if ((HasTypename && !NamedContext) ||
10311 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10312 auto *RD = NamedContext
10313 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10315 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10318 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10321 // If we have a complete, non-dependent source type, try to suggest a
10322 // way to get the same effect.
10326 // Find what this using-declaration was referring to.
10327 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10328 R.setHideTags(false);
10329 R.suppressDiagnostics();
10330 LookupQualifiedName(R, RD);
10332 if (R.getAsSingle<TypeDecl>()) {
10333 if (getLangOpts().CPlusPlus11) {
10334 // Convert 'using X::Y;' to 'using Y = X::Y;'.
10335 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10336 << 0 // alias declaration
10337 << FixItHint::CreateInsertion(SS.getBeginLoc(),
10338 NameInfo.getName().getAsString() +
10341 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10342 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10343 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10344 << 1 // typedef declaration
10345 << FixItHint::CreateReplacement(UsingLoc, "typedef")
10346 << FixItHint::CreateInsertion(
10347 InsertLoc, " " + NameInfo.getName().getAsString());
10349 } else if (R.getAsSingle<VarDecl>()) {
10350 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10351 // repeating the type of the static data member here.
10353 if (getLangOpts().CPlusPlus11) {
10354 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10355 FixIt = FixItHint::CreateReplacement(
10356 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10359 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10360 << 2 // reference declaration
10362 } else if (R.getAsSingle<EnumConstantDecl>()) {
10363 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10364 // repeating the type of the enumeration here, and we can't do so if
10365 // the type is anonymous.
10367 if (getLangOpts().CPlusPlus11) {
10368 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10369 FixIt = FixItHint::CreateReplacement(
10371 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10374 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10375 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10381 // Otherwise, this might be valid.
10385 // The current scope is a record.
10387 // If the named context is dependent, we can't decide much.
10388 if (!NamedContext) {
10389 // FIXME: in C++0x, we can diagnose if we can prove that the
10390 // nested-name-specifier does not refer to a base class, which is
10391 // still possible in some cases.
10393 // Otherwise we have to conservatively report that things might be
10398 if (!NamedContext->isRecord()) {
10399 // Ideally this would point at the last name in the specifier,
10400 // but we don't have that level of source info.
10401 Diag(SS.getRange().getBegin(),
10402 diag::err_using_decl_nested_name_specifier_is_not_class)
10403 << SS.getScopeRep() << SS.getRange();
10407 if (!NamedContext->isDependentContext() &&
10408 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10411 if (getLangOpts().CPlusPlus11) {
10412 // C++11 [namespace.udecl]p3:
10413 // In a using-declaration used as a member-declaration, the
10414 // nested-name-specifier shall name a base class of the class
10417 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10418 cast<CXXRecordDecl>(NamedContext))) {
10419 if (CurContext == NamedContext) {
10421 diag::err_using_decl_nested_name_specifier_is_current_class)
10426 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10427 Diag(SS.getRange().getBegin(),
10428 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10429 << SS.getScopeRep()
10430 << cast<CXXRecordDecl>(CurContext)
10439 // C++03 [namespace.udecl]p4:
10440 // A using-declaration used as a member-declaration shall refer
10441 // to a member of a base class of the class being defined [etc.].
10443 // Salient point: SS doesn't have to name a base class as long as
10444 // lookup only finds members from base classes. Therefore we can
10445 // diagnose here only if we can prove that that can't happen,
10446 // i.e. if the class hierarchies provably don't intersect.
10448 // TODO: it would be nice if "definitely valid" results were cached
10449 // in the UsingDecl and UsingShadowDecl so that these checks didn't
10450 // need to be repeated.
10452 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10453 auto Collect = [&Bases](const CXXRecordDecl *Base) {
10454 Bases.insert(Base);
10458 // Collect all bases. Return false if we find a dependent base.
10459 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10462 // Returns true if the base is dependent or is one of the accumulated base
10464 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10465 return !Bases.count(Base);
10468 // Return false if the class has a dependent base or if it or one
10469 // of its bases is present in the base set of the current context.
10470 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10471 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10474 Diag(SS.getRange().getBegin(),
10475 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10476 << SS.getScopeRep()
10477 << cast<CXXRecordDecl>(CurContext)
10483 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10484 MultiTemplateParamsArg TemplateParamLists,
10485 SourceLocation UsingLoc, UnqualifiedId &Name,
10486 const ParsedAttributesView &AttrList,
10487 TypeResult Type, Decl *DeclFromDeclSpec) {
10488 // Skip up to the relevant declaration scope.
10489 while (S->isTemplateParamScope())
10490 S = S->getParent();
10491 assert((S->getFlags() & Scope::DeclScope) &&
10492 "got alias-declaration outside of declaration scope");
10494 if (Type.isInvalid())
10497 bool Invalid = false;
10498 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10499 TypeSourceInfo *TInfo = nullptr;
10500 GetTypeFromParser(Type.get(), &TInfo);
10502 if (DiagnoseClassNameShadow(CurContext, NameInfo))
10505 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10506 UPPC_DeclarationType)) {
10508 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10509 TInfo->getTypeLoc().getBeginLoc());
10512 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10513 TemplateParamLists.size()
10514 ? forRedeclarationInCurContext()
10515 : ForVisibleRedeclaration);
10516 LookupName(Previous, S);
10518 // Warn about shadowing the name of a template parameter.
10519 if (Previous.isSingleResult() &&
10520 Previous.getFoundDecl()->isTemplateParameter()) {
10521 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10525 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10526 "name in alias declaration must be an identifier");
10527 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10528 Name.StartLocation,
10529 Name.Identifier, TInfo);
10531 NewTD->setAccess(AS);
10534 NewTD->setInvalidDecl();
10536 ProcessDeclAttributeList(S, NewTD, AttrList);
10537 AddPragmaAttributes(S, NewTD);
10539 CheckTypedefForVariablyModifiedType(S, NewTD);
10540 Invalid |= NewTD->isInvalidDecl();
10542 bool Redeclaration = false;
10545 if (TemplateParamLists.size()) {
10546 TypeAliasTemplateDecl *OldDecl = nullptr;
10547 TemplateParameterList *OldTemplateParams = nullptr;
10549 if (TemplateParamLists.size() != 1) {
10550 Diag(UsingLoc, diag::err_alias_template_extra_headers)
10551 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10552 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10554 TemplateParameterList *TemplateParams = TemplateParamLists[0];
10556 // Check that we can declare a template here.
10557 if (CheckTemplateDeclScope(S, TemplateParams))
10560 // Only consider previous declarations in the same scope.
10561 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10562 /*ExplicitInstantiationOrSpecialization*/false);
10563 if (!Previous.empty()) {
10564 Redeclaration = true;
10566 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10567 if (!OldDecl && !Invalid) {
10568 Diag(UsingLoc, diag::err_redefinition_different_kind)
10569 << Name.Identifier;
10571 NamedDecl *OldD = Previous.getRepresentativeDecl();
10572 if (OldD->getLocation().isValid())
10573 Diag(OldD->getLocation(), diag::note_previous_definition);
10578 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10579 if (TemplateParameterListsAreEqual(TemplateParams,
10580 OldDecl->getTemplateParameters(),
10582 TPL_TemplateMatch))
10583 OldTemplateParams =
10584 OldDecl->getMostRecentDecl()->getTemplateParameters();
10588 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10590 !Context.hasSameType(OldTD->getUnderlyingType(),
10591 NewTD->getUnderlyingType())) {
10592 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10593 // but we can't reasonably accept it.
10594 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10595 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10596 if (OldTD->getLocation().isValid())
10597 Diag(OldTD->getLocation(), diag::note_previous_definition);
10603 // Merge any previous default template arguments into our parameters,
10604 // and check the parameter list.
10605 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10606 TPC_TypeAliasTemplate))
10609 TypeAliasTemplateDecl *NewDecl =
10610 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10611 Name.Identifier, TemplateParams,
10613 NewTD->setDescribedAliasTemplate(NewDecl);
10615 NewDecl->setAccess(AS);
10618 NewDecl->setInvalidDecl();
10619 else if (OldDecl) {
10620 NewDecl->setPreviousDecl(OldDecl);
10621 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10626 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10627 setTagNameForLinkagePurposes(TD, NewTD);
10628 handleTagNumbering(TD, S);
10630 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10634 PushOnScopeChains(NewND, S);
10635 ActOnDocumentableDecl(NewND);
10639 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10640 SourceLocation AliasLoc,
10641 IdentifierInfo *Alias, CXXScopeSpec &SS,
10642 SourceLocation IdentLoc,
10643 IdentifierInfo *Ident) {
10645 // Lookup the namespace name.
10646 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10647 LookupParsedName(R, S, &SS);
10649 if (R.isAmbiguous())
10653 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10654 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10658 assert(!R.isAmbiguous() && !R.empty());
10659 NamedDecl *ND = R.getRepresentativeDecl();
10661 // Check if we have a previous declaration with the same name.
10662 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10663 ForVisibleRedeclaration);
10664 LookupName(PrevR, S);
10666 // Check we're not shadowing a template parameter.
10667 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10668 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10672 // Filter out any other lookup result from an enclosing scope.
10673 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10674 /*AllowInlineNamespace*/false);
10676 // Find the previous declaration and check that we can redeclare it.
10677 NamespaceAliasDecl *Prev = nullptr;
10678 if (PrevR.isSingleResult()) {
10679 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10680 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10681 // We already have an alias with the same name that points to the same
10682 // namespace; check that it matches.
10683 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10685 } else if (isVisible(PrevDecl)) {
10686 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10688 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10689 << AD->getNamespace();
10692 } else if (isVisible(PrevDecl)) {
10693 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10694 ? diag::err_redefinition
10695 : diag::err_redefinition_different_kind;
10696 Diag(AliasLoc, DiagID) << Alias;
10697 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10702 // The use of a nested name specifier may trigger deprecation warnings.
10703 DiagnoseUseOfDecl(ND, IdentLoc);
10705 NamespaceAliasDecl *AliasDecl =
10706 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10707 Alias, SS.getWithLocInContext(Context),
10710 AliasDecl->setPreviousDecl(Prev);
10712 PushOnScopeChains(AliasDecl, S);
10717 struct SpecialMemberExceptionSpecInfo
10718 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10719 SourceLocation Loc;
10720 Sema::ImplicitExceptionSpecification ExceptSpec;
10722 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10723 Sema::CXXSpecialMember CSM,
10724 Sema::InheritedConstructorInfo *ICI,
10725 SourceLocation Loc)
10726 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10728 bool visitBase(CXXBaseSpecifier *Base);
10729 bool visitField(FieldDecl *FD);
10731 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10734 void visitSubobjectCall(Subobject Subobj,
10735 Sema::SpecialMemberOverloadResult SMOR);
10739 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10740 auto *RT = Base->getType()->getAs<RecordType>();
10744 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10745 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10746 if (auto *BaseCtor = SMOR.getMethod()) {
10747 visitSubobjectCall(Base, BaseCtor);
10751 visitClassSubobject(BaseClass, Base, 0);
10755 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10756 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10757 Expr *E = FD->getInClassInitializer();
10759 // FIXME: It's a little wasteful to build and throw away a
10760 // CXXDefaultInitExpr here.
10761 // FIXME: We should have a single context note pointing at Loc, and
10762 // this location should be MD->getLocation() instead, since that's
10763 // the location where we actually use the default init expression.
10764 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10766 ExceptSpec.CalledExpr(E);
10767 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10768 ->getAs<RecordType>()) {
10769 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10770 FD->getType().getCVRQualifiers());
10775 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10778 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10779 bool IsMutable = Field && Field->isMutable();
10780 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10783 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10784 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10785 // Note, if lookup fails, it doesn't matter what exception specification we
10786 // choose because the special member will be deleted.
10787 if (CXXMethodDecl *MD = SMOR.getMethod())
10788 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10792 /// RAII object to register a special member as being currently declared.
10793 struct ComputingExceptionSpec {
10796 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10798 Sema::CodeSynthesisContext Ctx;
10799 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10800 Ctx.PointOfInstantiation = Loc;
10802 S.pushCodeSynthesisContext(Ctx);
10804 ~ComputingExceptionSpec() {
10805 S.popCodeSynthesisContext();
10810 static Sema::ImplicitExceptionSpecification
10811 ComputeDefaultedSpecialMemberExceptionSpec(
10812 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10813 Sema::InheritedConstructorInfo *ICI) {
10814 ComputingExceptionSpec CES(S, MD, Loc);
10816 CXXRecordDecl *ClassDecl = MD->getParent();
10818 // C++ [except.spec]p14:
10819 // An implicitly declared special member function (Clause 12) shall have an
10820 // exception-specification. [...]
10821 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10822 if (ClassDecl->isInvalidDecl())
10823 return Info.ExceptSpec;
10825 // FIXME: If this diagnostic fires, we're probably missing a check for
10826 // attempting to resolve an exception specification before it's known
10827 // at a higher level.
10828 if (S.RequireCompleteType(MD->getLocation(),
10829 S.Context.getRecordType(ClassDecl),
10830 diag::err_exception_spec_incomplete_type))
10831 return Info.ExceptSpec;
10833 // C++1z [except.spec]p7:
10834 // [Look for exceptions thrown by] a constructor selected [...] to
10835 // initialize a potentially constructed subobject,
10836 // C++1z [except.spec]p8:
10837 // The exception specification for an implicitly-declared destructor, or a
10838 // destructor without a noexcept-specifier, is potentially-throwing if and
10839 // only if any of the destructors for any of its potentially constructed
10840 // subojects is potentially throwing.
10841 // FIXME: We respect the first rule but ignore the "potentially constructed"
10842 // in the second rule to resolve a core issue (no number yet) that would have
10844 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10845 // struct B : A {};
10846 // struct C : B { void f(); };
10847 // ... due to giving B::~B() a non-throwing exception specification.
10848 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10849 : Info.VisitAllBases);
10851 return Info.ExceptSpec;
10855 /// RAII object to register a special member as being currently declared.
10856 struct DeclaringSpecialMember {
10858 Sema::SpecialMemberDecl D;
10859 Sema::ContextRAII SavedContext;
10860 bool WasAlreadyBeingDeclared;
10862 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10863 : S(S), D(RD, CSM), SavedContext(S, RD) {
10864 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10865 if (WasAlreadyBeingDeclared)
10866 // This almost never happens, but if it does, ensure that our cache
10867 // doesn't contain a stale result.
10868 S.SpecialMemberCache.clear();
10870 // Register a note to be produced if we encounter an error while
10871 // declaring the special member.
10872 Sema::CodeSynthesisContext Ctx;
10873 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10874 // FIXME: We don't have a location to use here. Using the class's
10875 // location maintains the fiction that we declare all special members
10876 // with the class, but (1) it's not clear that lying about that helps our
10877 // users understand what's going on, and (2) there may be outer contexts
10878 // on the stack (some of which are relevant) and printing them exposes
10880 Ctx.PointOfInstantiation = RD->getLocation();
10882 Ctx.SpecialMember = CSM;
10883 S.pushCodeSynthesisContext(Ctx);
10886 ~DeclaringSpecialMember() {
10887 if (!WasAlreadyBeingDeclared) {
10888 S.SpecialMembersBeingDeclared.erase(D);
10889 S.popCodeSynthesisContext();
10893 /// Are we already trying to declare this special member?
10894 bool isAlreadyBeingDeclared() const {
10895 return WasAlreadyBeingDeclared;
10900 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10901 // Look up any existing declarations, but don't trigger declaration of all
10902 // implicit special members with this name.
10903 DeclarationName Name = FD->getDeclName();
10904 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10905 ForExternalRedeclaration);
10906 for (auto *D : FD->getParent()->lookup(Name))
10907 if (auto *Acceptable = R.getAcceptableDecl(D))
10908 R.addDecl(Acceptable);
10910 R.suppressDiagnostics();
10912 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10915 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10917 ArrayRef<QualType> Args) {
10918 // Build an exception specification pointing back at this constructor.
10919 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10921 if (getLangOpts().OpenCLCPlusPlus) {
10922 // OpenCL: Implicitly defaulted special member are of the generic address
10924 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
10927 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
10928 SpecialMem->setType(QT);
10931 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10932 CXXRecordDecl *ClassDecl) {
10933 // C++ [class.ctor]p5:
10934 // A default constructor for a class X is a constructor of class X
10935 // that can be called without an argument. If there is no
10936 // user-declared constructor for class X, a default constructor is
10937 // implicitly declared. An implicitly-declared default constructor
10938 // is an inline public member of its class.
10939 assert(ClassDecl->needsImplicitDefaultConstructor() &&
10940 "Should not build implicit default constructor!");
10942 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10943 if (DSM.isAlreadyBeingDeclared())
10946 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10947 CXXDefaultConstructor,
10950 // Create the actual constructor declaration.
10951 CanQualType ClassType
10952 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10953 SourceLocation ClassLoc = ClassDecl->getLocation();
10954 DeclarationName Name
10955 = Context.DeclarationNames.getCXXConstructorName(ClassType);
10956 DeclarationNameInfo NameInfo(Name, ClassLoc);
10957 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10958 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10959 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10960 /*isImplicitlyDeclared=*/true, Constexpr);
10961 DefaultCon->setAccess(AS_public);
10962 DefaultCon->setDefaulted();
10964 if (getLangOpts().CUDA) {
10965 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10967 /* ConstRHS */ false,
10968 /* Diagnose */ false);
10971 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
10973 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10974 // constructors is easy to compute.
10975 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10977 // Note that we have declared this constructor.
10978 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10980 Scope *S = getScopeForContext(ClassDecl);
10981 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10983 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10984 SetDeclDeleted(DefaultCon, ClassLoc);
10987 PushOnScopeChains(DefaultCon, S, false);
10988 ClassDecl->addDecl(DefaultCon);
10993 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10994 CXXConstructorDecl *Constructor) {
10995 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10996 !Constructor->doesThisDeclarationHaveABody() &&
10997 !Constructor->isDeleted()) &&
10998 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10999 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11002 CXXRecordDecl *ClassDecl = Constructor->getParent();
11003 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11005 SynthesizedFunctionScope Scope(*this, Constructor);
11007 // The exception specification is needed because we are defining the
11009 ResolveExceptionSpec(CurrentLocation,
11010 Constructor->getType()->castAs<FunctionProtoType>());
11011 MarkVTableUsed(CurrentLocation, ClassDecl);
11013 // Add a context note for diagnostics produced after this point.
11014 Scope.addContextNote(CurrentLocation);
11016 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11017 Constructor->setInvalidDecl();
11021 SourceLocation Loc = Constructor->getEndLoc().isValid()
11022 ? Constructor->getEndLoc()
11023 : Constructor->getLocation();
11024 Constructor->setBody(new (Context) CompoundStmt(Loc));
11025 Constructor->markUsed(Context);
11027 if (ASTMutationListener *L = getASTMutationListener()) {
11028 L->CompletedImplicitDefinition(Constructor);
11031 DiagnoseUninitializedFields(*this, Constructor);
11034 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11035 // Perform any delayed checks on exception specifications.
11036 CheckDelayedMemberExceptionSpecs();
11039 /// Find or create the fake constructor we synthesize to model constructing an
11040 /// object of a derived class via a constructor of a base class.
11041 CXXConstructorDecl *
11042 Sema::findInheritingConstructor(SourceLocation Loc,
11043 CXXConstructorDecl *BaseCtor,
11044 ConstructorUsingShadowDecl *Shadow) {
11045 CXXRecordDecl *Derived = Shadow->getParent();
11046 SourceLocation UsingLoc = Shadow->getLocation();
11048 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11049 // For now we use the name of the base class constructor as a member of the
11050 // derived class to indicate a (fake) inherited constructor name.
11051 DeclarationName Name = BaseCtor->getDeclName();
11053 // Check to see if we already have a fake constructor for this inherited
11054 // constructor call.
11055 for (NamedDecl *Ctor : Derived->lookup(Name))
11056 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11057 ->getInheritedConstructor()
11060 return cast<CXXConstructorDecl>(Ctor);
11062 DeclarationNameInfo NameInfo(Name, UsingLoc);
11063 TypeSourceInfo *TInfo =
11064 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11065 FunctionProtoTypeLoc ProtoLoc =
11066 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11068 // Check the inherited constructor is valid and find the list of base classes
11069 // from which it was inherited.
11070 InheritedConstructorInfo ICI(*this, Loc, Shadow);
11073 BaseCtor->isConstexpr() &&
11074 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11075 false, BaseCtor, &ICI);
11077 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11078 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11079 BaseCtor->isExplicit(), /*Inline=*/true,
11080 /*ImplicitlyDeclared=*/true, Constexpr,
11081 InheritedConstructor(Shadow, BaseCtor));
11082 if (Shadow->isInvalidDecl())
11083 DerivedCtor->setInvalidDecl();
11085 // Build an unevaluated exception specification for this fake constructor.
11086 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11087 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11088 EPI.ExceptionSpec.Type = EST_Unevaluated;
11089 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11090 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11091 FPT->getParamTypes(), EPI));
11093 // Build the parameter declarations.
11094 SmallVector<ParmVarDecl *, 16> ParamDecls;
11095 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11096 TypeSourceInfo *TInfo =
11097 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11098 ParmVarDecl *PD = ParmVarDecl::Create(
11099 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11100 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11101 PD->setScopeInfo(0, I);
11103 // Ensure attributes are propagated onto parameters (this matters for
11104 // format, pass_object_size, ...).
11105 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11106 ParamDecls.push_back(PD);
11107 ProtoLoc.setParam(I, PD);
11110 // Set up the new constructor.
11111 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11112 DerivedCtor->setAccess(BaseCtor->getAccess());
11113 DerivedCtor->setParams(ParamDecls);
11114 Derived->addDecl(DerivedCtor);
11116 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11117 SetDeclDeleted(DerivedCtor, UsingLoc);
11119 return DerivedCtor;
11122 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11123 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11124 Ctor->getInheritedConstructor().getShadowDecl());
11125 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11129 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11130 CXXConstructorDecl *Constructor) {
11131 CXXRecordDecl *ClassDecl = Constructor->getParent();
11132 assert(Constructor->getInheritedConstructor() &&
11133 !Constructor->doesThisDeclarationHaveABody() &&
11134 !Constructor->isDeleted());
11135 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11138 // Initializations are performed "as if by a defaulted default constructor",
11139 // so enter the appropriate scope.
11140 SynthesizedFunctionScope Scope(*this, Constructor);
11142 // The exception specification is needed because we are defining the
11144 ResolveExceptionSpec(CurrentLocation,
11145 Constructor->getType()->castAs<FunctionProtoType>());
11146 MarkVTableUsed(CurrentLocation, ClassDecl);
11148 // Add a context note for diagnostics produced after this point.
11149 Scope.addContextNote(CurrentLocation);
11151 ConstructorUsingShadowDecl *Shadow =
11152 Constructor->getInheritedConstructor().getShadowDecl();
11153 CXXConstructorDecl *InheritedCtor =
11154 Constructor->getInheritedConstructor().getConstructor();
11156 // [class.inhctor.init]p1:
11157 // initialization proceeds as if a defaulted default constructor is used to
11158 // initialize the D object and each base class subobject from which the
11159 // constructor was inherited
11161 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11162 CXXRecordDecl *RD = Shadow->getParent();
11163 SourceLocation InitLoc = Shadow->getLocation();
11165 // Build explicit initializers for all base classes from which the
11166 // constructor was inherited.
11167 SmallVector<CXXCtorInitializer*, 8> Inits;
11168 for (bool VBase : {false, true}) {
11169 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11170 if (B.isVirtual() != VBase)
11173 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11177 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11178 if (!BaseCtor.first)
11181 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11182 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11183 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11185 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11186 Inits.push_back(new (Context) CXXCtorInitializer(
11187 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11188 SourceLocation()));
11192 // We now proceed as if for a defaulted default constructor, with the relevant
11193 // initializers replaced.
11195 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11196 Constructor->setInvalidDecl();
11200 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11201 Constructor->markUsed(Context);
11203 if (ASTMutationListener *L = getASTMutationListener()) {
11204 L->CompletedImplicitDefinition(Constructor);
11207 DiagnoseUninitializedFields(*this, Constructor);
11210 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11211 // C++ [class.dtor]p2:
11212 // If a class has no user-declared destructor, a destructor is
11213 // declared implicitly. An implicitly-declared destructor is an
11214 // inline public member of its class.
11215 assert(ClassDecl->needsImplicitDestructor());
11217 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11218 if (DSM.isAlreadyBeingDeclared())
11221 // Create the actual destructor declaration.
11222 CanQualType ClassType
11223 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11224 SourceLocation ClassLoc = ClassDecl->getLocation();
11225 DeclarationName Name
11226 = Context.DeclarationNames.getCXXDestructorName(ClassType);
11227 DeclarationNameInfo NameInfo(Name, ClassLoc);
11228 CXXDestructorDecl *Destructor
11229 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11230 QualType(), nullptr, /*isInline=*/true,
11231 /*isImplicitlyDeclared=*/true);
11232 Destructor->setAccess(AS_public);
11233 Destructor->setDefaulted();
11235 if (getLangOpts().CUDA) {
11236 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11238 /* ConstRHS */ false,
11239 /* Diagnose */ false);
11242 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11244 // We don't need to use SpecialMemberIsTrivial here; triviality for
11245 // destructors is easy to compute.
11246 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11247 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11248 ClassDecl->hasTrivialDestructorForCall());
11250 // Note that we have declared this destructor.
11251 ++ASTContext::NumImplicitDestructorsDeclared;
11253 Scope *S = getScopeForContext(ClassDecl);
11254 CheckImplicitSpecialMemberDeclaration(S, Destructor);
11256 // We can't check whether an implicit destructor is deleted before we complete
11257 // the definition of the class, because its validity depends on the alignment
11258 // of the class. We'll check this from ActOnFields once the class is complete.
11259 if (ClassDecl->isCompleteDefinition() &&
11260 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11261 SetDeclDeleted(Destructor, ClassLoc);
11263 // Introduce this destructor into its scope.
11265 PushOnScopeChains(Destructor, S, false);
11266 ClassDecl->addDecl(Destructor);
11271 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11272 CXXDestructorDecl *Destructor) {
11273 assert((Destructor->isDefaulted() &&
11274 !Destructor->doesThisDeclarationHaveABody() &&
11275 !Destructor->isDeleted()) &&
11276 "DefineImplicitDestructor - call it for implicit default dtor");
11277 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11280 CXXRecordDecl *ClassDecl = Destructor->getParent();
11281 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11283 SynthesizedFunctionScope Scope(*this, Destructor);
11285 // The exception specification is needed because we are defining the
11287 ResolveExceptionSpec(CurrentLocation,
11288 Destructor->getType()->castAs<FunctionProtoType>());
11289 MarkVTableUsed(CurrentLocation, ClassDecl);
11291 // Add a context note for diagnostics produced after this point.
11292 Scope.addContextNote(CurrentLocation);
11294 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11295 Destructor->getParent());
11297 if (CheckDestructor(Destructor)) {
11298 Destructor->setInvalidDecl();
11302 SourceLocation Loc = Destructor->getEndLoc().isValid()
11303 ? Destructor->getEndLoc()
11304 : Destructor->getLocation();
11305 Destructor->setBody(new (Context) CompoundStmt(Loc));
11306 Destructor->markUsed(Context);
11308 if (ASTMutationListener *L = getASTMutationListener()) {
11309 L->CompletedImplicitDefinition(Destructor);
11313 /// Perform any semantic analysis which needs to be delayed until all
11314 /// pending class member declarations have been parsed.
11315 void Sema::ActOnFinishCXXMemberDecls() {
11316 // If the context is an invalid C++ class, just suppress these checks.
11317 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11318 if (Record->isInvalidDecl()) {
11319 DelayedOverridingExceptionSpecChecks.clear();
11320 DelayedEquivalentExceptionSpecChecks.clear();
11321 DelayedDefaultedMemberExceptionSpecs.clear();
11324 checkForMultipleExportedDefaultConstructors(*this, Record);
11328 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11329 referenceDLLExportedClassMethods();
11332 void Sema::referenceDLLExportedClassMethods() {
11333 if (!DelayedDllExportClasses.empty()) {
11334 // Calling ReferenceDllExportedMembers might cause the current function to
11335 // be called again, so use a local copy of DelayedDllExportClasses.
11336 SmallVector<CXXRecordDecl *, 4> WorkList;
11337 std::swap(DelayedDllExportClasses, WorkList);
11338 for (CXXRecordDecl *Class : WorkList)
11339 ReferenceDllExportedMembers(*this, Class);
11343 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11344 assert(getLangOpts().CPlusPlus11 &&
11345 "adjusting dtor exception specs was introduced in c++11");
11347 if (Destructor->isDependentContext())
11350 // C++11 [class.dtor]p3:
11351 // A declaration of a destructor that does not have an exception-
11352 // specification is implicitly considered to have the same exception-
11353 // specification as an implicit declaration.
11354 const FunctionProtoType *DtorType = Destructor->getType()->
11355 getAs<FunctionProtoType>();
11356 if (DtorType->hasExceptionSpec())
11359 // Replace the destructor's type, building off the existing one. Fortunately,
11360 // the only thing of interest in the destructor type is its extended info.
11361 // The return and arguments are fixed.
11362 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11363 EPI.ExceptionSpec.Type = EST_Unevaluated;
11364 EPI.ExceptionSpec.SourceDecl = Destructor;
11365 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11367 // FIXME: If the destructor has a body that could throw, and the newly created
11368 // spec doesn't allow exceptions, we should emit a warning, because this
11369 // change in behavior can break conforming C++03 programs at runtime.
11370 // However, we don't have a body or an exception specification yet, so it
11371 // needs to be done somewhere else.
11375 /// An abstract base class for all helper classes used in building the
11376 // copy/move operators. These classes serve as factory functions and help us
11377 // avoid using the same Expr* in the AST twice.
11378 class ExprBuilder {
11379 ExprBuilder(const ExprBuilder&) = delete;
11380 ExprBuilder &operator=(const ExprBuilder&) = delete;
11383 static Expr *assertNotNull(Expr *E) {
11384 assert(E && "Expression construction must not fail.");
11390 virtual ~ExprBuilder() {}
11392 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11395 class RefBuilder: public ExprBuilder {
11400 Expr *build(Sema &S, SourceLocation Loc) const override {
11401 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11404 RefBuilder(VarDecl *Var, QualType VarType)
11405 : Var(Var), VarType(VarType) {}
11408 class ThisBuilder: public ExprBuilder {
11410 Expr *build(Sema &S, SourceLocation Loc) const override {
11411 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11415 class CastBuilder: public ExprBuilder {
11416 const ExprBuilder &Builder;
11418 ExprValueKind Kind;
11419 const CXXCastPath &Path;
11422 Expr *build(Sema &S, SourceLocation Loc) const override {
11423 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11424 CK_UncheckedDerivedToBase, Kind,
11428 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11429 const CXXCastPath &Path)
11430 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11433 class DerefBuilder: public ExprBuilder {
11434 const ExprBuilder &Builder;
11437 Expr *build(Sema &S, SourceLocation Loc) const override {
11438 return assertNotNull(
11439 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11442 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11445 class MemberBuilder: public ExprBuilder {
11446 const ExprBuilder &Builder;
11450 LookupResult &MemberLookup;
11453 Expr *build(Sema &S, SourceLocation Loc) const override {
11454 return assertNotNull(S.BuildMemberReferenceExpr(
11455 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11456 nullptr, MemberLookup, nullptr, nullptr).get());
11459 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11460 LookupResult &MemberLookup)
11461 : Builder(Builder), Type(Type), IsArrow(IsArrow),
11462 MemberLookup(MemberLookup) {}
11465 class MoveCastBuilder: public ExprBuilder {
11466 const ExprBuilder &Builder;
11469 Expr *build(Sema &S, SourceLocation Loc) const override {
11470 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11473 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11476 class LvalueConvBuilder: public ExprBuilder {
11477 const ExprBuilder &Builder;
11480 Expr *build(Sema &S, SourceLocation Loc) const override {
11481 return assertNotNull(
11482 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11485 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11488 class SubscriptBuilder: public ExprBuilder {
11489 const ExprBuilder &Base;
11490 const ExprBuilder &Index;
11493 Expr *build(Sema &S, SourceLocation Loc) const override {
11494 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11495 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11498 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11499 : Base(Base), Index(Index) {}
11502 } // end anonymous namespace
11504 /// When generating a defaulted copy or move assignment operator, if a field
11505 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11506 /// do so. This optimization only applies for arrays of scalars, and for arrays
11507 /// of class type where the selected copy/move-assignment operator is trivial.
11509 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11510 const ExprBuilder &ToB, const ExprBuilder &FromB) {
11511 // Compute the size of the memory buffer to be copied.
11512 QualType SizeType = S.Context.getSizeType();
11513 llvm::APInt Size(S.Context.getTypeSize(SizeType),
11514 S.Context.getTypeSizeInChars(T).getQuantity());
11516 // Take the address of the field references for "from" and "to". We
11517 // directly construct UnaryOperators here because semantic analysis
11518 // does not permit us to take the address of an xvalue.
11519 Expr *From = FromB.build(S, Loc);
11520 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11521 S.Context.getPointerType(From->getType()),
11522 VK_RValue, OK_Ordinary, Loc, false);
11523 Expr *To = ToB.build(S, Loc);
11524 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11525 S.Context.getPointerType(To->getType()),
11526 VK_RValue, OK_Ordinary, Loc, false);
11528 const Type *E = T->getBaseElementTypeUnsafe();
11529 bool NeedsCollectableMemCpy =
11530 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11532 // Create a reference to the __builtin_objc_memmove_collectable function
11533 StringRef MemCpyName = NeedsCollectableMemCpy ?
11534 "__builtin_objc_memmove_collectable" :
11535 "__builtin_memcpy";
11536 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11537 Sema::LookupOrdinaryName);
11538 S.LookupName(R, S.TUScope, true);
11540 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11542 // Something went horribly wrong earlier, and we will have complained
11544 return StmtError();
11546 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11547 VK_RValue, Loc, nullptr);
11548 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11550 Expr *CallArgs[] = {
11551 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11553 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11554 Loc, CallArgs, Loc);
11556 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11557 return Call.getAs<Stmt>();
11560 /// Builds a statement that copies/moves the given entity from \p From to
11563 /// This routine is used to copy/move the members of a class with an
11564 /// implicitly-declared copy/move assignment operator. When the entities being
11565 /// copied are arrays, this routine builds for loops to copy them.
11567 /// \param S The Sema object used for type-checking.
11569 /// \param Loc The location where the implicit copy/move is being generated.
11571 /// \param T The type of the expressions being copied/moved. Both expressions
11572 /// must have this type.
11574 /// \param To The expression we are copying/moving to.
11576 /// \param From The expression we are copying/moving from.
11578 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11579 /// Otherwise, it's a non-static member subobject.
11581 /// \param Copying Whether we're copying or moving.
11583 /// \param Depth Internal parameter recording the depth of the recursion.
11585 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11586 /// if a memcpy should be used instead.
11588 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11589 const ExprBuilder &To, const ExprBuilder &From,
11590 bool CopyingBaseSubobject, bool Copying,
11591 unsigned Depth = 0) {
11592 // C++11 [class.copy]p28:
11593 // Each subobject is assigned in the manner appropriate to its type:
11595 // - if the subobject is of class type, as if by a call to operator= with
11596 // the subobject as the object expression and the corresponding
11597 // subobject of x as a single function argument (as if by explicit
11598 // qualification; that is, ignoring any possible virtual overriding
11599 // functions in more derived classes);
11601 // C++03 [class.copy]p13:
11602 // - if the subobject is of class type, the copy assignment operator for
11603 // the class is used (as if by explicit qualification; that is,
11604 // ignoring any possible virtual overriding functions in more derived
11606 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11607 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11609 // Look for operator=.
11610 DeclarationName Name
11611 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11612 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11613 S.LookupQualifiedName(OpLookup, ClassDecl, false);
11615 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11617 if (!S.getLangOpts().CPlusPlus11) {
11618 LookupResult::Filter F = OpLookup.makeFilter();
11619 while (F.hasNext()) {
11620 NamedDecl *D = F.next();
11621 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11622 if (Method->isCopyAssignmentOperator() ||
11623 (!Copying && Method->isMoveAssignmentOperator()))
11631 // Suppress the protected check (C++ [class.protected]) for each of the
11632 // assignment operators we found. This strange dance is required when
11633 // we're assigning via a base classes's copy-assignment operator. To
11634 // ensure that we're getting the right base class subobject (without
11635 // ambiguities), we need to cast "this" to that subobject type; to
11636 // ensure that we don't go through the virtual call mechanism, we need
11637 // to qualify the operator= name with the base class (see below). However,
11638 // this means that if the base class has a protected copy assignment
11639 // operator, the protected member access check will fail. So, we
11640 // rewrite "protected" access to "public" access in this case, since we
11641 // know by construction that we're calling from a derived class.
11642 if (CopyingBaseSubobject) {
11643 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11645 if (L.getAccess() == AS_protected)
11646 L.setAccess(AS_public);
11650 // Create the nested-name-specifier that will be used to qualify the
11651 // reference to operator=; this is required to suppress the virtual
11654 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11655 SS.MakeTrivial(S.Context,
11656 NestedNameSpecifier::Create(S.Context, nullptr, false,
11660 // Create the reference to operator=.
11661 ExprResult OpEqualRef
11662 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11663 SS, /*TemplateKWLoc=*/SourceLocation(),
11664 /*FirstQualifierInScope=*/nullptr,
11666 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11667 /*SuppressQualifierCheck=*/true);
11668 if (OpEqualRef.isInvalid())
11669 return StmtError();
11671 // Build the call to the assignment operator.
11673 Expr *FromInst = From.build(S, Loc);
11674 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11675 OpEqualRef.getAs<Expr>(),
11676 Loc, FromInst, Loc);
11677 if (Call.isInvalid())
11678 return StmtError();
11680 // If we built a call to a trivial 'operator=' while copying an array,
11681 // bail out. We'll replace the whole shebang with a memcpy.
11682 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11683 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11684 return StmtResult((Stmt*)nullptr);
11686 // Convert to an expression-statement, and clean up any produced
11688 return S.ActOnExprStmt(Call);
11691 // - if the subobject is of scalar type, the built-in assignment
11692 // operator is used.
11693 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11695 ExprResult Assignment = S.CreateBuiltinBinOp(
11696 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11697 if (Assignment.isInvalid())
11698 return StmtError();
11699 return S.ActOnExprStmt(Assignment);
11702 // - if the subobject is an array, each element is assigned, in the
11703 // manner appropriate to the element type;
11705 // Construct a loop over the array bounds, e.g.,
11707 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11709 // that will copy each of the array elements.
11710 QualType SizeType = S.Context.getSizeType();
11712 // Create the iteration variable.
11713 IdentifierInfo *IterationVarName = nullptr;
11715 SmallString<8> Str;
11716 llvm::raw_svector_ostream OS(Str);
11717 OS << "__i" << Depth;
11718 IterationVarName = &S.Context.Idents.get(OS.str());
11720 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11721 IterationVarName, SizeType,
11722 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11725 // Initialize the iteration variable to zero.
11726 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11727 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11729 // Creates a reference to the iteration variable.
11730 RefBuilder IterationVarRef(IterationVar, SizeType);
11731 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11733 // Create the DeclStmt that holds the iteration variable.
11734 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11736 // Subscript the "from" and "to" expressions with the iteration variable.
11737 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11738 MoveCastBuilder FromIndexMove(FromIndexCopy);
11739 const ExprBuilder *FromIndex;
11741 FromIndex = &FromIndexCopy;
11743 FromIndex = &FromIndexMove;
11745 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11747 // Build the copy/move for an individual element of the array.
11749 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11750 ToIndex, *FromIndex, CopyingBaseSubobject,
11751 Copying, Depth + 1);
11752 // Bail out if copying fails or if we determined that we should use memcpy.
11753 if (Copy.isInvalid() || !Copy.get())
11756 // Create the comparison against the array bound.
11758 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11760 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11761 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11762 BO_NE, S.Context.BoolTy,
11763 VK_RValue, OK_Ordinary, Loc, FPOptions());
11765 // Create the pre-increment of the iteration variable. We can determine
11766 // whether the increment will overflow based on the value of the array
11768 Expr *Increment = new (S.Context)
11769 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11770 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11772 // Construct the loop that copies all elements of this array.
11773 return S.ActOnForStmt(
11774 Loc, Loc, InitStmt,
11775 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11776 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11780 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11781 const ExprBuilder &To, const ExprBuilder &From,
11782 bool CopyingBaseSubobject, bool Copying) {
11783 // Maybe we should use a memcpy?
11784 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11785 T.isTriviallyCopyableType(S.Context))
11786 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11788 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11789 CopyingBaseSubobject,
11792 // If we ended up picking a trivial assignment operator for an array of a
11793 // non-trivially-copyable class type, just emit a memcpy.
11794 if (!Result.isInvalid() && !Result.get())
11795 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11800 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11801 // Note: The following rules are largely analoguous to the copy
11802 // constructor rules. Note that virtual bases are not taken into account
11803 // for determining the argument type of the operator. Note also that
11804 // operators taking an object instead of a reference are allowed.
11805 assert(ClassDecl->needsImplicitCopyAssignment());
11807 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11808 if (DSM.isAlreadyBeingDeclared())
11811 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11812 QualType RetType = Context.getLValueReferenceType(ArgType);
11813 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11815 ArgType = ArgType.withConst();
11817 if (Context.getLangOpts().OpenCLCPlusPlus)
11818 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11820 ArgType = Context.getLValueReferenceType(ArgType);
11822 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11826 // An implicitly-declared copy assignment operator is an inline public
11827 // member of its class.
11828 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11829 SourceLocation ClassLoc = ClassDecl->getLocation();
11830 DeclarationNameInfo NameInfo(Name, ClassLoc);
11831 CXXMethodDecl *CopyAssignment =
11832 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11833 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11834 /*isInline=*/true, Constexpr, SourceLocation());
11835 CopyAssignment->setAccess(AS_public);
11836 CopyAssignment->setDefaulted();
11837 CopyAssignment->setImplicit();
11839 if (getLangOpts().CUDA) {
11840 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11842 /* ConstRHS */ Const,
11843 /* Diagnose */ false);
11846 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11848 // Add the parameter to the operator.
11849 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11850 ClassLoc, ClassLoc,
11851 /*Id=*/nullptr, ArgType,
11852 /*TInfo=*/nullptr, SC_None,
11854 CopyAssignment->setParams(FromParam);
11856 CopyAssignment->setTrivial(
11857 ClassDecl->needsOverloadResolutionForCopyAssignment()
11858 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11859 : ClassDecl->hasTrivialCopyAssignment());
11861 // Note that we have added this copy-assignment operator.
11862 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11864 Scope *S = getScopeForContext(ClassDecl);
11865 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11867 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11868 SetDeclDeleted(CopyAssignment, ClassLoc);
11871 PushOnScopeChains(CopyAssignment, S, false);
11872 ClassDecl->addDecl(CopyAssignment);
11874 return CopyAssignment;
11877 /// Diagnose an implicit copy operation for a class which is odr-used, but
11878 /// which is deprecated because the class has a user-declared copy constructor,
11879 /// copy assignment operator, or destructor.
11880 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11881 assert(CopyOp->isImplicit());
11883 CXXRecordDecl *RD = CopyOp->getParent();
11884 CXXMethodDecl *UserDeclaredOperation = nullptr;
11886 // In Microsoft mode, assignment operations don't affect constructors and
11888 if (RD->hasUserDeclaredDestructor()) {
11889 UserDeclaredOperation = RD->getDestructor();
11890 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11891 RD->hasUserDeclaredCopyConstructor() &&
11892 !S.getLangOpts().MSVCCompat) {
11893 // Find any user-declared copy constructor.
11894 for (auto *I : RD->ctors()) {
11895 if (I->isCopyConstructor()) {
11896 UserDeclaredOperation = I;
11900 assert(UserDeclaredOperation);
11901 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11902 RD->hasUserDeclaredCopyAssignment() &&
11903 !S.getLangOpts().MSVCCompat) {
11904 // Find any user-declared move assignment operator.
11905 for (auto *I : RD->methods()) {
11906 if (I->isCopyAssignmentOperator()) {
11907 UserDeclaredOperation = I;
11911 assert(UserDeclaredOperation);
11914 if (UserDeclaredOperation) {
11915 S.Diag(UserDeclaredOperation->getLocation(),
11916 diag::warn_deprecated_copy_operation)
11917 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11918 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11922 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11923 CXXMethodDecl *CopyAssignOperator) {
11924 assert((CopyAssignOperator->isDefaulted() &&
11925 CopyAssignOperator->isOverloadedOperator() &&
11926 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11927 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11928 !CopyAssignOperator->isDeleted()) &&
11929 "DefineImplicitCopyAssignment called for wrong function");
11930 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11933 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11934 if (ClassDecl->isInvalidDecl()) {
11935 CopyAssignOperator->setInvalidDecl();
11939 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11941 // The exception specification is needed because we are defining the
11943 ResolveExceptionSpec(CurrentLocation,
11944 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11946 // Add a context note for diagnostics produced after this point.
11947 Scope.addContextNote(CurrentLocation);
11949 // C++11 [class.copy]p18:
11950 // The [definition of an implicitly declared copy assignment operator] is
11951 // deprecated if the class has a user-declared copy constructor or a
11952 // user-declared destructor.
11953 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11954 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11956 // C++0x [class.copy]p30:
11957 // The implicitly-defined or explicitly-defaulted copy assignment operator
11958 // for a non-union class X performs memberwise copy assignment of its
11959 // subobjects. The direct base classes of X are assigned first, in the
11960 // order of their declaration in the base-specifier-list, and then the
11961 // immediate non-static data members of X are assigned, in the order in
11962 // which they were declared in the class definition.
11964 // The statements that form the synthesized function body.
11965 SmallVector<Stmt*, 8> Statements;
11967 // The parameter for the "other" object, which we are copying from.
11968 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11969 Qualifiers OtherQuals = Other->getType().getQualifiers();
11970 QualType OtherRefType = Other->getType();
11971 if (const LValueReferenceType *OtherRef
11972 = OtherRefType->getAs<LValueReferenceType>()) {
11973 OtherRefType = OtherRef->getPointeeType();
11974 OtherQuals = OtherRefType.getQualifiers();
11977 // Our location for everything implicitly-generated.
11978 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11979 ? CopyAssignOperator->getEndLoc()
11980 : CopyAssignOperator->getLocation();
11982 // Builds a DeclRefExpr for the "other" object.
11983 RefBuilder OtherRef(Other, OtherRefType);
11985 // Builds the "this" pointer.
11988 // Assign base classes.
11989 bool Invalid = false;
11990 for (auto &Base : ClassDecl->bases()) {
11991 // Form the assignment:
11992 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11993 QualType BaseType = Base.getType().getUnqualifiedType();
11994 if (!BaseType->isRecordType()) {
11999 CXXCastPath BasePath;
12000 BasePath.push_back(&Base);
12002 // Construct the "from" expression, which is an implicit cast to the
12003 // appropriately-qualified base type.
12004 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12005 VK_LValue, BasePath);
12007 // Dereference "this".
12008 DerefBuilder DerefThis(This);
12009 CastBuilder To(DerefThis,
12010 Context.getQualifiedType(
12011 BaseType, CopyAssignOperator->getTypeQualifiers()),
12012 VK_LValue, BasePath);
12015 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12017 /*CopyingBaseSubobject=*/true,
12019 if (Copy.isInvalid()) {
12020 CopyAssignOperator->setInvalidDecl();
12024 // Success! Record the copy.
12025 Statements.push_back(Copy.getAs<Expr>());
12028 // Assign non-static members.
12029 for (auto *Field : ClassDecl->fields()) {
12030 // FIXME: We should form some kind of AST representation for the implied
12031 // memcpy in a union copy operation.
12032 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12035 if (Field->isInvalidDecl()) {
12040 // Check for members of reference type; we can't copy those.
12041 if (Field->getType()->isReferenceType()) {
12042 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12043 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12044 Diag(Field->getLocation(), diag::note_declared_at);
12049 // Check for members of const-qualified, non-class type.
12050 QualType BaseType = Context.getBaseElementType(Field->getType());
12051 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12052 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12053 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12054 Diag(Field->getLocation(), diag::note_declared_at);
12059 // Suppress assigning zero-width bitfields.
12060 if (Field->isZeroLengthBitField(Context))
12063 QualType FieldType = Field->getType().getNonReferenceType();
12064 if (FieldType->isIncompleteArrayType()) {
12065 assert(ClassDecl->hasFlexibleArrayMember() &&
12066 "Incomplete array type is not valid");
12070 // Build references to the field in the object we're copying from and to.
12071 CXXScopeSpec SS; // Intentionally empty
12072 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12074 MemberLookup.addDecl(Field);
12075 MemberLookup.resolveKind();
12077 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12079 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12081 // Build the copy of this field.
12082 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12084 /*CopyingBaseSubobject=*/false,
12086 if (Copy.isInvalid()) {
12087 CopyAssignOperator->setInvalidDecl();
12091 // Success! Record the copy.
12092 Statements.push_back(Copy.getAs<Stmt>());
12096 // Add a "return *this;"
12097 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12099 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12100 if (Return.isInvalid())
12103 Statements.push_back(Return.getAs<Stmt>());
12107 CopyAssignOperator->setInvalidDecl();
12113 CompoundScopeRAII CompoundScope(*this);
12114 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12115 /*isStmtExpr=*/false);
12116 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12118 CopyAssignOperator->setBody(Body.getAs<Stmt>());
12119 CopyAssignOperator->markUsed(Context);
12121 if (ASTMutationListener *L = getASTMutationListener()) {
12122 L->CompletedImplicitDefinition(CopyAssignOperator);
12126 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12127 assert(ClassDecl->needsImplicitMoveAssignment());
12129 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12130 if (DSM.isAlreadyBeingDeclared())
12133 // Note: The following rules are largely analoguous to the move
12134 // constructor rules.
12136 QualType ArgType = Context.getTypeDeclType(ClassDecl);
12137 QualType RetType = Context.getLValueReferenceType(ArgType);
12138 ArgType = Context.getRValueReferenceType(ArgType);
12140 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12144 // An implicitly-declared move assignment operator is an inline public
12145 // member of its class.
12146 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12147 SourceLocation ClassLoc = ClassDecl->getLocation();
12148 DeclarationNameInfo NameInfo(Name, ClassLoc);
12149 CXXMethodDecl *MoveAssignment =
12150 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12151 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12152 /*isInline=*/true, Constexpr, SourceLocation());
12153 MoveAssignment->setAccess(AS_public);
12154 MoveAssignment->setDefaulted();
12155 MoveAssignment->setImplicit();
12157 if (getLangOpts().CUDA) {
12158 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12160 /* ConstRHS */ false,
12161 /* Diagnose */ false);
12164 // Build an exception specification pointing back at this member.
12165 FunctionProtoType::ExtProtoInfo EPI =
12166 getImplicitMethodEPI(*this, MoveAssignment);
12167 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12169 // Add the parameter to the operator.
12170 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12171 ClassLoc, ClassLoc,
12172 /*Id=*/nullptr, ArgType,
12173 /*TInfo=*/nullptr, SC_None,
12175 MoveAssignment->setParams(FromParam);
12177 MoveAssignment->setTrivial(
12178 ClassDecl->needsOverloadResolutionForMoveAssignment()
12179 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12180 : ClassDecl->hasTrivialMoveAssignment());
12182 // Note that we have added this copy-assignment operator.
12183 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12185 Scope *S = getScopeForContext(ClassDecl);
12186 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12188 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12189 ClassDecl->setImplicitMoveAssignmentIsDeleted();
12190 SetDeclDeleted(MoveAssignment, ClassLoc);
12194 PushOnScopeChains(MoveAssignment, S, false);
12195 ClassDecl->addDecl(MoveAssignment);
12197 return MoveAssignment;
12200 /// Check if we're implicitly defining a move assignment operator for a class
12201 /// with virtual bases. Such a move assignment might move-assign the virtual
12202 /// base multiple times.
12203 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12204 SourceLocation CurrentLocation) {
12205 assert(!Class->isDependentContext() && "should not define dependent move");
12207 // Only a virtual base could get implicitly move-assigned multiple times.
12208 // Only a non-trivial move assignment can observe this. We only want to
12209 // diagnose if we implicitly define an assignment operator that assigns
12210 // two base classes, both of which move-assign the same virtual base.
12211 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12212 Class->getNumBases() < 2)
12215 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12216 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12219 for (auto &BI : Class->bases()) {
12220 Worklist.push_back(&BI);
12221 while (!Worklist.empty()) {
12222 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12223 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12225 // If the base has no non-trivial move assignment operators,
12226 // we don't care about moves from it.
12227 if (!Base->hasNonTrivialMoveAssignment())
12230 // If there's nothing virtual here, skip it.
12231 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12234 // If we're not actually going to call a move assignment for this base,
12235 // or the selected move assignment is trivial, skip it.
12236 Sema::SpecialMemberOverloadResult SMOR =
12237 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12238 /*ConstArg*/false, /*VolatileArg*/false,
12239 /*RValueThis*/true, /*ConstThis*/false,
12240 /*VolatileThis*/false);
12241 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12242 !SMOR.getMethod()->isMoveAssignmentOperator())
12245 if (BaseSpec->isVirtual()) {
12246 // We're going to move-assign this virtual base, and its move
12247 // assignment operator is not trivial. If this can happen for
12248 // multiple distinct direct bases of Class, diagnose it. (If it
12249 // only happens in one base, we'll diagnose it when synthesizing
12250 // that base class's move assignment operator.)
12251 CXXBaseSpecifier *&Existing =
12252 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12254 if (Existing && Existing != &BI) {
12255 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12257 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12258 << (Base->getCanonicalDecl() ==
12259 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12260 << Base << Existing->getType() << Existing->getSourceRange();
12261 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12262 << (Base->getCanonicalDecl() ==
12263 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12264 << Base << BI.getType() << BaseSpec->getSourceRange();
12266 // Only diagnose each vbase once.
12267 Existing = nullptr;
12270 // Only walk over bases that have defaulted move assignment operators.
12271 // We assume that any user-provided move assignment operator handles
12272 // the multiple-moves-of-vbase case itself somehow.
12273 if (!SMOR.getMethod()->isDefaulted())
12276 // We're going to move the base classes of Base. Add them to the list.
12277 for (auto &BI : Base->bases())
12278 Worklist.push_back(&BI);
12284 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12285 CXXMethodDecl *MoveAssignOperator) {
12286 assert((MoveAssignOperator->isDefaulted() &&
12287 MoveAssignOperator->isOverloadedOperator() &&
12288 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12289 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12290 !MoveAssignOperator->isDeleted()) &&
12291 "DefineImplicitMoveAssignment called for wrong function");
12292 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12295 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12296 if (ClassDecl->isInvalidDecl()) {
12297 MoveAssignOperator->setInvalidDecl();
12301 // C++0x [class.copy]p28:
12302 // The implicitly-defined or move assignment operator for a non-union class
12303 // X performs memberwise move assignment of its subobjects. The direct base
12304 // classes of X are assigned first, in the order of their declaration in the
12305 // base-specifier-list, and then the immediate non-static data members of X
12306 // are assigned, in the order in which they were declared in the class
12309 // Issue a warning if our implicit move assignment operator will move
12310 // from a virtual base more than once.
12311 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12313 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12315 // The exception specification is needed because we are defining the
12317 ResolveExceptionSpec(CurrentLocation,
12318 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12320 // Add a context note for diagnostics produced after this point.
12321 Scope.addContextNote(CurrentLocation);
12323 // The statements that form the synthesized function body.
12324 SmallVector<Stmt*, 8> Statements;
12326 // The parameter for the "other" object, which we are move from.
12327 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12328 QualType OtherRefType = Other->getType()->
12329 getAs<RValueReferenceType>()->getPointeeType();
12331 // Our location for everything implicitly-generated.
12332 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12333 ? MoveAssignOperator->getEndLoc()
12334 : MoveAssignOperator->getLocation();
12336 // Builds a reference to the "other" object.
12337 RefBuilder OtherRef(Other, OtherRefType);
12339 MoveCastBuilder MoveOther(OtherRef);
12341 // Builds the "this" pointer.
12344 // Assign base classes.
12345 bool Invalid = false;
12346 for (auto &Base : ClassDecl->bases()) {
12347 // C++11 [class.copy]p28:
12348 // It is unspecified whether subobjects representing virtual base classes
12349 // are assigned more than once by the implicitly-defined copy assignment
12351 // FIXME: Do not assign to a vbase that will be assigned by some other base
12352 // class. For a move-assignment, this can result in the vbase being moved
12355 // Form the assignment:
12356 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12357 QualType BaseType = Base.getType().getUnqualifiedType();
12358 if (!BaseType->isRecordType()) {
12363 CXXCastPath BasePath;
12364 BasePath.push_back(&Base);
12366 // Construct the "from" expression, which is an implicit cast to the
12367 // appropriately-qualified base type.
12368 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12370 // Dereference "this".
12371 DerefBuilder DerefThis(This);
12373 // Implicitly cast "this" to the appropriately-qualified base type.
12374 CastBuilder To(DerefThis,
12375 Context.getQualifiedType(
12376 BaseType, MoveAssignOperator->getTypeQualifiers()),
12377 VK_LValue, BasePath);
12380 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12382 /*CopyingBaseSubobject=*/true,
12383 /*Copying=*/false);
12384 if (Move.isInvalid()) {
12385 MoveAssignOperator->setInvalidDecl();
12389 // Success! Record the move.
12390 Statements.push_back(Move.getAs<Expr>());
12393 // Assign non-static members.
12394 for (auto *Field : ClassDecl->fields()) {
12395 // FIXME: We should form some kind of AST representation for the implied
12396 // memcpy in a union copy operation.
12397 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12400 if (Field->isInvalidDecl()) {
12405 // Check for members of reference type; we can't move those.
12406 if (Field->getType()->isReferenceType()) {
12407 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12408 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12409 Diag(Field->getLocation(), diag::note_declared_at);
12414 // Check for members of const-qualified, non-class type.
12415 QualType BaseType = Context.getBaseElementType(Field->getType());
12416 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12417 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12418 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12419 Diag(Field->getLocation(), diag::note_declared_at);
12424 // Suppress assigning zero-width bitfields.
12425 if (Field->isZeroLengthBitField(Context))
12428 QualType FieldType = Field->getType().getNonReferenceType();
12429 if (FieldType->isIncompleteArrayType()) {
12430 assert(ClassDecl->hasFlexibleArrayMember() &&
12431 "Incomplete array type is not valid");
12435 // Build references to the field in the object we're copying from and to.
12436 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12438 MemberLookup.addDecl(Field);
12439 MemberLookup.resolveKind();
12440 MemberBuilder From(MoveOther, OtherRefType,
12441 /*IsArrow=*/false, MemberLookup);
12442 MemberBuilder To(This, getCurrentThisType(),
12443 /*IsArrow=*/true, MemberLookup);
12445 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12446 "Member reference with rvalue base must be rvalue except for reference "
12447 "members, which aren't allowed for move assignment.");
12449 // Build the move of this field.
12450 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12452 /*CopyingBaseSubobject=*/false,
12453 /*Copying=*/false);
12454 if (Move.isInvalid()) {
12455 MoveAssignOperator->setInvalidDecl();
12459 // Success! Record the copy.
12460 Statements.push_back(Move.getAs<Stmt>());
12464 // Add a "return *this;"
12465 ExprResult ThisObj =
12466 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12468 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12469 if (Return.isInvalid())
12472 Statements.push_back(Return.getAs<Stmt>());
12476 MoveAssignOperator->setInvalidDecl();
12482 CompoundScopeRAII CompoundScope(*this);
12483 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12484 /*isStmtExpr=*/false);
12485 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12487 MoveAssignOperator->setBody(Body.getAs<Stmt>());
12488 MoveAssignOperator->markUsed(Context);
12490 if (ASTMutationListener *L = getASTMutationListener()) {
12491 L->CompletedImplicitDefinition(MoveAssignOperator);
12495 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12496 CXXRecordDecl *ClassDecl) {
12497 // C++ [class.copy]p4:
12498 // If the class definition does not explicitly declare a copy
12499 // constructor, one is declared implicitly.
12500 assert(ClassDecl->needsImplicitCopyConstructor());
12502 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12503 if (DSM.isAlreadyBeingDeclared())
12506 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12507 QualType ArgType = ClassType;
12508 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12510 ArgType = ArgType.withConst();
12512 if (Context.getLangOpts().OpenCLCPlusPlus)
12513 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12515 ArgType = Context.getLValueReferenceType(ArgType);
12517 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12518 CXXCopyConstructor,
12521 DeclarationName Name
12522 = Context.DeclarationNames.getCXXConstructorName(
12523 Context.getCanonicalType(ClassType));
12524 SourceLocation ClassLoc = ClassDecl->getLocation();
12525 DeclarationNameInfo NameInfo(Name, ClassLoc);
12527 // An implicitly-declared copy constructor is an inline public
12528 // member of its class.
12529 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12530 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12531 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12533 CopyConstructor->setAccess(AS_public);
12534 CopyConstructor->setDefaulted();
12536 if (getLangOpts().CUDA) {
12537 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12539 /* ConstRHS */ Const,
12540 /* Diagnose */ false);
12543 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12545 // Add the parameter to the constructor.
12546 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12547 ClassLoc, ClassLoc,
12548 /*IdentifierInfo=*/nullptr,
12549 ArgType, /*TInfo=*/nullptr,
12551 CopyConstructor->setParams(FromParam);
12553 CopyConstructor->setTrivial(
12554 ClassDecl->needsOverloadResolutionForCopyConstructor()
12555 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12556 : ClassDecl->hasTrivialCopyConstructor());
12558 CopyConstructor->setTrivialForCall(
12559 ClassDecl->hasAttr<TrivialABIAttr>() ||
12560 (ClassDecl->needsOverloadResolutionForCopyConstructor()
12561 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12562 TAH_ConsiderTrivialABI)
12563 : ClassDecl->hasTrivialCopyConstructorForCall()));
12565 // Note that we have declared this constructor.
12566 ++ASTContext::NumImplicitCopyConstructorsDeclared;
12568 Scope *S = getScopeForContext(ClassDecl);
12569 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12571 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12572 ClassDecl->setImplicitCopyConstructorIsDeleted();
12573 SetDeclDeleted(CopyConstructor, ClassLoc);
12577 PushOnScopeChains(CopyConstructor, S, false);
12578 ClassDecl->addDecl(CopyConstructor);
12580 return CopyConstructor;
12583 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12584 CXXConstructorDecl *CopyConstructor) {
12585 assert((CopyConstructor->isDefaulted() &&
12586 CopyConstructor->isCopyConstructor() &&
12587 !CopyConstructor->doesThisDeclarationHaveABody() &&
12588 !CopyConstructor->isDeleted()) &&
12589 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12590 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12593 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12594 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12596 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12598 // The exception specification is needed because we are defining the
12600 ResolveExceptionSpec(CurrentLocation,
12601 CopyConstructor->getType()->castAs<FunctionProtoType>());
12602 MarkVTableUsed(CurrentLocation, ClassDecl);
12604 // Add a context note for diagnostics produced after this point.
12605 Scope.addContextNote(CurrentLocation);
12607 // C++11 [class.copy]p7:
12608 // The [definition of an implicitly declared copy constructor] is
12609 // deprecated if the class has a user-declared copy assignment operator
12610 // or a user-declared destructor.
12611 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12612 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12614 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12615 CopyConstructor->setInvalidDecl();
12617 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12618 ? CopyConstructor->getEndLoc()
12619 : CopyConstructor->getLocation();
12620 Sema::CompoundScopeRAII CompoundScope(*this);
12621 CopyConstructor->setBody(
12622 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12623 CopyConstructor->markUsed(Context);
12626 if (ASTMutationListener *L = getASTMutationListener()) {
12627 L->CompletedImplicitDefinition(CopyConstructor);
12631 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12632 CXXRecordDecl *ClassDecl) {
12633 assert(ClassDecl->needsImplicitMoveConstructor());
12635 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12636 if (DSM.isAlreadyBeingDeclared())
12639 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12641 QualType ArgType = ClassType;
12642 if (Context.getLangOpts().OpenCLCPlusPlus)
12643 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12644 ArgType = Context.getRValueReferenceType(ArgType);
12646 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12647 CXXMoveConstructor,
12650 DeclarationName Name
12651 = Context.DeclarationNames.getCXXConstructorName(
12652 Context.getCanonicalType(ClassType));
12653 SourceLocation ClassLoc = ClassDecl->getLocation();
12654 DeclarationNameInfo NameInfo(Name, ClassLoc);
12656 // C++11 [class.copy]p11:
12657 // An implicitly-declared copy/move constructor is an inline public
12658 // member of its class.
12659 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12660 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12661 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12663 MoveConstructor->setAccess(AS_public);
12664 MoveConstructor->setDefaulted();
12666 if (getLangOpts().CUDA) {
12667 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12669 /* ConstRHS */ false,
12670 /* Diagnose */ false);
12673 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12675 // Add the parameter to the constructor.
12676 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12677 ClassLoc, ClassLoc,
12678 /*IdentifierInfo=*/nullptr,
12679 ArgType, /*TInfo=*/nullptr,
12681 MoveConstructor->setParams(FromParam);
12683 MoveConstructor->setTrivial(
12684 ClassDecl->needsOverloadResolutionForMoveConstructor()
12685 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12686 : ClassDecl->hasTrivialMoveConstructor());
12688 MoveConstructor->setTrivialForCall(
12689 ClassDecl->hasAttr<TrivialABIAttr>() ||
12690 (ClassDecl->needsOverloadResolutionForMoveConstructor()
12691 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12692 TAH_ConsiderTrivialABI)
12693 : ClassDecl->hasTrivialMoveConstructorForCall()));
12695 // Note that we have declared this constructor.
12696 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12698 Scope *S = getScopeForContext(ClassDecl);
12699 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12701 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12702 ClassDecl->setImplicitMoveConstructorIsDeleted();
12703 SetDeclDeleted(MoveConstructor, ClassLoc);
12707 PushOnScopeChains(MoveConstructor, S, false);
12708 ClassDecl->addDecl(MoveConstructor);
12710 return MoveConstructor;
12713 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12714 CXXConstructorDecl *MoveConstructor) {
12715 assert((MoveConstructor->isDefaulted() &&
12716 MoveConstructor->isMoveConstructor() &&
12717 !MoveConstructor->doesThisDeclarationHaveABody() &&
12718 !MoveConstructor->isDeleted()) &&
12719 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12720 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12723 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12724 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12726 SynthesizedFunctionScope Scope(*this, MoveConstructor);
12728 // The exception specification is needed because we are defining the
12730 ResolveExceptionSpec(CurrentLocation,
12731 MoveConstructor->getType()->castAs<FunctionProtoType>());
12732 MarkVTableUsed(CurrentLocation, ClassDecl);
12734 // Add a context note for diagnostics produced after this point.
12735 Scope.addContextNote(CurrentLocation);
12737 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12738 MoveConstructor->setInvalidDecl();
12740 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12741 ? MoveConstructor->getEndLoc()
12742 : MoveConstructor->getLocation();
12743 Sema::CompoundScopeRAII CompoundScope(*this);
12744 MoveConstructor->setBody(ActOnCompoundStmt(
12745 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12746 MoveConstructor->markUsed(Context);
12749 if (ASTMutationListener *L = getASTMutationListener()) {
12750 L->CompletedImplicitDefinition(MoveConstructor);
12754 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12755 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12758 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12759 SourceLocation CurrentLocation,
12760 CXXConversionDecl *Conv) {
12761 SynthesizedFunctionScope Scope(*this, Conv);
12762 assert(!Conv->getReturnType()->isUndeducedType());
12764 CXXRecordDecl *Lambda = Conv->getParent();
12765 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12766 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12768 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12769 CallOp = InstantiateFunctionDeclaration(
12770 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12774 Invoker = InstantiateFunctionDeclaration(
12775 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12780 if (CallOp->isInvalidDecl())
12783 // Mark the call operator referenced (and add to pending instantiations
12785 // For both the conversion and static-invoker template specializations
12786 // we construct their body's in this function, so no need to add them
12787 // to the PendingInstantiations.
12788 MarkFunctionReferenced(CurrentLocation, CallOp);
12790 // Fill in the __invoke function with a dummy implementation. IR generation
12791 // will fill in the actual details. Update its type in case it contained
12793 Invoker->markUsed(Context);
12794 Invoker->setReferenced();
12795 Invoker->setType(Conv->getReturnType()->getPointeeType());
12796 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12798 // Construct the body of the conversion function { return __invoke; }.
12799 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12800 VK_LValue, Conv->getLocation()).get();
12801 assert(FunctionRef && "Can't refer to __invoke function?");
12802 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12803 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12804 Conv->getLocation()));
12805 Conv->markUsed(Context);
12806 Conv->setReferenced();
12808 if (ASTMutationListener *L = getASTMutationListener()) {
12809 L->CompletedImplicitDefinition(Conv);
12810 L->CompletedImplicitDefinition(Invoker);
12816 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12817 SourceLocation CurrentLocation,
12818 CXXConversionDecl *Conv)
12820 assert(!Conv->getParent()->isGenericLambda());
12822 SynthesizedFunctionScope Scope(*this, Conv);
12824 // Copy-initialize the lambda object as needed to capture it.
12825 Expr *This = ActOnCXXThis(CurrentLocation).get();
12826 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12828 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12829 Conv->getLocation(),
12832 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12833 // behavior. Note that only the general conversion function does this
12834 // (since it's unusable otherwise); in the case where we inline the
12835 // block literal, it has block literal lifetime semantics.
12836 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12837 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12838 CK_CopyAndAutoreleaseBlockObject,
12839 BuildBlock.get(), nullptr, VK_RValue);
12841 if (BuildBlock.isInvalid()) {
12842 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12843 Conv->setInvalidDecl();
12847 // Create the return statement that returns the block from the conversion
12849 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12850 if (Return.isInvalid()) {
12851 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12852 Conv->setInvalidDecl();
12856 // Set the body of the conversion function.
12857 Stmt *ReturnS = Return.get();
12858 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12859 Conv->getLocation()));
12860 Conv->markUsed(Context);
12862 // We're done; notify the mutation listener, if any.
12863 if (ASTMutationListener *L = getASTMutationListener()) {
12864 L->CompletedImplicitDefinition(Conv);
12868 /// Determine whether the given list arguments contains exactly one
12869 /// "real" (non-default) argument.
12870 static bool hasOneRealArgument(MultiExprArg Args) {
12871 switch (Args.size()) {
12876 if (!Args[1]->isDefaultArgument())
12881 return !Args[0]->isDefaultArgument();
12888 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12889 NamedDecl *FoundDecl,
12890 CXXConstructorDecl *Constructor,
12891 MultiExprArg ExprArgs,
12892 bool HadMultipleCandidates,
12893 bool IsListInitialization,
12894 bool IsStdInitListInitialization,
12895 bool RequiresZeroInit,
12896 unsigned ConstructKind,
12897 SourceRange ParenRange) {
12898 bool Elidable = false;
12900 // C++0x [class.copy]p34:
12901 // When certain criteria are met, an implementation is allowed to
12902 // omit the copy/move construction of a class object, even if the
12903 // copy/move constructor and/or destructor for the object have
12904 // side effects. [...]
12905 // - when a temporary class object that has not been bound to a
12906 // reference (12.2) would be copied/moved to a class object
12907 // with the same cv-unqualified type, the copy/move operation
12908 // can be omitted by constructing the temporary object
12909 // directly into the target of the omitted copy/move
12910 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12911 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12912 Expr *SubExpr = ExprArgs[0];
12913 Elidable = SubExpr->isTemporaryObject(
12914 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12917 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12918 FoundDecl, Constructor,
12919 Elidable, ExprArgs, HadMultipleCandidates,
12920 IsListInitialization,
12921 IsStdInitListInitialization, RequiresZeroInit,
12922 ConstructKind, ParenRange);
12926 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12927 NamedDecl *FoundDecl,
12928 CXXConstructorDecl *Constructor,
12930 MultiExprArg ExprArgs,
12931 bool HadMultipleCandidates,
12932 bool IsListInitialization,
12933 bool IsStdInitListInitialization,
12934 bool RequiresZeroInit,
12935 unsigned ConstructKind,
12936 SourceRange ParenRange) {
12937 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12938 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12939 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12940 return ExprError();
12943 return BuildCXXConstructExpr(
12944 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12945 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12946 RequiresZeroInit, ConstructKind, ParenRange);
12949 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12950 /// including handling of its default argument expressions.
12952 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12953 CXXConstructorDecl *Constructor,
12955 MultiExprArg ExprArgs,
12956 bool HadMultipleCandidates,
12957 bool IsListInitialization,
12958 bool IsStdInitListInitialization,
12959 bool RequiresZeroInit,
12960 unsigned ConstructKind,
12961 SourceRange ParenRange) {
12962 assert(declaresSameEntity(
12963 Constructor->getParent(),
12964 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12965 "given constructor for wrong type");
12966 MarkFunctionReferenced(ConstructLoc, Constructor);
12967 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12968 return ExprError();
12970 return CXXConstructExpr::Create(
12971 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12972 ExprArgs, HadMultipleCandidates, IsListInitialization,
12973 IsStdInitListInitialization, RequiresZeroInit,
12974 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12978 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12979 assert(Field->hasInClassInitializer());
12981 // If we already have the in-class initializer nothing needs to be done.
12982 if (Field->getInClassInitializer())
12983 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12985 // If we might have already tried and failed to instantiate, don't try again.
12986 if (Field->isInvalidDecl())
12987 return ExprError();
12989 // Maybe we haven't instantiated the in-class initializer. Go check the
12990 // pattern FieldDecl to see if it has one.
12991 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12993 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12994 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12995 DeclContext::lookup_result Lookup =
12996 ClassPattern->lookup(Field->getDeclName());
12998 // Lookup can return at most two results: the pattern for the field, or the
12999 // injected class name of the parent record. No other member can have the
13000 // same name as the field.
13001 // In modules mode, lookup can return multiple results (coming from
13002 // different modules).
13003 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13004 "more than two lookup results for field name");
13005 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13007 assert(isa<CXXRecordDecl>(Lookup[0]) &&
13008 "cannot have other non-field member with same name");
13009 for (auto L : Lookup)
13010 if (isa<FieldDecl>(L)) {
13011 Pattern = cast<FieldDecl>(L);
13014 assert(Pattern && "We must have set the Pattern!");
13017 if (!Pattern->hasInClassInitializer() ||
13018 InstantiateInClassInitializer(Loc, Field, Pattern,
13019 getTemplateInstantiationArgs(Field))) {
13020 // Don't diagnose this again.
13021 Field->setInvalidDecl();
13022 return ExprError();
13024 return CXXDefaultInitExpr::Create(Context, Loc, Field);
13028 // If the brace-or-equal-initializer of a non-static data member
13029 // invokes a defaulted default constructor of its class or of an
13030 // enclosing class in a potentially evaluated subexpression, the
13031 // program is ill-formed.
13033 // This resolution is unworkable: the exception specification of the
13034 // default constructor can be needed in an unevaluated context, in
13035 // particular, in the operand of a noexcept-expression, and we can be
13036 // unable to compute an exception specification for an enclosed class.
13038 // Any attempt to resolve the exception specification of a defaulted default
13039 // constructor before the initializer is lexically complete will ultimately
13040 // come here at which point we can diagnose it.
13041 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13042 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13043 << OutermostClass << Field;
13044 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13045 // Recover by marking the field invalid, unless we're in a SFINAE context.
13046 if (!isSFINAEContext())
13047 Field->setInvalidDecl();
13048 return ExprError();
13051 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13052 if (VD->isInvalidDecl()) return;
13054 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13055 if (ClassDecl->isInvalidDecl()) return;
13056 if (ClassDecl->hasIrrelevantDestructor()) return;
13057 if (ClassDecl->isDependentContext()) return;
13059 if (VD->isNoDestroy(getASTContext()))
13062 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13063 MarkFunctionReferenced(VD->getLocation(), Destructor);
13064 CheckDestructorAccess(VD->getLocation(), Destructor,
13065 PDiag(diag::err_access_dtor_var)
13066 << VD->getDeclName()
13068 DiagnoseUseOfDecl(Destructor, VD->getLocation());
13070 if (Destructor->isTrivial()) return;
13071 if (!VD->hasGlobalStorage()) return;
13073 // Emit warning for non-trivial dtor in global scope (a real global,
13074 // class-static, function-static).
13075 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13077 // TODO: this should be re-enabled for static locals by !CXAAtExit
13078 if (!VD->isStaticLocal())
13079 Diag(VD->getLocation(), diag::warn_global_destructor);
13082 /// Given a constructor and the set of arguments provided for the
13083 /// constructor, convert the arguments and add any required default arguments
13084 /// to form a proper call to this constructor.
13086 /// \returns true if an error occurred, false otherwise.
13088 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13089 MultiExprArg ArgsPtr,
13090 SourceLocation Loc,
13091 SmallVectorImpl<Expr*> &ConvertedArgs,
13092 bool AllowExplicit,
13093 bool IsListInitialization) {
13094 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13095 unsigned NumArgs = ArgsPtr.size();
13096 Expr **Args = ArgsPtr.data();
13098 const FunctionProtoType *Proto
13099 = Constructor->getType()->getAs<FunctionProtoType>();
13100 assert(Proto && "Constructor without a prototype?");
13101 unsigned NumParams = Proto->getNumParams();
13103 // If too few arguments are available, we'll fill in the rest with defaults.
13104 if (NumArgs < NumParams)
13105 ConvertedArgs.reserve(NumParams);
13107 ConvertedArgs.reserve(NumArgs);
13109 VariadicCallType CallType =
13110 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13111 SmallVector<Expr *, 8> AllArgs;
13112 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13114 llvm::makeArrayRef(Args, NumArgs),
13116 CallType, AllowExplicit,
13117 IsListInitialization);
13118 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13120 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13122 CheckConstructorCall(Constructor,
13123 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13130 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13131 const FunctionDecl *FnDecl) {
13132 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13133 if (isa<NamespaceDecl>(DC)) {
13134 return SemaRef.Diag(FnDecl->getLocation(),
13135 diag::err_operator_new_delete_declared_in_namespace)
13136 << FnDecl->getDeclName();
13139 if (isa<TranslationUnitDecl>(DC) &&
13140 FnDecl->getStorageClass() == SC_Static) {
13141 return SemaRef.Diag(FnDecl->getLocation(),
13142 diag::err_operator_new_delete_declared_static)
13143 << FnDecl->getDeclName();
13150 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13151 QualType QTy = PtrTy->getPointeeType();
13152 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13153 return SemaRef.Context.getPointerType(QTy);
13157 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13158 CanQualType ExpectedResultType,
13159 CanQualType ExpectedFirstParamType,
13160 unsigned DependentParamTypeDiag,
13161 unsigned InvalidParamTypeDiag) {
13162 QualType ResultType =
13163 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13165 // Check that the result type is not dependent.
13166 if (ResultType->isDependentType())
13167 return SemaRef.Diag(FnDecl->getLocation(),
13168 diag::err_operator_new_delete_dependent_result_type)
13169 << FnDecl->getDeclName() << ExpectedResultType;
13171 // OpenCL C++: the operator is valid on any address space.
13172 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13173 if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13174 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13178 // Check that the result type is what we expect.
13179 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13180 return SemaRef.Diag(FnDecl->getLocation(),
13181 diag::err_operator_new_delete_invalid_result_type)
13182 << FnDecl->getDeclName() << ExpectedResultType;
13184 // A function template must have at least 2 parameters.
13185 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13186 return SemaRef.Diag(FnDecl->getLocation(),
13187 diag::err_operator_new_delete_template_too_few_parameters)
13188 << FnDecl->getDeclName();
13190 // The function decl must have at least 1 parameter.
13191 if (FnDecl->getNumParams() == 0)
13192 return SemaRef.Diag(FnDecl->getLocation(),
13193 diag::err_operator_new_delete_too_few_parameters)
13194 << FnDecl->getDeclName();
13196 // Check the first parameter type is not dependent.
13197 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13198 if (FirstParamType->isDependentType())
13199 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13200 << FnDecl->getDeclName() << ExpectedFirstParamType;
13202 // Check that the first parameter type is what we expect.
13203 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13204 // OpenCL C++: the operator is valid on any address space.
13206 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13207 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13210 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13211 ExpectedFirstParamType)
13212 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13213 << FnDecl->getDeclName() << ExpectedFirstParamType;
13219 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13220 // C++ [basic.stc.dynamic.allocation]p1:
13221 // A program is ill-formed if an allocation function is declared in a
13222 // namespace scope other than global scope or declared static in global
13224 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13227 CanQualType SizeTy =
13228 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13230 // C++ [basic.stc.dynamic.allocation]p1:
13231 // The return type shall be void*. The first parameter shall have type
13233 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13235 diag::err_operator_new_dependent_param_type,
13236 diag::err_operator_new_param_type))
13239 // C++ [basic.stc.dynamic.allocation]p1:
13240 // The first parameter shall not have an associated default argument.
13241 if (FnDecl->getParamDecl(0)->hasDefaultArg())
13242 return SemaRef.Diag(FnDecl->getLocation(),
13243 diag::err_operator_new_default_arg)
13244 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13250 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13251 // C++ [basic.stc.dynamic.deallocation]p1:
13252 // A program is ill-formed if deallocation functions are declared in a
13253 // namespace scope other than global scope or declared static in global
13255 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13258 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13261 // Within a class C, the first parameter of a destroying operator delete
13262 // shall be of type C *. The first parameter of any other deallocation
13263 // function shall be of type void *.
13264 CanQualType ExpectedFirstParamType =
13265 MD && MD->isDestroyingOperatorDelete()
13266 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13267 SemaRef.Context.getRecordType(MD->getParent())))
13268 : SemaRef.Context.VoidPtrTy;
13270 // C++ [basic.stc.dynamic.deallocation]p2:
13271 // Each deallocation function shall return void
13272 if (CheckOperatorNewDeleteTypes(
13273 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13274 diag::err_operator_delete_dependent_param_type,
13275 diag::err_operator_delete_param_type))
13279 // A destroying operator delete shall be a usual deallocation function.
13280 if (MD && !MD->getParent()->isDependentContext() &&
13281 MD->isDestroyingOperatorDelete() &&
13282 !SemaRef.isUsualDeallocationFunction(MD)) {
13283 SemaRef.Diag(MD->getLocation(),
13284 diag::err_destroying_operator_delete_not_usual);
13291 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13292 /// of this overloaded operator is well-formed. If so, returns false;
13293 /// otherwise, emits appropriate diagnostics and returns true.
13294 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13295 assert(FnDecl && FnDecl->isOverloadedOperator() &&
13296 "Expected an overloaded operator declaration");
13298 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13300 // C++ [over.oper]p5:
13301 // The allocation and deallocation functions, operator new,
13302 // operator new[], operator delete and operator delete[], are
13303 // described completely in 3.7.3. The attributes and restrictions
13304 // found in the rest of this subclause do not apply to them unless
13305 // explicitly stated in 3.7.3.
13306 if (Op == OO_Delete || Op == OO_Array_Delete)
13307 return CheckOperatorDeleteDeclaration(*this, FnDecl);
13309 if (Op == OO_New || Op == OO_Array_New)
13310 return CheckOperatorNewDeclaration(*this, FnDecl);
13312 // C++ [over.oper]p6:
13313 // An operator function shall either be a non-static member
13314 // function or be a non-member function and have at least one
13315 // parameter whose type is a class, a reference to a class, an
13316 // enumeration, or a reference to an enumeration.
13317 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13318 if (MethodDecl->isStatic())
13319 return Diag(FnDecl->getLocation(),
13320 diag::err_operator_overload_static) << FnDecl->getDeclName();
13322 bool ClassOrEnumParam = false;
13323 for (auto Param : FnDecl->parameters()) {
13324 QualType ParamType = Param->getType().getNonReferenceType();
13325 if (ParamType->isDependentType() || ParamType->isRecordType() ||
13326 ParamType->isEnumeralType()) {
13327 ClassOrEnumParam = true;
13332 if (!ClassOrEnumParam)
13333 return Diag(FnDecl->getLocation(),
13334 diag::err_operator_overload_needs_class_or_enum)
13335 << FnDecl->getDeclName();
13338 // C++ [over.oper]p8:
13339 // An operator function cannot have default arguments (8.3.6),
13340 // except where explicitly stated below.
13342 // Only the function-call operator allows default arguments
13343 // (C++ [over.call]p1).
13344 if (Op != OO_Call) {
13345 for (auto Param : FnDecl->parameters()) {
13346 if (Param->hasDefaultArg())
13347 return Diag(Param->getLocation(),
13348 diag::err_operator_overload_default_arg)
13349 << FnDecl->getDeclName() << Param->getDefaultArgRange();
13353 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13354 { false, false, false }
13355 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13356 , { Unary, Binary, MemberOnly }
13357 #include "clang/Basic/OperatorKinds.def"
13360 bool CanBeUnaryOperator = OperatorUses[Op][0];
13361 bool CanBeBinaryOperator = OperatorUses[Op][1];
13362 bool MustBeMemberOperator = OperatorUses[Op][2];
13364 // C++ [over.oper]p8:
13365 // [...] Operator functions cannot have more or fewer parameters
13366 // than the number required for the corresponding operator, as
13367 // described in the rest of this subclause.
13368 unsigned NumParams = FnDecl->getNumParams()
13369 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13370 if (Op != OO_Call &&
13371 ((NumParams == 1 && !CanBeUnaryOperator) ||
13372 (NumParams == 2 && !CanBeBinaryOperator) ||
13373 (NumParams < 1) || (NumParams > 2))) {
13374 // We have the wrong number of parameters.
13375 unsigned ErrorKind;
13376 if (CanBeUnaryOperator && CanBeBinaryOperator) {
13377 ErrorKind = 2; // 2 -> unary or binary.
13378 } else if (CanBeUnaryOperator) {
13379 ErrorKind = 0; // 0 -> unary
13381 assert(CanBeBinaryOperator &&
13382 "All non-call overloaded operators are unary or binary!");
13383 ErrorKind = 1; // 1 -> binary
13386 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13387 << FnDecl->getDeclName() << NumParams << ErrorKind;
13390 // Overloaded operators other than operator() cannot be variadic.
13391 if (Op != OO_Call &&
13392 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13393 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13394 << FnDecl->getDeclName();
13397 // Some operators must be non-static member functions.
13398 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13399 return Diag(FnDecl->getLocation(),
13400 diag::err_operator_overload_must_be_member)
13401 << FnDecl->getDeclName();
13404 // C++ [over.inc]p1:
13405 // The user-defined function called operator++ implements the
13406 // prefix and postfix ++ operator. If this function is a member
13407 // function with no parameters, or a non-member function with one
13408 // parameter of class or enumeration type, it defines the prefix
13409 // increment operator ++ for objects of that type. If the function
13410 // is a member function with one parameter (which shall be of type
13411 // int) or a non-member function with two parameters (the second
13412 // of which shall be of type int), it defines the postfix
13413 // increment operator ++ for objects of that type.
13414 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13415 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13416 QualType ParamType = LastParam->getType();
13418 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13419 !ParamType->isDependentType())
13420 return Diag(LastParam->getLocation(),
13421 diag::err_operator_overload_post_incdec_must_be_int)
13422 << LastParam->getType() << (Op == OO_MinusMinus);
13429 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13430 FunctionTemplateDecl *TpDecl) {
13431 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13433 // Must have one or two template parameters.
13434 if (TemplateParams->size() == 1) {
13435 NonTypeTemplateParmDecl *PmDecl =
13436 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13438 // The template parameter must be a char parameter pack.
13439 if (PmDecl && PmDecl->isTemplateParameterPack() &&
13440 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13443 } else if (TemplateParams->size() == 2) {
13444 TemplateTypeParmDecl *PmType =
13445 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13446 NonTypeTemplateParmDecl *PmArgs =
13447 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13449 // The second template parameter must be a parameter pack with the
13450 // first template parameter as its type.
13451 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13452 PmArgs->isTemplateParameterPack()) {
13453 const TemplateTypeParmType *TArgs =
13454 PmArgs->getType()->getAs<TemplateTypeParmType>();
13455 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13456 TArgs->getIndex() == PmType->getIndex()) {
13457 if (!SemaRef.inTemplateInstantiation())
13458 SemaRef.Diag(TpDecl->getLocation(),
13459 diag::ext_string_literal_operator_template);
13465 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13466 diag::err_literal_operator_template)
13467 << TpDecl->getTemplateParameters()->getSourceRange();
13471 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13472 /// of this literal operator function is well-formed. If so, returns
13473 /// false; otherwise, emits appropriate diagnostics and returns true.
13474 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13475 if (isa<CXXMethodDecl>(FnDecl)) {
13476 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13477 << FnDecl->getDeclName();
13481 if (FnDecl->isExternC()) {
13482 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13483 if (const LinkageSpecDecl *LSD =
13484 FnDecl->getDeclContext()->getExternCContext())
13485 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13489 // This might be the definition of a literal operator template.
13490 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13492 // This might be a specialization of a literal operator template.
13494 TpDecl = FnDecl->getPrimaryTemplate();
13496 // template <char...> type operator "" name() and
13497 // template <class T, T...> type operator "" name() are the only valid
13498 // template signatures, and the only valid signatures with no parameters.
13500 if (FnDecl->param_size() != 0) {
13501 Diag(FnDecl->getLocation(),
13502 diag::err_literal_operator_template_with_params);
13506 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13509 } else if (FnDecl->param_size() == 1) {
13510 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13512 QualType ParamType = Param->getType().getUnqualifiedType();
13514 // Only unsigned long long int, long double, any character type, and const
13515 // char * are allowed as the only parameters.
13516 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13517 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13518 Context.hasSameType(ParamType, Context.CharTy) ||
13519 Context.hasSameType(ParamType, Context.WideCharTy) ||
13520 Context.hasSameType(ParamType, Context.Char8Ty) ||
13521 Context.hasSameType(ParamType, Context.Char16Ty) ||
13522 Context.hasSameType(ParamType, Context.Char32Ty)) {
13523 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13524 QualType InnerType = Ptr->getPointeeType();
13526 // Pointer parameter must be a const char *.
13527 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13529 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13530 Diag(Param->getSourceRange().getBegin(),
13531 diag::err_literal_operator_param)
13532 << ParamType << "'const char *'" << Param->getSourceRange();
13536 } else if (ParamType->isRealFloatingType()) {
13537 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13538 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13541 } else if (ParamType->isIntegerType()) {
13542 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13543 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13547 Diag(Param->getSourceRange().getBegin(),
13548 diag::err_literal_operator_invalid_param)
13549 << ParamType << Param->getSourceRange();
13553 } else if (FnDecl->param_size() == 2) {
13554 FunctionDecl::param_iterator Param = FnDecl->param_begin();
13556 // First, verify that the first parameter is correct.
13558 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13560 // Two parameter function must have a pointer to const as a
13561 // first parameter; let's strip those qualifiers.
13562 const PointerType *PT = FirstParamType->getAs<PointerType>();
13565 Diag((*Param)->getSourceRange().getBegin(),
13566 diag::err_literal_operator_param)
13567 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13571 QualType PointeeType = PT->getPointeeType();
13572 // First parameter must be const
13573 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13574 Diag((*Param)->getSourceRange().getBegin(),
13575 diag::err_literal_operator_param)
13576 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13580 QualType InnerType = PointeeType.getUnqualifiedType();
13581 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13582 // const char32_t* are allowed as the first parameter to a two-parameter
13584 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13585 Context.hasSameType(InnerType, Context.WideCharTy) ||
13586 Context.hasSameType(InnerType, Context.Char8Ty) ||
13587 Context.hasSameType(InnerType, Context.Char16Ty) ||
13588 Context.hasSameType(InnerType, Context.Char32Ty))) {
13589 Diag((*Param)->getSourceRange().getBegin(),
13590 diag::err_literal_operator_param)
13591 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13595 // Move on to the second and final parameter.
13598 // The second parameter must be a std::size_t.
13599 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13600 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13601 Diag((*Param)->getSourceRange().getBegin(),
13602 diag::err_literal_operator_param)
13603 << SecondParamType << Context.getSizeType()
13604 << (*Param)->getSourceRange();
13608 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13612 // Parameters are good.
13614 // A parameter-declaration-clause containing a default argument is not
13615 // equivalent to any of the permitted forms.
13616 for (auto Param : FnDecl->parameters()) {
13617 if (Param->hasDefaultArg()) {
13618 Diag(Param->getDefaultArgRange().getBegin(),
13619 diag::err_literal_operator_default_argument)
13620 << Param->getDefaultArgRange();
13625 StringRef LiteralName
13626 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13627 if (LiteralName[0] != '_' &&
13628 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13629 // C++11 [usrlit.suffix]p1:
13630 // Literal suffix identifiers that do not start with an underscore
13631 // are reserved for future standardization.
13632 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13633 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13639 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13640 /// linkage specification, including the language and (if present)
13641 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13642 /// language string literal. LBraceLoc, if valid, provides the location of
13643 /// the '{' brace. Otherwise, this linkage specification does not
13644 /// have any braces.
13645 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13647 SourceLocation LBraceLoc) {
13648 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13649 if (!Lit->isAscii()) {
13650 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13651 << LangStr->getSourceRange();
13655 StringRef Lang = Lit->getString();
13656 LinkageSpecDecl::LanguageIDs Language;
13658 Language = LinkageSpecDecl::lang_c;
13659 else if (Lang == "C++")
13660 Language = LinkageSpecDecl::lang_cxx;
13662 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13663 << LangStr->getSourceRange();
13667 // FIXME: Add all the various semantics of linkage specifications
13669 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13670 LangStr->getExprLoc(), Language,
13671 LBraceLoc.isValid());
13672 CurContext->addDecl(D);
13673 PushDeclContext(S, D);
13677 /// ActOnFinishLinkageSpecification - Complete the definition of
13678 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13679 /// valid, it's the position of the closing '}' brace in a linkage
13680 /// specification that uses braces.
13681 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13683 SourceLocation RBraceLoc) {
13684 if (RBraceLoc.isValid()) {
13685 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13686 LSDecl->setRBraceLoc(RBraceLoc);
13689 return LinkageSpec;
13692 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13693 const ParsedAttributesView &AttrList,
13694 SourceLocation SemiLoc) {
13695 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13696 // Attribute declarations appertain to empty declaration so we handle
13698 ProcessDeclAttributeList(S, ED, AttrList);
13700 CurContext->addDecl(ED);
13704 /// Perform semantic analysis for the variable declaration that
13705 /// occurs within a C++ catch clause, returning the newly-created
13707 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13708 TypeSourceInfo *TInfo,
13709 SourceLocation StartLoc,
13710 SourceLocation Loc,
13711 IdentifierInfo *Name) {
13712 bool Invalid = false;
13713 QualType ExDeclType = TInfo->getType();
13715 // Arrays and functions decay.
13716 if (ExDeclType->isArrayType())
13717 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13718 else if (ExDeclType->isFunctionType())
13719 ExDeclType = Context.getPointerType(ExDeclType);
13721 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13722 // The exception-declaration shall not denote a pointer or reference to an
13723 // incomplete type, other than [cv] void*.
13724 // N2844 forbids rvalue references.
13725 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13726 Diag(Loc, diag::err_catch_rvalue_ref);
13730 if (ExDeclType->isVariablyModifiedType()) {
13731 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13735 QualType BaseType = ExDeclType;
13736 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13737 unsigned DK = diag::err_catch_incomplete;
13738 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13739 BaseType = Ptr->getPointeeType();
13741 DK = diag::err_catch_incomplete_ptr;
13742 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13743 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13744 BaseType = Ref->getPointeeType();
13746 DK = diag::err_catch_incomplete_ref;
13748 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13749 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13752 if (!Invalid && !ExDeclType->isDependentType() &&
13753 RequireNonAbstractType(Loc, ExDeclType,
13754 diag::err_abstract_type_in_decl,
13755 AbstractVariableType))
13758 // Only the non-fragile NeXT runtime currently supports C++ catches
13759 // of ObjC types, and no runtime supports catching ObjC types by value.
13760 if (!Invalid && getLangOpts().ObjC) {
13761 QualType T = ExDeclType;
13762 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13763 T = RT->getPointeeType();
13765 if (T->isObjCObjectType()) {
13766 Diag(Loc, diag::err_objc_object_catch);
13768 } else if (T->isObjCObjectPointerType()) {
13769 // FIXME: should this be a test for macosx-fragile specifically?
13770 if (getLangOpts().ObjCRuntime.isFragile())
13771 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13775 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13776 ExDeclType, TInfo, SC_None);
13777 ExDecl->setExceptionVariable(true);
13779 // In ARC, infer 'retaining' for variables of retainable type.
13780 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13783 if (!Invalid && !ExDeclType->isDependentType()) {
13784 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13785 // Insulate this from anything else we might currently be parsing.
13786 EnterExpressionEvaluationContext scope(
13787 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13789 // C++ [except.handle]p16:
13790 // The object declared in an exception-declaration or, if the
13791 // exception-declaration does not specify a name, a temporary (12.2) is
13792 // copy-initialized (8.5) from the exception object. [...]
13793 // The object is destroyed when the handler exits, after the destruction
13794 // of any automatic objects initialized within the handler.
13796 // We just pretend to initialize the object with itself, then make sure
13797 // it can be destroyed later.
13798 QualType initType = Context.getExceptionObjectType(ExDeclType);
13800 InitializedEntity entity =
13801 InitializedEntity::InitializeVariable(ExDecl);
13802 InitializationKind initKind =
13803 InitializationKind::CreateCopy(Loc, SourceLocation());
13805 Expr *opaqueValue =
13806 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13807 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13808 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13809 if (result.isInvalid())
13812 // If the constructor used was non-trivial, set this as the
13814 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13815 if (!construct->getConstructor()->isTrivial()) {
13816 Expr *init = MaybeCreateExprWithCleanups(construct);
13817 ExDecl->setInit(init);
13820 // And make sure it's destructable.
13821 FinalizeVarWithDestructor(ExDecl, recordType);
13827 ExDecl->setInvalidDecl();
13832 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13834 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13835 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13836 bool Invalid = D.isInvalidType();
13838 // Check for unexpanded parameter packs.
13839 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13840 UPPC_ExceptionType)) {
13841 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13842 D.getIdentifierLoc());
13846 IdentifierInfo *II = D.getIdentifier();
13847 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13848 LookupOrdinaryName,
13849 ForVisibleRedeclaration)) {
13850 // The scope should be freshly made just for us. There is just no way
13851 // it contains any previous declaration, except for function parameters in
13852 // a function-try-block's catch statement.
13853 assert(!S->isDeclScope(PrevDecl));
13854 if (isDeclInScope(PrevDecl, CurContext, S)) {
13855 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13856 << D.getIdentifier();
13857 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13859 } else if (PrevDecl->isTemplateParameter())
13860 // Maybe we will complain about the shadowed template parameter.
13861 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13864 if (D.getCXXScopeSpec().isSet() && !Invalid) {
13865 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13866 << D.getCXXScopeSpec().getRange();
13870 VarDecl *ExDecl = BuildExceptionDeclaration(
13871 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13873 ExDecl->setInvalidDecl();
13875 // Add the exception declaration into this scope.
13877 PushOnScopeChains(ExDecl, S);
13879 CurContext->addDecl(ExDecl);
13881 ProcessDeclAttributes(S, ExDecl, D);
13885 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13887 Expr *AssertMessageExpr,
13888 SourceLocation RParenLoc) {
13889 StringLiteral *AssertMessage =
13890 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13892 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13895 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13896 AssertMessage, RParenLoc, false);
13899 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13901 StringLiteral *AssertMessage,
13902 SourceLocation RParenLoc,
13904 assert(AssertExpr != nullptr && "Expected non-null condition");
13905 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13907 // In a static_assert-declaration, the constant-expression shall be a
13908 // constant expression that can be contextually converted to bool.
13909 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13910 if (Converted.isInvalid())
13913 Converted = ConstantExpr::Create(Context, Converted.get());
13916 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13917 diag::err_static_assert_expression_is_not_constant,
13918 /*AllowFold=*/false).isInvalid())
13921 if (!Failed && !Cond) {
13922 SmallString<256> MsgBuffer;
13923 llvm::raw_svector_ostream Msg(MsgBuffer);
13925 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13927 Expr *InnerCond = nullptr;
13928 std::string InnerCondDescription;
13929 std::tie(InnerCond, InnerCondDescription) =
13930 findFailedBooleanCondition(Converted.get());
13931 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13932 && !isa<IntegerLiteral>(InnerCond)) {
13933 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13934 << InnerCondDescription << !AssertMessage
13935 << Msg.str() << InnerCond->getSourceRange();
13937 Diag(StaticAssertLoc, diag::err_static_assert_failed)
13938 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13944 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13945 /*DiscardedValue*/false,
13946 /*IsConstexpr*/true);
13947 if (FullAssertExpr.isInvalid())
13950 AssertExpr = FullAssertExpr.get();
13952 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13953 AssertExpr, AssertMessage, RParenLoc,
13956 CurContext->addDecl(Decl);
13960 /// Perform semantic analysis of the given friend type declaration.
13962 /// \returns A friend declaration that.
13963 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13964 SourceLocation FriendLoc,
13965 TypeSourceInfo *TSInfo) {
13966 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13968 QualType T = TSInfo->getType();
13969 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13971 // C++03 [class.friend]p2:
13972 // An elaborated-type-specifier shall be used in a friend declaration
13975 // * The class-key of the elaborated-type-specifier is required.
13976 if (!CodeSynthesisContexts.empty()) {
13977 // Do not complain about the form of friend template types during any kind
13978 // of code synthesis. For template instantiation, we will have complained
13979 // when the template was defined.
13981 if (!T->isElaboratedTypeSpecifier()) {
13982 // If we evaluated the type to a record type, suggest putting
13984 if (const RecordType *RT = T->getAs<RecordType>()) {
13985 RecordDecl *RD = RT->getDecl();
13987 SmallString<16> InsertionText(" ");
13988 InsertionText += RD->getKindName();
13990 Diag(TypeRange.getBegin(),
13991 getLangOpts().CPlusPlus11 ?
13992 diag::warn_cxx98_compat_unelaborated_friend_type :
13993 diag::ext_unelaborated_friend_type)
13994 << (unsigned) RD->getTagKind()
13996 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14000 getLangOpts().CPlusPlus11 ?
14001 diag::warn_cxx98_compat_nonclass_type_friend :
14002 diag::ext_nonclass_type_friend)
14006 } else if (T->getAs<EnumType>()) {
14008 getLangOpts().CPlusPlus11 ?
14009 diag::warn_cxx98_compat_enum_friend :
14010 diag::ext_enum_friend)
14015 // C++11 [class.friend]p3:
14016 // A friend declaration that does not declare a function shall have one
14017 // of the following forms:
14018 // friend elaborated-type-specifier ;
14019 // friend simple-type-specifier ;
14020 // friend typename-specifier ;
14021 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14022 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14025 // If the type specifier in a friend declaration designates a (possibly
14026 // cv-qualified) class type, that class is declared as a friend; otherwise,
14027 // the friend declaration is ignored.
14028 return FriendDecl::Create(Context, CurContext,
14029 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14033 /// Handle a friend tag declaration where the scope specifier was
14035 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14036 unsigned TagSpec, SourceLocation TagLoc,
14037 CXXScopeSpec &SS, IdentifierInfo *Name,
14038 SourceLocation NameLoc,
14039 const ParsedAttributesView &Attr,
14040 MultiTemplateParamsArg TempParamLists) {
14041 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14043 bool IsMemberSpecialization = false;
14044 bool Invalid = false;
14046 if (TemplateParameterList *TemplateParams =
14047 MatchTemplateParametersToScopeSpecifier(
14048 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14049 IsMemberSpecialization, Invalid)) {
14050 if (TemplateParams->size() > 0) {
14051 // This is a declaration of a class template.
14055 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14056 NameLoc, Attr, TemplateParams, AS_public,
14057 /*ModulePrivateLoc=*/SourceLocation(),
14058 FriendLoc, TempParamLists.size() - 1,
14059 TempParamLists.data()).get();
14061 // The "template<>" header is extraneous.
14062 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14063 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14064 IsMemberSpecialization = true;
14068 if (Invalid) return nullptr;
14070 bool isAllExplicitSpecializations = true;
14071 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14072 if (TempParamLists[I]->size()) {
14073 isAllExplicitSpecializations = false;
14078 // FIXME: don't ignore attributes.
14080 // If it's explicit specializations all the way down, just forget
14081 // about the template header and build an appropriate non-templated
14082 // friend. TODO: for source fidelity, remember the headers.
14083 if (isAllExplicitSpecializations) {
14084 if (SS.isEmpty()) {
14085 bool Owned = false;
14086 bool IsDependent = false;
14087 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14089 /*ModulePrivateLoc=*/SourceLocation(),
14090 MultiTemplateParamsArg(), Owned, IsDependent,
14091 /*ScopedEnumKWLoc=*/SourceLocation(),
14092 /*ScopedEnumUsesClassTag=*/false,
14093 /*UnderlyingType=*/TypeResult(),
14094 /*IsTypeSpecifier=*/false,
14095 /*IsTemplateParamOrArg=*/false);
14098 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14099 ElaboratedTypeKeyword Keyword
14100 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14101 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14106 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14107 if (isa<DependentNameType>(T)) {
14108 DependentNameTypeLoc TL =
14109 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14110 TL.setElaboratedKeywordLoc(TagLoc);
14111 TL.setQualifierLoc(QualifierLoc);
14112 TL.setNameLoc(NameLoc);
14114 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14115 TL.setElaboratedKeywordLoc(TagLoc);
14116 TL.setQualifierLoc(QualifierLoc);
14117 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14120 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14121 TSI, FriendLoc, TempParamLists);
14122 Friend->setAccess(AS_public);
14123 CurContext->addDecl(Friend);
14127 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14131 // Handle the case of a templated-scope friend class. e.g.
14132 // template <class T> class A<T>::B;
14133 // FIXME: we don't support these right now.
14134 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14135 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14136 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14137 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14138 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14139 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14140 TL.setElaboratedKeywordLoc(TagLoc);
14141 TL.setQualifierLoc(SS.getWithLocInContext(Context));
14142 TL.setNameLoc(NameLoc);
14144 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14145 TSI, FriendLoc, TempParamLists);
14146 Friend->setAccess(AS_public);
14147 Friend->setUnsupportedFriend(true);
14148 CurContext->addDecl(Friend);
14152 /// Handle a friend type declaration. This works in tandem with
14155 /// Notes on friend class templates:
14157 /// We generally treat friend class declarations as if they were
14158 /// declaring a class. So, for example, the elaborated type specifier
14159 /// in a friend declaration is required to obey the restrictions of a
14160 /// class-head (i.e. no typedefs in the scope chain), template
14161 /// parameters are required to match up with simple template-ids, &c.
14162 /// However, unlike when declaring a template specialization, it's
14163 /// okay to refer to a template specialization without an empty
14164 /// template parameter declaration, e.g.
14165 /// friend class A<T>::B<unsigned>;
14166 /// We permit this as a special case; if there are any template
14167 /// parameters present at all, require proper matching, i.e.
14168 /// template <> template \<class T> friend class A<int>::B;
14169 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14170 MultiTemplateParamsArg TempParams) {
14171 SourceLocation Loc = DS.getBeginLoc();
14173 assert(DS.isFriendSpecified());
14174 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14176 // C++ [class.friend]p3:
14177 // A friend declaration that does not declare a function shall have one of
14178 // the following forms:
14179 // friend elaborated-type-specifier ;
14180 // friend simple-type-specifier ;
14181 // friend typename-specifier ;
14183 // Any declaration with a type qualifier does not have that form. (It's
14184 // legal to specify a qualified type as a friend, you just can't write the
14186 if (DS.getTypeQualifiers()) {
14187 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14188 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14189 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14190 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14191 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14192 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14193 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14194 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14195 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14196 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14199 // Try to convert the decl specifier to a type. This works for
14200 // friend templates because ActOnTag never produces a ClassTemplateDecl
14201 // for a TUK_Friend.
14202 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14203 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14204 QualType T = TSI->getType();
14205 if (TheDeclarator.isInvalidType())
14208 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14211 // This is definitely an error in C++98. It's probably meant to
14212 // be forbidden in C++0x, too, but the specification is just
14215 // The problem is with declarations like the following:
14216 // template <T> friend A<T>::foo;
14217 // where deciding whether a class C is a friend or not now hinges
14218 // on whether there exists an instantiation of A that causes
14219 // 'foo' to equal C. There are restrictions on class-heads
14220 // (which we declare (by fiat) elaborated friend declarations to
14221 // be) that makes this tractable.
14223 // FIXME: handle "template <> friend class A<T>;", which
14224 // is possibly well-formed? Who even knows?
14225 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14226 Diag(Loc, diag::err_tagless_friend_type_template)
14227 << DS.getSourceRange();
14231 // C++98 [class.friend]p1: A friend of a class is a function
14232 // or class that is not a member of the class . . .
14233 // This is fixed in DR77, which just barely didn't make the C++03
14234 // deadline. It's also a very silly restriction that seriously
14235 // affects inner classes and which nobody else seems to implement;
14236 // thus we never diagnose it, not even in -pedantic.
14238 // But note that we could warn about it: it's always useless to
14239 // friend one of your own members (it's not, however, worthless to
14240 // friend a member of an arbitrary specialization of your template).
14243 if (!TempParams.empty())
14244 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14247 DS.getFriendSpecLoc());
14249 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14254 D->setAccess(AS_public);
14255 CurContext->addDecl(D);
14260 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14261 MultiTemplateParamsArg TemplateParams) {
14262 const DeclSpec &DS = D.getDeclSpec();
14264 assert(DS.isFriendSpecified());
14265 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14267 SourceLocation Loc = D.getIdentifierLoc();
14268 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14270 // C++ [class.friend]p1
14271 // A friend of a class is a function or class....
14272 // Note that this sees through typedefs, which is intended.
14273 // It *doesn't* see through dependent types, which is correct
14274 // according to [temp.arg.type]p3:
14275 // If a declaration acquires a function type through a
14276 // type dependent on a template-parameter and this causes
14277 // a declaration that does not use the syntactic form of a
14278 // function declarator to have a function type, the program
14280 if (!TInfo->getType()->isFunctionType()) {
14281 Diag(Loc, diag::err_unexpected_friend);
14283 // It might be worthwhile to try to recover by creating an
14284 // appropriate declaration.
14288 // C++ [namespace.memdef]p3
14289 // - If a friend declaration in a non-local class first declares a
14290 // class or function, the friend class or function is a member
14291 // of the innermost enclosing namespace.
14292 // - The name of the friend is not found by simple name lookup
14293 // until a matching declaration is provided in that namespace
14294 // scope (either before or after the class declaration granting
14296 // - If a friend function is called, its name may be found by the
14297 // name lookup that considers functions from namespaces and
14298 // classes associated with the types of the function arguments.
14299 // - When looking for a prior declaration of a class or a function
14300 // declared as a friend, scopes outside the innermost enclosing
14301 // namespace scope are not considered.
14303 CXXScopeSpec &SS = D.getCXXScopeSpec();
14304 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14305 assert(NameInfo.getName());
14307 // Check for unexpanded parameter packs.
14308 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14309 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14310 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14313 // The context we found the declaration in, or in which we should
14314 // create the declaration.
14316 Scope *DCScope = S;
14317 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14318 ForExternalRedeclaration);
14320 // There are five cases here.
14321 // - There's no scope specifier and we're in a local class. Only look
14322 // for functions declared in the immediately-enclosing block scope.
14323 // We recover from invalid scope qualifiers as if they just weren't there.
14324 FunctionDecl *FunctionContainingLocalClass = nullptr;
14325 if ((SS.isInvalid() || !SS.isSet()) &&
14326 (FunctionContainingLocalClass =
14327 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14328 // C++11 [class.friend]p11:
14329 // If a friend declaration appears in a local class and the name
14330 // specified is an unqualified name, a prior declaration is
14331 // looked up without considering scopes that are outside the
14332 // innermost enclosing non-class scope. For a friend function
14333 // declaration, if there is no prior declaration, the program is
14336 // Find the innermost enclosing non-class scope. This is the block
14337 // scope containing the local class definition (or for a nested class,
14338 // the outer local class).
14339 DCScope = S->getFnParent();
14341 // Look up the function name in the scope.
14342 Previous.clear(LookupLocalFriendName);
14343 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14345 if (!Previous.empty()) {
14346 // All possible previous declarations must have the same context:
14347 // either they were declared at block scope or they are members of
14348 // one of the enclosing local classes.
14349 DC = Previous.getRepresentativeDecl()->getDeclContext();
14351 // This is ill-formed, but provide the context that we would have
14352 // declared the function in, if we were permitted to, for error recovery.
14353 DC = FunctionContainingLocalClass;
14355 adjustContextForLocalExternDecl(DC);
14357 // C++ [class.friend]p6:
14358 // A function can be defined in a friend declaration of a class if and
14359 // only if the class is a non-local class (9.8), the function name is
14360 // unqualified, and the function has namespace scope.
14361 if (D.isFunctionDefinition()) {
14362 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14365 // - There's no scope specifier, in which case we just go to the
14366 // appropriate scope and look for a function or function template
14367 // there as appropriate.
14368 } else if (SS.isInvalid() || !SS.isSet()) {
14369 // C++11 [namespace.memdef]p3:
14370 // If the name in a friend declaration is neither qualified nor
14371 // a template-id and the declaration is a function or an
14372 // elaborated-type-specifier, the lookup to determine whether
14373 // the entity has been previously declared shall not consider
14374 // any scopes outside the innermost enclosing namespace.
14375 bool isTemplateId =
14376 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14378 // Find the appropriate context according to the above.
14381 // Skip class contexts. If someone can cite chapter and verse
14382 // for this behavior, that would be nice --- it's what GCC and
14383 // EDG do, and it seems like a reasonable intent, but the spec
14384 // really only says that checks for unqualified existing
14385 // declarations should stop at the nearest enclosing namespace,
14386 // not that they should only consider the nearest enclosing
14388 while (DC->isRecord())
14389 DC = DC->getParent();
14391 DeclContext *LookupDC = DC;
14392 while (LookupDC->isTransparentContext())
14393 LookupDC = LookupDC->getParent();
14396 LookupQualifiedName(Previous, LookupDC);
14398 if (!Previous.empty()) {
14403 if (isTemplateId) {
14404 if (isa<TranslationUnitDecl>(LookupDC)) break;
14406 if (LookupDC->isFileContext()) break;
14408 LookupDC = LookupDC->getParent();
14411 DCScope = getScopeForDeclContext(S, DC);
14413 // - There's a non-dependent scope specifier, in which case we
14414 // compute it and do a previous lookup there for a function
14415 // or function template.
14416 } else if (!SS.getScopeRep()->isDependent()) {
14417 DC = computeDeclContext(SS);
14418 if (!DC) return nullptr;
14420 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14422 LookupQualifiedName(Previous, DC);
14424 // C++ [class.friend]p1: A friend of a class is a function or
14425 // class that is not a member of the class . . .
14426 if (DC->Equals(CurContext))
14427 Diag(DS.getFriendSpecLoc(),
14428 getLangOpts().CPlusPlus11 ?
14429 diag::warn_cxx98_compat_friend_is_member :
14430 diag::err_friend_is_member);
14432 if (D.isFunctionDefinition()) {
14433 // C++ [class.friend]p6:
14434 // A function can be defined in a friend declaration of a class if and
14435 // only if the class is a non-local class (9.8), the function name is
14436 // unqualified, and the function has namespace scope.
14438 // FIXME: We should only do this if the scope specifier names the
14439 // innermost enclosing namespace; otherwise the fixit changes the
14440 // meaning of the code.
14441 SemaDiagnosticBuilder DB
14442 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14444 DB << SS.getScopeRep();
14445 if (DC->isFileContext())
14446 DB << FixItHint::CreateRemoval(SS.getRange());
14450 // - There's a scope specifier that does not match any template
14451 // parameter lists, in which case we use some arbitrary context,
14452 // create a method or method template, and wait for instantiation.
14453 // - There's a scope specifier that does match some template
14454 // parameter lists, which we don't handle right now.
14456 if (D.isFunctionDefinition()) {
14457 // C++ [class.friend]p6:
14458 // A function can be defined in a friend declaration of a class if and
14459 // only if the class is a non-local class (9.8), the function name is
14460 // unqualified, and the function has namespace scope.
14461 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14462 << SS.getScopeRep();
14466 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14469 if (!DC->isRecord()) {
14471 switch (D.getName().getKind()) {
14472 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14473 case UnqualifiedIdKind::IK_ConstructorName:
14476 case UnqualifiedIdKind::IK_DestructorName:
14479 case UnqualifiedIdKind::IK_ConversionFunctionId:
14482 case UnqualifiedIdKind::IK_DeductionGuideName:
14485 case UnqualifiedIdKind::IK_Identifier:
14486 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14487 case UnqualifiedIdKind::IK_LiteralOperatorId:
14488 case UnqualifiedIdKind::IK_OperatorFunctionId:
14489 case UnqualifiedIdKind::IK_TemplateId:
14492 // This implies that it has to be an operator or function.
14493 if (DiagArg >= 0) {
14494 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14499 // FIXME: This is an egregious hack to cope with cases where the scope stack
14500 // does not contain the declaration context, i.e., in an out-of-line
14501 // definition of a class.
14502 Scope FakeDCScope(S, Scope::DeclScope, Diags);
14504 FakeDCScope.setEntity(DC);
14505 DCScope = &FakeDCScope;
14508 bool AddToScope = true;
14509 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14510 TemplateParams, AddToScope);
14511 if (!ND) return nullptr;
14513 assert(ND->getLexicalDeclContext() == CurContext);
14515 // If we performed typo correction, we might have added a scope specifier
14516 // and changed the decl context.
14517 DC = ND->getDeclContext();
14519 // Add the function declaration to the appropriate lookup tables,
14520 // adjusting the redeclarations list as necessary. We don't
14521 // want to do this yet if the friending class is dependent.
14523 // Also update the scope-based lookup if the target context's
14524 // lookup context is in lexical scope.
14525 if (!CurContext->isDependentContext()) {
14526 DC = DC->getRedeclContext();
14527 DC->makeDeclVisibleInContext(ND);
14528 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14529 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14532 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14533 D.getIdentifierLoc(), ND,
14534 DS.getFriendSpecLoc());
14535 FrD->setAccess(AS_public);
14536 CurContext->addDecl(FrD);
14538 if (ND->isInvalidDecl()) {
14539 FrD->setInvalidDecl();
14541 if (DC->isRecord()) CheckFriendAccess(ND);
14544 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14545 FD = FTD->getTemplatedDecl();
14547 FD = cast<FunctionDecl>(ND);
14549 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14550 // default argument expression, that declaration shall be a definition
14551 // and shall be the only declaration of the function or function
14552 // template in the translation unit.
14553 if (functionDeclHasDefaultArgument(FD)) {
14554 // We can't look at FD->getPreviousDecl() because it may not have been set
14555 // if we're in a dependent context. If the function is known to be a
14556 // redeclaration, we will have narrowed Previous down to the right decl.
14557 if (D.isRedeclaration()) {
14558 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14559 Diag(Previous.getRepresentativeDecl()->getLocation(),
14560 diag::note_previous_declaration);
14561 } else if (!D.isFunctionDefinition())
14562 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14565 // Mark templated-scope function declarations as unsupported.
14566 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14567 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14568 << SS.getScopeRep() << SS.getRange()
14569 << cast<CXXRecordDecl>(CurContext);
14570 FrD->setUnsupportedFriend(true);
14577 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14578 AdjustDeclIfTemplate(Dcl);
14580 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14582 Diag(DelLoc, diag::err_deleted_non_function);
14586 // Deleted function does not have a body.
14587 Fn->setWillHaveBody(false);
14589 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14590 // Don't consider the implicit declaration we generate for explicit
14591 // specializations. FIXME: Do not generate these implicit declarations.
14592 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14593 Prev->getPreviousDecl()) &&
14594 !Prev->isDefined()) {
14595 Diag(DelLoc, diag::err_deleted_decl_not_first);
14596 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14597 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14598 : diag::note_previous_declaration);
14600 // If the declaration wasn't the first, we delete the function anyway for
14602 Fn = Fn->getCanonicalDecl();
14605 // dllimport/dllexport cannot be deleted.
14606 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14607 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14608 Fn->setInvalidDecl();
14611 if (Fn->isDeleted())
14614 // See if we're deleting a function which is already known to override a
14615 // non-deleted virtual function.
14616 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14617 bool IssuedDiagnostic = false;
14618 for (const CXXMethodDecl *O : MD->overridden_methods()) {
14619 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14620 if (!IssuedDiagnostic) {
14621 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14622 IssuedDiagnostic = true;
14624 Diag(O->getLocation(), diag::note_overridden_virtual_function);
14627 // If this function was implicitly deleted because it was defaulted,
14628 // explain why it was deleted.
14629 if (IssuedDiagnostic && MD->isDefaulted())
14630 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14634 // C++11 [basic.start.main]p3:
14635 // A program that defines main as deleted [...] is ill-formed.
14637 Diag(DelLoc, diag::err_deleted_main);
14639 // C++11 [dcl.fct.def.delete]p4:
14640 // A deleted function is implicitly inline.
14641 Fn->setImplicitlyInline();
14642 Fn->setDeletedAsWritten();
14645 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14646 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14649 if (MD->getParent()->isDependentType()) {
14650 MD->setDefaulted();
14651 MD->setExplicitlyDefaulted();
14655 CXXSpecialMember Member = getSpecialMember(MD);
14656 if (Member == CXXInvalid) {
14657 if (!MD->isInvalidDecl())
14658 Diag(DefaultLoc, diag::err_default_special_members);
14662 MD->setDefaulted();
14663 MD->setExplicitlyDefaulted();
14665 // Unset that we will have a body for this function. We might not,
14666 // if it turns out to be trivial, and we don't need this marking now
14667 // that we've marked it as defaulted.
14668 MD->setWillHaveBody(false);
14670 // If this definition appears within the record, do the checking when
14671 // the record is complete.
14672 const FunctionDecl *Primary = MD;
14673 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14674 // Ask the template instantiation pattern that actually had the
14675 // '= default' on it.
14678 // If the method was defaulted on its first declaration, we will have
14679 // already performed the checking in CheckCompletedCXXClass. Such a
14680 // declaration doesn't trigger an implicit definition.
14681 if (Primary->getCanonicalDecl()->isDefaulted())
14684 CheckExplicitlyDefaultedSpecialMember(MD);
14686 if (!MD->isInvalidDecl())
14687 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14689 Diag(DefaultLoc, diag::err_default_special_members);
14693 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14694 for (Stmt *SubStmt : S->children()) {
14697 if (isa<ReturnStmt>(SubStmt))
14698 Self.Diag(SubStmt->getBeginLoc(),
14699 diag::err_return_in_constructor_handler);
14700 if (!isa<Expr>(SubStmt))
14701 SearchForReturnInStmt(Self, SubStmt);
14705 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14706 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14707 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14708 SearchForReturnInStmt(*this, Handler);
14712 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14713 const CXXMethodDecl *Old) {
14714 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14715 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14717 if (OldFT->hasExtParameterInfos()) {
14718 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14719 // A parameter of the overriding method should be annotated with noescape
14720 // if the corresponding parameter of the overridden method is annotated.
14721 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14722 !NewFT->getExtParameterInfo(I).isNoEscape()) {
14723 Diag(New->getParamDecl(I)->getLocation(),
14724 diag::warn_overriding_method_missing_noescape);
14725 Diag(Old->getParamDecl(I)->getLocation(),
14726 diag::note_overridden_marked_noescape);
14730 // Virtual overrides must have the same code_seg.
14731 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14732 const auto *NewCSA = New->getAttr<CodeSegAttr>();
14733 if ((NewCSA || OldCSA) &&
14734 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14735 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14736 Diag(Old->getLocation(), diag::note_previous_declaration);
14740 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14742 // If the calling conventions match, everything is fine
14743 if (NewCC == OldCC)
14746 // If the calling conventions mismatch because the new function is static,
14747 // suppress the calling convention mismatch error; the error about static
14748 // function override (err_static_overrides_virtual from
14749 // Sema::CheckFunctionDeclaration) is more clear.
14750 if (New->getStorageClass() == SC_Static)
14753 Diag(New->getLocation(),
14754 diag::err_conflicting_overriding_cc_attributes)
14755 << New->getDeclName() << New->getType() << Old->getType();
14756 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14760 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14761 const CXXMethodDecl *Old) {
14762 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14763 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14765 if (Context.hasSameType(NewTy, OldTy) ||
14766 NewTy->isDependentType() || OldTy->isDependentType())
14769 // Check if the return types are covariant
14770 QualType NewClassTy, OldClassTy;
14772 /// Both types must be pointers or references to classes.
14773 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14774 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14775 NewClassTy = NewPT->getPointeeType();
14776 OldClassTy = OldPT->getPointeeType();
14778 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14779 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14780 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14781 NewClassTy = NewRT->getPointeeType();
14782 OldClassTy = OldRT->getPointeeType();
14787 // The return types aren't either both pointers or references to a class type.
14788 if (NewClassTy.isNull()) {
14789 Diag(New->getLocation(),
14790 diag::err_different_return_type_for_overriding_virtual_function)
14791 << New->getDeclName() << NewTy << OldTy
14792 << New->getReturnTypeSourceRange();
14793 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14794 << Old->getReturnTypeSourceRange();
14799 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14800 // C++14 [class.virtual]p8:
14801 // If the class type in the covariant return type of D::f differs from
14802 // that of B::f, the class type in the return type of D::f shall be
14803 // complete at the point of declaration of D::f or shall be the class
14805 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14806 if (!RT->isBeingDefined() &&
14807 RequireCompleteType(New->getLocation(), NewClassTy,
14808 diag::err_covariant_return_incomplete,
14809 New->getDeclName()))
14813 // Check if the new class derives from the old class.
14814 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14815 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14816 << New->getDeclName() << NewTy << OldTy
14817 << New->getReturnTypeSourceRange();
14818 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14819 << Old->getReturnTypeSourceRange();
14823 // Check if we the conversion from derived to base is valid.
14824 if (CheckDerivedToBaseConversion(
14825 NewClassTy, OldClassTy,
14826 diag::err_covariant_return_inaccessible_base,
14827 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14828 New->getLocation(), New->getReturnTypeSourceRange(),
14829 New->getDeclName(), nullptr)) {
14830 // FIXME: this note won't trigger for delayed access control
14831 // diagnostics, and it's impossible to get an undelayed error
14832 // here from access control during the original parse because
14833 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14834 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14835 << Old->getReturnTypeSourceRange();
14840 // The qualifiers of the return types must be the same.
14841 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14842 Diag(New->getLocation(),
14843 diag::err_covariant_return_type_different_qualifications)
14844 << New->getDeclName() << NewTy << OldTy
14845 << New->getReturnTypeSourceRange();
14846 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14847 << Old->getReturnTypeSourceRange();
14852 // The new class type must have the same or less qualifiers as the old type.
14853 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14854 Diag(New->getLocation(),
14855 diag::err_covariant_return_type_class_type_more_qualified)
14856 << New->getDeclName() << NewTy << OldTy
14857 << New->getReturnTypeSourceRange();
14858 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14859 << Old->getReturnTypeSourceRange();
14866 /// Mark the given method pure.
14868 /// \param Method the method to be marked pure.
14870 /// \param InitRange the source range that covers the "0" initializer.
14871 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14872 SourceLocation EndLoc = InitRange.getEnd();
14873 if (EndLoc.isValid())
14874 Method->setRangeEnd(EndLoc);
14876 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14881 if (!Method->isInvalidDecl())
14882 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14883 << Method->getDeclName() << InitRange;
14887 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14888 if (D->getFriendObjectKind())
14889 Diag(D->getLocation(), diag::err_pure_friend);
14890 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14891 CheckPureMethod(M, ZeroLoc);
14893 Diag(D->getLocation(), diag::err_illegal_initializer);
14896 /// Determine whether the given declaration is a global variable or
14897 /// static data member.
14898 static bool isNonlocalVariable(const Decl *D) {
14899 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14900 return Var->hasGlobalStorage();
14905 /// Invoked when we are about to parse an initializer for the declaration
14908 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14909 /// static data member of class X, names should be looked up in the scope of
14910 /// class X. If the declaration had a scope specifier, a scope will have
14911 /// been created and passed in for this purpose. Otherwise, S will be null.
14912 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14913 // If there is no declaration, there was an error parsing it.
14914 if (!D || D->isInvalidDecl())
14917 // We will always have a nested name specifier here, but this declaration
14918 // might not be out of line if the specifier names the current namespace:
14921 if (S && D->isOutOfLine())
14922 EnterDeclaratorContext(S, D->getDeclContext());
14924 // If we are parsing the initializer for a static data member, push a
14925 // new expression evaluation context that is associated with this static
14927 if (isNonlocalVariable(D))
14928 PushExpressionEvaluationContext(
14929 ExpressionEvaluationContext::PotentiallyEvaluated, D);
14932 /// Invoked after we are finished parsing an initializer for the declaration D.
14933 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14934 // If there is no declaration, there was an error parsing it.
14935 if (!D || D->isInvalidDecl())
14938 if (isNonlocalVariable(D))
14939 PopExpressionEvaluationContext();
14941 if (S && D->isOutOfLine())
14942 ExitDeclaratorContext(S);
14945 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14946 /// C++ if/switch/while/for statement.
14947 /// e.g: "if (int x = f()) {...}"
14948 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14950 // The declarator shall not specify a function or an array.
14951 // The type-specifier-seq shall not contain typedef and shall not declare a
14952 // new class or enumeration.
14953 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14954 "Parser allowed 'typedef' as storage class of condition decl.");
14956 Decl *Dcl = ActOnDeclarator(S, D);
14960 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14961 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14962 << D.getSourceRange();
14969 void Sema::LoadExternalVTableUses() {
14970 if (!ExternalSource)
14973 SmallVector<ExternalVTableUse, 4> VTables;
14974 ExternalSource->ReadUsedVTables(VTables);
14975 SmallVector<VTableUse, 4> NewUses;
14976 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14977 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14978 = VTablesUsed.find(VTables[I].Record);
14979 // Even if a definition wasn't required before, it may be required now.
14980 if (Pos != VTablesUsed.end()) {
14981 if (!Pos->second && VTables[I].DefinitionRequired)
14982 Pos->second = true;
14986 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14987 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14990 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14993 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14994 bool DefinitionRequired) {
14995 // Ignore any vtable uses in unevaluated operands or for classes that do
14996 // not have a vtable.
14997 if (!Class->isDynamicClass() || Class->isDependentContext() ||
14998 CurContext->isDependentContext() || isUnevaluatedContext())
15000 // Do not mark as used if compiling for the device outside of the target
15002 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15003 !isInOpenMPDeclareTargetContext() &&
15004 !isInOpenMPTargetExecutionDirective()) {
15005 if (!DefinitionRequired)
15006 MarkVirtualMembersReferenced(Loc, Class);
15010 // Try to insert this class into the map.
15011 LoadExternalVTableUses();
15012 Class = Class->getCanonicalDecl();
15013 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15014 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15016 // If we already had an entry, check to see if we are promoting this vtable
15017 // to require a definition. If so, we need to reappend to the VTableUses
15018 // list, since we may have already processed the first entry.
15019 if (DefinitionRequired && !Pos.first->second) {
15020 Pos.first->second = true;
15022 // Otherwise, we can early exit.
15026 // The Microsoft ABI requires that we perform the destructor body
15027 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15028 // the deleting destructor is emitted with the vtable, not with the
15029 // destructor definition as in the Itanium ABI.
15030 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15031 CXXDestructorDecl *DD = Class->getDestructor();
15032 if (DD && DD->isVirtual() && !DD->isDeleted()) {
15033 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15034 // If this is an out-of-line declaration, marking it referenced will
15035 // not do anything. Manually call CheckDestructor to look up operator
15037 ContextRAII SavedContext(*this, DD);
15038 CheckDestructor(DD);
15040 MarkFunctionReferenced(Loc, Class->getDestructor());
15046 // Local classes need to have their virtual members marked
15047 // immediately. For all other classes, we mark their virtual members
15048 // at the end of the translation unit.
15049 if (Class->isLocalClass())
15050 MarkVirtualMembersReferenced(Loc, Class);
15052 VTableUses.push_back(std::make_pair(Class, Loc));
15055 bool Sema::DefineUsedVTables() {
15056 LoadExternalVTableUses();
15057 if (VTableUses.empty())
15060 // Note: The VTableUses vector could grow as a result of marking
15061 // the members of a class as "used", so we check the size each
15062 // time through the loop and prefer indices (which are stable) to
15063 // iterators (which are not).
15064 bool DefinedAnything = false;
15065 for (unsigned I = 0; I != VTableUses.size(); ++I) {
15066 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15069 TemplateSpecializationKind ClassTSK =
15070 Class->getTemplateSpecializationKind();
15072 SourceLocation Loc = VTableUses[I].second;
15074 bool DefineVTable = true;
15076 // If this class has a key function, but that key function is
15077 // defined in another translation unit, we don't need to emit the
15078 // vtable even though we're using it.
15079 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15080 if (KeyFunction && !KeyFunction->hasBody()) {
15081 // The key function is in another translation unit.
15082 DefineVTable = false;
15083 TemplateSpecializationKind TSK =
15084 KeyFunction->getTemplateSpecializationKind();
15085 assert(TSK != TSK_ExplicitInstantiationDefinition &&
15086 TSK != TSK_ImplicitInstantiation &&
15087 "Instantiations don't have key functions");
15089 } else if (!KeyFunction) {
15090 // If we have a class with no key function that is the subject
15091 // of an explicit instantiation declaration, suppress the
15092 // vtable; it will live with the explicit instantiation
15094 bool IsExplicitInstantiationDeclaration =
15095 ClassTSK == TSK_ExplicitInstantiationDeclaration;
15096 for (auto R : Class->redecls()) {
15097 TemplateSpecializationKind TSK
15098 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15099 if (TSK == TSK_ExplicitInstantiationDeclaration)
15100 IsExplicitInstantiationDeclaration = true;
15101 else if (TSK == TSK_ExplicitInstantiationDefinition) {
15102 IsExplicitInstantiationDeclaration = false;
15107 if (IsExplicitInstantiationDeclaration)
15108 DefineVTable = false;
15111 // The exception specifications for all virtual members may be needed even
15112 // if we are not providing an authoritative form of the vtable in this TU.
15113 // We may choose to emit it available_externally anyway.
15114 if (!DefineVTable) {
15115 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15119 // Mark all of the virtual members of this class as referenced, so
15120 // that we can build a vtable. Then, tell the AST consumer that a
15121 // vtable for this class is required.
15122 DefinedAnything = true;
15123 MarkVirtualMembersReferenced(Loc, Class);
15124 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15125 if (VTablesUsed[Canonical])
15126 Consumer.HandleVTable(Class);
15128 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15129 // no key function or the key function is inlined. Don't warn in C++ ABIs
15130 // that lack key functions, since the user won't be able to make one.
15131 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15132 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15133 const FunctionDecl *KeyFunctionDef = nullptr;
15134 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15135 KeyFunctionDef->isInlined())) {
15136 Diag(Class->getLocation(),
15137 ClassTSK == TSK_ExplicitInstantiationDefinition
15138 ? diag::warn_weak_template_vtable
15139 : diag::warn_weak_vtable)
15144 VTableUses.clear();
15146 return DefinedAnything;
15149 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15150 const CXXRecordDecl *RD) {
15151 for (const auto *I : RD->methods())
15152 if (I->isVirtual() && !I->isPure())
15153 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15156 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15157 const CXXRecordDecl *RD) {
15158 // Mark all functions which will appear in RD's vtable as used.
15159 CXXFinalOverriderMap FinalOverriders;
15160 RD->getFinalOverriders(FinalOverriders);
15161 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15162 E = FinalOverriders.end();
15164 for (OverridingMethods::const_iterator OI = I->second.begin(),
15165 OE = I->second.end();
15167 assert(OI->second.size() > 0 && "no final overrider");
15168 CXXMethodDecl *Overrider = OI->second.front().Method;
15170 // C++ [basic.def.odr]p2:
15171 // [...] A virtual member function is used if it is not pure. [...]
15172 if (!Overrider->isPure())
15173 MarkFunctionReferenced(Loc, Overrider);
15177 // Only classes that have virtual bases need a VTT.
15178 if (RD->getNumVBases() == 0)
15181 for (const auto &I : RD->bases()) {
15182 const CXXRecordDecl *Base =
15183 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15184 if (Base->getNumVBases() == 0)
15186 MarkVirtualMembersReferenced(Loc, Base);
15190 /// SetIvarInitializers - This routine builds initialization ASTs for the
15191 /// Objective-C implementation whose ivars need be initialized.
15192 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15193 if (!getLangOpts().CPlusPlus)
15195 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15196 SmallVector<ObjCIvarDecl*, 8> ivars;
15197 CollectIvarsToConstructOrDestruct(OID, ivars);
15200 SmallVector<CXXCtorInitializer*, 32> AllToInit;
15201 for (unsigned i = 0; i < ivars.size(); i++) {
15202 FieldDecl *Field = ivars[i];
15203 if (Field->isInvalidDecl())
15206 CXXCtorInitializer *Member;
15207 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15208 InitializationKind InitKind =
15209 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15211 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15212 ExprResult MemberInit =
15213 InitSeq.Perform(*this, InitEntity, InitKind, None);
15214 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15215 // Note, MemberInit could actually come back empty if no initialization
15216 // is required (e.g., because it would call a trivial default constructor)
15217 if (!MemberInit.get() || MemberInit.isInvalid())
15221 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15223 MemberInit.getAs<Expr>(),
15225 AllToInit.push_back(Member);
15227 // Be sure that the destructor is accessible and is marked as referenced.
15228 if (const RecordType *RecordTy =
15229 Context.getBaseElementType(Field->getType())
15230 ->getAs<RecordType>()) {
15231 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15232 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15233 MarkFunctionReferenced(Field->getLocation(), Destructor);
15234 CheckDestructorAccess(Field->getLocation(), Destructor,
15235 PDiag(diag::err_access_dtor_ivar)
15236 << Context.getBaseElementType(Field->getType()));
15240 ObjCImplementation->setIvarInitializers(Context,
15241 AllToInit.data(), AllToInit.size());
15246 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15247 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15248 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15249 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15251 if (Ctor->isInvalidDecl())
15254 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15256 // Target may not be determinable yet, for instance if this is a dependent
15257 // call in an uninstantiated template.
15259 const FunctionDecl *FNTarget = nullptr;
15260 (void)Target->hasBody(FNTarget);
15261 Target = const_cast<CXXConstructorDecl*>(
15262 cast_or_null<CXXConstructorDecl>(FNTarget));
15265 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15266 // Avoid dereferencing a null pointer here.
15267 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15269 if (!Current.insert(Canonical).second)
15272 // We know that beyond here, we aren't chaining into a cycle.
15273 if (!Target || !Target->isDelegatingConstructor() ||
15274 Target->isInvalidDecl() || Valid.count(TCanonical)) {
15275 Valid.insert(Current.begin(), Current.end());
15277 // We've hit a cycle.
15278 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15279 Current.count(TCanonical)) {
15280 // If we haven't diagnosed this cycle yet, do so now.
15281 if (!Invalid.count(TCanonical)) {
15282 S.Diag((*Ctor->init_begin())->getSourceLocation(),
15283 diag::warn_delegating_ctor_cycle)
15286 // Don't add a note for a function delegating directly to itself.
15287 if (TCanonical != Canonical)
15288 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15290 CXXConstructorDecl *C = Target;
15291 while (C->getCanonicalDecl() != Canonical) {
15292 const FunctionDecl *FNTarget = nullptr;
15293 (void)C->getTargetConstructor()->hasBody(FNTarget);
15294 assert(FNTarget && "Ctor cycle through bodiless function");
15296 C = const_cast<CXXConstructorDecl*>(
15297 cast<CXXConstructorDecl>(FNTarget));
15298 S.Diag(C->getLocation(), diag::note_which_delegates_to);
15302 Invalid.insert(Current.begin(), Current.end());
15305 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15310 void Sema::CheckDelegatingCtorCycles() {
15311 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15313 for (DelegatingCtorDeclsType::iterator
15314 I = DelegatingCtorDecls.begin(ExternalSource),
15315 E = DelegatingCtorDecls.end();
15317 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15319 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15320 (*CI)->setInvalidDecl();
15324 /// AST visitor that finds references to the 'this' expression.
15325 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15329 explicit FindCXXThisExpr(Sema &S) : S(S) { }
15331 bool VisitCXXThisExpr(CXXThisExpr *E) {
15332 S.Diag(E->getLocation(), diag::err_this_static_member_func)
15333 << E->isImplicit();
15339 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15340 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15344 TypeLoc TL = TSInfo->getTypeLoc();
15345 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15349 // C++11 [expr.prim.general]p3:
15350 // [The expression this] shall not appear before the optional
15351 // cv-qualifier-seq and it shall not appear within the declaration of a
15352 // static member function (although its type and value category are defined
15353 // within a static member function as they are within a non-static member
15354 // function). [ Note: this is because declaration matching does not occur
15355 // until the complete declarator is known. - end note ]
15356 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15357 FindCXXThisExpr Finder(*this);
15359 // If the return type came after the cv-qualifier-seq, check it now.
15360 if (Proto->hasTrailingReturn() &&
15361 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15364 // Check the exception specification.
15365 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15368 return checkThisInStaticMemberFunctionAttributes(Method);
15371 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15372 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15376 TypeLoc TL = TSInfo->getTypeLoc();
15377 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15381 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15382 FindCXXThisExpr Finder(*this);
15384 switch (Proto->getExceptionSpecType()) {
15386 case EST_Uninstantiated:
15387 case EST_Unevaluated:
15388 case EST_BasicNoexcept:
15389 case EST_DynamicNone:
15394 case EST_DependentNoexcept:
15395 case EST_NoexceptFalse:
15396 case EST_NoexceptTrue:
15397 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15402 for (const auto &E : Proto->exceptions()) {
15403 if (!Finder.TraverseType(E))
15412 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15413 FindCXXThisExpr Finder(*this);
15415 // Check attributes.
15416 for (const auto *A : Method->attrs()) {
15417 // FIXME: This should be emitted by tblgen.
15418 Expr *Arg = nullptr;
15419 ArrayRef<Expr *> Args;
15420 if (const auto *G = dyn_cast<GuardedByAttr>(A))
15422 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15424 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15425 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15426 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15427 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15428 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15429 Arg = ETLF->getSuccessValue();
15430 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15431 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15432 Arg = STLF->getSuccessValue();
15433 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15434 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15435 Arg = LR->getArg();
15436 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15437 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15438 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15439 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15440 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15441 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15442 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15443 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15444 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15445 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15447 if (Arg && !Finder.TraverseStmt(Arg))
15450 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15451 if (!Finder.TraverseStmt(Args[I]))
15459 void Sema::checkExceptionSpecification(
15460 bool IsTopLevel, ExceptionSpecificationType EST,
15461 ArrayRef<ParsedType> DynamicExceptions,
15462 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15463 SmallVectorImpl<QualType> &Exceptions,
15464 FunctionProtoType::ExceptionSpecInfo &ESI) {
15465 Exceptions.clear();
15467 if (EST == EST_Dynamic) {
15468 Exceptions.reserve(DynamicExceptions.size());
15469 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15470 // FIXME: Preserve type source info.
15471 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15474 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15475 collectUnexpandedParameterPacks(ET, Unexpanded);
15476 if (!Unexpanded.empty()) {
15477 DiagnoseUnexpandedParameterPacks(
15478 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15484 // Check that the type is valid for an exception spec, and
15486 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15487 Exceptions.push_back(ET);
15489 ESI.Exceptions = Exceptions;
15493 if (isComputedNoexcept(EST)) {
15494 assert((NoexceptExpr->isTypeDependent() ||
15495 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15497 "Parser should have made sure that the expression is boolean");
15498 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15499 ESI.Type = EST_BasicNoexcept;
15503 ESI.NoexceptExpr = NoexceptExpr;
15508 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15509 ExceptionSpecificationType EST,
15510 SourceRange SpecificationRange,
15511 ArrayRef<ParsedType> DynamicExceptions,
15512 ArrayRef<SourceRange> DynamicExceptionRanges,
15513 Expr *NoexceptExpr) {
15517 // Dig out the method we're referring to.
15518 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15519 MethodD = FunTmpl->getTemplatedDecl();
15521 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15525 // Check the exception specification.
15526 llvm::SmallVector<QualType, 4> Exceptions;
15527 FunctionProtoType::ExceptionSpecInfo ESI;
15528 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15529 DynamicExceptionRanges, NoexceptExpr, Exceptions,
15532 // Update the exception specification on the function type.
15533 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15535 if (Method->isStatic())
15536 checkThisInStaticMemberFunctionExceptionSpec(Method);
15538 if (Method->isVirtual()) {
15539 // Check overrides, which we previously had to delay.
15540 for (const CXXMethodDecl *O : Method->overridden_methods())
15541 CheckOverridingFunctionExceptionSpec(Method, O);
15545 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15547 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15548 SourceLocation DeclStart, Declarator &D,
15550 InClassInitStyle InitStyle,
15551 AccessSpecifier AS,
15552 const ParsedAttr &MSPropertyAttr) {
15553 IdentifierInfo *II = D.getIdentifier();
15555 Diag(DeclStart, diag::err_anonymous_property);
15558 SourceLocation Loc = D.getIdentifierLoc();
15560 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15561 QualType T = TInfo->getType();
15562 if (getLangOpts().CPlusPlus) {
15563 CheckExtraCXXDefaultArguments(D);
15565 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15566 UPPC_DataMemberType)) {
15567 D.setInvalidType();
15569 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15573 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15575 if (D.getDeclSpec().isInlineSpecified())
15576 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15577 << getLangOpts().CPlusPlus17;
15578 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15579 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15580 diag::err_invalid_thread)
15581 << DeclSpec::getSpecifierName(TSCS);
15583 // Check to see if this name was declared as a member previously
15584 NamedDecl *PrevDecl = nullptr;
15585 LookupResult Previous(*this, II, Loc, LookupMemberName,
15586 ForVisibleRedeclaration);
15587 LookupName(Previous, S);
15588 switch (Previous.getResultKind()) {
15589 case LookupResult::Found:
15590 case LookupResult::FoundUnresolvedValue:
15591 PrevDecl = Previous.getAsSingle<NamedDecl>();
15594 case LookupResult::FoundOverloaded:
15595 PrevDecl = Previous.getRepresentativeDecl();
15598 case LookupResult::NotFound:
15599 case LookupResult::NotFoundInCurrentInstantiation:
15600 case LookupResult::Ambiguous:
15604 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15605 // Maybe we will complain about the shadowed template parameter.
15606 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15607 // Just pretend that we didn't see the previous declaration.
15608 PrevDecl = nullptr;
15611 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15612 PrevDecl = nullptr;
15614 SourceLocation TSSL = D.getBeginLoc();
15615 MSPropertyDecl *NewPD =
15616 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15617 MSPropertyAttr.getPropertyDataGetter(),
15618 MSPropertyAttr.getPropertyDataSetter());
15619 ProcessDeclAttributes(TUScope, NewPD, D);
15620 NewPD->setAccess(AS);
15622 if (NewPD->isInvalidDecl())
15623 Record->setInvalidDecl();
15625 if (D.getDeclSpec().isModulePrivateSpecified())
15626 NewPD->setModulePrivate();
15628 if (NewPD->isInvalidDecl() && PrevDecl) {
15629 // Don't introduce NewFD into scope; there's already something
15630 // with the same name in the same scope.
15632 PushOnScopeChains(NewPD, S);
15634 Record->addDecl(NewPD);