Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 1239, column 25
Called C++ object pointer is null

Annotated Source Code

1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
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/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/LiteralSupport.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaInternal.h"
39#include "clang/Sema/Template.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringExtras.h"
43#include <map>
44#include <set>
45
46using namespace clang;
47
48//===----------------------------------------------------------------------===//
49// CheckDefaultArgumentVisitor
50//===----------------------------------------------------------------------===//
51
52namespace {
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
58 class CheckDefaultArgumentVisitor
59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60 Expr *DefaultArg;
61 Sema *S;
62
63 public:
64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65 : DefaultArg(defarg), S(s) {}
66
67 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
69 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70 bool VisitLambdaExpr(LambdaExpr *Lambda);
71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72 };
73
74 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
77 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
79 return IsInvalid;
80 }
81
82 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86 NamedDecl *Decl = DRE->getDecl();
87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
96 return S->Diag(DRE->getLocStart(),
97 diag::err_param_default_argument_references_param)
98 << Param->getDeclName() << DefaultArg->getSourceRange();
99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
102 // expressions.
103 if (VDecl->isLocalVarDecl())
104 return S->Diag(DRE->getLocStart(),
105 diag::err_param_default_argument_references_local)
106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
107 }
108
109 return false;
110 }
111
112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
116 // member function.
117 return S->Diag(ThisE->getLocStart(),
118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
120 }
121
122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126 Expr *E = *i;
127
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?"
) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 131, __PRETTY_FUNCTION__))
;
132 }
133
134 Invalid |= Visit(E);
135 }
136 return Invalid;
137 }
138
139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
144 return false;
145
146 return S->Diag(Lambda->getLocStart(),
147 diag::err_lambda_capture_default_arg);
148 }
149}
150
151void
152Sema::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)
156 return;
157
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161 if (!Proto)
162 return;
163
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165
166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
168 return;
169
170 switch(EST) {
171 // If this function can throw any exceptions, make a note of that.
172 case EST_MSAny:
173 case EST_None:
174 ClearExceptions();
175 ComputedEST = EST;
176 return;
177 // FIXME: If the call to this decl is using any of its default arguments, we
178 // need to search them for potentially-throwing calls.
179 // If this function has a basic noexcept, it doesn't affect the outcome.
180 case EST_BasicNoexcept:
181 return;
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 case EST_DynamicNone:
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 // Check out noexcept specs.
189 case EST_ComputedNoexcept:
190 {
191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
193 assert(NR != FunctionProtoType::NR_NoNoexcept &&((NR != FunctionProtoType::NR_NoNoexcept && "Must have noexcept result for EST_ComputedNoexcept."
) ? static_cast<void> (0) : __assert_fail ("NR != FunctionProtoType::NR_NoNoexcept && \"Must have noexcept result for EST_ComputedNoexcept.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 194, __PRETTY_FUNCTION__))
194 "Must have noexcept result for EST_ComputedNoexcept.")((NR != FunctionProtoType::NR_NoNoexcept && "Must have noexcept result for EST_ComputedNoexcept."
) ? static_cast<void> (0) : __assert_fail ("NR != FunctionProtoType::NR_NoNoexcept && \"Must have noexcept result for EST_ComputedNoexcept.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 194, __PRETTY_FUNCTION__))
;
195 assert(NR != FunctionProtoType::NR_Dependent &&((NR != FunctionProtoType::NR_Dependent && "Should not generate implicit declarations for dependent cases, "
"and don't know how to handle them anyway.") ? static_cast<
void> (0) : __assert_fail ("NR != FunctionProtoType::NR_Dependent && \"Should not generate implicit declarations for dependent cases, \" \"and don't know how to handle them anyway.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 197, __PRETTY_FUNCTION__))
196 "Should not generate implicit declarations for dependent cases, "((NR != FunctionProtoType::NR_Dependent && "Should not generate implicit declarations for dependent cases, "
"and don't know how to handle them anyway.") ? static_cast<
void> (0) : __assert_fail ("NR != FunctionProtoType::NR_Dependent && \"Should not generate implicit declarations for dependent cases, \" \"and don't know how to handle them anyway.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 197, __PRETTY_FUNCTION__))
197 "and don't know how to handle them anyway.")((NR != FunctionProtoType::NR_Dependent && "Should not generate implicit declarations for dependent cases, "
"and don't know how to handle them anyway.") ? static_cast<
void> (0) : __assert_fail ("NR != FunctionProtoType::NR_Dependent && \"Should not generate implicit declarations for dependent cases, \" \"and don't know how to handle them anyway.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 197, __PRETTY_FUNCTION__))
;
198 // noexcept(false) -> no spec on the new function
199 if (NR == FunctionProtoType::NR_Throw) {
200 ClearExceptions();
201 ComputedEST = EST_None;
202 }
203 // noexcept(true) won't change anything either.
204 return;
205 }
206 default:
207 break;
208 }
209 assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier."
) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 209, __PRETTY_FUNCTION__))
;
210 assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 211, __PRETTY_FUNCTION__))
211 "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 211, __PRETTY_FUNCTION__))
;
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);
217}
218
219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220 if (!E || ComputedEST == EST_MSAny)
221 return;
222
223 // FIXME:
224 //
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.
231 //
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).
235 //
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.
238 //
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.
243
244 if (Self->canThrow(E))
245 ComputedEST = EST_None;
246}
247
248bool
249Sema::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();
254 return true;
255 }
256
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,
264 Param);
265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269 if (Result.isInvalid())
270 return true;
271 Arg = Result.getAs<Expr>();
272
273 CheckCompletedExpr(Arg, EqualLoc);
274 Arg = MaybeCreateExprWithCleanups(Arg);
275
276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
278
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);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
291 return false;
292}
293
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.
297void
298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
301 return;
302
303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
304 UnparsedDefaultArgLocs.erase(Param);
305
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();
311 return;
312 }
313
314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
320 // C++11 [dcl.fct.default]p3
321 // A default argument expression [...] shall not be specified for a
322 // parameter pack.
323 if (Param->isParameterPack()) {
324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325 << DefaultArg->getSourceRange();
326 return;
327 }
328
329 // Check that the default argument is well-formed
330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331 if (DefaultArgChecker.Visit(DefaultArg)) {
332 Param->setInvalidDecl();
333 return;
334 }
335
336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337}
338
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.
343void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344 SourceLocation EqualLoc,
345 SourceLocation ArgLoc) {
346 if (!param)
347 return;
348
349 ParmVarDecl *Param = cast<ParmVarDecl>(param);
350 Param->setUnparsedDefaultArg();
351 UnparsedDefaultArgLocs[Param] = ArgLoc;
352}
353
354/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355/// the default argument for the parameter param failed.
356void Sema::ActOnParamDefaultArgumentError(Decl *param,
357 SourceLocation EqualLoc) {
358 if (!param)
359 return;
360
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(),
367 VK_RValue));
368}
369
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.
375void 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
390 // arguments.
391 MightBeFunction = false;
392 continue;
393 }
394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395 ++argIdx) {
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);
400 SourceRange SR;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
404 else
405 SR = UnparsedDefaultArgLocs[Param];
406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407 << SR;
408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
411 Param->setDefaultArg(nullptr);
412 }
413 }
414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
416 }
417 }
418}
419
420static 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())
424 return false;
425 if (!PVD->hasInheritedDefaultArg())
426 return true;
427 }
428 return false;
429}
430
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.
435bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436 Scope *S) {
437 bool Invalid = false;
438
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();
445
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()
452 ? nullptr
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456 continue;
457
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.
463 continue;
464 }
465
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficent, and if neither is local, then they are in the same scope.)
471 continue;
472 }
473
474 // We found the right previous declaration.
475 break;
476 }
477
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).
490 //
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()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
506 if (OldParamHasDfl && NewParamHasDfl) {
507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
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());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524 Invalid = false;
525 }
526 }
527
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:
533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
536 Diag(NewParam->getLocation(), DiagDefaultParamID)
537 << NewParam->getDefaultArgRange();
538
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);
545 }
546
547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
549 } else if (OldParamHasDfl) {
550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
552 // strips off any top-level ExprWithCleanups.
553 NewParam->setHasInheritedDefaultArg();
554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
559 else
560 NewParam->setDefaultArg(OldParam->getInit());
561 } else if (NewParamHasDfl) {
562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
569 << false;
570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
581 // instantiated.
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
591 //
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
595 // dependent type.
596 int WhichKind = 2;
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
600 WhichKind = 0;
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602 WhichKind = 1;
603 else
604 WhichKind = 2;
605 }
606
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
609 << WhichKind
610 << NewParam->getDefaultArgRange();
611 }
612 }
613 }
614
615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0)
: __assert_fail ("NewParam->hasDefaultArg()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 624, __PRETTY_FUNCTION__))
;
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
628 }
629 }
630
631 const FunctionDecl *Def;
632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633 // template has a constexpr specifier then all its declarations shall
634 // contain the constexpr specifier.
635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
639 Invalid = true;
640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
647 Invalid = true;
648 }
649
650 // FIXME: It's not clear what should happen if multiple declarations of a
651 // deduction guide have different explicitness. For now at least we simply
652 // reject any case where the explicitness changes.
653 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
654 if (NewGuide && NewGuide->isExplicitSpecified() !=
655 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
656 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
657 << NewGuide->isExplicitSpecified();
658 Diag(Old->getLocation(), diag::note_previous_declaration);
659 }
660
661 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
662 // argument expression, that declaration shall be a definition and shall be
663 // the only declaration of the function or function template in the
664 // translation unit.
665 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
666 functionDeclHasDefaultArgument(Old)) {
667 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
668 Diag(Old->getLocation(), diag::note_previous_declaration);
669 Invalid = true;
670 }
671
672 return Invalid;
673}
674
675NamedDecl *
676Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
677 MultiTemplateParamsArg TemplateParamLists) {
678 assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0
) : __assert_fail ("D.isDecompositionDeclarator()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 678, __PRETTY_FUNCTION__))
;
679 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
680
681 // The syntax only allows a decomposition declarator as a simple-declaration
682 // or a for-range-declaration, but we parse it in more cases than that.
683 if (!D.mayHaveDecompositionDeclarator()) {
684 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
685 << Decomp.getSourceRange();
686 return nullptr;
687 }
688
689 if (!TemplateParamLists.empty()) {
690 // FIXME: There's no rule against this, but there are also no rules that
691 // would actually make it usable, so we reject it for now.
692 Diag(TemplateParamLists.front()->getTemplateLoc(),
693 diag::err_decomp_decl_template);
694 return nullptr;
695 }
696
697 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
698 ? diag::warn_cxx14_compat_decomp_decl
699 : diag::ext_decomp_decl)
700 << Decomp.getSourceRange();
701
702 // The semantic context is always just the current context.
703 DeclContext *const DC = CurContext;
704
705 // C++1z [dcl.dcl]/8:
706 // The decl-specifier-seq shall contain only the type-specifier auto
707 // and cv-qualifiers.
708 auto &DS = D.getDeclSpec();
709 {
710 SmallVector<StringRef, 8> BadSpecifiers;
711 SmallVector<SourceLocation, 8> BadSpecifierLocs;
712 if (auto SCS = DS.getStorageClassSpec()) {
713 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
714 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
715 }
716 if (auto TSCS = DS.getThreadStorageClassSpec()) {
717 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
718 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
719 }
720 if (DS.isConstexprSpecified()) {
721 BadSpecifiers.push_back("constexpr");
722 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
723 }
724 if (DS.isInlineSpecified()) {
725 BadSpecifiers.push_back("inline");
726 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
727 }
728 if (!BadSpecifiers.empty()) {
729 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
730 Err << (int)BadSpecifiers.size()
731 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
732 // Don't add FixItHints to remove the specifiers; we do still respect
733 // them when building the underlying variable.
734 for (auto Loc : BadSpecifierLocs)
735 Err << SourceRange(Loc, Loc);
736 }
737 // We can't recover from it being declared as a typedef.
738 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
739 return nullptr;
740 }
741
742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
743 QualType R = TInfo->getType();
744
745 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
746 UPPC_DeclarationType))
747 D.setInvalidType();
748
749 // The syntax only allows a single ref-qualifier prior to the decomposition
750 // declarator. No other declarator chunks are permitted. Also check the type
751 // specifier here.
752 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
753 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
754 (D.getNumTypeObjects() == 1 &&
755 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
756 Diag(Decomp.getLSquareLoc(),
757 (D.hasGroupingParens() ||
758 (D.getNumTypeObjects() &&
759 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
760 ? diag::err_decomp_decl_parens
761 : diag::err_decomp_decl_type)
762 << R;
763
764 // In most cases, there's no actual problem with an explicitly-specified
765 // type, but a function type won't work here, and ActOnVariableDeclarator
766 // shouldn't be called for such a type.
767 if (R->isFunctionType())
768 D.setInvalidType();
769 }
770
771 // Build the BindingDecls.
772 SmallVector<BindingDecl*, 8> Bindings;
773
774 // Build the BindingDecls.
775 for (auto &B : D.getDecompositionDeclarator().bindings()) {
776 // Check for name conflicts.
777 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
778 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
779 ForRedeclaration);
780 LookupName(Previous, S,
781 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
782
783 // It's not permitted to shadow a template parameter name.
784 if (Previous.isSingleResult() &&
785 Previous.getFoundDecl()->isTemplateParameter()) {
786 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
787 Previous.getFoundDecl());
788 Previous.clear();
789 }
790
791 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
792 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
793 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
794 /*AllowInlineNamespace*/false);
795 if (!Previous.empty()) {
796 auto *Old = Previous.getRepresentativeDecl();
797 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
798 Diag(Old->getLocation(), diag::note_previous_definition);
799 }
800
801 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
802 PushOnScopeChains(BD, S, true);
803 Bindings.push_back(BD);
804 ParsingInitForAutoVars.insert(BD);
805 }
806
807 // There are no prior lookup results for the variable itself, because it
808 // is unnamed.
809 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
810 Decomp.getLSquareLoc());
811 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
812
813 // Build the variable that holds the non-decomposed object.
814 bool AddToScope = true;
815 NamedDecl *New =
816 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
817 MultiTemplateParamsArg(), AddToScope, Bindings);
818 CurContext->addHiddenDecl(New);
819
820 if (isInOpenMPDeclareTargetContext())
821 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
822
823 return New;
824}
825
826static bool checkSimpleDecomposition(
827 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
828 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
829 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
830 if ((int64_t)Bindings.size() != NumElems) {
831 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
832 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
833 << (NumElems < Bindings.size());
834 return true;
835 }
836
837 unsigned I = 0;
838 for (auto *B : Bindings) {
839 SourceLocation Loc = B->getLocation();
840 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
841 if (E.isInvalid())
842 return true;
843 E = GetInit(Loc, E.get(), I++);
844 if (E.isInvalid())
845 return true;
846 B->setBinding(ElemType, E.get());
847 }
848
849 return false;
850}
851
852static bool checkArrayLikeDecomposition(Sema &S,
853 ArrayRef<BindingDecl *> Bindings,
854 ValueDecl *Src, QualType DecompType,
855 const llvm::APSInt &NumElems,
856 QualType ElemType) {
857 return checkSimpleDecomposition(
858 S, Bindings, Src, DecompType, NumElems, ElemType,
859 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
860 ExprResult E = S.ActOnIntegerConstant(Loc, I);
861 if (E.isInvalid())
862 return ExprError();
863 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
864 });
865}
866
867static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
868 ValueDecl *Src, QualType DecompType,
869 const ConstantArrayType *CAT) {
870 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
871 llvm::APSInt(CAT->getSize()),
872 CAT->getElementType());
873}
874
875static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
876 ValueDecl *Src, QualType DecompType,
877 const VectorType *VT) {
878 return checkArrayLikeDecomposition(
879 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
880 S.Context.getQualifiedType(VT->getElementType(),
881 DecompType.getQualifiers()));
882}
883
884static bool checkComplexDecomposition(Sema &S,
885 ArrayRef<BindingDecl *> Bindings,
886 ValueDecl *Src, QualType DecompType,
887 const ComplexType *CT) {
888 return checkSimpleDecomposition(
889 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
890 S.Context.getQualifiedType(CT->getElementType(),
891 DecompType.getQualifiers()),
892 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
893 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
894 });
895}
896
897static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
898 TemplateArgumentListInfo &Args) {
899 SmallString<128> SS;
900 llvm::raw_svector_ostream OS(SS);
901 bool First = true;
902 for (auto &Arg : Args.arguments()) {
903 if (!First)
904 OS << ", ";
905 Arg.getArgument().print(PrintingPolicy, OS);
906 First = false;
907 }
908 return OS.str();
909}
910
911static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
912 SourceLocation Loc, StringRef Trait,
913 TemplateArgumentListInfo &Args,
914 unsigned DiagID) {
915 auto DiagnoseMissing = [&] {
916 if (DiagID)
917 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
918 Args);
919 return true;
920 };
921
922 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
923 NamespaceDecl *Std = S.getStdNamespace();
924 if (!Std)
925 return DiagnoseMissing();
926
927 // Look up the trait itself, within namespace std. We can diagnose various
928 // problems with this lookup even if we've been asked to not diagnose a
929 // missing specialization, because this can only fail if the user has been
930 // declaring their own names in namespace std or we don't support the
931 // standard library implementation in use.
932 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
933 Loc, Sema::LookupOrdinaryName);
934 if (!S.LookupQualifiedName(Result, Std))
935 return DiagnoseMissing();
936 if (Result.isAmbiguous())
937 return true;
938
939 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
940 if (!TraitTD) {
941 Result.suppressDiagnostics();
942 NamedDecl *Found = *Result.begin();
943 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
944 S.Diag(Found->getLocation(), diag::note_declared_at);
945 return true;
946 }
947
948 // Build the template-id.
949 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
950 if (TraitTy.isNull())
951 return true;
952 if (!S.isCompleteType(Loc, TraitTy)) {
953 if (DiagID)
954 S.RequireCompleteType(
955 Loc, TraitTy, DiagID,
956 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
957 return true;
958 }
959
960 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
961 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 961, __PRETTY_FUNCTION__))
;
962
963 // Look up the member of the trait type.
964 S.LookupQualifiedName(TraitMemberLookup, RD);
965 return TraitMemberLookup.isAmbiguous();
966}
967
968static TemplateArgumentLoc
969getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
970 uint64_t I) {
971 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
972 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
973}
974
975static TemplateArgumentLoc
976getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
977 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
978}
979
980namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
981
982static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
983 llvm::APSInt &Size) {
984 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
985
986 DeclarationName Value = S.PP.getIdentifierInfo("value");
987 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
988
989 // Form template argument list for tuple_size<T>.
990 TemplateArgumentListInfo Args(Loc, Loc);
991 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
992
993 // If there's no tuple_size specialization, it's not tuple-like.
994 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
995 return IsTupleLike::NotTupleLike;
996
997 // If we get this far, we've committed to the tuple interpretation, but
998 // we can still fail if there actually isn't a usable ::value.
999
1000 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1001 LookupResult &R;
1002 TemplateArgumentListInfo &Args;
1003 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1004 : R(R), Args(Args) {}
1005 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1006 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1007 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1008 }
1009 } Diagnoser(R, Args);
1010
1011 if (R.empty()) {
1012 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1013 return IsTupleLike::Error;
1014 }
1015
1016 ExprResult E =
1017 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1018 if (E.isInvalid())
1019 return IsTupleLike::Error;
1020
1021 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1022 if (E.isInvalid())
1023 return IsTupleLike::Error;
1024
1025 return IsTupleLike::TupleLike;
1026}
1027
1028/// \return std::tuple_element<I, T>::type.
1029static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1030 unsigned I, QualType T) {
1031 // Form template argument list for tuple_element<I, T>.
1032 TemplateArgumentListInfo Args(Loc, Loc);
1033 Args.addArgument(
1034 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1035 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1036
1037 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1038 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1039 if (lookupStdTypeTraitMember(
1040 S, R, Loc, "tuple_element", Args,
1041 diag::err_decomp_decl_std_tuple_element_not_specialized))
1042 return QualType();
1043
1044 auto *TD = R.getAsSingle<TypeDecl>();
1045 if (!TD) {
1046 R.suppressDiagnostics();
1047 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1048 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1049 if (!R.empty())
1050 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1051 return QualType();
1052 }
1053
1054 return S.Context.getTypeDeclType(TD);
1055}
1056
1057namespace {
1058struct BindingDiagnosticTrap {
1059 Sema &S;
1060 DiagnosticErrorTrap Trap;
1061 BindingDecl *BD;
1062
1063 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1064 : S(S), Trap(S.Diags), BD(BD) {}
1065 ~BindingDiagnosticTrap() {
1066 if (Trap.hasErrorOccurred())
1067 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1068 }
1069};
1070}
1071
1072static bool checkTupleLikeDecomposition(Sema &S,
1073 ArrayRef<BindingDecl *> Bindings,
1074 VarDecl *Src, QualType DecompType,
1075 const llvm::APSInt &TupleSize) {
1076 if ((int64_t)Bindings.size() != TupleSize) {
1077 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1078 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1079 << (TupleSize < Bindings.size());
1080 return true;
1081 }
1082
1083 if (Bindings.empty())
1084 return false;
1085
1086 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1087
1088 // [dcl.decomp]p3:
1089 // The unqualified-id get is looked up in the scope of E by class member
1090 // access lookup
1091 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1092 bool UseMemberGet = false;
1093 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1094 if (auto *RD = DecompType->getAsCXXRecordDecl())
1095 S.LookupQualifiedName(MemberGet, RD);
1096 if (MemberGet.isAmbiguous())
1097 return true;
1098 UseMemberGet = !MemberGet.empty();
1099 S.FilterAcceptableTemplateNames(MemberGet);
1100 }
1101
1102 unsigned I = 0;
1103 for (auto *B : Bindings) {
1104 BindingDiagnosticTrap Trap(S, B);
1105 SourceLocation Loc = B->getLocation();
1106
1107 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1108 if (E.isInvalid())
1109 return true;
1110
1111 // e is an lvalue if the type of the entity is an lvalue reference and
1112 // an xvalue otherwise
1113 if (!Src->getType()->isLValueReferenceType())
1114 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1115 E.get(), nullptr, VK_XValue);
1116
1117 TemplateArgumentListInfo Args(Loc, Loc);
1118 Args.addArgument(
1119 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1120
1121 if (UseMemberGet) {
1122 // if [lookup of member get] finds at least one declaration, the
1123 // initializer is e.get<i-1>().
1124 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1125 CXXScopeSpec(), SourceLocation(), nullptr,
1126 MemberGet, &Args, nullptr);
1127 if (E.isInvalid())
1128 return true;
1129
1130 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1131 } else {
1132 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1133 // in the associated namespaces.
1134 Expr *Get = UnresolvedLookupExpr::Create(
1135 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1136 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1137 UnresolvedSetIterator(), UnresolvedSetIterator());
1138
1139 Expr *Arg = E.get();
1140 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1141 }
1142 if (E.isInvalid())
1143 return true;
1144 Expr *Init = E.get();
1145
1146 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1147 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1148 if (T.isNull())
1149 return true;
1150
1151 // each vi is a variable of type "reference to T" initialized with the
1152 // initializer, where the reference is an lvalue reference if the
1153 // initializer is an lvalue and an rvalue reference otherwise
1154 QualType RefType =
1155 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1156 if (RefType.isNull())
1157 return true;
1158 auto *RefVD = VarDecl::Create(
1159 S.Context, Src->getDeclContext(), Loc, Loc,
1160 B->getDeclName().getAsIdentifierInfo(), RefType,
1161 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1162 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1163 RefVD->setTSCSpec(Src->getTSCSpec());
1164 RefVD->setImplicit();
1165 if (Src->isInlineSpecified())
1166 RefVD->setInlineSpecified();
1167 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1168
1169 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1170 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1171 InitializationSequence Seq(S, Entity, Kind, Init);
1172 E = Seq.Perform(S, Entity, Kind, Init);
1173 if (E.isInvalid())
1174 return true;
1175 E = S.ActOnFinishFullExpr(E.get(), Loc);
1176 if (E.isInvalid())
1177 return true;
1178 RefVD->setInit(E.get());
1179 RefVD->checkInitIsICE();
1180
1181 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1182 DeclarationNameInfo(B->getDeclName(), Loc),
1183 RefVD);
1184 if (E.isInvalid())
1185 return true;
1186
1187 B->setBinding(T, E.get());
1188 I++;
1189 }
1190
1191 return false;
1192}
1193
1194/// Find the base class to decompose in a built-in decomposition of a class type.
1195/// This base class search is, unfortunately, not quite like any other that we
1196/// perform anywhere else in C++.
1197static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1198 SourceLocation Loc,
1199 const CXXRecordDecl *RD,
1200 CXXCastPath &BasePath) {
1201 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1202 CXXBasePath &Path) {
1203 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1204 };
1205
1206 const CXXRecordDecl *ClassWithFields = nullptr;
1207 if (RD->hasDirectFields())
13
Assuming the condition is false
14
Taking false branch
1208 // [dcl.decomp]p4:
1209 // Otherwise, all of E's non-static data members shall be public direct
1210 // members of E ...
1211 ClassWithFields = RD;
1212 else {
1213 // ... or of ...
1214 CXXBasePaths Paths;
1215 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1216 if (!RD->lookupInBases(BaseHasFields, Paths)) {
15
Assuming the condition is false
16
Taking false branch
1217 // If no classes have fields, just decompose RD itself. (This will work
1218 // if and only if zero bindings were provided.)
1219 return RD;
1220 }
1221
1222 CXXBasePath *BestPath = nullptr;
17
'BestPath' initialized to a null pointer value
1223 for (auto &P : Paths) {
1224 if (!BestPath)
1225 BestPath = &P;
1226 else if (!S.Context.hasSameType(P.back().Base->getType(),
1227 BestPath->back().Base->getType())) {
1228 // ... the same ...
1229 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1230 << false << RD << BestPath->back().Base->getType()
1231 << P.back().Base->getType();
1232 return nullptr;
1233 } else if (P.Access < BestPath->Access) {
1234 BestPath = &P;
1235 }
1236 }
1237
1238 // ... unambiguous ...
1239 QualType BaseType = BestPath->back().Base->getType();
18
Called C++ object pointer is null
1240 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1241 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1242 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1243 return nullptr;
1244 }
1245
1246 // ... public base class of E.
1247 if (BestPath->Access != AS_public) {
1248 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1249 << RD << BaseType;
1250 for (auto &BS : *BestPath) {
1251 if (BS.Base->getAccessSpecifier() != AS_public) {
1252 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1253 << (BS.Base->getAccessSpecifier() == AS_protected)
1254 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1255 break;
1256 }
1257 }
1258 return nullptr;
1259 }
1260
1261 ClassWithFields = BaseType->getAsCXXRecordDecl();
1262 S.BuildBasePathArray(Paths, BasePath);
1263 }
1264
1265 // The above search did not check whether the selected class itself has base
1266 // classes with fields, so check that now.
1267 CXXBasePaths Paths;
1268 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1269 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1270 << (ClassWithFields == RD) << RD << ClassWithFields
1271 << Paths.front().back().Base->getType();
1272 return nullptr;
1273 }
1274
1275 return ClassWithFields;
1276}
1277
1278static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1279 ValueDecl *Src, QualType DecompType,
1280 const CXXRecordDecl *RD) {
1281 CXXCastPath BasePath;
1282 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
12
Calling 'findDecomposableBaseClass'
1283 if (!RD)
1284 return true;
1285 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1286 DecompType.getQualifiers());
1287
1288 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1289 unsigned NumFields =
1290 std::count_if(RD->field_begin(), RD->field_end(),
1291 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1292 assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0)
: __assert_fail ("Bindings.size() != NumFields", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1292, __PRETTY_FUNCTION__))
;
1293 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1294 << DecompType << (unsigned)Bindings.size() << NumFields
1295 << (NumFields < Bindings.size());
1296 return true;
1297 };
1298
1299 // all of E's non-static data members shall be public [...] members,
1300 // E shall not have an anonymous union member, ...
1301 unsigned I = 0;
1302 for (auto *FD : RD->fields()) {
1303 if (FD->isUnnamedBitfield())
1304 continue;
1305
1306 if (FD->isAnonymousStructOrUnion()) {
1307 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1308 << DecompType << FD->getType()->isUnionType();
1309 S.Diag(FD->getLocation(), diag::note_declared_at);
1310 return true;
1311 }
1312
1313 // We have a real field to bind.
1314 if (I >= Bindings.size())
1315 return DiagnoseBadNumberOfBindings();
1316 auto *B = Bindings[I++];
1317
1318 SourceLocation Loc = B->getLocation();
1319 if (FD->getAccess() != AS_public) {
1320 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1321
1322 // Determine whether the access specifier was explicit.
1323 bool Implicit = true;
1324 for (const auto *D : RD->decls()) {
1325 if (declaresSameEntity(D, FD))
1326 break;
1327 if (isa<AccessSpecDecl>(D)) {
1328 Implicit = false;
1329 break;
1330 }
1331 }
1332
1333 S.Diag(FD->getLocation(), diag::note_access_natural)
1334 << (FD->getAccess() == AS_protected) << Implicit;
1335 return true;
1336 }
1337
1338 // Initialize the binding to Src.FD.
1339 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1340 if (E.isInvalid())
1341 return true;
1342 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1343 VK_LValue, &BasePath);
1344 if (E.isInvalid())
1345 return true;
1346 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1347 CXXScopeSpec(), FD,
1348 DeclAccessPair::make(FD, FD->getAccess()),
1349 DeclarationNameInfo(FD->getDeclName(), Loc));
1350 if (E.isInvalid())
1351 return true;
1352
1353 // If the type of the member is T, the referenced type is cv T, where cv is
1354 // the cv-qualification of the decomposition expression.
1355 //
1356 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1357 // 'const' to the type of the field.
1358 Qualifiers Q = DecompType.getQualifiers();
1359 if (FD->isMutable())
1360 Q.removeConst();
1361 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1362 }
1363
1364 if (I != Bindings.size())
1365 return DiagnoseBadNumberOfBindings();
1366
1367 return false;
1368}
1369
1370void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1371 QualType DecompType = DD->getType();
1372
1373 // If the type of the decomposition is dependent, then so is the type of
1374 // each binding.
1375 if (DecompType->isDependentType()) {
1
Taking false branch
1376 for (auto *B : DD->bindings())
1377 B->setType(Context.DependentTy);
1378 return;
1379 }
1380
1381 DecompType = DecompType.getNonReferenceType();
1382 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1383
1384 // C++1z [dcl.decomp]/2:
1385 // If E is an array type [...]
1386 // As an extension, we also support decomposition of built-in complex and
1387 // vector types.
1388 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
2
Taking false branch
1389 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1390 DD->setInvalidDecl();
1391 return;
1392 }
1393 if (auto *VT = DecompType->getAs<VectorType>()) {
3
Assuming 'VT' is null
4
Taking false branch
1394 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1395 DD->setInvalidDecl();
1396 return;
1397 }
1398 if (auto *CT = DecompType->getAs<ComplexType>()) {
5
Assuming 'CT' is null
6
Taking false branch
1399 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1400 DD->setInvalidDecl();
1401 return;
1402 }
1403
1404 // C++1z [dcl.decomp]/3:
1405 // if the expression std::tuple_size<E>::value is a well-formed integral
1406 // constant expression, [...]
1407 llvm::APSInt TupleSize(32);
1408 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
7
Control jumps to 'case NotTupleLike:' at line 1418
1409 case IsTupleLike::Error:
1410 DD->setInvalidDecl();
1411 return;
1412
1413 case IsTupleLike::TupleLike:
1414 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1415 DD->setInvalidDecl();
1416 return;
1417
1418 case IsTupleLike::NotTupleLike:
1419 break;
8
Execution continues on line 1424
1420 }
1421
1422 // C++1z [dcl.dcl]/8:
1423 // [E shall be of array or non-union class type]
1424 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1425 if (!RD || RD->isUnion()) {
9
Assuming 'RD' is non-null
10
Taking false branch
1426 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1427 << DD << !RD << DecompType;
1428 DD->setInvalidDecl();
1429 return;
1430 }
1431
1432 // C++1z [dcl.decomp]/4:
1433 // all of E's non-static data members shall be [...] direct members of
1434 // E or of the same unambiguous public base class of E, ...
1435 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
11
Calling 'checkMemberDecomposition'
1436 DD->setInvalidDecl();
1437}
1438
1439/// \brief Merge the exception specifications of two variable declarations.
1440///
1441/// This is called when there's a redeclaration of a VarDecl. The function
1442/// checks if the redeclaration might have an exception specification and
1443/// validates compatibility and merges the specs if necessary.
1444void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1445 // Shortcut if exceptions are disabled.
1446 if (!getLangOpts().CXXExceptions)
1447 return;
1448
1449 assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1450, __PRETTY_FUNCTION__))
1450 "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1450, __PRETTY_FUNCTION__))
;
1451
1452 QualType NewType = New->getType();
1453 QualType OldType = Old->getType();
1454
1455 // We're only interested in pointers and references to functions, as well
1456 // as pointers to member functions.
1457 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1458 NewType = R->getPointeeType();
1459 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1460 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1461 NewType = P->getPointeeType();
1462 OldType = OldType->getAs<PointerType>()->getPointeeType();
1463 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1464 NewType = M->getPointeeType();
1465 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1466 }
1467
1468 if (!NewType->isFunctionProtoType())
1469 return;
1470
1471 // There's lots of special cases for functions. For function pointers, system
1472 // libraries are hopefully not as broken so that we don't need these
1473 // workarounds.
1474 if (CheckEquivalentExceptionSpec(
1475 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1476 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1477 New->setInvalidDecl();
1478 }
1479}
1480
1481/// CheckCXXDefaultArguments - Verify that the default arguments for a
1482/// function declaration are well-formed according to C++
1483/// [dcl.fct.default].
1484void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1485 unsigned NumParams = FD->getNumParams();
1486 unsigned p;
1487
1488 // Find first parameter with a default argument
1489 for (p = 0; p < NumParams; ++p) {
1490 ParmVarDecl *Param = FD->getParamDecl(p);
1491 if (Param->hasDefaultArg())
1492 break;
1493 }
1494
1495 // C++11 [dcl.fct.default]p4:
1496 // In a given function declaration, each parameter subsequent to a parameter
1497 // with a default argument shall have a default argument supplied in this or
1498 // a previous declaration or shall be a function parameter pack. A default
1499 // argument shall not be redefined by a later declaration (not even to the
1500 // same value).
1501 unsigned LastMissingDefaultArg = 0;
1502 for (; p < NumParams; ++p) {
1503 ParmVarDecl *Param = FD->getParamDecl(p);
1504 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1505 if (Param->isInvalidDecl())
1506 /* We already complained about this parameter. */;
1507 else if (Param->getIdentifier())
1508 Diag(Param->getLocation(),
1509 diag::err_param_default_argument_missing_name)
1510 << Param->getIdentifier();
1511 else
1512 Diag(Param->getLocation(),
1513 diag::err_param_default_argument_missing);
1514
1515 LastMissingDefaultArg = p;
1516 }
1517 }
1518
1519 if (LastMissingDefaultArg > 0) {
1520 // Some default arguments were missing. Clear out all of the
1521 // default arguments up to (and including) the last missing
1522 // default argument, so that we leave the function parameters
1523 // in a semantically valid state.
1524 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1525 ParmVarDecl *Param = FD->getParamDecl(p);
1526 if (Param->hasDefaultArg()) {
1527 Param->setDefaultArg(nullptr);
1528 }
1529 }
1530 }
1531}
1532
1533// CheckConstexprParameterTypes - Check whether a function's parameter types
1534// are all literal types. If so, return true. If not, produce a suitable
1535// diagnostic and return false.
1536static bool CheckConstexprParameterTypes(Sema &SemaRef,
1537 const FunctionDecl *FD) {
1538 unsigned ArgIndex = 0;
1539 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1540 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1541 e = FT->param_type_end();
1542 i != e; ++i, ++ArgIndex) {
1543 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1544 SourceLocation ParamLoc = PD->getLocation();
1545 if (!(*i)->isDependentType() &&
1546 SemaRef.RequireLiteralType(ParamLoc, *i,
1547 diag::err_constexpr_non_literal_param,
1548 ArgIndex+1, PD->getSourceRange(),
1549 isa<CXXConstructorDecl>(FD)))
1550 return false;
1551 }
1552 return true;
1553}
1554
1555/// \brief Get diagnostic %select index for tag kind for
1556/// record diagnostic message.
1557/// WARNING: Indexes apply to particular diagnostics only!
1558///
1559/// \returns diagnostic %select index.
1560static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1561 switch (Tag) {
1562 case TTK_Struct: return 0;
1563 case TTK_Interface: return 1;
1564 case TTK_Class: return 2;
1565 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1565)
;
1566 }
1567}
1568
1569// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1570// the requirements of a constexpr function definition or a constexpr
1571// constructor definition. If so, return true. If not, produce appropriate
1572// diagnostics and return false.
1573//
1574// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1575bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1576 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1577 if (MD && MD->isInstance()) {
1578 // C++11 [dcl.constexpr]p4:
1579 // The definition of a constexpr constructor shall satisfy the following
1580 // constraints:
1581 // - the class shall not have any virtual base classes;
1582 const CXXRecordDecl *RD = MD->getParent();
1583 if (RD->getNumVBases()) {
1584 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1585 << isa<CXXConstructorDecl>(NewFD)
1586 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1587 for (const auto &I : RD->vbases())
1588 Diag(I.getLocStart(),
1589 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1590 return false;
1591 }
1592 }
1593
1594 if (!isa<CXXConstructorDecl>(NewFD)) {
1595 // C++11 [dcl.constexpr]p3:
1596 // The definition of a constexpr function shall satisfy the following
1597 // constraints:
1598 // - it shall not be virtual;
1599 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1600 if (Method && Method->isVirtual()) {
1601 Method = Method->getCanonicalDecl();
1602 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1603
1604 // If it's not obvious why this function is virtual, find an overridden
1605 // function which uses the 'virtual' keyword.
1606 const CXXMethodDecl *WrittenVirtual = Method;
1607 while (!WrittenVirtual->isVirtualAsWritten())
1608 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1609 if (WrittenVirtual != Method)
1610 Diag(WrittenVirtual->getLocation(),
1611 diag::note_overridden_virtual_function);
1612 return false;
1613 }
1614
1615 // - its return type shall be a literal type;
1616 QualType RT = NewFD->getReturnType();
1617 if (!RT->isDependentType() &&
1618 RequireLiteralType(NewFD->getLocation(), RT,
1619 diag::err_constexpr_non_literal_return))
1620 return false;
1621 }
1622
1623 // - each of its parameter types shall be a literal type;
1624 if (!CheckConstexprParameterTypes(*this, NewFD))
1625 return false;
1626
1627 return true;
1628}
1629
1630/// Check the given declaration statement is legal within a constexpr function
1631/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1632///
1633/// \return true if the body is OK (maybe only as an extension), false if we
1634/// have diagnosed a problem.
1635static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1636 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1637 // C++11 [dcl.constexpr]p3 and p4:
1638 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1639 // contain only
1640 for (const auto *DclIt : DS->decls()) {
1641 switch (DclIt->getKind()) {
1642 case Decl::StaticAssert:
1643 case Decl::Using:
1644 case Decl::UsingShadow:
1645 case Decl::UsingDirective:
1646 case Decl::UnresolvedUsingTypename:
1647 case Decl::UnresolvedUsingValue:
1648 // - static_assert-declarations
1649 // - using-declarations,
1650 // - using-directives,
1651 continue;
1652
1653 case Decl::Typedef:
1654 case Decl::TypeAlias: {
1655 // - typedef declarations and alias-declarations that do not define
1656 // classes or enumerations,
1657 const auto *TN = cast<TypedefNameDecl>(DclIt);
1658 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1659 // Don't allow variably-modified types in constexpr functions.
1660 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1661 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1662 << TL.getSourceRange() << TL.getType()
1663 << isa<CXXConstructorDecl>(Dcl);
1664 return false;
1665 }
1666 continue;
1667 }
1668
1669 case Decl::Enum:
1670 case Decl::CXXRecord:
1671 // C++1y allows types to be defined, not just declared.
1672 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1673 SemaRef.Diag(DS->getLocStart(),
1674 SemaRef.getLangOpts().CPlusPlus14
1675 ? diag::warn_cxx11_compat_constexpr_type_definition
1676 : diag::ext_constexpr_type_definition)
1677 << isa<CXXConstructorDecl>(Dcl);
1678 continue;
1679
1680 case Decl::EnumConstant:
1681 case Decl::IndirectField:
1682 case Decl::ParmVar:
1683 // These can only appear with other declarations which are banned in
1684 // C++11 and permitted in C++1y, so ignore them.
1685 continue;
1686
1687 case Decl::Var:
1688 case Decl::Decomposition: {
1689 // C++1y [dcl.constexpr]p3 allows anything except:
1690 // a definition of a variable of non-literal type or of static or
1691 // thread storage duration or for which no initialization is performed.
1692 const auto *VD = cast<VarDecl>(DclIt);
1693 if (VD->isThisDeclarationADefinition()) {
1694 if (VD->isStaticLocal()) {
1695 SemaRef.Diag(VD->getLocation(),
1696 diag::err_constexpr_local_var_static)
1697 << isa<CXXConstructorDecl>(Dcl)
1698 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1699 return false;
1700 }
1701 if (!VD->getType()->isDependentType() &&
1702 SemaRef.RequireLiteralType(
1703 VD->getLocation(), VD->getType(),
1704 diag::err_constexpr_local_var_non_literal_type,
1705 isa<CXXConstructorDecl>(Dcl)))
1706 return false;
1707 if (!VD->getType()->isDependentType() &&
1708 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1709 SemaRef.Diag(VD->getLocation(),
1710 diag::err_constexpr_local_var_no_init)
1711 << isa<CXXConstructorDecl>(Dcl);
1712 return false;
1713 }
1714 }
1715 SemaRef.Diag(VD->getLocation(),
1716 SemaRef.getLangOpts().CPlusPlus14
1717 ? diag::warn_cxx11_compat_constexpr_local_var
1718 : diag::ext_constexpr_local_var)
1719 << isa<CXXConstructorDecl>(Dcl);
1720 continue;
1721 }
1722
1723 case Decl::NamespaceAlias:
1724 case Decl::Function:
1725 // These are disallowed in C++11 and permitted in C++1y. Allow them
1726 // everywhere as an extension.
1727 if (!Cxx1yLoc.isValid())
1728 Cxx1yLoc = DS->getLocStart();
1729 continue;
1730
1731 default:
1732 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1733 << isa<CXXConstructorDecl>(Dcl);
1734 return false;
1735 }
1736 }
1737
1738 return true;
1739}
1740
1741/// Check that the given field is initialized within a constexpr constructor.
1742///
1743/// \param Dcl The constexpr constructor being checked.
1744/// \param Field The field being checked. This may be a member of an anonymous
1745/// struct or union nested within the class being checked.
1746/// \param Inits All declarations, including anonymous struct/union members and
1747/// indirect members, for which any initialization was provided.
1748/// \param Diagnosed Set to true if an error is produced.
1749static void CheckConstexprCtorInitializer(Sema &SemaRef,
1750 const FunctionDecl *Dcl,
1751 FieldDecl *Field,
1752 llvm::SmallSet<Decl*, 16> &Inits,
1753 bool &Diagnosed) {
1754 if (Field->isInvalidDecl())
1755 return;
1756
1757 if (Field->isUnnamedBitfield())
1758 return;
1759
1760 // Anonymous unions with no variant members and empty anonymous structs do not
1761 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1762 // indirect fields don't need initializing.
1763 if (Field->isAnonymousStructOrUnion() &&
1764 (Field->getType()->isUnionType()
1765 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1766 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1767 return;
1768
1769 if (!Inits.count(Field)) {
1770 if (!Diagnosed) {
1771 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1772 Diagnosed = true;
1773 }
1774 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1775 } else if (Field->isAnonymousStructOrUnion()) {
1776 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1777 for (auto *I : RD->fields())
1778 // If an anonymous union contains an anonymous struct of which any member
1779 // is initialized, all members must be initialized.
1780 if (!RD->isUnion() || Inits.count(I))
1781 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1782 }
1783}
1784
1785/// Check the provided statement is allowed in a constexpr function
1786/// definition.
1787static bool
1788CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1789 SmallVectorImpl<SourceLocation> &ReturnStmts,
1790 SourceLocation &Cxx1yLoc) {
1791 // - its function-body shall be [...] a compound-statement that contains only
1792 switch (S->getStmtClass()) {
1793 case Stmt::NullStmtClass:
1794 // - null statements,
1795 return true;
1796
1797 case Stmt::DeclStmtClass:
1798 // - static_assert-declarations
1799 // - using-declarations,
1800 // - using-directives,
1801 // - typedef declarations and alias-declarations that do not define
1802 // classes or enumerations,
1803 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1804 return false;
1805 return true;
1806
1807 case Stmt::ReturnStmtClass:
1808 // - and exactly one return statement;
1809 if (isa<CXXConstructorDecl>(Dcl)) {
1810 // C++1y allows return statements in constexpr constructors.
1811 if (!Cxx1yLoc.isValid())
1812 Cxx1yLoc = S->getLocStart();
1813 return true;
1814 }
1815
1816 ReturnStmts.push_back(S->getLocStart());
1817 return true;
1818
1819 case Stmt::CompoundStmtClass: {
1820 // C++1y allows compound-statements.
1821 if (!Cxx1yLoc.isValid())
1822 Cxx1yLoc = S->getLocStart();
1823
1824 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1825 for (auto *BodyIt : CompStmt->body()) {
1826 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1827 Cxx1yLoc))
1828 return false;
1829 }
1830 return true;
1831 }
1832
1833 case Stmt::AttributedStmtClass:
1834 if (!Cxx1yLoc.isValid())
1835 Cxx1yLoc = S->getLocStart();
1836 return true;
1837
1838 case Stmt::IfStmtClass: {
1839 // C++1y allows if-statements.
1840 if (!Cxx1yLoc.isValid())
1841 Cxx1yLoc = S->getLocStart();
1842
1843 IfStmt *If = cast<IfStmt>(S);
1844 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1845 Cxx1yLoc))
1846 return false;
1847 if (If->getElse() &&
1848 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1849 Cxx1yLoc))
1850 return false;
1851 return true;
1852 }
1853
1854 case Stmt::WhileStmtClass:
1855 case Stmt::DoStmtClass:
1856 case Stmt::ForStmtClass:
1857 case Stmt::CXXForRangeStmtClass:
1858 case Stmt::ContinueStmtClass:
1859 // C++1y allows all of these. We don't allow them as extensions in C++11,
1860 // because they don't make sense without variable mutation.
1861 if (!SemaRef.getLangOpts().CPlusPlus14)
1862 break;
1863 if (!Cxx1yLoc.isValid())
1864 Cxx1yLoc = S->getLocStart();
1865 for (Stmt *SubStmt : S->children())
1866 if (SubStmt &&
1867 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1868 Cxx1yLoc))
1869 return false;
1870 return true;
1871
1872 case Stmt::SwitchStmtClass:
1873 case Stmt::CaseStmtClass:
1874 case Stmt::DefaultStmtClass:
1875 case Stmt::BreakStmtClass:
1876 // C++1y allows switch-statements, and since they don't need variable
1877 // mutation, we can reasonably allow them in C++11 as an extension.
1878 if (!Cxx1yLoc.isValid())
1879 Cxx1yLoc = S->getLocStart();
1880 for (Stmt *SubStmt : S->children())
1881 if (SubStmt &&
1882 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1883 Cxx1yLoc))
1884 return false;
1885 return true;
1886
1887 default:
1888 if (!isa<Expr>(S))
1889 break;
1890
1891 // C++1y allows expression-statements.
1892 if (!Cxx1yLoc.isValid())
1893 Cxx1yLoc = S->getLocStart();
1894 return true;
1895 }
1896
1897 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1898 << isa<CXXConstructorDecl>(Dcl);
1899 return false;
1900}
1901
1902/// Check the body for the given constexpr function declaration only contains
1903/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1904///
1905/// \return true if the body is OK, false if we have diagnosed a problem.
1906bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1907 if (isa<CXXTryStmt>(Body)) {
1908 // C++11 [dcl.constexpr]p3:
1909 // The definition of a constexpr function shall satisfy the following
1910 // constraints: [...]
1911 // - its function-body shall be = delete, = default, or a
1912 // compound-statement
1913 //
1914 // C++11 [dcl.constexpr]p4:
1915 // In the definition of a constexpr constructor, [...]
1916 // - its function-body shall not be a function-try-block;
1917 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1918 << isa<CXXConstructorDecl>(Dcl);
1919 return false;
1920 }
1921
1922 SmallVector<SourceLocation, 4> ReturnStmts;
1923
1924 // - its function-body shall be [...] a compound-statement that contains only
1925 // [... list of cases ...]
1926 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1927 SourceLocation Cxx1yLoc;
1928 for (auto *BodyIt : CompBody->body()) {
1929 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1930 return false;
1931 }
1932
1933 if (Cxx1yLoc.isValid())
1934 Diag(Cxx1yLoc,
1935 getLangOpts().CPlusPlus14
1936 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1937 : diag::ext_constexpr_body_invalid_stmt)
1938 << isa<CXXConstructorDecl>(Dcl);
1939
1940 if (const CXXConstructorDecl *Constructor
1941 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1942 const CXXRecordDecl *RD = Constructor->getParent();
1943 // DR1359:
1944 // - every non-variant non-static data member and base class sub-object
1945 // shall be initialized;
1946 // DR1460:
1947 // - if the class is a union having variant members, exactly one of them
1948 // shall be initialized;
1949 if (RD->isUnion()) {
1950 if (Constructor->getNumCtorInitializers() == 0 &&
1951 RD->hasVariantMembers()) {
1952 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1953 return false;
1954 }
1955 } else if (!Constructor->isDependentContext() &&
1956 !Constructor->isDelegatingConstructor()) {
1957 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"
) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1957, __PRETTY_FUNCTION__))
;
1958
1959 // Skip detailed checking if we have enough initializers, and we would
1960 // allow at most one initializer per member.
1961 bool AnyAnonStructUnionMembers = false;
1962 unsigned Fields = 0;
1963 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1964 E = RD->field_end(); I != E; ++I, ++Fields) {
1965 if (I->isAnonymousStructOrUnion()) {
1966 AnyAnonStructUnionMembers = true;
1967 break;
1968 }
1969 }
1970 // DR1460:
1971 // - if the class is a union-like class, but is not a union, for each of
1972 // its anonymous union members having variant members, exactly one of
1973 // them shall be initialized;
1974 if (AnyAnonStructUnionMembers ||
1975 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1976 // Check initialization of non-static data members. Base classes are
1977 // always initialized so do not need to be checked. Dependent bases
1978 // might not have initializers in the member initializer list.
1979 llvm::SmallSet<Decl*, 16> Inits;
1980 for (const auto *I: Constructor->inits()) {
1981 if (FieldDecl *FD = I->getMember())
1982 Inits.insert(FD);
1983 else if (IndirectFieldDecl *ID = I->getIndirectMember())
1984 Inits.insert(ID->chain_begin(), ID->chain_end());
1985 }
1986
1987 bool Diagnosed = false;
1988 for (auto *I : RD->fields())
1989 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1990 if (Diagnosed)
1991 return false;
1992 }
1993 }
1994 } else {
1995 if (ReturnStmts.empty()) {
1996 // C++1y doesn't require constexpr functions to contain a 'return'
1997 // statement. We still do, unless the return type might be void, because
1998 // otherwise if there's no return statement, the function cannot
1999 // be used in a core constant expression.
2000 bool OK = getLangOpts().CPlusPlus14 &&
2001 (Dcl->getReturnType()->isVoidType() ||
2002 Dcl->getReturnType()->isDependentType());
2003 Diag(Dcl->getLocation(),
2004 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2005 : diag::err_constexpr_body_no_return);
2006 if (!OK)
2007 return false;
2008 } else if (ReturnStmts.size() > 1) {
2009 Diag(ReturnStmts.back(),
2010 getLangOpts().CPlusPlus14
2011 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2012 : diag::ext_constexpr_body_multiple_return);
2013 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2014 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2015 }
2016 }
2017
2018 // C++11 [dcl.constexpr]p5:
2019 // if no function argument values exist such that the function invocation
2020 // substitution would produce a constant expression, the program is
2021 // ill-formed; no diagnostic required.
2022 // C++11 [dcl.constexpr]p3:
2023 // - every constructor call and implicit conversion used in initializing the
2024 // return value shall be one of those allowed in a constant expression.
2025 // C++11 [dcl.constexpr]p4:
2026 // - every constructor involved in initializing non-static data members and
2027 // base class sub-objects shall be a constexpr constructor.
2028 SmallVector<PartialDiagnosticAt, 8> Diags;
2029 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2030 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2031 << isa<CXXConstructorDecl>(Dcl);
2032 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2033 Diag(Diags[I].first, Diags[I].second);
2034 // Don't return false here: we allow this for compatibility in
2035 // system headers.
2036 }
2037
2038 return true;
2039}
2040
2041/// isCurrentClassName - Determine whether the identifier II is the
2042/// name of the class type currently being defined. In the case of
2043/// nested classes, this will only return true if II is the name of
2044/// the innermost class.
2045bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2046 const CXXScopeSpec *SS) {
2047 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2047, __PRETTY_FUNCTION__))
;
2048
2049 CXXRecordDecl *CurDecl;
2050 if (SS && SS->isSet() && !SS->isInvalid()) {
2051 DeclContext *DC = computeDeclContext(*SS, true);
2052 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2053 } else
2054 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2055
2056 if (CurDecl && CurDecl->getIdentifier())
2057 return &II == CurDecl->getIdentifier();
2058 return false;
2059}
2060
2061/// \brief Determine whether the identifier II is a typo for the name of
2062/// the class type currently being defined. If so, update it to the identifier
2063/// that should have been used.
2064bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2065 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2065, __PRETTY_FUNCTION__))
;
2066
2067 if (!getLangOpts().SpellChecking)
2068 return false;
2069
2070 CXXRecordDecl *CurDecl;
2071 if (SS && SS->isSet() && !SS->isInvalid()) {
2072 DeclContext *DC = computeDeclContext(*SS, true);
2073 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2074 } else
2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2076
2077 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2078 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2079 < II->getLength()) {
2080 II = CurDecl->getIdentifier();
2081 return true;
2082 }
2083
2084 return false;
2085}
2086
2087/// \brief Determine whether the given class is a base class of the given
2088/// class, including looking at dependent bases.
2089static bool findCircularInheritance(const CXXRecordDecl *Class,
2090 const CXXRecordDecl *Current) {
2091 SmallVector<const CXXRecordDecl*, 8> Queue;
2092
2093 Class = Class->getCanonicalDecl();
2094 while (true) {
2095 for (const auto &I : Current->bases()) {
2096 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2097 if (!Base)
2098 continue;
2099
2100 Base = Base->getDefinition();
2101 if (!Base)
2102 continue;
2103
2104 if (Base->getCanonicalDecl() == Class)
2105 return true;
2106
2107 Queue.push_back(Base);
2108 }
2109
2110 if (Queue.empty())
2111 return false;
2112
2113 Current = Queue.pop_back_val();
2114 }
2115
2116 return false;
2117}
2118
2119/// \brief Check the validity of a C++ base class specifier.
2120///
2121/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2122/// and returns NULL otherwise.
2123CXXBaseSpecifier *
2124Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2125 SourceRange SpecifierRange,
2126 bool Virtual, AccessSpecifier Access,
2127 TypeSourceInfo *TInfo,
2128 SourceLocation EllipsisLoc) {
2129 QualType BaseType = TInfo->getType();
2130
2131 // C++ [class.union]p1:
2132 // A union shall not have base classes.
2133 if (Class->isUnion()) {
2134 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2135 << SpecifierRange;
2136 return nullptr;
2137 }
2138
2139 if (EllipsisLoc.isValid() &&
2140 !TInfo->getType()->containsUnexpandedParameterPack()) {
2141 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2142 << TInfo->getTypeLoc().getSourceRange();
2143 EllipsisLoc = SourceLocation();
2144 }
2145
2146 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2147
2148 if (BaseType->isDependentType()) {
2149 // Make sure that we don't have circular inheritance among our dependent
2150 // bases. For non-dependent bases, the check for completeness below handles
2151 // this.
2152 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2153 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2154 ((BaseDecl = BaseDecl->getDefinition()) &&
2155 findCircularInheritance(Class, BaseDecl))) {
2156 Diag(BaseLoc, diag::err_circular_inheritance)
2157 << BaseType << Context.getTypeDeclType(Class);
2158
2159 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2160 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2161 << BaseType;
2162
2163 return nullptr;
2164 }
2165 }
2166
2167 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2168 Class->getTagKind() == TTK_Class,
2169 Access, TInfo, EllipsisLoc);
2170 }
2171
2172 // Base specifiers must be record types.
2173 if (!BaseType->isRecordType()) {
2174 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2175 return nullptr;
2176 }
2177
2178 // C++ [class.union]p1:
2179 // A union shall not be used as a base class.
2180 if (BaseType->isUnionType()) {
2181 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2182 return nullptr;
2183 }
2184
2185 // For the MS ABI, propagate DLL attributes to base class templates.
2186 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2187 if (Attr *ClassAttr = getDLLAttr(Class)) {
2188 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2189 BaseType->getAsCXXRecordDecl())) {
2190 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2191 BaseLoc);
2192 }
2193 }
2194 }
2195
2196 // C++ [class.derived]p2:
2197 // The class-name in a base-specifier shall not be an incompletely
2198 // defined class.
2199 if (RequireCompleteType(BaseLoc, BaseType,
2200 diag::err_incomplete_base_class, SpecifierRange)) {
2201 Class->setInvalidDecl();
2202 return nullptr;
2203 }
2204
2205 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2206 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2207 assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast
<void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2207, __PRETTY_FUNCTION__))
;
2208 BaseDecl = BaseDecl->getDefinition();
2209 assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition"
) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2209, __PRETTY_FUNCTION__))
;
2210 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2211 assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast
<void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2211, __PRETTY_FUNCTION__))
;
2212
2213 // A class which contains a flexible array member is not suitable for use as a
2214 // base class:
2215 // - If the layout determines that a base comes before another base,
2216 // the flexible array member would index into the subsequent base.
2217 // - If the layout determines that base comes before the derived class,
2218 // the flexible array member would index into the derived class.
2219 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2220 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2221 << CXXBaseDecl->getDeclName();
2222 return nullptr;
2223 }
2224
2225 // C++ [class]p3:
2226 // If a class is marked final and it appears as a base-type-specifier in
2227 // base-clause, the program is ill-formed.
2228 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2229 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2230 << CXXBaseDecl->getDeclName()
2231 << FA->isSpelledAsSealed();
2232 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2233 << CXXBaseDecl->getDeclName() << FA->getRange();
2234 return nullptr;
2235 }
2236
2237 if (BaseDecl->isInvalidDecl())
2238 Class->setInvalidDecl();
2239
2240 // Create the base specifier.
2241 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2242 Class->getTagKind() == TTK_Class,
2243 Access, TInfo, EllipsisLoc);
2244}
2245
2246/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2247/// one entry in the base class list of a class specifier, for
2248/// example:
2249/// class foo : public bar, virtual private baz {
2250/// 'public bar' and 'virtual private baz' are each base-specifiers.
2251BaseResult
2252Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2253 ParsedAttributes &Attributes,
2254 bool Virtual, AccessSpecifier Access,
2255 ParsedType basetype, SourceLocation BaseLoc,
2256 SourceLocation EllipsisLoc) {
2257 if (!classdecl)
2258 return true;
2259
2260 AdjustDeclIfTemplate(classdecl);
2261 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2262 if (!Class)
2263 return true;
2264
2265 // We haven't yet attached the base specifiers.
2266 Class->setIsParsingBaseSpecifiers();
2267
2268 // We do not support any C++11 attributes on base-specifiers yet.
2269 // Diagnose any attributes we see.
2270 if (!Attributes.empty()) {
2271 for (AttributeList *Attr = Attributes.getList(); Attr;
2272 Attr = Attr->getNext()) {
2273 if (Attr->isInvalid() ||
2274 Attr->getKind() == AttributeList::IgnoredAttribute)
2275 continue;
2276 Diag(Attr->getLoc(),
2277 Attr->getKind() == AttributeList::UnknownAttribute
2278 ? diag::warn_unknown_attribute_ignored
2279 : diag::err_base_specifier_attribute)
2280 << Attr->getName();
2281 }
2282 }
2283
2284 TypeSourceInfo *TInfo = nullptr;
2285 GetTypeFromParser(basetype, &TInfo);
2286
2287 if (EllipsisLoc.isInvalid() &&
2288 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2289 UPPC_BaseType))
2290 return true;
2291
2292 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2293 Virtual, Access, TInfo,
2294 EllipsisLoc))
2295 return BaseSpec;
2296 else
2297 Class->setInvalidDecl();
2298
2299 return true;
2300}
2301
2302/// Use small set to collect indirect bases. As this is only used
2303/// locally, there's no need to abstract the small size parameter.
2304typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2305
2306/// \brief Recursively add the bases of Type. Don't add Type itself.
2307static void
2308NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2309 const QualType &Type)
2310{
2311 // Even though the incoming type is a base, it might not be
2312 // a class -- it could be a template parm, for instance.
2313 if (auto Rec = Type->getAs<RecordType>()) {
2314 auto Decl = Rec->getAsCXXRecordDecl();
2315
2316 // Iterate over its bases.
2317 for (const auto &BaseSpec : Decl->bases()) {
2318 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2319 .getUnqualifiedType();
2320 if (Set.insert(Base).second)
2321 // If we've not already seen it, recurse.
2322 NoteIndirectBases(Context, Set, Base);
2323 }
2324 }
2325}
2326
2327/// \brief Performs the actual work of attaching the given base class
2328/// specifiers to a C++ class.
2329bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2330 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2331 if (Bases.empty())
2332 return false;
2333
2334 // Used to keep track of which base types we have already seen, so
2335 // that we can properly diagnose redundant direct base types. Note
2336 // that the key is always the unqualified canonical type of the base
2337 // class.
2338 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2339
2340 // Used to track indirect bases so we can see if a direct base is
2341 // ambiguous.
2342 IndirectBaseSet IndirectBaseTypes;
2343
2344 // Copy non-redundant base specifiers into permanent storage.
2345 unsigned NumGoodBases = 0;
2346 bool Invalid = false;
2347 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2348 QualType NewBaseType
2349 = Context.getCanonicalType(Bases[idx]->getType());
2350 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2351
2352 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2353 if (KnownBase) {
2354 // C++ [class.mi]p3:
2355 // A class shall not be specified as a direct base class of a
2356 // derived class more than once.
2357 Diag(Bases[idx]->getLocStart(),
2358 diag::err_duplicate_base_class)
2359 << KnownBase->getType()
2360 << Bases[idx]->getSourceRange();
2361
2362 // Delete the duplicate base class specifier; we're going to
2363 // overwrite its pointer later.
2364 Context.Deallocate(Bases[idx]);
2365
2366 Invalid = true;
2367 } else {
2368 // Okay, add this new base class.
2369 KnownBase = Bases[idx];
2370 Bases[NumGoodBases++] = Bases[idx];
2371
2372 // Note this base's direct & indirect bases, if there could be ambiguity.
2373 if (Bases.size() > 1)
2374 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2375
2376 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2377 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2378 if (Class->isInterface() &&
2379 (!RD->isInterface() ||
2380 KnownBase->getAccessSpecifier() != AS_public)) {
2381 // The Microsoft extension __interface does not permit bases that
2382 // are not themselves public interfaces.
2383 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2384 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2385 << RD->getSourceRange();
2386 Invalid = true;
2387 }
2388 if (RD->hasAttr<WeakAttr>())
2389 Class->addAttr(WeakAttr::CreateImplicit(Context));
2390 }
2391 }
2392 }
2393
2394 // Attach the remaining base class specifiers to the derived class.
2395 Class->setBases(Bases.data(), NumGoodBases);
2396
2397 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2398 // Check whether this direct base is inaccessible due to ambiguity.
2399 QualType BaseType = Bases[idx]->getType();
2400 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2401 .getUnqualifiedType();
2402
2403 if (IndirectBaseTypes.count(CanonicalBase)) {
2404 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2405 /*DetectVirtual=*/true);
2406 bool found
2407 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2408 assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2408, __PRETTY_FUNCTION__))
;
2409 (void)found;
2410
2411 if (Paths.isAmbiguous(CanonicalBase))
2412 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2413 << BaseType << getAmbiguousPathsDisplayString(Paths)
2414 << Bases[idx]->getSourceRange();
2415 else
2416 assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) :
__assert_fail ("Bases[idx]->isVirtual()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2416, __PRETTY_FUNCTION__))
;
2417 }
2418
2419 // Delete the base class specifier, since its data has been copied
2420 // into the CXXRecordDecl.
2421 Context.Deallocate(Bases[idx]);
2422 }
2423
2424 return Invalid;
2425}
2426
2427/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2428/// class, after checking whether there are any duplicate base
2429/// classes.
2430void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2431 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2432 if (!ClassDecl || Bases.empty())
2433 return;
2434
2435 AdjustDeclIfTemplate(ClassDecl);
2436 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2437}
2438
2439/// \brief Determine whether the type \p Derived is a C++ class that is
2440/// derived from the type \p Base.
2441bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2442 if (!getLangOpts().CPlusPlus)
2443 return false;
2444
2445 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2446 if (!DerivedRD)
2447 return false;
2448
2449 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2450 if (!BaseRD)
2451 return false;
2452
2453 // If either the base or the derived type is invalid, don't try to
2454 // check whether one is derived from the other.
2455 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2456 return false;
2457
2458 // FIXME: In a modules build, do we need the entire path to be visible for us
2459 // to be able to use the inheritance relationship?
2460 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2461 return false;
2462
2463 return DerivedRD->isDerivedFrom(BaseRD);
2464}
2465
2466/// \brief Determine whether the type \p Derived is a C++ class that is
2467/// derived from the type \p Base.
2468bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2469 CXXBasePaths &Paths) {
2470 if (!getLangOpts().CPlusPlus)
2471 return false;
2472
2473 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2474 if (!DerivedRD)
2475 return false;
2476
2477 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2478 if (!BaseRD)
2479 return false;
2480
2481 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2482 return false;
2483
2484 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2485}
2486
2487void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2488 CXXCastPath &BasePathArray) {
2489 assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!"
) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2489, __PRETTY_FUNCTION__))
;
2490 assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ?
static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2490, __PRETTY_FUNCTION__))
;
2491
2492 const CXXBasePath &Path = Paths.front();
2493
2494 // We first go backward and check if we have a virtual base.
2495 // FIXME: It would be better if CXXBasePath had the base specifier for
2496 // the nearest virtual base.
2497 unsigned Start = 0;
2498 for (unsigned I = Path.size(); I != 0; --I) {
2499 if (Path[I - 1].Base->isVirtual()) {
2500 Start = I - 1;
2501 break;
2502 }
2503 }
2504
2505 // Now add all bases.
2506 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2507 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2508}
2509
2510/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2511/// conversion (where Derived and Base are class types) is
2512/// well-formed, meaning that the conversion is unambiguous (and
2513/// that all of the base classes are accessible). Returns true
2514/// and emits a diagnostic if the code is ill-formed, returns false
2515/// otherwise. Loc is the location where this routine should point to
2516/// if there is an error, and Range is the source range to highlight
2517/// if there is an error.
2518///
2519/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2520/// diagnostic for the respective type of error will be suppressed, but the
2521/// check for ill-formed code will still be performed.
2522bool
2523Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2524 unsigned InaccessibleBaseID,
2525 unsigned AmbigiousBaseConvID,
2526 SourceLocation Loc, SourceRange Range,
2527 DeclarationName Name,
2528 CXXCastPath *BasePath,
2529 bool IgnoreAccess) {
2530 // First, determine whether the path from Derived to Base is
2531 // ambiguous. This is slightly more expensive than checking whether
2532 // the Derived to Base conversion exists, because here we need to
2533 // explore multiple paths to determine if there is an ambiguity.
2534 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2535 /*DetectVirtual=*/false);
2536 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2537 assert(DerivationOkay &&((DerivationOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Can only be used with a derived-to-base conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2538, __PRETTY_FUNCTION__))
2538 "Can only be used with a derived-to-base conversion")((DerivationOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Can only be used with a derived-to-base conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2538, __PRETTY_FUNCTION__))
;
2539 (void)DerivationOkay;
2540
2541 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2542 if (!IgnoreAccess) {
2543 // Check that the base class can be accessed.
2544 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2545 InaccessibleBaseID)) {
2546 case AR_inaccessible:
2547 return true;
2548 case AR_accessible:
2549 case AR_dependent:
2550 case AR_delayed:
2551 break;
2552 }
2553 }
2554
2555 // Build a base path if necessary.
2556 if (BasePath)
2557 BuildBasePathArray(Paths, *BasePath);
2558 return false;
2559 }
2560
2561 if (AmbigiousBaseConvID) {
2562 // We know that the derived-to-base conversion is ambiguous, and
2563 // we're going to produce a diagnostic. Perform the derived-to-base
2564 // search just one more time to compute all of the possible paths so
2565 // that we can print them out. This is more expensive than any of
2566 // the previous derived-to-base checks we've done, but at this point
2567 // performance isn't as much of an issue.
2568 Paths.clear();
2569 Paths.setRecordingPaths(true);
2570 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2571 assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2571, __PRETTY_FUNCTION__))
;
2572 (void)StillOkay;
2573
2574 // Build up a textual representation of the ambiguous paths, e.g.,
2575 // D -> B -> A, that will be used to illustrate the ambiguous
2576 // conversions in the diagnostic. We only print one of the paths
2577 // to each base class subobject.
2578 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2579
2580 Diag(Loc, AmbigiousBaseConvID)
2581 << Derived << Base << PathDisplayStr << Range << Name;
2582 }
2583 return true;
2584}
2585
2586bool
2587Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2588 SourceLocation Loc, SourceRange Range,
2589 CXXCastPath *BasePath,
2590 bool IgnoreAccess) {
2591 return CheckDerivedToBaseConversion(
2592 Derived, Base, diag::err_upcast_to_inaccessible_base,
2593 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2594 BasePath, IgnoreAccess);
2595}
2596
2597
2598/// @brief Builds a string representing ambiguous paths from a
2599/// specific derived class to different subobjects of the same base
2600/// class.
2601///
2602/// This function builds a string that can be used in error messages
2603/// to show the different paths that one can take through the
2604/// inheritance hierarchy to go from the derived class to different
2605/// subobjects of a base class. The result looks something like this:
2606/// @code
2607/// struct D -> struct B -> struct A
2608/// struct D -> struct C -> struct A
2609/// @endcode
2610std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2611 std::string PathDisplayStr;
2612 std::set<unsigned> DisplayedPaths;
2613 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2614 Path != Paths.end(); ++Path) {
2615 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2616 // We haven't displayed a path to this particular base
2617 // class subobject yet.
2618 PathDisplayStr += "\n ";
2619 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2620 for (CXXBasePath::const_iterator Element = Path->begin();
2621 Element != Path->end(); ++Element)
2622 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2623 }
2624 }
2625
2626 return PathDisplayStr;
2627}
2628
2629//===----------------------------------------------------------------------===//
2630// C++ class member Handling
2631//===----------------------------------------------------------------------===//
2632
2633/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2634bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2635 SourceLocation ASLoc,
2636 SourceLocation ColonLoc,
2637 AttributeList *Attrs) {
2638 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2638, __PRETTY_FUNCTION__))
;
2639 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2640 ASLoc, ColonLoc);
2641 CurContext->addHiddenDecl(ASDecl);
2642 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2643}
2644
2645/// CheckOverrideControl - Check C++11 override control semantics.
2646void Sema::CheckOverrideControl(NamedDecl *D) {
2647 if (D->isInvalidDecl())
2648 return;
2649
2650 // We only care about "override" and "final" declarations.
2651 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2652 return;
2653
2654 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2655
2656 // We can't check dependent instance methods.
2657 if (MD && MD->isInstance() &&
2658 (MD->getParent()->hasAnyDependentBases() ||
2659 MD->getType()->isDependentType()))
2660 return;
2661
2662 if (MD && !MD->isVirtual()) {
2663 // If we have a non-virtual method, check if if hides a virtual method.
2664 // (In that case, it's most likely the method has the wrong type.)
2665 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2666 FindHiddenVirtualMethods(MD, OverloadedMethods);
2667
2668 if (!OverloadedMethods.empty()) {
2669 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2670 Diag(OA->getLocation(),
2671 diag::override_keyword_hides_virtual_member_function)
2672 << "override" << (OverloadedMethods.size() > 1);
2673 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2674 Diag(FA->getLocation(),
2675 diag::override_keyword_hides_virtual_member_function)
2676 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2677 << (OverloadedMethods.size() > 1);
2678 }
2679 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2680 MD->setInvalidDecl();
2681 return;
2682 }
2683 // Fall through into the general case diagnostic.
2684 // FIXME: We might want to attempt typo correction here.
2685 }
2686
2687 if (!MD || !MD->isVirtual()) {
2688 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2689 Diag(OA->getLocation(),
2690 diag::override_keyword_only_allowed_on_virtual_member_functions)
2691 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2692 D->dropAttr<OverrideAttr>();
2693 }
2694 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2695 Diag(FA->getLocation(),
2696 diag::override_keyword_only_allowed_on_virtual_member_functions)
2697 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2698 << FixItHint::CreateRemoval(FA->getLocation());
2699 D->dropAttr<FinalAttr>();
2700 }
2701 return;
2702 }
2703
2704 // C++11 [class.virtual]p5:
2705 // If a function is marked with the virt-specifier override and
2706 // does not override a member function of a base class, the program is
2707 // ill-formed.
2708 bool HasOverriddenMethods =
2709 MD->begin_overridden_methods() != MD->end_overridden_methods();
2710 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2711 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2712 << MD->getDeclName();
2713}
2714
2715void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2716 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2717 return;
2718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2719 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2720 isa<CXXDestructorDecl>(MD))
2721 return;
2722
2723 SourceLocation Loc = MD->getLocation();
2724 SourceLocation SpellingLoc = Loc;
2725 if (getSourceManager().isMacroArgExpansion(Loc))
2726 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2727 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2728 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2729 return;
2730
2731 if (MD->size_overridden_methods() > 0) {
2732 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2733 << MD->getDeclName();
2734 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2735 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2736 }
2737}
2738
2739/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2740/// function overrides a virtual member function marked 'final', according to
2741/// C++11 [class.virtual]p4.
2742bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2743 const CXXMethodDecl *Old) {
2744 FinalAttr *FA = Old->getAttr<FinalAttr>();
2745 if (!FA)
2746 return false;
2747
2748 Diag(New->getLocation(), diag::err_final_function_overridden)
2749 << New->getDeclName()
2750 << FA->isSpelledAsSealed();
2751 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2752 return true;
2753}
2754
2755static bool InitializationHasSideEffects(const FieldDecl &FD) {
2756 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2757 // FIXME: Destruction of ObjC lifetime types has side-effects.
2758 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2759 return !RD->isCompleteDefinition() ||
2760 !RD->hasTrivialDefaultConstructor() ||
2761 !RD->hasTrivialDestructor();
2762 return false;
2763}
2764
2765static AttributeList *getMSPropertyAttr(AttributeList *list) {
2766 for (AttributeList *it = list; it != nullptr; it = it->getNext())
2767 if (it->isDeclspecPropertyAttribute())
2768 return it;
2769 return nullptr;
2770}
2771
2772// Check if there is a field shadowing.
2773void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2774 DeclarationName FieldName,
2775 const CXXRecordDecl *RD) {
2776 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2777 return;
2778
2779 // To record a shadowed field in a base
2780 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2781 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2782 CXXBasePath &Path) {
2783 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2784 // Record an ambiguous path directly
2785 if (Bases.find(Base) != Bases.end())
2786 return true;
2787 for (const auto Field : Base->lookup(FieldName)) {
2788 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2789 Field->getAccess() != AS_private) {
2790 assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void>
(0) : __assert_fail ("Field->getAccess() != AS_none", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2790, __PRETTY_FUNCTION__))
;
2791 assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> (
0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2791, __PRETTY_FUNCTION__))
;
2792 Bases[Base] = Field;
2793 return true;
2794 }
2795 }
2796 return false;
2797 };
2798
2799 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2800 /*DetectVirtual=*/true);
2801 if (!RD->lookupInBases(FieldShadowed, Paths))
2802 return;
2803
2804 for (const auto &P : Paths) {
2805 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2806 auto It = Bases.find(Base);
2807 // Skip duplicated bases
2808 if (It == Bases.end())
2809 continue;
2810 auto BaseField = It->second;
2811 assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void
> (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2811, __PRETTY_FUNCTION__))
;
2812 if (AS_none !=
2813 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2814 Diag(Loc, diag::warn_shadow_field)
2815 << FieldName.getAsString() << RD->getName() << Base->getName();
2816 Diag(BaseField->getLocation(), diag::note_shadow_field);
2817 Bases.erase(It);
2818 }
2819 }
2820}
2821
2822/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2823/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2824/// bitfield width if there is one, 'InitExpr' specifies the initializer if
2825/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2826/// present (but parsing it has been deferred).
2827NamedDecl *
2828Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2829 MultiTemplateParamsArg TemplateParameterLists,
2830 Expr *BW, const VirtSpecifiers &VS,
2831 InClassInitStyle InitStyle) {
2832 const DeclSpec &DS = D.getDeclSpec();
2833 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2834 DeclarationName Name = NameInfo.getName();
2835 SourceLocation Loc = NameInfo.getLoc();
2836
2837 // For anonymous bitfields, the location should point to the type.
2838 if (Loc.isInvalid())
2839 Loc = D.getLocStart();
2840
2841 Expr *BitWidth = static_cast<Expr*>(BW);
2842
2843 assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void
> (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2843, __PRETTY_FUNCTION__))
;
2844 assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("!DS.isFriendSpecified()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2844, __PRETTY_FUNCTION__))
;
2845
2846 bool isFunc = D.isDeclarationOfFunction();
2847
2848 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2849 // The Microsoft extension __interface only permits public member functions
2850 // and prohibits constructors, destructors, operators, non-public member
2851 // functions, static methods and data members.
2852 unsigned InvalidDecl;
2853 bool ShowDeclName = true;
2854 if (!isFunc)
2855 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2856 else if (AS != AS_public)
2857 InvalidDecl = 2;
2858 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2859 InvalidDecl = 3;
2860 else switch (Name.getNameKind()) {
2861 case DeclarationName::CXXConstructorName:
2862 InvalidDecl = 4;
2863 ShowDeclName = false;
2864 break;
2865
2866 case DeclarationName::CXXDestructorName:
2867 InvalidDecl = 5;
2868 ShowDeclName = false;
2869 break;
2870
2871 case DeclarationName::CXXOperatorName:
2872 case DeclarationName::CXXConversionFunctionName:
2873 InvalidDecl = 6;
2874 break;
2875
2876 default:
2877 InvalidDecl = 0;
2878 break;
2879 }
2880
2881 if (InvalidDecl) {
2882 if (ShowDeclName)
2883 Diag(Loc, diag::err_invalid_member_in_interface)
2884 << (InvalidDecl-1) << Name;
2885 else
2886 Diag(Loc, diag::err_invalid_member_in_interface)
2887 << (InvalidDecl-1) << "";
2888 return nullptr;
2889 }
2890 }
2891
2892 // C++ 9.2p6: A member shall not be declared to have automatic storage
2893 // duration (auto, register) or with the extern storage-class-specifier.
2894 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2895 // data members and cannot be applied to names declared const or static,
2896 // and cannot be applied to reference members.
2897 switch (DS.getStorageClassSpec()) {
2898 case DeclSpec::SCS_unspecified:
2899 case DeclSpec::SCS_typedef:
2900 case DeclSpec::SCS_static:
2901 break;
2902 case DeclSpec::SCS_mutable:
2903 if (isFunc) {
2904 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2905
2906 // FIXME: It would be nicer if the keyword was ignored only for this
2907 // declarator. Otherwise we could get follow-up errors.
2908 D.getMutableDeclSpec().ClearStorageClassSpecs();
2909 }
2910 break;
2911 default:
2912 Diag(DS.getStorageClassSpecLoc(),
2913 diag::err_storageclass_invalid_for_member);
2914 D.getMutableDeclSpec().ClearStorageClassSpecs();
2915 break;
2916 }
2917
2918 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2919 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2920 !isFunc);
2921
2922 if (DS.isConstexprSpecified() && isInstField) {
2923 SemaDiagnosticBuilder B =
2924 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2925 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2926 if (InitStyle == ICIS_NoInit) {
2927 B << 0 << 0;
2928 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2929 B << FixItHint::CreateRemoval(ConstexprLoc);
2930 else {
2931 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2932 D.getMutableDeclSpec().ClearConstexprSpec();
2933 const char *PrevSpec;
2934 unsigned DiagID;
2935 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2936 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2937 (void)Failed;
2938 assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail"
) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2938, __PRETTY_FUNCTION__))
;
2939 }
2940 } else {
2941 B << 1;
2942 const char *PrevSpec;
2943 unsigned DiagID;
2944 if (D.getMutableDeclSpec().SetStorageClassSpec(
2945 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2946 Context.getPrintingPolicy())) {
2947 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2948, __PRETTY_FUNCTION__))
2948 "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2948, __PRETTY_FUNCTION__))
;
2949 B << 1;
2950 } else {
2951 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2952 isInstField = false;
2953 }
2954 }
2955 }
2956
2957 NamedDecl *Member;
2958 if (isInstField) {
2959 CXXScopeSpec &SS = D.getCXXScopeSpec();
2960
2961 // Data members must have identifiers for names.
2962 if (!Name.isIdentifier()) {
2963 Diag(Loc, diag::err_bad_variable_name)
2964 << Name;
2965 return nullptr;
2966 }
2967
2968 IdentifierInfo *II = Name.getAsIdentifierInfo();
2969
2970 // Member field could not be with "template" keyword.
2971 // So TemplateParameterLists should be empty in this case.
2972 if (TemplateParameterLists.size()) {
2973 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2974 if (TemplateParams->size()) {
2975 // There is no such thing as a member field template.
2976 Diag(D.getIdentifierLoc(), diag::err_template_member)
2977 << II
2978 << SourceRange(TemplateParams->getTemplateLoc(),
2979 TemplateParams->getRAngleLoc());
2980 } else {
2981 // There is an extraneous 'template<>' for this member.
2982 Diag(TemplateParams->getTemplateLoc(),
2983 diag::err_template_member_noparams)
2984 << II
2985 << SourceRange(TemplateParams->getTemplateLoc(),
2986 TemplateParams->getRAngleLoc());
2987 }
2988 return nullptr;
2989 }
2990
2991 if (SS.isSet() && !SS.isInvalid()) {
2992 // The user provided a superfluous scope specifier inside a class
2993 // definition:
2994 //
2995 // class X {
2996 // int X::member;
2997 // };
2998 if (DeclContext *DC = computeDeclContext(SS, false))
2999 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
3000 else
3001 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3002 << Name << SS.getRange();
3003
3004 SS.clear();
3005 }
3006
3007 AttributeList *MSPropertyAttr =
3008 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
3009 if (MSPropertyAttr) {
3010 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3011 BitWidth, InitStyle, AS, MSPropertyAttr);
3012 if (!Member)
3013 return nullptr;
3014 isInstField = false;
3015 } else {
3016 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3017 BitWidth, InitStyle, AS);
3018 if (!Member)
3019 return nullptr;
3020 }
3021
3022 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3023 } else {
3024 Member = HandleDeclarator(S, D, TemplateParameterLists);
3025 if (!Member)
3026 return nullptr;
3027
3028 // Non-instance-fields can't have a bitfield.
3029 if (BitWidth) {
3030 if (Member->isInvalidDecl()) {
3031 // don't emit another diagnostic.
3032 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3033 // C++ 9.6p3: A bit-field shall not be a static member.
3034 // "static member 'A' cannot be a bit-field"
3035 Diag(Loc, diag::err_static_not_bitfield)
3036 << Name << BitWidth->getSourceRange();
3037 } else if (isa<TypedefDecl>(Member)) {
3038 // "typedef member 'x' cannot be a bit-field"
3039 Diag(Loc, diag::err_typedef_not_bitfield)
3040 << Name << BitWidth->getSourceRange();
3041 } else {
3042 // A function typedef ("typedef int f(); f a;").
3043 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3044 Diag(Loc, diag::err_not_integral_type_bitfield)
3045 << Name << cast<ValueDecl>(Member)->getType()
3046 << BitWidth->getSourceRange();
3047 }
3048
3049 BitWidth = nullptr;
3050 Member->setInvalidDecl();
3051 }
3052
3053 Member->setAccess(AS);
3054
3055 // If we have declared a member function template or static data member
3056 // template, set the access of the templated declaration as well.
3057 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3058 FunTmpl->getTemplatedDecl()->setAccess(AS);
3059 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3060 VarTmpl->getTemplatedDecl()->setAccess(AS);
3061 }
3062
3063 if (VS.isOverrideSpecified())
3064 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3065 if (VS.isFinalSpecified())
3066 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3067 VS.isFinalSpelledSealed()));
3068
3069 if (VS.getLastLocation().isValid()) {
3070 // Update the end location of a method that has a virt-specifiers.
3071 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3072 MD->setRangeEnd(VS.getLastLocation());
3073 }
3074
3075 CheckOverrideControl(Member);
3076
3077 assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?"
) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3077, __PRETTY_FUNCTION__))
;
3078
3079 if (isInstField) {
3080 FieldDecl *FD = cast<FieldDecl>(Member);
3081 FieldCollector->Add(FD);
3082
3083 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3084 // Remember all explicit private FieldDecls that have a name, no side
3085 // effects and are not part of a dependent type declaration.
3086 if (!FD->isImplicit() && FD->getDeclName() &&
3087 FD->getAccess() == AS_private &&
3088 !FD->hasAttr<UnusedAttr>() &&
3089 !FD->getParent()->isDependentContext() &&
3090 !InitializationHasSideEffects(*FD))
3091 UnusedPrivateFields.insert(FD);
3092 }
3093 }
3094
3095 return Member;
3096}
3097
3098namespace {
3099 class UninitializedFieldVisitor
3100 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3101 Sema &S;
3102 // List of Decls to generate a warning on. Also remove Decls that become
3103 // initialized.
3104 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3105 // List of base classes of the record. Classes are removed after their
3106 // initializers.
3107 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3108 // Vector of decls to be removed from the Decl set prior to visiting the
3109 // nodes. These Decls may have been initialized in the prior initializer.
3110 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3111 // If non-null, add a note to the warning pointing back to the constructor.
3112 const CXXConstructorDecl *Constructor;
3113 // Variables to hold state when processing an initializer list. When
3114 // InitList is true, special case initialization of FieldDecls matching
3115 // InitListFieldDecl.
3116 bool InitList;
3117 FieldDecl *InitListFieldDecl;
3118 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3119
3120 public:
3121 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3122 UninitializedFieldVisitor(Sema &S,
3123 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3124 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3125 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3126 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3127
3128 // Returns true if the use of ME is not an uninitialized use.
3129 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3130 bool CheckReferenceOnly) {
3131 llvm::SmallVector<FieldDecl*, 4> Fields;
3132 bool ReferenceField = false;
3133 while (ME) {
3134 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3135 if (!FD)
3136 return false;
3137 Fields.push_back(FD);
3138 if (FD->getType()->isReferenceType())
3139 ReferenceField = true;
3140 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3141 }
3142
3143 // Binding a reference to an unintialized field is not an
3144 // uninitialized use.
3145 if (CheckReferenceOnly && !ReferenceField)
3146 return true;
3147
3148 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3149 // Discard the first field since it is the field decl that is being
3150 // initialized.
3151 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3152 UsedFieldIndex.push_back((*I)->getFieldIndex());
3153 }
3154
3155 for (auto UsedIter = UsedFieldIndex.begin(),
3156 UsedEnd = UsedFieldIndex.end(),
3157 OrigIter = InitFieldIndex.begin(),
3158 OrigEnd = InitFieldIndex.end();
3159 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3160 if (*UsedIter < *OrigIter)
3161 return true;
3162 if (*UsedIter > *OrigIter)
3163 break;
3164 }
3165
3166 return false;
3167 }
3168
3169 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3170 bool AddressOf) {
3171 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3172 return;
3173
3174 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3175 // or union.
3176 MemberExpr *FieldME = ME;
3177
3178 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3179
3180 Expr *Base = ME;
3181 while (MemberExpr *SubME =
3182 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3183
3184 if (isa<VarDecl>(SubME->getMemberDecl()))
3185 return;
3186
3187 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3188 if (!FD->isAnonymousStructOrUnion())
3189 FieldME = SubME;
3190
3191 if (!FieldME->getType().isPODType(S.Context))
3192 AllPODFields = false;
3193
3194 Base = SubME->getBase();
3195 }
3196
3197 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3198 return;
3199
3200 if (AddressOf && AllPODFields)
3201 return;
3202
3203 ValueDecl* FoundVD = FieldME->getMemberDecl();
3204
3205 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3206 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3207 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3208 }
3209
3210 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3211 QualType T = BaseCast->getType();
3212 if (T->isPointerType() &&
3213 BaseClasses.count(T->getPointeeType())) {
3214 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3215 << T->getPointeeType() << FoundVD;
3216 }
3217 }
3218 }
3219
3220 if (!Decls.count(FoundVD))
3221 return;
3222
3223 const bool IsReference = FoundVD->getType()->isReferenceType();
3224
3225 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3226 // Special checking for initializer lists.
3227 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3228 return;
3229 }
3230 } else {
3231 // Prevent double warnings on use of unbounded references.
3232 if (CheckReferenceOnly && !IsReference)
3233 return;
3234 }
3235
3236 unsigned diag = IsReference
3237 ? diag::warn_reference_field_is_uninit
3238 : diag::warn_field_is_uninit;
3239 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3240 if (Constructor)
3241 S.Diag(Constructor->getLocation(),
3242 diag::note_uninit_in_this_constructor)
3243 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3244
3245 }
3246
3247 void HandleValue(Expr *E, bool AddressOf) {
3248 E = E->IgnoreParens();
3249
3250 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3251 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3252 AddressOf /*AddressOf*/);
3253 return;
3254 }
3255
3256 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3257 Visit(CO->getCond());
3258 HandleValue(CO->getTrueExpr(), AddressOf);
3259 HandleValue(CO->getFalseExpr(), AddressOf);
3260 return;
3261 }
3262
3263 if (BinaryConditionalOperator *BCO =
3264 dyn_cast<BinaryConditionalOperator>(E)) {
3265 Visit(BCO->getCond());
3266 HandleValue(BCO->getFalseExpr(), AddressOf);
3267 return;
3268 }
3269
3270 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3271 HandleValue(OVE->getSourceExpr(), AddressOf);
3272 return;
3273 }
3274
3275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3276 switch (BO->getOpcode()) {
3277 default:
3278 break;
3279 case(BO_PtrMemD):
3280 case(BO_PtrMemI):
3281 HandleValue(BO->getLHS(), AddressOf);
3282 Visit(BO->getRHS());
3283 return;
3284 case(BO_Comma):
3285 Visit(BO->getLHS());
3286 HandleValue(BO->getRHS(), AddressOf);
3287 return;
3288 }
3289 }
3290
3291 Visit(E);
3292 }
3293
3294 void CheckInitListExpr(InitListExpr *ILE) {
3295 InitFieldIndex.push_back(0);
3296 for (auto Child : ILE->children()) {
3297 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3298 CheckInitListExpr(SubList);
3299 } else {
3300 Visit(Child);
3301 }
3302 ++InitFieldIndex.back();
3303 }
3304 InitFieldIndex.pop_back();
3305 }
3306
3307 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3308 FieldDecl *Field, const Type *BaseClass) {
3309 // Remove Decls that may have been initialized in the previous
3310 // initializer.
3311 for (ValueDecl* VD : DeclsToRemove)
3312 Decls.erase(VD);
3313 DeclsToRemove.clear();
3314
3315 Constructor = FieldConstructor;
3316 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3317
3318 if (ILE && Field) {
3319 InitList = true;
3320 InitListFieldDecl = Field;
3321 InitFieldIndex.clear();
3322 CheckInitListExpr(ILE);
3323 } else {
3324 InitList = false;
3325 Visit(E);
3326 }
3327
3328 if (Field)
3329 Decls.erase(Field);
3330 if (BaseClass)
3331 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3332 }
3333
3334 void VisitMemberExpr(MemberExpr *ME) {
3335 // All uses of unbounded reference fields will warn.
3336 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3337 }
3338
3339 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3340 if (E->getCastKind() == CK_LValueToRValue) {
3341 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3342 return;
3343 }
3344
3345 Inherited::VisitImplicitCastExpr(E);
3346 }
3347
3348 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3349 if (E->getConstructor()->isCopyConstructor()) {
3350 Expr *ArgExpr = E->getArg(0);
3351 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3352 if (ILE->getNumInits() == 1)
3353 ArgExpr = ILE->getInit(0);
3354 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3355 if (ICE->getCastKind() == CK_NoOp)
3356 ArgExpr = ICE->getSubExpr();
3357 HandleValue(ArgExpr, false /*AddressOf*/);
3358 return;
3359 }
3360 Inherited::VisitCXXConstructExpr(E);
3361 }
3362
3363 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3364 Expr *Callee = E->getCallee();
3365 if (isa<MemberExpr>(Callee)) {
3366 HandleValue(Callee, false /*AddressOf*/);
3367 for (auto Arg : E->arguments())
3368 Visit(Arg);
3369 return;
3370 }
3371
3372 Inherited::VisitCXXMemberCallExpr(E);
3373 }
3374
3375 void VisitCallExpr(CallExpr *E) {
3376 // Treat std::move as a use.
3377 if (E->getNumArgs() == 1) {
3378 if (FunctionDecl *FD = E->getDirectCallee()) {
3379 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3380 FD->getIdentifier()->isStr("move")) {
3381 HandleValue(E->getArg(0), false /*AddressOf*/);
3382 return;
3383 }
3384 }
3385 }
3386
3387 Inherited::VisitCallExpr(E);
3388 }
3389
3390 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3391 Expr *Callee = E->getCallee();
3392
3393 if (isa<UnresolvedLookupExpr>(Callee))
3394 return Inherited::VisitCXXOperatorCallExpr(E);
3395
3396 Visit(Callee);
3397 for (auto Arg : E->arguments())
3398 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3399 }
3400
3401 void VisitBinaryOperator(BinaryOperator *E) {
3402 // If a field assignment is detected, remove the field from the
3403 // uninitiailized field set.
3404 if (E->getOpcode() == BO_Assign)
3405 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3406 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3407 if (!FD->getType()->isReferenceType())
3408 DeclsToRemove.push_back(FD);
3409
3410 if (E->isCompoundAssignmentOp()) {
3411 HandleValue(E->getLHS(), false /*AddressOf*/);
3412 Visit(E->getRHS());
3413 return;
3414 }
3415
3416 Inherited::VisitBinaryOperator(E);
3417 }
3418
3419 void VisitUnaryOperator(UnaryOperator *E) {
3420 if (E->isIncrementDecrementOp()) {
3421 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3422 return;
3423 }
3424 if (E->getOpcode() == UO_AddrOf) {
3425 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3426 HandleValue(ME->getBase(), true /*AddressOf*/);
3427 return;
3428 }
3429 }
3430
3431 Inherited::VisitUnaryOperator(E);
3432 }
3433 };
3434
3435 // Diagnose value-uses of fields to initialize themselves, e.g.
3436 // foo(foo)
3437 // where foo is not also a parameter to the constructor.
3438 // Also diagnose across field uninitialized use such as
3439 // x(y), y(x)
3440 // TODO: implement -Wuninitialized and fold this into that framework.
3441 static void DiagnoseUninitializedFields(
3442 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3443
3444 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3445 Constructor->getLocation())) {
3446 return;
3447 }
3448
3449 if (Constructor->isInvalidDecl())
3450 return;
3451
3452 const CXXRecordDecl *RD = Constructor->getParent();
3453
3454 if (RD->getDescribedClassTemplate())
3455 return;
3456
3457 // Holds fields that are uninitialized.
3458 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3459
3460 // At the beginning, all fields are uninitialized.
3461 for (auto *I : RD->decls()) {
3462 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3463 UninitializedFields.insert(FD);
3464 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3465 UninitializedFields.insert(IFD->getAnonField());
3466 }
3467 }
3468
3469 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3470 for (auto I : RD->bases())
3471 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3472
3473 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3474 return;
3475
3476 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3477 UninitializedFields,
3478 UninitializedBaseClasses);
3479
3480 for (const auto *FieldInit : Constructor->inits()) {
3481 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3482 break;
3483
3484 Expr *InitExpr = FieldInit->getInit();
3485 if (!InitExpr)
3486 continue;
3487
3488 if (CXXDefaultInitExpr *Default =
3489 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3490 InitExpr = Default->getExpr();
3491 if (!InitExpr)
3492 continue;
3493 // In class initializers will point to the constructor.
3494 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3495 FieldInit->getAnyMember(),
3496 FieldInit->getBaseClass());
3497 } else {
3498 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3499 FieldInit->getAnyMember(),
3500 FieldInit->getBaseClass());
3501 }
3502 }
3503 }
3504} // namespace
3505
3506/// \brief Enter a new C++ default initializer scope. After calling this, the
3507/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3508/// parsing or instantiating the initializer failed.
3509void Sema::ActOnStartCXXInClassMemberInitializer() {
3510 // Create a synthetic function scope to represent the call to the constructor
3511 // that notionally surrounds a use of this initializer.
3512 PushFunctionScope();
3513}
3514
3515/// \brief This is invoked after parsing an in-class initializer for a
3516/// non-static C++ class member, and after instantiating an in-class initializer
3517/// in a class template. Such actions are deferred until the class is complete.
3518void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3519 SourceLocation InitLoc,
3520 Expr *InitExpr) {
3521 // Pop the notional constructor scope we created earlier.
3522 PopFunctionScopeInfo(nullptr, D);
3523
3524 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3525 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3526, __PRETTY_FUNCTION__))
3526 "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3526, __PRETTY_FUNCTION__))
;
3527
3528 if (!InitExpr) {
3529 D->setInvalidDecl();
3530 if (FD)
3531 FD->removeInClassInitializer();
3532 return;
3533 }
3534
3535 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3536 FD->setInvalidDecl();
3537 FD->removeInClassInitializer();
3538 return;
3539 }
3540
3541 ExprResult Init = InitExpr;
3542 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3543 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3544 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3545 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3546 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3547 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3548 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3549 if (Init.isInvalid()) {
3550 FD->setInvalidDecl();
3551 return;
3552 }
3553 }
3554
3555 // C++11 [class.base.init]p7:
3556 // The initialization of each base and member constitutes a
3557 // full-expression.
3558 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3559 if (Init.isInvalid()) {
3560 FD->setInvalidDecl();
3561 return;
3562 }
3563
3564 InitExpr = Init.get();
3565
3566 FD->setInClassInitializer(InitExpr);
3567}
3568
3569/// \brief Find the direct and/or virtual base specifiers that
3570/// correspond to the given base type, for use in base initialization
3571/// within a constructor.
3572static bool FindBaseInitializer(Sema &SemaRef,
3573 CXXRecordDecl *ClassDecl,
3574 QualType BaseType,
3575 const CXXBaseSpecifier *&DirectBaseSpec,
3576 const CXXBaseSpecifier *&VirtualBaseSpec) {
3577 // First, check for a direct base class.
3578 DirectBaseSpec = nullptr;
3579 for (const auto &Base : ClassDecl->bases()) {
3580 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3581 // We found a direct base of this type. That's what we're
3582 // initializing.
3583 DirectBaseSpec = &Base;
3584 break;
3585 }
3586 }
3587
3588 // Check for a virtual base class.
3589 // FIXME: We might be able to short-circuit this if we know in advance that
3590 // there are no virtual bases.
3591 VirtualBaseSpec = nullptr;
3592 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3593 // We haven't found a base yet; search the class hierarchy for a
3594 // virtual base class.
3595 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3596 /*DetectVirtual=*/false);
3597 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3598 SemaRef.Context.getTypeDeclType(ClassDecl),
3599 BaseType, Paths)) {
3600 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3601 Path != Paths.end(); ++Path) {
3602 if (Path->back().Base->isVirtual()) {
3603 VirtualBaseSpec = Path->back().Base;
3604 break;
3605 }
3606 }
3607 }
3608 }
3609
3610 return DirectBaseSpec || VirtualBaseSpec;
3611}
3612
3613/// \brief Handle a C++ member initializer using braced-init-list syntax.
3614MemInitResult
3615Sema::ActOnMemInitializer(Decl *ConstructorD,
3616 Scope *S,
3617 CXXScopeSpec &SS,
3618 IdentifierInfo *MemberOrBase,
3619 ParsedType TemplateTypeTy,
3620 const DeclSpec &DS,
3621 SourceLocation IdLoc,
3622 Expr *InitList,
3623 SourceLocation EllipsisLoc) {
3624 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3625 DS, IdLoc, InitList,
3626 EllipsisLoc);
3627}
3628
3629/// \brief Handle a C++ member initializer using parentheses syntax.
3630MemInitResult
3631Sema::ActOnMemInitializer(Decl *ConstructorD,
3632 Scope *S,
3633 CXXScopeSpec &SS,
3634 IdentifierInfo *MemberOrBase,
3635 ParsedType TemplateTypeTy,
3636 const DeclSpec &DS,
3637 SourceLocation IdLoc,
3638 SourceLocation LParenLoc,
3639 ArrayRef<Expr *> Args,
3640 SourceLocation RParenLoc,
3641 SourceLocation EllipsisLoc) {
3642 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3643 Args, RParenLoc);
3644 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3645 DS, IdLoc, List, EllipsisLoc);
3646}
3647
3648namespace {
3649
3650// Callback to only accept typo corrections that can be a valid C++ member
3651// intializer: either a non-static field member or a base class.
3652class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3653public:
3654 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3655 : ClassDecl(ClassDecl) {}
3656
3657 bool ValidateCandidate(const TypoCorrection &candidate) override {
3658 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3659 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3660 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3661 return isa<TypeDecl>(ND);
3662 }
3663 return false;
3664 }
3665
3666private:
3667 CXXRecordDecl *ClassDecl;
3668};
3669
3670}
3671
3672/// \brief Handle a C++ member initializer.
3673MemInitResult
3674Sema::BuildMemInitializer(Decl *ConstructorD,
3675 Scope *S,
3676 CXXScopeSpec &SS,
3677 IdentifierInfo *MemberOrBase,
3678 ParsedType TemplateTypeTy,
3679 const DeclSpec &DS,
3680 SourceLocation IdLoc,
3681 Expr *Init,
3682 SourceLocation EllipsisLoc) {
3683 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3684 if (!Res.isUsable())
3685 return true;
3686 Init = Res.get();
3687
3688 if (!ConstructorD)
3689 return true;
3690
3691 AdjustDeclIfTemplate(ConstructorD);
3692
3693 CXXConstructorDecl *Constructor
3694 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3695 if (!Constructor) {
3696 // The user wrote a constructor initializer on a function that is
3697 // not a C++ constructor. Ignore the error for now, because we may
3698 // have more member initializers coming; we'll diagnose it just
3699 // once in ActOnMemInitializers.
3700 return true;
3701 }
3702
3703 CXXRecordDecl *ClassDecl = Constructor->getParent();
3704
3705 // C++ [class.base.init]p2:
3706 // Names in a mem-initializer-id are looked up in the scope of the
3707 // constructor's class and, if not found in that scope, are looked
3708 // up in the scope containing the constructor's definition.
3709 // [Note: if the constructor's class contains a member with the
3710 // same name as a direct or virtual base class of the class, a
3711 // mem-initializer-id naming the member or base class and composed
3712 // of a single identifier refers to the class member. A
3713 // mem-initializer-id for the hidden base class may be specified
3714 // using a qualified name. ]
3715 if (!SS.getScopeRep() && !TemplateTypeTy) {
3716 // Look for a member, first.
3717 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3718 if (!Result.empty()) {
3719 ValueDecl *Member;
3720 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3721 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3722 if (EllipsisLoc.isValid())
3723 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3724 << MemberOrBase
3725 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3726
3727 return BuildMemberInitializer(Member, Init, IdLoc);
3728 }
3729 }
3730 }
3731 // It didn't name a member, so see if it names a class.
3732 QualType BaseType;
3733 TypeSourceInfo *TInfo = nullptr;
3734
3735 if (TemplateTypeTy) {
3736 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3737 } else if (DS.getTypeSpecType() == TST_decltype) {
3738 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3739 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3740 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3741 return true;
3742 } else {
3743 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3744 LookupParsedName(R, S, &SS);
3745
3746 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3747 if (!TyD) {
3748 if (R.isAmbiguous()) return true;
3749
3750 // We don't want access-control diagnostics here.
3751 R.suppressDiagnostics();
3752
3753 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3754 bool NotUnknownSpecialization = false;
3755 DeclContext *DC = computeDeclContext(SS, false);
3756 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3757 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3758
3759 if (!NotUnknownSpecialization) {
3760 // When the scope specifier can refer to a member of an unknown
3761 // specialization, we take it as a type name.
3762 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3763 SS.getWithLocInContext(Context),
3764 *MemberOrBase, IdLoc);
3765 if (BaseType.isNull())
3766 return true;
3767
3768 R.clear();
3769 R.setLookupName(MemberOrBase);
3770 }
3771 }
3772
3773 // If no results were found, try to correct typos.
3774 TypoCorrection Corr;
3775 if (R.empty() && BaseType.isNull() &&
3776 (Corr = CorrectTypo(
3777 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3778 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3779 CTK_ErrorRecovery, ClassDecl))) {
3780 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3781 // We have found a non-static data member with a similar
3782 // name to what was typed; complain and initialize that
3783 // member.
3784 diagnoseTypo(Corr,
3785 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3786 << MemberOrBase << true);
3787 return BuildMemberInitializer(Member, Init, IdLoc);
3788 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3789 const CXXBaseSpecifier *DirectBaseSpec;
3790 const CXXBaseSpecifier *VirtualBaseSpec;
3791 if (FindBaseInitializer(*this, ClassDecl,
3792 Context.getTypeDeclType(Type),
3793 DirectBaseSpec, VirtualBaseSpec)) {
3794 // We have found a direct or virtual base class with a
3795 // similar name to what was typed; complain and initialize
3796 // that base class.
3797 diagnoseTypo(Corr,
3798 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3799 << MemberOrBase << false,
3800 PDiag() /*Suppress note, we provide our own.*/);
3801
3802 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3803 : VirtualBaseSpec;
3804 Diag(BaseSpec->getLocStart(),
3805 diag::note_base_class_specified_here)
3806 << BaseSpec->getType()
3807 << BaseSpec->getSourceRange();
3808
3809 TyD = Type;
3810 }
3811 }
3812 }
3813
3814 if (!TyD && BaseType.isNull()) {
3815 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3816 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3817 return true;
3818 }
3819 }
3820
3821 if (BaseType.isNull()) {
3822 BaseType = Context.getTypeDeclType(TyD);
3823 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3824 if (SS.isSet()) {
3825 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3826 BaseType);
3827 TInfo = Context.CreateTypeSourceInfo(BaseType);
3828 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3829 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3830 TL.setElaboratedKeywordLoc(SourceLocation());
3831 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3832 }
3833 }
3834 }
3835
3836 if (!TInfo)
3837 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3838
3839 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3840}
3841
3842/// Checks a member initializer expression for cases where reference (or
3843/// pointer) members are bound to by-value parameters (or their addresses).
3844static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3845 Expr *Init,
3846 SourceLocation IdLoc) {
3847 QualType MemberTy = Member->getType();
3848
3849 // We only handle pointers and references currently.
3850 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3851 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3852 return;
3853
3854 const bool IsPointer = MemberTy->isPointerType();
3855 if (IsPointer) {
3856 if (const UnaryOperator *Op
3857 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3858 // The only case we're worried about with pointers requires taking the
3859 // address.
3860 if (Op->getOpcode() != UO_AddrOf)
3861 return;
3862
3863 Init = Op->getSubExpr();
3864 } else {
3865 // We only handle address-of expression initializers for pointers.
3866 return;
3867 }
3868 }
3869
3870 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3871 // We only warn when referring to a non-reference parameter declaration.
3872 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3873 if (!Parameter || Parameter->getType()->isReferenceType())
3874 return;
3875
3876 S.Diag(Init->getExprLoc(),
3877 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3878 : diag::warn_bind_ref_member_to_parameter)
3879 << Member << Parameter << Init->getSourceRange();
3880 } else {
3881 // Other initializers are fine.
3882 return;
3883 }
3884
3885 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3886 << (unsigned)IsPointer;
3887}
3888
3889MemInitResult
3890Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3891 SourceLocation IdLoc) {
3892 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3893 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3894 assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3895, __PRETTY_FUNCTION__))
3895 "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3895, __PRETTY_FUNCTION__))
;
3896
3897 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3898 return true;
3899
3900 if (Member->isInvalidDecl())
3901 return true;
3902
3903 MultiExprArg Args;
3904 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3905 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3906 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3907 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3908 } else {
3909 // Template instantiation doesn't reconstruct ParenListExprs for us.
3910 Args = Init;
3911 }
3912
3913 SourceRange InitRange = Init->getSourceRange();
3914
3915 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3916 // Can't check initialization for a member of dependent type or when
3917 // any of the arguments are type-dependent expressions.
3918 DiscardCleanupsInEvaluationContext();
3919 } else {
3920 bool InitList = false;
3921 if (isa<InitListExpr>(Init)) {
3922 InitList = true;
3923 Args = Init;
3924 }
3925
3926 // Initialize the member.
3927 InitializedEntity MemberEntity =
3928 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3929 : InitializedEntity::InitializeMember(IndirectMember,
3930 nullptr);
3931 InitializationKind Kind =
3932 InitList ? InitializationKind::CreateDirectList(IdLoc)
3933 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3934 InitRange.getEnd());
3935
3936 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3937 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3938 nullptr);
3939 if (MemberInit.isInvalid())
3940 return true;
3941
3942 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3943
3944 // C++11 [class.base.init]p7:
3945 // The initialization of each base and member constitutes a
3946 // full-expression.
3947 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3948 if (MemberInit.isInvalid())
3949 return true;
3950
3951 Init = MemberInit.get();
3952 }
3953
3954 if (DirectMember) {
3955 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3956 InitRange.getBegin(), Init,
3957 InitRange.getEnd());
3958 } else {
3959 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3960 InitRange.getBegin(), Init,
3961 InitRange.getEnd());
3962 }
3963}
3964
3965MemInitResult
3966Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3967 CXXRecordDecl *ClassDecl) {
3968 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3969 if (!LangOpts.CPlusPlus11)
3970 return Diag(NameLoc, diag::err_delegating_ctor)
3971 << TInfo->getTypeLoc().getLocalSourceRange();
3972 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3973
3974 bool InitList = true;
3975 MultiExprArg Args = Init;
3976 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3977 InitList = false;
3978 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3979 }
3980
3981 SourceRange InitRange = Init->getSourceRange();
3982 // Initialize the object.
3983 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3984 QualType(ClassDecl->getTypeForDecl(), 0));
3985 InitializationKind Kind =
3986 InitList ? InitializationKind::CreateDirectList(NameLoc)
3987 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3988 InitRange.getEnd());
3989 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3990 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3991 Args, nullptr);
3992 if (DelegationInit.isInvalid())
3993 return true;
3994
3995 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3996, __PRETTY_FUNCTION__))
3996 "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3996, __PRETTY_FUNCTION__))
;
3997
3998 // C++11 [class.base.init]p7:
3999 // The initialization of each base and member constitutes a
4000 // full-expression.
4001 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4002 InitRange.getBegin());
4003 if (DelegationInit.isInvalid())
4004 return true;
4005
4006 // If we are in a dependent context, template instantiation will
4007 // perform this type-checking again. Just save the arguments that we
4008 // received in a ParenListExpr.
4009 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4010 // of the information that we have about the base
4011 // initializer. However, deconstructing the ASTs is a dicey process,
4012 // and this approach is far more likely to get the corner cases right.
4013 if (CurContext->isDependentContext())
4014 DelegationInit = Init;
4015
4016 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4017 DelegationInit.getAs<Expr>(),
4018 InitRange.getEnd());
4019}
4020
4021MemInitResult
4022Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4023 Expr *Init, CXXRecordDecl *ClassDecl,
4024 SourceLocation EllipsisLoc) {
4025 SourceLocation BaseLoc
4026 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4027
4028 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4029 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4030 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4031
4032 // C++ [class.base.init]p2:
4033 // [...] Unless the mem-initializer-id names a nonstatic data
4034 // member of the constructor's class or a direct or virtual base
4035 // of that class, the mem-initializer is ill-formed. A
4036 // mem-initializer-list can initialize a base class using any
4037 // name that denotes that base class type.
4038 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4039
4040 SourceRange InitRange = Init->getSourceRange();
4041 if (EllipsisLoc.isValid()) {
4042 // This is a pack expansion.
4043 if (!BaseType->containsUnexpandedParameterPack()) {
4044 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4045 << SourceRange(BaseLoc, InitRange.getEnd());
4046
4047 EllipsisLoc = SourceLocation();
4048 }
4049 } else {
4050 // Check for any unexpanded parameter packs.
4051 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4052 return true;
4053
4054 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4055 return true;
4056 }
4057
4058 // Check for direct and virtual base classes.
4059 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4060 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4061 if (!Dependent) {
4062 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4063 BaseType))
4064 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4065
4066 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4067 VirtualBaseSpec);
4068
4069 // C++ [base.class.init]p2:
4070 // Unless the mem-initializer-id names a nonstatic data member of the
4071 // constructor's class or a direct or virtual base of that class, the
4072 // mem-initializer is ill-formed.
4073 if (!DirectBaseSpec && !VirtualBaseSpec) {
4074 // If the class has any dependent bases, then it's possible that
4075 // one of those types will resolve to the same type as
4076 // BaseType. Therefore, just treat this as a dependent base
4077 // class initialization. FIXME: Should we try to check the
4078 // initialization anyway? It seems odd.
4079 if (ClassDecl->hasAnyDependentBases())
4080 Dependent = true;
4081 else
4082 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4083 << BaseType << Context.getTypeDeclType(ClassDecl)
4084 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4085 }
4086 }
4087
4088 if (Dependent) {
4089 DiscardCleanupsInEvaluationContext();
4090
4091 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4092 /*IsVirtual=*/false,
4093 InitRange.getBegin(), Init,
4094 InitRange.getEnd(), EllipsisLoc);
4095 }
4096
4097 // C++ [base.class.init]p2:
4098 // If a mem-initializer-id is ambiguous because it designates both
4099 // a direct non-virtual base class and an inherited virtual base
4100 // class, the mem-initializer is ill-formed.
4101 if (DirectBaseSpec && VirtualBaseSpec)
4102 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4103 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4104
4105 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4106 if (!BaseSpec)
4107 BaseSpec = VirtualBaseSpec;
4108
4109 // Initialize the base.
4110 bool InitList = true;
4111 MultiExprArg Args = Init;
4112 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4113 InitList = false;
4114 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4115 }
4116
4117 InitializedEntity BaseEntity =
4118 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4119 InitializationKind Kind =
4120 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4121 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4122 InitRange.getEnd());
4123 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4124 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4125 if (BaseInit.isInvalid())
4126 return true;
4127
4128 // C++11 [class.base.init]p7:
4129 // The initialization of each base and member constitutes a
4130 // full-expression.
4131 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4132 if (BaseInit.isInvalid())
4133 return true;
4134
4135 // If we are in a dependent context, template instantiation will
4136 // perform this type-checking again. Just save the arguments that we
4137 // received in a ParenListExpr.
4138 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4139 // of the information that we have about the base
4140 // initializer. However, deconstructing the ASTs is a dicey process,
4141 // and this approach is far more likely to get the corner cases right.
4142 if (CurContext->isDependentContext())
4143 BaseInit = Init;
4144
4145 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4146 BaseSpec->isVirtual(),
4147 InitRange.getBegin(),
4148 BaseInit.getAs<Expr>(),
4149 InitRange.getEnd(), EllipsisLoc);
4150}
4151
4152// Create a static_cast\<T&&>(expr).
4153static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4154 if (T.isNull()) T = E->getType();
4155 QualType TargetType = SemaRef.BuildReferenceType(
4156 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4157 SourceLocation ExprLoc = E->getLocStart();
4158 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4159 TargetType, ExprLoc);
4160
4161 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4162 SourceRange(ExprLoc, ExprLoc),
4163 E->getSourceRange()).get();
4164}
4165
4166/// ImplicitInitializerKind - How an implicit base or member initializer should
4167/// initialize its base or member.
4168enum ImplicitInitializerKind {
4169 IIK_Default,
4170 IIK_Copy,
4171 IIK_Move,
4172 IIK_Inherit
4173};
4174
4175static bool
4176BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4177 ImplicitInitializerKind ImplicitInitKind,
4178 CXXBaseSpecifier *BaseSpec,
4179 bool IsInheritedVirtualBase,
4180 CXXCtorInitializer *&CXXBaseInit) {
4181 InitializedEntity InitEntity
4182 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4183 IsInheritedVirtualBase);
4184
4185 ExprResult BaseInit;
4186
4187 switch (ImplicitInitKind) {
4188 case IIK_Inherit:
4189 case IIK_Default: {
4190 InitializationKind InitKind
4191 = InitializationKind::CreateDefault(Constructor->getLocation());
4192 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4193 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4194 break;
4195 }
4196
4197 case IIK_Move:
4198 case IIK_Copy: {
4199 bool Moving = ImplicitInitKind == IIK_Move;
4200 ParmVarDecl *Param = Constructor->getParamDecl(0);
4201 QualType ParamType = Param->getType().getNonReferenceType();
4202
4203 Expr *CopyCtorArg =
4204 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4205 SourceLocation(), Param, false,
4206 Constructor->getLocation(), ParamType,
4207 VK_LValue, nullptr);
4208
4209 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4210
4211 // Cast to the base class to avoid ambiguities.
4212 QualType ArgTy =
4213 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4214 ParamType.getQualifiers());
4215
4216 if (Moving) {
4217 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4218 }
4219
4220 CXXCastPath BasePath;
4221 BasePath.push_back(BaseSpec);
4222 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4223 CK_UncheckedDerivedToBase,
4224 Moving ? VK_XValue : VK_LValue,
4225 &BasePath).get();
4226
4227 InitializationKind InitKind
4228 = InitializationKind::CreateDirect(Constructor->getLocation(),
4229 SourceLocation(), SourceLocation());
4230 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4231 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4232 break;
4233 }
4234 }
4235
4236 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4237 if (BaseInit.isInvalid())
4238 return true;
4239
4240 CXXBaseInit =
4241 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4242 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4243 SourceLocation()),
4244 BaseSpec->isVirtual(),
4245 SourceLocation(),
4246 BaseInit.getAs<Expr>(),
4247 SourceLocation(),
4248 SourceLocation());
4249
4250 return false;
4251}
4252
4253static bool RefersToRValueRef(Expr *MemRef) {
4254 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4255 return Referenced->getType()->isRValueReferenceType();
4256}
4257
4258static bool
4259BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4260 ImplicitInitializerKind ImplicitInitKind,
4261 FieldDecl *Field, IndirectFieldDecl *Indirect,
4262 CXXCtorInitializer *&CXXMemberInit) {
4263 if (Field->isInvalidDecl())
4264 return true;
4265
4266 SourceLocation Loc = Constructor->getLocation();
4267
4268 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4269 bool Moving = ImplicitInitKind == IIK_Move;
4270 ParmVarDecl *Param = Constructor->getParamDecl(0);
4271 QualType ParamType = Param->getType().getNonReferenceType();
4272
4273 // Suppress copying zero-width bitfields.
4274 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4275 return false;
4276
4277 Expr *MemberExprBase =
4278 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4279 SourceLocation(), Param, false,
4280 Loc, ParamType, VK_LValue, nullptr);
4281
4282 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4283
4284 if (Moving) {
4285 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4286 }
4287
4288 // Build a reference to this field within the parameter.
4289 CXXScopeSpec SS;
4290 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4291 Sema::LookupMemberName);
4292 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4293 : cast<ValueDecl>(Field), AS_public);
4294 MemberLookup.resolveKind();
4295 ExprResult CtorArg
4296 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4297 ParamType, Loc,
4298 /*IsArrow=*/false,
4299 SS,
4300 /*TemplateKWLoc=*/SourceLocation(),
4301 /*FirstQualifierInScope=*/nullptr,
4302 MemberLookup,
4303 /*TemplateArgs=*/nullptr,
4304 /*S*/nullptr);
4305 if (CtorArg.isInvalid())
4306 return true;
4307
4308 // C++11 [class.copy]p15:
4309 // - if a member m has rvalue reference type T&&, it is direct-initialized
4310 // with static_cast<T&&>(x.m);
4311 if (RefersToRValueRef(CtorArg.get())) {
4312 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4313 }
4314
4315 InitializedEntity Entity =
4316 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4317 /*Implicit*/ true)
4318 : InitializedEntity::InitializeMember(Field, nullptr,
4319 /*Implicit*/ true);
4320
4321 // Direct-initialize to use the copy constructor.
4322 InitializationKind InitKind =
4323 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4324
4325 Expr *CtorArgE = CtorArg.getAs<Expr>();
4326 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4327 ExprResult MemberInit =
4328 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4329 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4330 if (MemberInit.isInvalid())
4331 return true;
4332
4333 if (Indirect)
4334 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4335 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4336 else
4337 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4338 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4339 return false;
4340 }
4341
4342 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4343, __PRETTY_FUNCTION__))
4343 "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4343, __PRETTY_FUNCTION__))
;
4344
4345 QualType FieldBaseElementType =
4346 SemaRef.Context.getBaseElementType(Field->getType());
4347
4348 if (FieldBaseElementType->isRecordType()) {
4349 InitializedEntity InitEntity =
4350 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4351 /*Implicit*/ true)
4352 : InitializedEntity::InitializeMember(Field, nullptr,
4353 /*Implicit*/ true);
4354 InitializationKind InitKind =
4355 InitializationKind::CreateDefault(Loc);
4356
4357 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4358 ExprResult MemberInit =
4359 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4360
4361 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4362 if (MemberInit.isInvalid())
4363 return true;
4364
4365 if (Indirect)
4366 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4367 Indirect, Loc,
4368 Loc,
4369 MemberInit.get(),
4370 Loc);
4371 else
4372 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4373 Field, Loc, Loc,
4374 MemberInit.get(),
4375 Loc);
4376 return false;
4377 }
4378
4379 if (!Field->getParent()->isUnion()) {
4380 if (FieldBaseElementType->isReferenceType()) {
4381 SemaRef.Diag(Constructor->getLocation(),
4382 diag::err_uninitialized_member_in_ctor)
4383 << (int)Constructor->isImplicit()
4384 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4385 << 0 << Field->getDeclName();
4386 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4387 return true;
4388 }
4389
4390 if (FieldBaseElementType.isConstQualified()) {
4391 SemaRef.Diag(Constructor->getLocation(),
4392 diag::err_uninitialized_member_in_ctor)
4393 << (int)Constructor->isImplicit()
4394 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4395 << 1 << Field->getDeclName();
4396 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4397 return true;
4398 }
4399 }
4400
4401 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4402 FieldBaseElementType->isObjCRetainableType() &&
4403 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4404 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4405 // ARC:
4406 // Default-initialize Objective-C pointers to NULL.
4407 CXXMemberInit
4408 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4409 Loc, Loc,
4410 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4411 Loc);
4412 return false;
4413 }
4414
4415 // Nothing to initialize.
4416 CXXMemberInit = nullptr;
4417 return false;
4418}
4419
4420namespace {
4421struct BaseAndFieldInfo {
4422 Sema &S;
4423 CXXConstructorDecl *Ctor;
4424 bool AnyErrorsInInits;
4425 ImplicitInitializerKind IIK;
4426 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4427 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4428 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4429
4430 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4431 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4432 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4433 if (Ctor->getInheritedConstructor())
4434 IIK = IIK_Inherit;
4435 else if (Generated && Ctor->isCopyConstructor())
4436 IIK = IIK_Copy;
4437 else if (Generated && Ctor->isMoveConstructor())
4438 IIK = IIK_Move;
4439 else
4440 IIK = IIK_Default;
4441 }
4442
4443 bool isImplicitCopyOrMove() const {
4444 switch (IIK) {
4445 case IIK_Copy:
4446 case IIK_Move:
4447 return true;
4448
4449 case IIK_Default:
4450 case IIK_Inherit:
4451 return false;
4452 }
4453
4454 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4454)
;
4455 }
4456
4457 bool addFieldInitializer(CXXCtorInitializer *Init) {
4458 AllToInit.push_back(Init);
4459
4460 // Check whether this initializer makes the field "used".
4461 if (Init->getInit()->HasSideEffects(S.Context))
4462 S.UnusedPrivateFields.remove(Init->getAnyMember());
4463
4464 return false;
4465 }
4466
4467 bool isInactiveUnionMember(FieldDecl *Field) {
4468 RecordDecl *Record = Field->getParent();
4469 if (!Record->isUnion())
4470 return false;
4471
4472 if (FieldDecl *Active =
4473 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4474 return Active != Field->getCanonicalDecl();
4475
4476 // In an implicit copy or move constructor, ignore any in-class initializer.
4477 if (isImplicitCopyOrMove())
4478 return true;
4479
4480 // If there's no explicit initialization, the field is active only if it
4481 // has an in-class initializer...
4482 if (Field->hasInClassInitializer())
4483 return false;
4484 // ... or it's an anonymous struct or union whose class has an in-class
4485 // initializer.
4486 if (!Field->isAnonymousStructOrUnion())
4487 return true;
4488 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4489 return !FieldRD->hasInClassInitializer();
4490 }
4491
4492 /// \brief Determine whether the given field is, or is within, a union member
4493 /// that is inactive (because there was an initializer given for a different
4494 /// member of the union, or because the union was not initialized at all).
4495 bool isWithinInactiveUnionMember(FieldDecl *Field,
4496 IndirectFieldDecl *Indirect) {
4497 if (!Indirect)
4498 return isInactiveUnionMember(Field);
4499
4500 for (auto *C : Indirect->chain()) {
4501 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4502 if (Field && isInactiveUnionMember(Field))
4503 return true;
4504 }
4505 return false;
4506 }
4507};
4508}
4509
4510/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4511/// array type.
4512static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4513 if (T->isIncompleteArrayType())
4514 return true;
4515
4516 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4517 if (!ArrayT->getSize())
4518 return true;
4519
4520 T = ArrayT->getElementType();
4521 }
4522
4523 return false;
4524}
4525
4526static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4527 FieldDecl *Field,
4528 IndirectFieldDecl *Indirect = nullptr) {
4529 if (Field->isInvalidDecl())
4530 return false;
4531
4532 // Overwhelmingly common case: we have a direct initializer for this field.
4533 if (CXXCtorInitializer *Init =
4534 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4535 return Info.addFieldInitializer(Init);
4536
4537 // C++11 [class.base.init]p8:
4538 // if the entity is a non-static data member that has a
4539 // brace-or-equal-initializer and either
4540 // -- the constructor's class is a union and no other variant member of that
4541 // union is designated by a mem-initializer-id or
4542 // -- the constructor's class is not a union, and, if the entity is a member
4543 // of an anonymous union, no other member of that union is designated by
4544 // a mem-initializer-id,
4545 // the entity is initialized as specified in [dcl.init].
4546 //
4547 // We also apply the same rules to handle anonymous structs within anonymous
4548 // unions.
4549 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4550 return false;
4551
4552 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4553 ExprResult DIE =
4554 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4555 if (DIE.isInvalid())
4556 return true;
4557 CXXCtorInitializer *Init;
4558 if (Indirect)
4559 Init = new (SemaRef.Context)
4560 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4561 SourceLocation(), DIE.get(), SourceLocation());
4562 else
4563 Init = new (SemaRef.Context)
4564 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4565 SourceLocation(), DIE.get(), SourceLocation());
4566 return Info.addFieldInitializer(Init);
4567 }
4568
4569 // Don't initialize incomplete or zero-length arrays.
4570 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4571 return false;
4572
4573 // Don't try to build an implicit initializer if there were semantic
4574 // errors in any of the initializers (and therefore we might be
4575 // missing some that the user actually wrote).
4576 if (Info.AnyErrorsInInits)
4577 return false;
4578
4579 CXXCtorInitializer *Init = nullptr;
4580 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4581 Indirect, Init))
4582 return true;
4583
4584 if (!Init)
4585 return false;
4586
4587 return Info.addFieldInitializer(Init);
4588}
4589
4590bool
4591Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4592 CXXCtorInitializer *Initializer) {
4593 assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast<
void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4593, __PRETTY_FUNCTION__))
;
4594 Constructor->setNumCtorInitializers(1);
4595 CXXCtorInitializer **initializer =
4596 new (Context) CXXCtorInitializer*[1];
4597 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4598 Constructor->setCtorInitializers(initializer);
4599
4600 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4601 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4602 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4603 }
4604
4605 DelegatingCtorDecls.push_back(Constructor);
4606
4607 DiagnoseUninitializedFields(*this, Constructor);
4608
4609 return false;
4610}
4611
4612bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4613 ArrayRef<CXXCtorInitializer *> Initializers) {
4614 if (Constructor->isDependentContext()) {
4615 // Just store the initializers as written, they will be checked during
4616 // instantiation.
4617 if (!Initializers.empty()) {
4618 Constructor->setNumCtorInitializers(Initializers.size());
4619 CXXCtorInitializer **baseOrMemberInitializers =
4620 new (Context) CXXCtorInitializer*[Initializers.size()];
4621 memcpy(baseOrMemberInitializers, Initializers.data(),
4622 Initializers.size() * sizeof(CXXCtorInitializer*));
4623 Constructor->setCtorInitializers(baseOrMemberInitializers);
4624 }
4625
4626 // Let template instantiation know whether we had errors.
4627 if (AnyErrors)
4628 Constructor->setInvalidDecl();
4629
4630 return false;
4631 }
4632
4633 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4634
4635 // We need to build the initializer AST according to order of construction
4636 // and not what user specified in the Initializers list.
4637 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4638 if (!ClassDecl)
4639 return true;
4640
4641 bool HadError = false;
4642
4643 for (unsigned i = 0; i < Initializers.size(); i++) {
4644 CXXCtorInitializer *Member = Initializers[i];
4645
4646 if (Member->isBaseInitializer())
4647 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4648 else {
4649 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4650
4651 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4652 for (auto *C : F->chain()) {
4653 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4654 if (FD && FD->getParent()->isUnion())
4655 Info.ActiveUnionMember.insert(std::make_pair(
4656 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4657 }
4658 } else if (FieldDecl *FD = Member->getMember()) {
4659 if (FD->getParent()->isUnion())
4660 Info.ActiveUnionMember.insert(std::make_pair(
4661 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4662 }
4663 }
4664 }
4665
4666 // Keep track of the direct virtual bases.
4667 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4668 for (auto &I : ClassDecl->bases()) {
4669 if (I.isVirtual())
4670 DirectVBases.insert(&I);
4671 }
4672
4673 // Push virtual bases before others.
4674 for (auto &VBase : ClassDecl->vbases()) {
4675 if (CXXCtorInitializer *Value
4676 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4677 // [class.base.init]p7, per DR257:
4678 // A mem-initializer where the mem-initializer-id names a virtual base
4679 // class is ignored during execution of a constructor of any class that
4680 // is not the most derived class.
4681 if (ClassDecl->isAbstract()) {
4682 // FIXME: Provide a fixit to remove the base specifier. This requires
4683 // tracking the location of the associated comma for a base specifier.
4684 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4685 << VBase.getType() << ClassDecl;
4686 DiagnoseAbstractType(ClassDecl);
4687 }
4688
4689 Info.AllToInit.push_back(Value);
4690 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4691 // [class.base.init]p8, per DR257:
4692 // If a given [...] base class is not named by a mem-initializer-id
4693 // [...] and the entity is not a virtual base class of an abstract
4694 // class, then [...] the entity is default-initialized.
4695 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4696 CXXCtorInitializer *CXXBaseInit;
4697 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4698 &VBase, IsInheritedVirtualBase,
4699 CXXBaseInit)) {
4700 HadError = true;
4701 continue;
4702 }
4703
4704 Info.AllToInit.push_back(CXXBaseInit);
4705 }
4706 }
4707
4708 // Non-virtual bases.
4709 for (auto &Base : ClassDecl->bases()) {
4710 // Virtuals are in the virtual base list and already constructed.
4711 if (Base.isVirtual())
4712 continue;
4713
4714 if (CXXCtorInitializer *Value
4715 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4716 Info.AllToInit.push_back(Value);
4717 } else if (!AnyErrors) {
4718 CXXCtorInitializer *CXXBaseInit;
4719 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4720 &Base, /*IsInheritedVirtualBase=*/false,
4721 CXXBaseInit)) {
4722 HadError = true;
4723 continue;
4724 }
4725
4726 Info.AllToInit.push_back(CXXBaseInit);
4727 }
4728 }
4729
4730 // Fields.
4731 for (auto *Mem : ClassDecl->decls()) {
4732 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4733 // C++ [class.bit]p2:
4734 // A declaration for a bit-field that omits the identifier declares an
4735 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4736 // initialized.
4737 if (F->isUnnamedBitfield())
4738 continue;
4739
4740 // If we're not generating the implicit copy/move constructor, then we'll
4741 // handle anonymous struct/union fields based on their individual
4742 // indirect fields.
4743 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4744 continue;
4745
4746 if (CollectFieldInitializer(*this, Info, F))
4747 HadError = true;
4748 continue;
4749 }
4750
4751 // Beyond this point, we only consider default initialization.
4752 if (Info.isImplicitCopyOrMove())
4753 continue;
4754
4755 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4756 if (F->getType()->isIncompleteArrayType()) {
4757 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4758, __PRETTY_FUNCTION__))
4758 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4758, __PRETTY_FUNCTION__))
;
4759 continue;
4760 }
4761
4762 // Initialize each field of an anonymous struct individually.
4763 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4764 HadError = true;
4765
4766 continue;
4767 }
4768 }
4769
4770 unsigned NumInitializers = Info.AllToInit.size();
4771 if (NumInitializers > 0) {
4772 Constructor->setNumCtorInitializers(NumInitializers);
4773 CXXCtorInitializer **baseOrMemberInitializers =
4774 new (Context) CXXCtorInitializer*[NumInitializers];
4775 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4776 NumInitializers * sizeof(CXXCtorInitializer*));
4777 Constructor->setCtorInitializers(baseOrMemberInitializers);
4778
4779 // Constructors implicitly reference the base and member
4780 // destructors.
4781 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4782 Constructor->getParent());
4783 }
4784
4785 return HadError;
4786}
4787
4788static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4789 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4790 const RecordDecl *RD = RT->getDecl();
4791 if (RD->isAnonymousStructOrUnion()) {
4792 for (auto *Field : RD->fields())
4793 PopulateKeysForFields(Field, IdealInits);
4794 return;
4795 }
4796 }
4797 IdealInits.push_back(Field->getCanonicalDecl());
4798}
4799
4800static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4801 return Context.getCanonicalType(BaseType).getTypePtr();
4802}
4803
4804static const void *GetKeyForMember(ASTContext &Context,
4805 CXXCtorInitializer *Member) {
4806 if (!Member->isAnyMemberInitializer())
4807 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4808
4809 return Member->getAnyMember()->getCanonicalDecl();
4810}
4811
4812static void DiagnoseBaseOrMemInitializerOrder(
4813 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4814 ArrayRef<CXXCtorInitializer *> Inits) {
4815 if (Constructor->getDeclContext()->isDependentContext())
4816 return;
4817
4818 // Don't check initializers order unless the warning is enabled at the
4819 // location of at least one initializer.
4820 bool ShouldCheckOrder = false;
4821 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4822 CXXCtorInitializer *Init = Inits[InitIndex];
4823 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4824 Init->getSourceLocation())) {
4825 ShouldCheckOrder = true;
4826 break;
4827 }
4828 }
4829 if (!ShouldCheckOrder)
4830 return;
4831
4832 // Build the list of bases and members in the order that they'll
4833 // actually be initialized. The explicit initializers should be in
4834 // this same order but may be missing things.
4835 SmallVector<const void*, 32> IdealInitKeys;
4836
4837 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4838
4839 // 1. Virtual bases.
4840 for (const auto &VBase : ClassDecl->vbases())
4841 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4842
4843 // 2. Non-virtual bases.
4844 for (const auto &Base : ClassDecl->bases()) {
4845 if (Base.isVirtual())
4846 continue;
4847 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4848 }
4849
4850 // 3. Direct fields.
4851 for (auto *Field : ClassDecl->fields()) {
4852 if (Field->isUnnamedBitfield())
4853 continue;
4854
4855 PopulateKeysForFields(Field, IdealInitKeys);
4856 }
4857
4858 unsigned NumIdealInits = IdealInitKeys.size();
4859 unsigned IdealIndex = 0;
4860
4861 CXXCtorInitializer *PrevInit = nullptr;
4862 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4863 CXXCtorInitializer *Init = Inits[InitIndex];
4864 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4865
4866 // Scan forward to try to find this initializer in the idealized
4867 // initializers list.
4868 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4869 if (InitKey == IdealInitKeys[IdealIndex])
4870 break;
4871
4872 // If we didn't find this initializer, it must be because we
4873 // scanned past it on a previous iteration. That can only
4874 // happen if we're out of order; emit a warning.
4875 if (IdealIndex == NumIdealInits && PrevInit) {
4876 Sema::SemaDiagnosticBuilder D =
4877 SemaRef.Diag(PrevInit->getSourceLocation(),
4878 diag::warn_initializer_out_of_order);
4879
4880 if (PrevInit->isAnyMemberInitializer())
4881 D << 0 << PrevInit->getAnyMember()->getDeclName();
4882 else
4883 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4884
4885 if (Init->isAnyMemberInitializer())
4886 D << 0 << Init->getAnyMember()->getDeclName();
4887 else
4888 D << 1 << Init->getTypeSourceInfo()->getType();
4889
4890 // Move back to the initializer's location in the ideal list.
4891 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4892 if (InitKey == IdealInitKeys[IdealIndex])
4893 break;
4894
4895 assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4896, __PRETTY_FUNCTION__))
4896 "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4896, __PRETTY_FUNCTION__))
;
4897 }
4898
4899 PrevInit = Init;
4900 }
4901}
4902
4903namespace {
4904bool CheckRedundantInit(Sema &S,
4905 CXXCtorInitializer *Init,
4906 CXXCtorInitializer *&PrevInit) {
4907 if (!PrevInit) {
4908 PrevInit = Init;
4909 return false;
4910 }
4911
4912 if (FieldDecl *Field = Init->getAnyMember())
4913 S.Diag(Init->getSourceLocation(),
4914 diag::err_multiple_mem_initialization)
4915 << Field->getDeclName()
4916 << Init->getSourceRange();
4917 else {
4918 const Type *BaseClass = Init->getBaseClass();
4919 assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast
<void> (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4919, __PRETTY_FUNCTION__))
;
4920 S.Diag(Init->getSourceLocation(),
4921 diag::err_multiple_base_initialization)
4922 << QualType(BaseClass, 0)
4923 << Init->getSourceRange();
4924 }
4925 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4926 << 0 << PrevInit->getSourceRange();
4927
4928 return true;
4929}
4930
4931typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4932typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4933
4934bool CheckRedundantUnionInit(Sema &S,
4935 CXXCtorInitializer *Init,
4936 RedundantUnionMap &Unions) {
4937 FieldDecl *Field = Init->getAnyMember();
4938 RecordDecl *Parent = Field->getParent();
4939 NamedDecl *Child = Field;
4940
4941 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4942 if (Parent->isUnion()) {
4943 UnionEntry &En = Unions[Parent];
4944 if (En.first && En.first != Child) {
4945 S.Diag(Init->getSourceLocation(),
4946 diag::err_multiple_mem_union_initialization)
4947 << Field->getDeclName()
4948 << Init->getSourceRange();
4949 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4950 << 0 << En.second->getSourceRange();
4951 return true;
4952 }
4953 if (!En.first) {
4954 En.first = Child;
4955 En.second = Init;
4956 }
4957 if (!Parent->isAnonymousStructOrUnion())
4958 return false;
4959 }
4960
4961 Child = Parent;
4962 Parent = cast<RecordDecl>(Parent->getDeclContext());
4963 }
4964
4965 return false;
4966}
4967}
4968
4969/// ActOnMemInitializers - Handle the member initializers for a constructor.
4970void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4971 SourceLocation ColonLoc,
4972 ArrayRef<CXXCtorInitializer*> MemInits,
4973 bool AnyErrors) {
4974 if (!ConstructorDecl)
4975 return;
4976
4977 AdjustDeclIfTemplate(ConstructorDecl);
4978
4979 CXXConstructorDecl *Constructor
4980 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4981
4982 if (!Constructor) {
4983 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4984 return;
4985 }
4986
4987 // Mapping for the duplicate initializers check.
4988 // For member initializers, this is keyed with a FieldDecl*.
4989 // For base initializers, this is keyed with a Type*.
4990 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4991
4992 // Mapping for the inconsistent anonymous-union initializers check.
4993 RedundantUnionMap MemberUnions;
4994
4995 bool HadError = false;
4996 for (unsigned i = 0; i < MemInits.size(); i++) {
4997 CXXCtorInitializer *Init = MemInits[i];
4998
4999 // Set the source order index.
5000 Init->setSourceOrder(i);
5001
5002 if (Init->isAnyMemberInitializer()) {
5003 const void *Key = GetKeyForMember(Context, Init);
5004 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5005 CheckRedundantUnionInit(*this, Init, MemberUnions))
5006 HadError = true;
5007 } else if (Init->isBaseInitializer()) {
5008 const void *Key = GetKeyForMember(Context, Init);
5009 if (CheckRedundantInit(*this, Init, Members[Key]))
5010 HadError = true;
5011 } else {
5012 assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void>
(0) : __assert_fail ("Init->isDelegatingInitializer()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5012, __PRETTY_FUNCTION__))
;
5013 // This must be the only initializer
5014 if (MemInits.size() != 1) {
5015 Diag(Init->getSourceLocation(),
5016 diag::err_delegating_initializer_alone)
5017 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5018 // We will treat this as being the only initializer.
5019 }
5020 SetDelegatingInitializer(Constructor, MemInits[i]);
5021 // Return immediately as the initializer is set.
5022 return;
5023 }
5024 }
5025
5026 if (HadError)
5027 return;
5028
5029 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5030
5031 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5032
5033 DiagnoseUninitializedFields(*this, Constructor);
5034}
5035
5036void
5037Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5038 CXXRecordDecl *ClassDecl) {
5039 // Ignore dependent contexts. Also ignore unions, since their members never
5040 // have destructors implicitly called.
5041 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5042 return;
5043
5044 // FIXME: all the access-control diagnostics are positioned on the
5045 // field/base declaration. That's probably good; that said, the
5046 // user might reasonably want to know why the destructor is being
5047 // emitted, and we currently don't say.
5048
5049 // Non-static data members.
5050 for (auto *Field : ClassDecl->fields()) {
5051 if (Field->isInvalidDecl())
5052 continue;
5053
5054 // Don't destroy incomplete or zero-length arrays.
5055 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5056 continue;
5057
5058 QualType FieldType = Context.getBaseElementType(Field->getType());
5059
5060 const RecordType* RT = FieldType->getAs<RecordType>();
5061 if (!RT)
5062 continue;
5063
5064 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5065 if (FieldClassDecl->isInvalidDecl())
5066 continue;
5067 if (FieldClassDecl->hasIrrelevantDestructor())
5068 continue;
5069 // The destructor for an implicit anonymous union member is never invoked.
5070 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5071 continue;
5072
5073 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5074 assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5074, __PRETTY_FUNCTION__))
;
5075 CheckDestructorAccess(Field->getLocation(), Dtor,
5076 PDiag(diag::err_access_dtor_field)
5077 << Field->getDeclName()
5078 << FieldType);
5079
5080 MarkFunctionReferenced(Location, Dtor);
5081 DiagnoseUseOfDecl(Dtor, Location);
5082 }
5083
5084 // We only potentially invoke the destructors of potentially constructed
5085 // subobjects.
5086 bool VisitVirtualBases = !ClassDecl->isAbstract();
5087
5088 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5089
5090 // Bases.
5091 for (const auto &Base : ClassDecl->bases()) {
5092 // Bases are always records in a well-formed non-dependent class.
5093 const RecordType *RT = Base.getType()->getAs<RecordType>();
5094
5095 // Remember direct virtual bases.
5096 if (Base.isVirtual()) {
5097 if (!VisitVirtualBases)
5098 continue;
5099 DirectVirtualBases.insert(RT);
5100 }
5101
5102 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5103 // If our base class is invalid, we probably can't get its dtor anyway.
5104 if (BaseClassDecl->isInvalidDecl())
5105 continue;
5106 if (BaseClassDecl->hasIrrelevantDestructor())
5107 continue;
5108
5109 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5110 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5110, __PRETTY_FUNCTION__))
;
5111
5112 // FIXME: caret should be on the start of the class name
5113 CheckDestructorAccess(Base.getLocStart(), Dtor,
5114 PDiag(diag::err_access_dtor_base)
5115 << Base.getType()
5116 << Base.getSourceRange(),
5117 Context.getTypeDeclType(ClassDecl));
5118
5119 MarkFunctionReferenced(Location, Dtor);
5120 DiagnoseUseOfDecl(Dtor, Location);
5121 }
5122
5123 if (!VisitVirtualBases)
5124 return;
5125
5126 // Virtual bases.
5127 for (const auto &VBase : ClassDecl->vbases()) {
5128 // Bases are always records in a well-formed non-dependent class.
5129 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5130
5131 // Ignore direct virtual bases.
5132 if (DirectVirtualBases.count(RT))
5133 continue;
5134
5135 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5136 // If our base class is invalid, we probably can't get its dtor anyway.
5137 if (BaseClassDecl->isInvalidDecl())
5138 continue;
5139 if (BaseClassDecl->hasIrrelevantDestructor())
5140 continue;
5141
5142 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5143 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5143, __PRETTY_FUNCTION__))
;
5144 if (CheckDestructorAccess(
5145 ClassDecl->getLocation(), Dtor,
5146 PDiag(diag::err_access_dtor_vbase)
5147 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5148 Context.getTypeDeclType(ClassDecl)) ==
5149 AR_accessible) {
5150 CheckDerivedToBaseConversion(
5151 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5152 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5153 SourceRange(), DeclarationName(), nullptr);
5154 }
5155
5156 MarkFunctionReferenced(Location, Dtor);
5157 DiagnoseUseOfDecl(Dtor, Location);
5158 }
5159}
5160
5161void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5162 if (!CDtorDecl)
5163 return;
5164
5165 if (CXXConstructorDecl *Constructor
5166 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5167 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5168 DiagnoseUninitializedFields(*this, Constructor);
5169 }
5170}
5171
5172bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5173 if (!getLangOpts().CPlusPlus)
5174 return false;
5175
5176 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5177 if (!RD)
5178 return false;
5179
5180 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5181 // class template specialization here, but doing so breaks a lot of code.
5182
5183 // We can't answer whether something is abstract until it has a
5184 // definition. If it's currently being defined, we'll walk back
5185 // over all the declarations when we have a full definition.
5186 const CXXRecordDecl *Def = RD->getDefinition();
5187 if (!Def || Def->isBeingDefined())
5188 return false;
5189
5190 return RD->isAbstract();
5191}
5192
5193bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5194 TypeDiagnoser &Diagnoser) {
5195 if (!isAbstractType(Loc, T))
5196 return false;
5197
5198 T = Context.getBaseElementType(T);
5199 Diagnoser.diagnose(*this, Loc, T);
5200 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5201 return true;
5202}
5203
5204void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5205 // Check if we've already emitted the list of pure virtual functions
5206 // for this class.
5207 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5208 return;
5209
5210 // If the diagnostic is suppressed, don't emit the notes. We're only
5211 // going to emit them once, so try to attach them to a diagnostic we're
5212 // actually going to show.
5213 if (Diags.isLastDiagnosticIgnored())
5214 return;
5215
5216 CXXFinalOverriderMap FinalOverriders;
5217 RD->getFinalOverriders(FinalOverriders);
5218
5219 // Keep a set of seen pure methods so we won't diagnose the same method
5220 // more than once.
5221 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5222
5223 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5224 MEnd = FinalOverriders.end();
5225 M != MEnd;
5226 ++M) {
5227 for (OverridingMethods::iterator SO = M->second.begin(),
5228 SOEnd = M->second.end();
5229 SO != SOEnd; ++SO) {
5230 // C++ [class.abstract]p4:
5231 // A class is abstract if it contains or inherits at least one
5232 // pure virtual function for which the final overrider is pure
5233 // virtual.
5234
5235 //
5236 if (SO->second.size() != 1)
5237 continue;
5238
5239 if (!SO->second.front().Method->isPure())
5240 continue;
5241
5242 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5243 continue;
5244
5245 Diag(SO->second.front().Method->getLocation(),
5246 diag::note_pure_virtual_function)
5247 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5248 }
5249 }
5250
5251 if (!PureVirtualClassDiagSet)
5252 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5253 PureVirtualClassDiagSet->insert(RD);
5254}
5255
5256namespace {
5257struct AbstractUsageInfo {
5258 Sema &S;
5259 CXXRecordDecl *Record;
5260 CanQualType AbstractType;
5261 bool Invalid;
5262
5263 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5264 : S(S), Record(Record),
5265 AbstractType(S.Context.getCanonicalType(
5266 S.Context.getTypeDeclType(Record))),
5267 Invalid(false) {}
5268
5269 void DiagnoseAbstractType() {
5270 if (Invalid) return;
5271 S.DiagnoseAbstractType(Record);
5272 Invalid = true;
5273 }
5274
5275 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5276};
5277
5278struct CheckAbstractUsage {
5279 AbstractUsageInfo &Info;
5280 const NamedDecl *Ctx;
5281
5282 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5283 : Info(Info), Ctx(Ctx) {}
5284
5285 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5286 switch (TL.getTypeLocClass()) {
5287#define ABSTRACT_TYPELOC(CLASS, PARENT)
5288#define TYPELOC(CLASS, PARENT) \
5289 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5290#include "clang/AST/TypeLocNodes.def"
5291 }
5292 }
5293
5294 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5295 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5296 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5297 if (!TL.getParam(I))
5298 continue;
5299
5300 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5301 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5302 }
5303 }
5304
5305 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5306 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5307 }
5308
5309 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5310 // Visit the type parameters from a permissive context.
5311 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5312 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5313 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5314 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5315 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5316 // TODO: other template argument types?
5317 }
5318 }
5319
5320 // Visit pointee types from a permissive context.
5321#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5322 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5323 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5324 }
5325 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5326 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5327 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5328 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5329 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5330
5331 /// Handle all the types we haven't given a more specific
5332 /// implementation for above.
5333 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5334 // Every other kind of type that we haven't called out already
5335 // that has an inner type is either (1) sugar or (2) contains that
5336 // inner type in some way as a subobject.
5337 if (TypeLoc Next = TL.getNextTypeLoc())
5338 return Visit(Next, Sel);
5339
5340 // If there's no inner type and we're in a permissive context,
5341 // don't diagnose.
5342 if (Sel == Sema::AbstractNone) return;
5343
5344 // Check whether the type matches the abstract type.
5345 QualType T = TL.getType();
5346 if (T->isArrayType()) {
5347 Sel = Sema::AbstractArrayType;
5348 T = Info.S.Context.getBaseElementType(T);
5349 }
5350 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5351 if (CT != Info.AbstractType) return;
5352
5353 // It matched; do some magic.
5354 if (Sel == Sema::AbstractArrayType) {
5355 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5356 << T << TL.getSourceRange();
5357 } else {
5358 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5359 << Sel << T << TL.getSourceRange();
5360 }
5361 Info.DiagnoseAbstractType();
5362 }
5363};
5364
5365void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5366 Sema::AbstractDiagSelID Sel) {
5367 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5368}
5369
5370}
5371
5372/// Check for invalid uses of an abstract type in a method declaration.
5373static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5374 CXXMethodDecl *MD) {
5375 // No need to do the check on definitions, which require that
5376 // the return/param types be complete.
5377 if (MD->doesThisDeclarationHaveABody())
5378 return;
5379
5380 // For safety's sake, just ignore it if we don't have type source
5381 // information. This should never happen for non-implicit methods,
5382 // but...
5383 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5384 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5385}
5386
5387/// Check for invalid uses of an abstract type within a class definition.
5388static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5389 CXXRecordDecl *RD) {
5390 for (auto *D : RD->decls()) {
5391 if (D->isImplicit()) continue;
5392
5393 // Methods and method templates.
5394 if (isa<CXXMethodDecl>(D)) {
5395 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5396 } else if (isa<FunctionTemplateDecl>(D)) {
5397 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5398 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5399
5400 // Fields and static variables.
5401 } else if (isa<FieldDecl>(D)) {
5402 FieldDecl *FD = cast<FieldDecl>(D);
5403 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5404 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5405 } else if (isa<VarDecl>(D)) {
5406 VarDecl *VD = cast<VarDecl>(D);
5407 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5408 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5409
5410 // Nested classes and class templates.
5411 } else if (isa<CXXRecordDecl>(D)) {
5412 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5413 } else if (isa<ClassTemplateDecl>(D)) {
5414 CheckAbstractClassUsage(Info,
5415 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5416 }
5417 }
5418}
5419
5420static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5421 Attr *ClassAttr = getDLLAttr(Class);
5422 if (!ClassAttr)
5423 return;
5424
5425 assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast<
void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5425, __PRETTY_FUNCTION__))
;
5426
5427 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5428
5429 if (TSK == TSK_ExplicitInstantiationDeclaration)
5430 // Don't go any further if this is just an explicit instantiation
5431 // declaration.
5432 return;
5433
5434 for (Decl *Member : Class->decls()) {
5435 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5436 if (!MD)
5437 continue;
5438
5439 if (Member->getAttr<DLLExportAttr>()) {
5440 if (MD->isUserProvided()) {
5441 // Instantiate non-default class member functions ...
5442
5443 // .. except for certain kinds of template specializations.
5444 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5445 continue;
5446
5447 S.MarkFunctionReferenced(Class->getLocation(), MD);
5448
5449 // The function will be passed to the consumer when its definition is
5450 // encountered.
5451 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5452 MD->isCopyAssignmentOperator() ||
5453 MD->isMoveAssignmentOperator()) {
5454 // Synthesize and instantiate non-trivial implicit methods, explicitly
5455 // defaulted methods, and the copy and move assignment operators. The
5456 // latter are exported even if they are trivial, because the address of
5457 // an operator can be taken and should compare equal accross libraries.
5458 DiagnosticErrorTrap Trap(S.Diags);
5459 S.MarkFunctionReferenced(Class->getLocation(), MD);
5460 if (Trap.hasErrorOccurred()) {
5461 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5462 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5463 break;
5464 }
5465
5466 // There is no later point when we will see the definition of this
5467 // function, so pass it to the consumer now.
5468 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5469 }
5470 }
5471 }
5472}
5473
5474static void checkForMultipleExportedDefaultConstructors(Sema &S,
5475 CXXRecordDecl *Class) {
5476 // Only the MS ABI has default constructor closures, so we don't need to do
5477 // this semantic checking anywhere else.
5478 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5479 return;
5480
5481 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5482 for (Decl *Member : Class->decls()) {
5483 // Look for exported default constructors.
5484 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5485 if (!CD || !CD->isDefaultConstructor())
5486 continue;
5487 auto *Attr = CD->getAttr<DLLExportAttr>();
5488 if (!Attr)
5489 continue;
5490
5491 // If the class is non-dependent, mark the default arguments as ODR-used so
5492 // that we can properly codegen the constructor closure.
5493 if (!Class->isDependentContext()) {
5494 for (ParmVarDecl *PD : CD->parameters()) {
5495 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5496 S.DiscardCleanupsInEvaluationContext();
5497 }
5498 }
5499
5500 if (LastExportedDefaultCtor) {
5501 S.Diag(LastExportedDefaultCtor->getLocation(),
5502 diag::err_attribute_dll_ambiguous_default_ctor)
5503 << Class;
5504 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5505 << CD->getDeclName();
5506 return;
5507 }
5508 LastExportedDefaultCtor = CD;
5509 }
5510}
5511
5512/// \brief Check class-level dllimport/dllexport attribute.
5513void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5514 Attr *ClassAttr = getDLLAttr(Class);
5515
5516 // MSVC inherits DLL attributes to partial class template specializations.
5517 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5518 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5519 if (Attr *TemplateAttr =
5520 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5521 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5522 A->setInherited(true);
5523 ClassAttr = A;
5524 }
5525 }
5526 }
5527
5528 if (!ClassAttr)
5529 return;
5530
5531 if (!Class->isExternallyVisible()) {
5532 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5533 << Class << ClassAttr;
5534 return;
5535 }
5536
5537 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5538 !ClassAttr->isInherited()) {
5539 // Diagnose dll attributes on members of class with dll attribute.
5540 for (Decl *Member : Class->decls()) {
5541 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5542 continue;
5543 InheritableAttr *MemberAttr = getDLLAttr(Member);
5544 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5545 continue;
5546
5547 Diag(MemberAttr->getLocation(),
5548 diag::err_attribute_dll_member_of_dll_class)
5549 << MemberAttr << ClassAttr;
5550 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5551 Member->setInvalidDecl();
5552 }
5553 }
5554
5555 if (Class->getDescribedClassTemplate())
5556 // Don't inherit dll attribute until the template is instantiated.
5557 return;
5558
5559 // The class is either imported or exported.
5560 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5561
5562 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5563
5564 // Ignore explicit dllexport on explicit class template instantiation declarations.
5565 if (ClassExported && !ClassAttr->isInherited() &&
5566 TSK == TSK_ExplicitInstantiationDeclaration) {
5567 Class->dropAttr<DLLExportAttr>();
5568 return;
5569 }
5570
5571 // Force declaration of implicit members so they can inherit the attribute.
5572 ForceDeclarationOfImplicitMembers(Class);
5573
5574 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5575 // seem to be true in practice?
5576
5577 for (Decl *Member : Class->decls()) {
5578 VarDecl *VD = dyn_cast<VarDecl>(Member);
5579 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5580
5581 // Only methods and static fields inherit the attributes.
5582 if (!VD && !MD)
5583 continue;
5584
5585 if (MD) {
5586 // Don't process deleted methods.
5587 if (MD->isDeleted())
5588 continue;
5589
5590 if (MD->isInlined()) {
5591 // MinGW does not import or export inline methods.
5592 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5593 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5594 continue;
5595
5596 // MSVC versions before 2015 don't export the move assignment operators
5597 // and move constructor, so don't attempt to import/export them if
5598 // we have a definition.
5599 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5600 if ((MD->isMoveAssignmentOperator() ||
5601 (Ctor && Ctor->isMoveConstructor())) &&
5602 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5603 continue;
5604
5605 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5606 // operator is exported anyway.
5607 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5608 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5609 continue;
5610 }
5611 }
5612
5613 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5614 continue;
5615
5616 if (!getDLLAttr(Member)) {
5617 auto *NewAttr =
5618 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5619 NewAttr->setInherited(true);
5620 Member->addAttr(NewAttr);
5621 }
5622 }
5623
5624 if (ClassExported)
5625 DelayedDllExportClasses.push_back(Class);
5626}
5627
5628/// \brief Perform propagation of DLL attributes from a derived class to a
5629/// templated base class for MS compatibility.
5630void Sema::propagateDLLAttrToBaseClassTemplate(
5631 CXXRecordDecl *Class, Attr *ClassAttr,
5632 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5633 if (getDLLAttr(
5634 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5635 // If the base class template has a DLL attribute, don't try to change it.
5636 return;
5637 }
5638
5639 auto TSK = BaseTemplateSpec->getSpecializationKind();
5640 if (!getDLLAttr(BaseTemplateSpec) &&
5641 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5642 TSK == TSK_ImplicitInstantiation)) {
5643 // The template hasn't been instantiated yet (or it has, but only as an
5644 // explicit instantiation declaration or implicit instantiation, which means
5645 // we haven't codegenned any members yet), so propagate the attribute.
5646 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5647 NewAttr->setInherited(true);
5648 BaseTemplateSpec->addAttr(NewAttr);
5649
5650 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5651 // needs to be run again to work see the new attribute. Otherwise this will
5652 // get run whenever the template is instantiated.
5653 if (TSK != TSK_Undeclared)
5654 checkClassLevelDLLAttribute(BaseTemplateSpec);
5655
5656 return;
5657 }
5658
5659 if (getDLLAttr(BaseTemplateSpec)) {
5660 // The template has already been specialized or instantiated with an
5661 // attribute, explicitly or through propagation. We should not try to change
5662 // it.
5663 return;
5664 }
5665
5666 // The template was previously instantiated or explicitly specialized without
5667 // a dll attribute, It's too late for us to add an attribute, so warn that
5668 // this is unsupported.
5669 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5670 << BaseTemplateSpec->isExplicitSpecialization();
5671 Diag(ClassAttr->getLocation(), diag::note_attribute);
5672 if (BaseTemplateSpec->isExplicitSpecialization()) {
5673 Diag(BaseTemplateSpec->getLocation(),
5674 diag::note_template_class_explicit_specialization_was_here)
5675 << BaseTemplateSpec;
5676 } else {
5677 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5678 diag::note_template_class_instantiation_was_here)
5679 << BaseTemplateSpec;
5680 }
5681}
5682
5683static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5684 SourceLocation DefaultLoc) {
5685 switch (S.getSpecialMember(MD)) {
5686 case Sema::CXXDefaultConstructor:
5687 S.DefineImplicitDefaultConstructor(DefaultLoc,
5688 cast<CXXConstructorDecl>(MD));
5689 break;
5690 case Sema::CXXCopyConstructor:
5691 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5692 break;
5693 case Sema::CXXCopyAssignment:
5694 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5695 break;
5696 case Sema::CXXDestructor:
5697 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5698 break;
5699 case Sema::CXXMoveConstructor:
5700 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5701 break;
5702 case Sema::CXXMoveAssignment:
5703 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5704 break;
5705 case Sema::CXXInvalid:
5706 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5706)
;
5707 }
5708}
5709
5710/// \brief Perform semantic checks on a class definition that has been
5711/// completing, introducing implicitly-declared members, checking for
5712/// abstract types, etc.
5713void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5714 if (!Record)
5715 return;
5716
5717 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5718 AbstractUsageInfo Info(*this, Record);
5719 CheckAbstractClassUsage(Info, Record);
5720 }
5721
5722 // If this is not an aggregate type and has no user-declared constructor,
5723 // complain about any non-static data members of reference or const scalar
5724 // type, since they will never get initializers.
5725 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5726 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5727 !Record->isLambda()) {
5728 bool Complained = false;
5729 for (const auto *F : Record->fields()) {
5730 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5731 continue;
5732
5733 if (F->getType()->isReferenceType() ||
5734 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5735 if (!Complained) {
5736 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5737 << Record->getTagKind() << Record;
5738 Complained = true;
5739 }
5740
5741 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5742 << F->getType()->isReferenceType()
5743 << F->getDeclName();
5744 }
5745 }
5746 }
5747
5748 if (Record->getIdentifier()) {
5749 // C++ [class.mem]p13:
5750 // If T is the name of a class, then each of the following shall have a
5751 // name different from T:
5752 // - every member of every anonymous union that is a member of class T.
5753 //
5754 // C++ [class.mem]p14:
5755 // In addition, if class T has a user-declared constructor (12.1), every
5756 // non-static data member of class T shall have a name different from T.
5757 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5758 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5759 ++I) {
5760 NamedDecl *D = *I;
5761 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5762 isa<IndirectFieldDecl>(D)) {
5763 Diag(D->getLocation(), diag::err_member_name_of_class)
5764 << D->getDeclName();
5765 break;
5766 }
5767 }
5768 }
5769
5770 // Warn if the class has virtual methods but non-virtual public destructor.
5771 if (Record->isPolymorphic() && !Record->isDependentType()) {
5772 CXXDestructorDecl *dtor = Record->getDestructor();
5773 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5774 !Record->hasAttr<FinalAttr>())
5775 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5776 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5777 }
5778
5779 if (Record->isAbstract()) {
5780 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5781 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5782 << FA->isSpelledAsSealed();
5783 DiagnoseAbstractType(Record);
5784 }
5785 }
5786
5787 bool HasMethodWithOverrideControl = false,
5788 HasOverridingMethodWithoutOverrideControl = false;
5789 if (!Record->isDependentType()) {
5790 for (auto *M : Record->methods()) {
5791 // See if a method overloads virtual methods in a base
5792 // class without overriding any.
5793 if (!M->isStatic())
5794 DiagnoseHiddenVirtualMethods(M);
5795 if (M->hasAttr<OverrideAttr>())
5796 HasMethodWithOverrideControl = true;
5797 else if (M->size_overridden_methods() > 0)
5798 HasOverridingMethodWithoutOverrideControl = true;
5799 // Check whether the explicitly-defaulted special members are valid.
5800 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5801 CheckExplicitlyDefaultedSpecialMember(M);
5802
5803 // For an explicitly defaulted or deleted special member, we defer
5804 // determining triviality until the class is complete. That time is now!
5805 CXXSpecialMember CSM = getSpecialMember(M);
5806 if (!M->isImplicit() && !M->isUserProvided()) {
5807 if (CSM != CXXInvalid) {
5808 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5809
5810 // Inform the class that we've finished declaring this member.
5811 Record->finishedDefaultedOrDeletedMember(M);
5812 }
5813 }
5814
5815 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5816 M->hasAttr<DLLExportAttr>()) {
5817 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5818 M->isTrivial() &&
5819 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5820 CSM == CXXDestructor))
5821 M->dropAttr<DLLExportAttr>();
5822
5823 if (M->hasAttr<DLLExportAttr>()) {
5824 DefineImplicitSpecialMember(*this, M, M->getLocation());
5825 ActOnFinishInlineFunctionDef(M);
5826 }
5827 }
5828 }
5829 }
5830
5831 if (HasMethodWithOverrideControl &&
5832 HasOverridingMethodWithoutOverrideControl) {
5833 // At least one method has the 'override' control declared.
5834 // Diagnose all other overridden methods which do not have 'override' specified on them.
5835 for (auto *M : Record->methods())
5836 DiagnoseAbsenceOfOverrideControl(M);
5837 }
5838
5839 // ms_struct is a request to use the same ABI rules as MSVC. Check
5840 // whether this class uses any C++ features that are implemented
5841 // completely differently in MSVC, and if so, emit a diagnostic.
5842 // That diagnostic defaults to an error, but we allow projects to
5843 // map it down to a warning (or ignore it). It's a fairly common
5844 // practice among users of the ms_struct pragma to mass-annotate
5845 // headers, sweeping up a bunch of types that the project doesn't
5846 // really rely on MSVC-compatible layout for. We must therefore
5847 // support "ms_struct except for C++ stuff" as a secondary ABI.
5848 if (Record->isMsStruct(Context) &&
5849 (Record->isPolymorphic() || Record->getNumBases())) {
5850 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5851 }
5852
5853 checkClassLevelDLLAttribute(Record);
5854}
5855
5856/// Look up the special member function that would be called by a special
5857/// member function for a subobject of class type.
5858///
5859/// \param Class The class type of the subobject.
5860/// \param CSM The kind of special member function.
5861/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5862/// \param ConstRHS True if this is a copy operation with a const object
5863/// on its RHS, that is, if the argument to the outer special member
5864/// function is 'const' and this is not a field marked 'mutable'.
5865static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
5866 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5867 unsigned FieldQuals, bool ConstRHS) {
5868 unsigned LHSQuals = 0;
5869 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5870 LHSQuals = FieldQuals;
5871
5872 unsigned RHSQuals = FieldQuals;
5873 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5874 RHSQuals = 0;
5875 else if (ConstRHS)
5876 RHSQuals |= Qualifiers::Const;
5877
5878 return S.LookupSpecialMember(Class, CSM,
5879 RHSQuals & Qualifiers::Const,
5880 RHSQuals & Qualifiers::Volatile,
5881 false,
5882 LHSQuals & Qualifiers::Const,
5883 LHSQuals & Qualifiers::Volatile);
5884}
5885
5886class Sema::InheritedConstructorInfo {
5887 Sema &S;
5888 SourceLocation UseLoc;
5889
5890 /// A mapping from the base classes through which the constructor was
5891 /// inherited to the using shadow declaration in that base class (or a null
5892 /// pointer if the constructor was declared in that base class).
5893 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5894 InheritedFromBases;
5895
5896public:
5897 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5898 ConstructorUsingShadowDecl *Shadow)
5899 : S(S), UseLoc(UseLoc) {
5900 bool DiagnosedMultipleConstructedBases = false;
5901 CXXRecordDecl *ConstructedBase = nullptr;
5902 UsingDecl *ConstructedBaseUsing = nullptr;
5903
5904 // Find the set of such base class subobjects and check that there's a
5905 // unique constructed subobject.
5906 for (auto *D : Shadow->redecls()) {
5907 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5908 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5909 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5910
5911 InheritedFromBases.insert(
5912 std::make_pair(DNominatedBase->getCanonicalDecl(),
5913 DShadow->getNominatedBaseClassShadowDecl()));
5914 if (DShadow->constructsVirtualBase())
5915 InheritedFromBases.insert(
5916 std::make_pair(DConstructedBase->getCanonicalDecl(),
5917 DShadow->getConstructedBaseClassShadowDecl()));
5918 else
5919 assert(DNominatedBase == DConstructedBase)((DNominatedBase == DConstructedBase) ? static_cast<void>
(0) : __assert_fail ("DNominatedBase == DConstructedBase", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5919, __PRETTY_FUNCTION__))
;
5920
5921 // [class.inhctor.init]p2:
5922 // If the constructor was inherited from multiple base class subobjects
5923 // of type B, the program is ill-formed.
5924 if (!ConstructedBase) {
5925 ConstructedBase = DConstructedBase;
5926 ConstructedBaseUsing = D->getUsingDecl();
5927 } else if (ConstructedBase != DConstructedBase &&
5928 !Shadow->isInvalidDecl()) {
5929 if (!DiagnosedMultipleConstructedBases) {
5930 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5931 << Shadow->getTargetDecl();
5932 S.Diag(ConstructedBaseUsing->getLocation(),
5933 diag::note_ambiguous_inherited_constructor_using)
5934 << ConstructedBase;
5935 DiagnosedMultipleConstructedBases = true;
5936 }
5937 S.Diag(D->getUsingDecl()->getLocation(),
5938 diag::note_ambiguous_inherited_constructor_using)
5939 << DConstructedBase;
5940 }
5941 }
5942
5943 if (DiagnosedMultipleConstructedBases)
5944 Shadow->setInvalidDecl();
5945 }
5946
5947 /// Find the constructor to use for inherited construction of a base class,
5948 /// and whether that base class constructor inherits the constructor from a
5949 /// virtual base class (in which case it won't actually invoke it).
5950 std::pair<CXXConstructorDecl *, bool>
5951 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5952 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5953 if (It == InheritedFromBases.end())
5954 return std::make_pair(nullptr, false);
5955
5956 // This is an intermediary class.
5957 if (It->second)
5958 return std::make_pair(
5959 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5960 It->second->constructsVirtualBase());
5961
5962 // This is the base class from which the constructor was inherited.
5963 return std::make_pair(Ctor, false);
5964 }
5965};
5966
5967/// Is the special member function which would be selected to perform the
5968/// specified operation on the specified class type a constexpr constructor?
5969static bool
5970specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5971 Sema::CXXSpecialMember CSM, unsigned Quals,
5972 bool ConstRHS,
5973 CXXConstructorDecl *InheritedCtor = nullptr,
5974 Sema::InheritedConstructorInfo *Inherited = nullptr) {
5975 // If we're inheriting a constructor, see if we need to call it for this base
5976 // class.
5977 if (InheritedCtor) {
5978 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5978, __PRETTY_FUNCTION__))
;
5979 auto BaseCtor =
5980 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5981 if (BaseCtor)
5982 return BaseCtor->isConstexpr();
5983 }
5984
5985 if (CSM == Sema::CXXDefaultConstructor)
5986 return ClassDecl->hasConstexprDefaultConstructor();
5987
5988 Sema::SpecialMemberOverloadResult SMOR =
5989 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5990 if (!SMOR.getMethod())
5991 // A constructor we wouldn't select can't be "involved in initializing"
5992 // anything.
5993 return true;
5994 return SMOR.getMethod()->isConstexpr();
5995}
5996
5997/// Determine whether the specified special member function would be constexpr
5998/// if it were implicitly defined.
5999static bool defaultedSpecialMemberIsConstexpr(
6000 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6001 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6002 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6003 if (!S.getLangOpts().CPlusPlus11)
6004 return false;
6005
6006 // C++11 [dcl.constexpr]p4:
6007 // In the definition of a constexpr constructor [...]
6008 bool Ctor = true;
6009 switch (CSM) {
6010 case Sema::CXXDefaultConstructor:
6011 if (Inherited)
6012 break;
6013 // Since default constructor lookup is essentially trivial (and cannot
6014 // involve, for instance, template instantiation), we compute whether a
6015 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6016 //
6017 // This is important for performance; we need to know whether the default
6018 // constructor is constexpr to determine whether the type is a literal type.
6019 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6020
6021 case Sema::CXXCopyConstructor:
6022 case Sema::CXXMoveConstructor:
6023 // For copy or move constructors, we need to perform overload resolution.
6024 break;
6025
6026 case Sema::CXXCopyAssignment:
6027 case Sema::CXXMoveAssignment:
6028 if (!S.getLangOpts().CPlusPlus14)
6029 return false;
6030 // In C++1y, we need to perform overload resolution.
6031 Ctor = false;
6032 break;
6033
6034 case Sema::CXXDestructor:
6035 case Sema::CXXInvalid:
6036 return false;
6037 }
6038
6039 // -- if the class is a non-empty union, or for each non-empty anonymous
6040 // union member of a non-union class, exactly one non-static data member
6041 // shall be initialized; [DR1359]
6042 //
6043 // If we squint, this is guaranteed, since exactly one non-static data member
6044 // will be initialized (if the constructor isn't deleted), we just don't know
6045 // which one.
6046 if (Ctor && ClassDecl->isUnion())
6047 return CSM == Sema::CXXDefaultConstructor
6048 ? ClassDecl->hasInClassInitializer() ||
6049 !ClassDecl->hasVariantMembers()
6050 : true;
6051
6052 // -- the class shall not have any virtual base classes;
6053 if (Ctor && ClassDecl->getNumVBases())
6054 return false;
6055
6056 // C++1y [class.copy]p26:
6057 // -- [the class] is a literal type, and
6058 if (!Ctor && !ClassDecl->isLiteral())
6059 return false;
6060
6061 // -- every constructor involved in initializing [...] base class
6062 // sub-objects shall be a constexpr constructor;
6063 // -- the assignment operator selected to copy/move each direct base
6064 // class is a constexpr function, and
6065 for (const auto &B : ClassDecl->bases()) {
6066 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6067 if (!BaseType) continue;
6068
6069 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6070 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6071 InheritedCtor, Inherited))
6072 return false;
6073 }
6074
6075 // -- every constructor involved in initializing non-static data members
6076 // [...] shall be a constexpr constructor;
6077 // -- every non-static data member and base class sub-object shall be
6078 // initialized
6079 // -- for each non-static data member of X that is of class type (or array
6080 // thereof), the assignment operator selected to copy/move that member is
6081 // a constexpr function
6082 for (const auto *F : ClassDecl->fields()) {
6083 if (F->isInvalidDecl())
6084 continue;
6085 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6086 continue;
6087 QualType BaseType = S.Context.getBaseElementType(F->getType());
6088 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6089 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6090 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6091 BaseType.getCVRQualifiers(),
6092 ConstArg && !F->isMutable()))
6093 return false;
6094 } else if (CSM == Sema::CXXDefaultConstructor) {
6095 return false;
6096 }
6097 }
6098
6099 // All OK, it's constexpr!
6100 return true;
6101}
6102
6103static Sema::ImplicitExceptionSpecification
6104ComputeDefaultedSpecialMemberExceptionSpec(
6105 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6106 Sema::InheritedConstructorInfo *ICI);
6107
6108static Sema::ImplicitExceptionSpecification
6109computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6110 auto CSM = S.getSpecialMember(MD);
6111 if (CSM != Sema::CXXInvalid)
6112 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6113
6114 auto *CD = cast<CXXConstructorDecl>(MD);
6115 assert(CD->getInheritedConstructor() &&((CD->getInheritedConstructor() && "only special members have implicit exception specs"
) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6116, __PRETTY_FUNCTION__))
6116 "only special members have implicit exception specs")((CD->getInheritedConstructor() && "only special members have implicit exception specs"
) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6116, __PRETTY_FUNCTION__))
;
6117 Sema::InheritedConstructorInfo ICI(
6118 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6119 return ComputeDefaultedSpecialMemberExceptionSpec(
6120 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6121}
6122
6123static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6124 CXXMethodDecl *MD) {
6125 FunctionProtoType::ExtProtoInfo EPI;
6126
6127 // Build an exception specification pointing back at this member.
6128 EPI.ExceptionSpec.Type = EST_Unevaluated;
6129 EPI.ExceptionSpec.SourceDecl = MD;
6130
6131 // Set the calling convention to the default for C++ instance methods.
6132 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6133 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6134 /*IsCXXMethod=*/true));
6135 return EPI;
6136}
6137
6138void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6139 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6140 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6141 return;
6142
6143 // Evaluate the exception specification.
6144 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6145 auto ESI = IES.getExceptionSpec();
6146
6147 // Update the type of the special member to use it.
6148 UpdateExceptionSpec(MD, ESI);
6149
6150 // A user-provided destructor can be defined outside the class. When that
6151 // happens, be sure to update the exception specification on both
6152 // declarations.
6153 const FunctionProtoType *CanonicalFPT =
6154 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6155 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6156 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6157}
6158
6159void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6160 CXXRecordDecl *RD = MD->getParent();
6161 CXXSpecialMember CSM = getSpecialMember(MD);
6162
6163 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6164, __PRETTY_FUNCTION__))
6164 "not an explicitly-defaulted special member")((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6164, __PRETTY_FUNCTION__))
;
6165
6166 // Whether this was the first-declared instance of the constructor.
6167 // This affects whether we implicitly add an exception spec and constexpr.
6168 bool First = MD == MD->getCanonicalDecl();
6169
6170 bool HadError = false;
6171
6172 // C++11 [dcl.fct.def.default]p1:
6173 // A function that is explicitly defaulted shall
6174 // -- be a special member function (checked elsewhere),
6175 // -- have the same type (except for ref-qualifiers, and except that a
6176 // copy operation can take a non-const reference) as an implicit
6177 // declaration, and
6178 // -- not have default arguments.
6179 unsigned ExpectedParams = 1;
6180 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6181 ExpectedParams = 0;
6182 if (MD->getNumParams() != ExpectedParams) {
6183 // This also checks for default arguments: a copy or move constructor with a
6184 // default argument is classified as a default constructor, and assignment
6185 // operations and destructors can't have default arguments.
6186 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6187 << CSM << MD->getSourceRange();
6188 HadError = true;
6189 } else if (MD->isVariadic()) {
6190 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6191 << CSM << MD->getSourceRange();
6192 HadError = true;
6193 }
6194
6195 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6196
6197 bool CanHaveConstParam = false;
6198 if (CSM == CXXCopyConstructor)
6199 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6200 else if (CSM == CXXCopyAssignment)
6201 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6202
6203 QualType ReturnType = Context.VoidTy;
6204 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6205 // Check for return type matching.
6206 ReturnType = Type->getReturnType();
6207 QualType ExpectedReturnType =
6208 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6209 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6210 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6211 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6212 HadError = true;
6213 }
6214
6215 // A defaulted special member cannot have cv-qualifiers.
6216 if (Type->getTypeQuals()) {
6217 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6218 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6219 HadError = true;
6220 }
6221 }
6222
6223 // Check for parameter type matching.
6224 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6225 bool HasConstParam = false;
6226 if (ExpectedParams && ArgType->isReferenceType()) {
6227 // Argument must be reference to possibly-const T.
6228 QualType ReferentType = ArgType->getPointeeType();
6229 HasConstParam = ReferentType.isConstQualified();
6230
6231 if (ReferentType.isVolatileQualified()) {
6232 Diag(MD->getLocation(),
6233 diag::err_defaulted_special_member_volatile_param) << CSM;
6234 HadError = true;
6235 }
6236
6237 if (HasConstParam && !CanHaveConstParam) {
6238 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6239 Diag(MD->getLocation(),
6240 diag::err_defaulted_special_member_copy_const_param)
6241 << (CSM == CXXCopyAssignment);
6242 // FIXME: Explain why this special member can't be const.
6243 } else {
6244 Diag(MD->getLocation(),
6245 diag::err_defaulted_special_member_move_const_param)
6246 << (CSM == CXXMoveAssignment);
6247 }
6248 HadError = true;
6249 }
6250 } else if (ExpectedParams) {
6251 // A copy assignment operator can take its argument by value, but a
6252 // defaulted one cannot.
6253 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")((CSM == CXXCopyAssignment && "unexpected non-ref argument"
) ? static_cast<void> (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6253, __PRETTY_FUNCTION__))
;
6254 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6255 HadError = true;
6256 }
6257
6258 // C++11 [dcl.fct.def.default]p2:
6259 // An explicitly-defaulted function may be declared constexpr only if it
6260 // would have been implicitly declared as constexpr,
6261 // Do not apply this rule to members of class templates, since core issue 1358
6262 // makes such functions always instantiate to constexpr functions. For
6263 // functions which cannot be constexpr (for non-constructors in C++11 and for
6264 // destructors in C++1y), this is checked elsewhere.
6265 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6266 HasConstParam);
6267 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6268 : isa<CXXConstructorDecl>(MD)) &&
6269 MD->isConstexpr() && !Constexpr &&
6270 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6271 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6272 // FIXME: Explain why the special member can't be constexpr.
6273 HadError = true;
6274 }
6275
6276 // and may have an explicit exception-specification only if it is compatible
6277 // with the exception-specification on the implicit declaration.
6278 if (Type->hasExceptionSpec()) {
6279 // Delay the check if this is the first declaration of the special member,
6280 // since we may not have parsed some necessary in-class initializers yet.
6281 if (First) {
6282 // If the exception specification needs to be instantiated, do so now,
6283 // before we clobber it with an EST_Unevaluated specification below.
6284 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6285 InstantiateExceptionSpec(MD->getLocStart(), MD);
6286 Type = MD->getType()->getAs<FunctionProtoType>();
6287 }
6288 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6289 } else
6290 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6291 }
6292
6293 // If a function is explicitly defaulted on its first declaration,
6294 if (First) {
6295 // -- it is implicitly considered to be constexpr if the implicit
6296 // definition would be,
6297 MD->setConstexpr(Constexpr);
6298
6299 // -- it is implicitly considered to have the same exception-specification
6300 // as if it had been implicitly declared,
6301 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6302 EPI.ExceptionSpec.Type = EST_Unevaluated;
6303 EPI.ExceptionSpec.SourceDecl = MD;
6304 MD->setType(Context.getFunctionType(ReturnType,
6305 llvm::makeArrayRef(&ArgType,
6306 ExpectedParams),
6307 EPI));
6308 }
6309
6310 if (ShouldDeleteSpecialMember(MD, CSM)) {
6311 if (First) {
6312 SetDeclDeleted(MD, MD->getLocation());
6313 } else {
6314 // C++11 [dcl.fct.def.default]p4:
6315 // [For a] user-provided explicitly-defaulted function [...] if such a
6316 // function is implicitly defined as deleted, the program is ill-formed.
6317 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6318 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6319 HadError = true;
6320 }
6321 }
6322
6323 if (HadError)
6324 MD->setInvalidDecl();
6325}
6326
6327/// Check whether the exception specification provided for an
6328/// explicitly-defaulted special member matches the exception specification
6329/// that would have been generated for an implicit special member, per
6330/// C++11 [dcl.fct.def.default]p2.
6331void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6332 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6333 // If the exception specification was explicitly specified but hadn't been
6334 // parsed when the method was defaulted, grab it now.
6335 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6336 SpecifiedType =
6337 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6338
6339 // Compute the implicit exception specification.
6340 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6341 /*IsCXXMethod=*/true);
6342 FunctionProtoType::ExtProtoInfo EPI(CC);
6343 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6344 EPI.ExceptionSpec = IES.getExceptionSpec();
6345 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6346 Context.getFunctionType(Context.VoidTy, None, EPI));
6347
6348 // Ensure that it matches.
6349 CheckEquivalentExceptionSpec(
6350 PDiag(diag::err_incorrect_defaulted_exception_spec)
6351 << getSpecialMember(MD), PDiag(),
6352 ImplicitType, SourceLocation(),
6353 SpecifiedType, MD->getLocation());
6354}
6355
6356void Sema::CheckDelayedMemberExceptionSpecs() {
6357 decltype(DelayedExceptionSpecChecks) Checks;
6358 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6359
6360 std::swap(Checks, DelayedExceptionSpecChecks);
6361 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6362
6363 // Perform any deferred checking of exception specifications for virtual
6364 // destructors.
6365 for (auto &Check : Checks)
6366 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6367
6368 // Check that any explicitly-defaulted methods have exception specifications
6369 // compatible with their implicit exception specifications.
6370 for (auto &Spec : Specs)
6371 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6372}
6373
6374namespace {
6375/// CRTP base class for visiting operations performed by a special member
6376/// function (or inherited constructor).
6377template<typename Derived>
6378struct SpecialMemberVisitor {
6379 Sema &S;
6380 CXXMethodDecl *MD;
6381 Sema::CXXSpecialMember CSM;
6382 Sema::InheritedConstructorInfo *ICI;
6383
6384 // Properties of the special member, computed for convenience.
6385 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6386
6387 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6388 Sema::InheritedConstructorInfo *ICI)
6389 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6390 switch (CSM) {
6391 case Sema::CXXDefaultConstructor:
6392 case Sema::CXXCopyConstructor:
6393 case Sema::CXXMoveConstructor:
6394 IsConstructor = true;
6395 break;
6396 case Sema::CXXCopyAssignment:
6397 case Sema::CXXMoveAssignment:
6398 IsAssignment = true;
6399 break;
6400 case Sema::CXXDestructor:
6401 break;
6402 case Sema::CXXInvalid:
6403 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6403)
;
6404 }
6405
6406 if (MD->getNumParams()) {
6407 if (const ReferenceType *RT =
6408 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6409 ConstArg = RT->getPointeeType().isConstQualified();
6410 }
6411 }
6412
6413 Derived &getDerived() { return static_cast<Derived&>(*this); }
6414
6415 /// Is this a "move" special member?
6416 bool isMove() const {
6417 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6418 }
6419
6420 /// Look up the corresponding special member in the given class.
6421 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6422 unsigned Quals, bool IsMutable) {
6423 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6424 ConstArg && !IsMutable);
6425 }
6426
6427 /// Look up the constructor for the specified base class to see if it's
6428 /// overridden due to this being an inherited constructor.
6429 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6430 if (!ICI)
6431 return {};
6432 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6432, __PRETTY_FUNCTION__))
;
6433 auto *BaseCtor =
6434 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6435 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6436 return MD;
6437 return {};
6438 }
6439
6440 /// A base or member subobject.
6441 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6442
6443 /// Get the location to use for a subobject in diagnostics.
6444 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6445 // FIXME: For an indirect virtual base, the direct base leading to
6446 // the indirect virtual base would be a more useful choice.
6447 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6448 return B->getBaseTypeLoc();
6449 else
6450 return Subobj.get<FieldDecl*>()->getLocation();
6451 }
6452
6453 enum BasesToVisit {
6454 /// Visit all non-virtual (direct) bases.
6455 VisitNonVirtualBases,
6456 /// Visit all direct bases, virtual or not.
6457 VisitDirectBases,
6458 /// Visit all non-virtual bases, and all virtual bases if the class
6459 /// is not abstract.
6460 VisitPotentiallyConstructedBases,
6461 /// Visit all direct or virtual bases.
6462 VisitAllBases
6463 };
6464
6465 // Visit the bases and members of the class.
6466 bool visit(BasesToVisit Bases) {
6467 CXXRecordDecl *RD = MD->getParent();
6468
6469 if (Bases == VisitPotentiallyConstructedBases)
6470 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6471
6472 for (auto &B : RD->bases())
6473 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6474 getDerived().visitBase(&B))
6475 return true;
6476
6477 if (Bases == VisitAllBases)
6478 for (auto &B : RD->vbases())
6479 if (getDerived().visitBase(&B))
6480 return true;
6481
6482 for (auto *F : RD->fields())
6483 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6484 getDerived().visitField(F))
6485 return true;
6486
6487 return false;
6488 }
6489};
6490}
6491
6492namespace {
6493struct SpecialMemberDeletionInfo
6494 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6495 bool Diagnose;
6496
6497 SourceLocation Loc;
6498
6499 bool AllFieldsAreConst;
6500
6501 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6502 Sema::CXXSpecialMember CSM,
6503 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6504 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6505 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6506
6507 bool inUnion() const { return MD->getParent()->isUnion(); }
6508
6509 Sema::CXXSpecialMember getEffectiveCSM() {
6510 return ICI ? Sema::CXXInvalid : CSM;
6511 }
6512
6513 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6514 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6515
6516 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6517 bool shouldDeleteForField(FieldDecl *FD);
6518 bool shouldDeleteForAllConstMembers();
6519
6520 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6521 unsigned Quals);
6522 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6523 Sema::SpecialMemberOverloadResult SMOR,
6524 bool IsDtorCallInCtor);
6525
6526 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6527};
6528}
6529
6530/// Is the given special member inaccessible when used on the given
6531/// sub-object.
6532bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6533 CXXMethodDecl *target) {
6534 /// If we're operating on a base class, the object type is the
6535 /// type of this special member.
6536 QualType objectTy;
6537 AccessSpecifier access = target->getAccess();
6538 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6539 objectTy = S.Context.getTypeDeclType(MD->getParent());
6540 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6541
6542 // If we're operating on a field, the object type is the type of the field.
6543 } else {
6544 objectTy = S.Context.getTypeDeclType(target->getParent());
6545 }
6546
6547 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6548}
6549
6550/// Check whether we should delete a special member due to the implicit
6551/// definition containing a call to a special member of a subobject.
6552bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6553 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6554 bool IsDtorCallInCtor) {
6555 CXXMethodDecl *Decl = SMOR.getMethod();
6556 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6557
6558 int DiagKind = -1;
6559
6560 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6561 DiagKind = !Decl ? 0 : 1;
6562 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6563 DiagKind = 2;
6564 else if (!isAccessible(Subobj, Decl))
6565 DiagKind = 3;
6566 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6567 !Decl->isTrivial()) {
6568 // A member of a union must have a trivial corresponding special member.
6569 // As a weird special case, a destructor call from a union's constructor
6570 // must be accessible and non-deleted, but need not be trivial. Such a
6571 // destructor is never actually called, but is semantically checked as
6572 // if it were.
6573 DiagKind = 4;
6574 }
6575
6576 if (DiagKind == -1)
6577 return false;
6578
6579 if (Diagnose) {
6580 if (Field) {
6581 S.Diag(Field->getLocation(),
6582 diag::note_deleted_special_member_class_subobject)
6583 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6584 << Field << DiagKind << IsDtorCallInCtor;
6585 } else {
6586 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6587 S.Diag(Base->getLocStart(),
6588 diag::note_deleted_special_member_class_subobject)
6589 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6590 << Base->getType() << DiagKind << IsDtorCallInCtor;
6591 }
6592
6593 if (DiagKind == 1)
6594 S.NoteDeletedFunction(Decl);
6595 // FIXME: Explain inaccessibility if DiagKind == 3.
6596 }
6597
6598 return true;
6599}
6600
6601/// Check whether we should delete a special member function due to having a
6602/// direct or virtual base class or non-static data member of class type M.
6603bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6604 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6605 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6606 bool IsMutable = Field && Field->isMutable();
6607
6608 // C++11 [class.ctor]p5:
6609 // -- any direct or virtual base class, or non-static data member with no
6610 // brace-or-equal-initializer, has class type M (or array thereof) and
6611 // either M has no default constructor or overload resolution as applied
6612 // to M's default constructor results in an ambiguity or in a function
6613 // that is deleted or inaccessible
6614 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6615 // -- a direct or virtual base class B that cannot be copied/moved because
6616 // overload resolution, as applied to B's corresponding special member,
6617 // results in an ambiguity or a function that is deleted or inaccessible
6618 // from the defaulted special member
6619 // C++11 [class.dtor]p5:
6620 // -- any direct or virtual base class [...] has a type with a destructor
6621 // that is deleted or inaccessible
6622 if (!(CSM == Sema::CXXDefaultConstructor &&
6623 Field && Field->hasInClassInitializer()) &&
6624 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6625 false))
6626 return true;
6627
6628 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6629 // -- any direct or virtual base class or non-static data member has a
6630 // type with a destructor that is deleted or inaccessible
6631 if (IsConstructor) {
6632 Sema::SpecialMemberOverloadResult SMOR =
6633 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6634 false, false, false, false, false);
6635 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6636 return true;
6637 }
6638
6639 return false;
6640}
6641
6642/// Check whether we should delete a special member function due to the class
6643/// having a particular direct or virtual base class.
6644bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6645 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6646 // If program is correct, BaseClass cannot be null, but if it is, the error
6647 // must be reported elsewhere.
6648 if (!BaseClass)
6649 return false;
6650 // If we have an inheriting constructor, check whether we're calling an
6651 // inherited constructor instead of a default constructor.
6652 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6653 if (auto *BaseCtor = SMOR.getMethod()) {
6654 // Note that we do not check access along this path; other than that,
6655 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6656 // FIXME: Check that the base has a usable destructor! Sink this into
6657 // shouldDeleteForClassSubobject.
6658 if (BaseCtor->isDeleted() && Diagnose) {
6659 S.Diag(Base->getLocStart(),
6660 diag::note_deleted_special_member_class_subobject)
6661 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6662 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6663 S.NoteDeletedFunction(BaseCtor);
6664 }
6665 return BaseCtor->isDeleted();
6666 }
6667 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6668}
6669
6670/// Check whether we should delete a special member function due to the class
6671/// having a particular non-static data member.
6672bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6673 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6674 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6675
6676 if (CSM == Sema::CXXDefaultConstructor) {
6677 // For a default constructor, all references must be initialized in-class
6678 // and, if a union, it must have a non-const member.
6679 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6680 if (Diagnose)
6681 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6682 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6683 return true;
6684 }
6685 // C++11 [class.ctor]p5: any non-variant non-static data member of
6686 // const-qualified type (or array thereof) with no
6687 // brace-or-equal-initializer does not have a user-provided default
6688 // constructor.
6689 if (!inUnion() && FieldType.isConstQualified() &&
6690 !FD->hasInClassInitializer() &&
6691 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6692 if (Diagnose)
6693 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6694 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6695 return true;
6696 }
6697
6698 if (inUnion() && !FieldType.isConstQualified())
6699 AllFieldsAreConst = false;
6700 } else if (CSM == Sema::CXXCopyConstructor) {
6701 // For a copy constructor, data members must not be of rvalue reference
6702 // type.
6703 if (FieldType->isRValueReferenceType()) {
6704 if (Diagnose)
6705 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6706 << MD->getParent() << FD << FieldType;
6707 return true;
6708 }
6709 } else if (IsAssignment) {
6710 // For an assignment operator, data members must not be of reference type.
6711 if (FieldType->isReferenceType()) {
6712 if (Diagnose)
6713 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6714 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6715 return true;
6716 }
6717 if (!FieldRecord && FieldType.isConstQualified()) {
6718 // C++11 [class.copy]p23:
6719 // -- a non-static data member of const non-class type (or array thereof)
6720 if (Diagnose)
6721 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6722 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6723 return true;
6724 }
6725 }
6726
6727 if (FieldRecord) {
6728 // Some additional restrictions exist on the variant members.
6729 if (!inUnion() && FieldRecord->isUnion() &&
6730 FieldRecord->isAnonymousStructOrUnion()) {
6731 bool AllVariantFieldsAreConst = true;
6732
6733 // FIXME: Handle anonymous unions declared within anonymous unions.
6734 for (auto *UI : FieldRecord->fields()) {
6735 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6736
6737 if (!UnionFieldType.isConstQualified())
6738 AllVariantFieldsAreConst = false;
6739
6740 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6741 if (UnionFieldRecord &&
6742 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6743 UnionFieldType.getCVRQualifiers()))
6744 return true;
6745 }
6746
6747 // At least one member in each anonymous union must be non-const
6748 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6749 !FieldRecord->field_empty()) {
6750 if (Diagnose)
6751 S.Diag(FieldRecord->getLocation(),
6752 diag::note_deleted_default_ctor_all_const)
6753 << !!ICI << MD->getParent() << /*anonymous union*/1;
6754 return true;
6755 }
6756
6757 // Don't check the implicit member of the anonymous union type.
6758 // This is technically non-conformant, but sanity demands it.
6759 return false;
6760 }
6761
6762 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6763 FieldType.getCVRQualifiers()))
6764 return true;
6765 }
6766
6767 return false;
6768}
6769
6770/// C++11 [class.ctor] p5:
6771/// A defaulted default constructor for a class X is defined as deleted if
6772/// X is a union and all of its variant members are of const-qualified type.
6773bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6774 // This is a silly definition, because it gives an empty union a deleted
6775 // default constructor. Don't do that.
6776 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6777 bool AnyFields = false;
6778 for (auto *F : MD->getParent()->fields())
6779 if ((AnyFields = !F->isUnnamedBitfield()))
6780 break;
6781 if (!AnyFields)
6782 return false;
6783 if (Diagnose)
6784 S.Diag(MD->getParent()->getLocation(),
6785 diag::note_deleted_default_ctor_all_const)
6786 << !!ICI << MD->getParent() << /*not anonymous union*/0;
6787 return true;
6788 }
6789 return false;
6790}
6791
6792/// Determine whether a defaulted special member function should be defined as
6793/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6794/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6795bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6796 InheritedConstructorInfo *ICI,
6797 bool Diagnose) {
6798 if (MD->isInvalidDecl())
6799 return false;
6800 CXXRecordDecl *RD = MD->getParent();
6801 assert(!RD->isDependentType() && "do deletion after instantiation")((!RD->isDependentType() && "do deletion after instantiation"
) ? static_cast<void> (0) : __assert_fail ("!RD->isDependentType() && \"do deletion after instantiation\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6801, __PRETTY_FUNCTION__))
;
6802 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6803 return false;
6804
6805 // C++11 [expr.lambda.prim]p19:
6806 // The closure type associated with a lambda-expression has a
6807 // deleted (8.4.3) default constructor and a deleted copy
6808 // assignment operator.
6809 if (RD->isLambda() &&
6810 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6811 if (Diagnose)
6812 Diag(RD->getLocation(), diag::note_lambda_decl);
6813 return true;
6814 }
6815
6816 // For an anonymous struct or union, the copy and assignment special members
6817 // will never be used, so skip the check. For an anonymous union declared at
6818 // namespace scope, the constructor and destructor are used.
6819 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6820 RD->isAnonymousStructOrUnion())
6821 return false;
6822
6823 // C++11 [class.copy]p7, p18:
6824 // If the class definition declares a move constructor or move assignment
6825 // operator, an implicitly declared copy constructor or copy assignment
6826 // operator is defined as deleted.
6827 if (MD->isImplicit() &&
6828 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6829 CXXMethodDecl *UserDeclaredMove = nullptr;
6830
6831 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6832 // deletion of the corresponding copy operation, not both copy operations.
6833 // MSVC 2015 has adopted the standards conforming behavior.
6834 bool DeletesOnlyMatchingCopy =
6835 getLangOpts().MSVCCompat &&
6836 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6837
6838 if (RD->hasUserDeclaredMoveConstructor() &&
6839 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6840 if (!Diagnose) return true;
6841
6842 // Find any user-declared move constructor.
6843 for (auto *I : RD->ctors()) {
6844 if (I->isMoveConstructor()) {
6845 UserDeclaredMove = I;
6846 break;
6847 }
6848 }
6849 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6849, __PRETTY_FUNCTION__))
;
6850 } else if (RD->hasUserDeclaredMoveAssignment() &&
6851 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6852 if (!Diagnose) return true;
6853
6854 // Find any user-declared move assignment operator.
6855 for (auto *I : RD->methods()) {
6856 if (I->isMoveAssignmentOperator()) {
6857 UserDeclaredMove = I;
6858 break;
6859 }
6860 }
6861 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6861, __PRETTY_FUNCTION__))
;
6862 }
6863
6864 if (UserDeclaredMove) {
6865 Diag(UserDeclaredMove->getLocation(),
6866 diag::note_deleted_copy_user_declared_move)
6867 << (CSM == CXXCopyAssignment) << RD
6868 << UserDeclaredMove->isMoveAssignmentOperator();
6869 return true;
6870 }
6871 }
6872
6873 // Do access control from the special member function
6874 ContextRAII MethodContext(*this, MD);
6875
6876 // C++11 [class.dtor]p5:
6877 // -- for a virtual destructor, lookup of the non-array deallocation function
6878 // results in an ambiguity or in a function that is deleted or inaccessible
6879 if (CSM == CXXDestructor && MD->isVirtual()) {
6880 FunctionDecl *OperatorDelete = nullptr;
6881 DeclarationName Name =
6882 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6883 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6884 OperatorDelete, /*Diagnose*/false)) {
6885 if (Diagnose)
6886 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6887 return true;
6888 }
6889 }
6890
6891 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6892
6893 // Per DR1611, do not consider virtual bases of constructors of abstract
6894 // classes, since we are not going to construct them.
6895 // Per DR1658, do not consider virtual bases of destructors of abstract
6896 // classes either.
6897 // Per DR2180, for assignment operators we only assign (and thus only
6898 // consider) direct bases.
6899 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6900 : SMI.VisitPotentiallyConstructedBases))
6901 return true;
6902
6903 if (SMI.shouldDeleteForAllConstMembers())
6904 return true;
6905
6906 if (getLangOpts().CUDA) {
6907 // We should delete the special member in CUDA mode if target inference
6908 // failed.
6909 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6910 Diagnose);
6911 }
6912
6913 return false;
6914}
6915
6916/// Perform lookup for a special member of the specified kind, and determine
6917/// whether it is trivial. If the triviality can be determined without the
6918/// lookup, skip it. This is intended for use when determining whether a
6919/// special member of a containing object is trivial, and thus does not ever
6920/// perform overload resolution for default constructors.
6921///
6922/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6923/// member that was most likely to be intended to be trivial, if any.
6924static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6925 Sema::CXXSpecialMember CSM, unsigned Quals,
6926 bool ConstRHS, CXXMethodDecl **Selected) {
6927 if (Selected)
6928 *Selected = nullptr;
6929
6930 switch (CSM) {
6931 case Sema::CXXInvalid:
6932 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6932)
;
6933
6934 case Sema::CXXDefaultConstructor:
6935 // C++11 [class.ctor]p5:
6936 // A default constructor is trivial if:
6937 // - all the [direct subobjects] have trivial default constructors
6938 //
6939 // Note, no overload resolution is performed in this case.
6940 if (RD->hasTrivialDefaultConstructor())
6941 return true;
6942
6943 if (Selected) {
6944 // If there's a default constructor which could have been trivial, dig it
6945 // out. Otherwise, if there's any user-provided default constructor, point
6946 // to that as an example of why there's not a trivial one.
6947 CXXConstructorDecl *DefCtor = nullptr;
6948 if (RD->needsImplicitDefaultConstructor())
6949 S.DeclareImplicitDefaultConstructor(RD);
6950 for (auto *CI : RD->ctors()) {
6951 if (!CI->isDefaultConstructor())
6952 continue;
6953 DefCtor = CI;
6954 if (!DefCtor->isUserProvided())
6955 break;
6956 }
6957
6958 *Selected = DefCtor;
6959 }
6960
6961 return false;
6962
6963 case Sema::CXXDestructor:
6964 // C++11 [class.dtor]p5:
6965 // A destructor is trivial if:
6966 // - all the direct [subobjects] have trivial destructors
6967 if (RD->hasTrivialDestructor())
6968 return true;
6969
6970 if (Selected) {
6971 if (RD->needsImplicitDestructor())
6972 S.DeclareImplicitDestructor(RD);
6973 *Selected = RD->getDestructor();
6974 }
6975
6976 return false;
6977
6978 case Sema::CXXCopyConstructor:
6979 // C++11 [class.copy]p12:
6980 // A copy constructor is trivial if:
6981 // - the constructor selected to copy each direct [subobject] is trivial
6982 if (RD->hasTrivialCopyConstructor()) {
6983 if (Quals == Qualifiers::Const)
6984 // We must either select the trivial copy constructor or reach an
6985 // ambiguity; no need to actually perform overload resolution.
6986 return true;
6987 } else if (!Selected) {
6988 return false;
6989 }
6990 // In C++98, we are not supposed to perform overload resolution here, but we
6991 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6992 // cases like B as having a non-trivial copy constructor:
6993 // struct A { template<typename T> A(T&); };
6994 // struct B { mutable A a; };
6995 goto NeedOverloadResolution;
6996
6997 case Sema::CXXCopyAssignment:
6998 // C++11 [class.copy]p25:
6999 // A copy assignment operator is trivial if:
7000 // - the assignment operator selected to copy each direct [subobject] is
7001 // trivial
7002 if (RD->hasTrivialCopyAssignment()) {
7003 if (Quals == Qualifiers::Const)
7004 return true;
7005 } else if (!Selected) {
7006 return false;
7007 }
7008 // In C++98, we are not supposed to perform overload resolution here, but we
7009 // treat that as a language defect.
7010 goto NeedOverloadResolution;
7011
7012 case Sema::CXXMoveConstructor:
7013 case Sema::CXXMoveAssignment:
7014 NeedOverloadResolution:
7015 Sema::SpecialMemberOverloadResult SMOR =
7016 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7017
7018 // The standard doesn't describe how to behave if the lookup is ambiguous.
7019 // We treat it as not making the member non-trivial, just like the standard
7020 // mandates for the default constructor. This should rarely matter, because
7021 // the member will also be deleted.
7022 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7023 return true;
7024
7025 if (!SMOR.getMethod()) {
7026 assert(SMOR.getKind() ==((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7027, __PRETTY_FUNCTION__))
7027 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7027, __PRETTY_FUNCTION__))
;
7028 return false;
7029 }
7030
7031 // We deliberately don't check if we found a deleted special member. We're
7032 // not supposed to!
7033 if (Selected)
7034 *Selected = SMOR.getMethod();
7035 return SMOR.getMethod()->isTrivial();
7036 }
7037
7038 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7038)
;
7039}
7040
7041static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7042 for (auto *CI : RD->ctors())
7043 if (!CI->isImplicit())
7044 return CI;
7045
7046 // Look for constructor templates.
7047 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7048 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7049 if (CXXConstructorDecl *CD =
7050 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7051 return CD;
7052 }
7053
7054 return nullptr;
7055}
7056
7057/// The kind of subobject we are checking for triviality. The values of this
7058/// enumeration are used in diagnostics.
7059enum TrivialSubobjectKind {
7060 /// The subobject is a base class.
7061 TSK_BaseClass,
7062 /// The subobject is a non-static data member.
7063 TSK_Field,
7064 /// The object is actually the complete object.
7065 TSK_CompleteObject
7066};
7067
7068/// Check whether the special member selected for a given type would be trivial.
7069static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7070 QualType SubType, bool ConstRHS,
7071 Sema::CXXSpecialMember CSM,
7072 TrivialSubobjectKind Kind,
7073 bool Diagnose) {
7074 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7075 if (!SubRD)
7076 return true;
7077
7078 CXXMethodDecl *Selected;
7079 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7080 ConstRHS, Diagnose ? &Selected : nullptr))
7081 return true;
7082
7083 if (Diagnose) {
7084 if (ConstRHS)
7085 SubType.addConst();
7086
7087 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7088 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7089 << Kind << SubType.getUnqualifiedType();
7090 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7091 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7092 } else if (!Selected)
7093 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7094 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7095 else if (Selected->isUserProvided()) {
7096 if (Kind == TSK_CompleteObject)
7097 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7098 << Kind << SubType.getUnqualifiedType() << CSM;
7099 else {
7100 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7101 << Kind << SubType.getUnqualifiedType() << CSM;
7102 S.Diag(Selected->getLocation(), diag::note_declared_at);
7103 }
7104 } else {
7105 if (Kind != TSK_CompleteObject)
7106 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7107 << Kind << SubType.getUnqualifiedType() << CSM;
7108
7109 // Explain why the defaulted or deleted special member isn't trivial.
7110 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7111 }
7112 }
7113
7114 return false;
7115}
7116
7117/// Check whether the members of a class type allow a special member to be
7118/// trivial.
7119static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7120 Sema::CXXSpecialMember CSM,
7121 bool ConstArg, bool Diagnose) {
7122 for (const auto *FI : RD->fields()) {
7123 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7124 continue;
7125
7126 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7127
7128 // Pretend anonymous struct or union members are members of this class.
7129 if (FI->isAnonymousStructOrUnion()) {
7130 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7131 CSM, ConstArg, Diagnose))
7132 return false;
7133 continue;
7134 }
7135
7136 // C++11 [class.ctor]p5:
7137 // A default constructor is trivial if [...]
7138 // -- no non-static data member of its class has a
7139 // brace-or-equal-initializer
7140 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7141 if (Diagnose)
7142 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7143 return false;
7144 }
7145
7146 // Objective C ARC 4.3.5:
7147 // [...] nontrivally ownership-qualified types are [...] not trivially
7148 // default constructible, copy constructible, move constructible, copy
7149 // assignable, move assignable, or destructible [...]
7150 if (S.getLangOpts().ObjCAutoRefCount &&
7151 FieldType.hasNonTrivialObjCLifetime()) {
7152 if (Diagnose)
7153 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7154 << RD << FieldType.getObjCLifetime();
7155 return false;
7156 }
7157
7158 bool ConstRHS = ConstArg && !FI->isMutable();
7159 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7160 CSM, TSK_Field, Diagnose))
7161 return false;
7162 }
7163
7164 return true;
7165}
7166
7167/// Diagnose why the specified class does not have a trivial special member of
7168/// the given kind.
7169void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7170 QualType Ty = Context.getRecordType(RD);
7171
7172 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7173 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7174 TSK_CompleteObject, /*Diagnose*/true);
7175}
7176
7177/// Determine whether a defaulted or deleted special member function is trivial,
7178/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7179/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7180bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7181 bool Diagnose) {
7182 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")((!MD->isUserProvided() && CSM != CXXInvalid &&
"not special enough") ? static_cast<void> (0) : __assert_fail
("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7182, __PRETTY_FUNCTION__))
;
7183
7184 CXXRecordDecl *RD = MD->getParent();
7185
7186 bool ConstArg = false;
7187
7188 // C++11 [class.copy]p12, p25: [DR1593]
7189 // A [special member] is trivial if [...] its parameter-type-list is
7190 // equivalent to the parameter-type-list of an implicit declaration [...]
7191 switch (CSM) {
7192 case CXXDefaultConstructor:
7193 case CXXDestructor:
7194 // Trivial default constructors and destructors cannot have parameters.
7195 break;
7196
7197 case CXXCopyConstructor:
7198 case CXXCopyAssignment: {
7199 // Trivial copy operations always have const, non-volatile parameter types.
7200 ConstArg = true;
7201 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7202 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7203 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7204 if (Diagnose)
7205 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7206 << Param0->getSourceRange() << Param0->getType()
7207 << Context.getLValueReferenceType(
7208 Context.getRecordType(RD).withConst());
7209 return false;
7210 }
7211 break;
7212 }
7213
7214 case CXXMoveConstructor:
7215 case CXXMoveAssignment: {
7216 // Trivial move operations always have non-cv-qualified parameters.
7217 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7218 const RValueReferenceType *RT =
7219 Param0->getType()->getAs<RValueReferenceType>();
7220 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7221 if (Diagnose)
7222 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7223 << Param0->getSourceRange() << Param0->getType()
7224 << Context.getRValueReferenceType(Context.getRecordType(RD));
7225 return false;
7226 }
7227 break;
7228 }
7229
7230 case CXXInvalid:
7231 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7231)
;
7232 }
7233
7234 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7235 if (Diagnose)
7236 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7237 diag::note_nontrivial_default_arg)
7238 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7239 return false;
7240 }
7241 if (MD->isVariadic()) {
7242 if (Diagnose)
7243 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7244 return false;
7245 }
7246
7247 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7248 // A copy/move [constructor or assignment operator] is trivial if
7249 // -- the [member] selected to copy/move each direct base class subobject
7250 // is trivial
7251 //
7252 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7253 // A [default constructor or destructor] is trivial if
7254 // -- all the direct base classes have trivial [default constructors or
7255 // destructors]
7256 for (const auto &BI : RD->bases())
7257 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7258 ConstArg, CSM, TSK_BaseClass, Diagnose))
7259 return false;
7260
7261 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7262 // A copy/move [constructor or assignment operator] for a class X is
7263 // trivial if
7264 // -- for each non-static data member of X that is of class type (or array
7265 // thereof), the constructor selected to copy/move that member is
7266 // trivial
7267 //
7268 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7269 // A [default constructor or destructor] is trivial if
7270 // -- for all of the non-static data members of its class that are of class
7271 // type (or array thereof), each such class has a trivial [default
7272 // constructor or destructor]
7273 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7274 return false;
7275
7276 // C++11 [class.dtor]p5:
7277 // A destructor is trivial if [...]
7278 // -- the destructor is not virtual
7279 if (CSM == CXXDestructor && MD->isVirtual()) {
7280 if (Diagnose)
7281 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7282 return false;
7283 }
7284
7285 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7286 // A [special member] for class X is trivial if [...]
7287 // -- class X has no virtual functions and no virtual base classes
7288 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7289 if (!Diagnose)
7290 return false;
7291
7292 if (RD->getNumVBases()) {
7293 // Check for virtual bases. We already know that the corresponding
7294 // member in all bases is trivial, so vbases must all be direct.
7295 CXXBaseSpecifier &BS = *RD->vbases_begin();
7296 assert(BS.isVirtual())((BS.isVirtual()) ? static_cast<void> (0) : __assert_fail
("BS.isVirtual()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7296, __PRETTY_FUNCTION__))
;
7297 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7298 return false;
7299 }
7300
7301 // Must have a virtual method.
7302 for (const auto *MI : RD->methods()) {
7303 if (MI->isVirtual()) {
7304 SourceLocation MLoc = MI->getLocStart();
7305 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7306 return false;
7307 }
7308 }
7309
7310 llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7310)
;
7311 }
7312
7313 // Looks like it's trivial!
7314 return true;
7315}
7316
7317namespace {
7318struct FindHiddenVirtualMethod {
7319 Sema *S;
7320 CXXMethodDecl *Method;
7321 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7322 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7323
7324private:
7325 /// Check whether any most overriden method from MD in Methods
7326 static bool CheckMostOverridenMethods(
7327 const CXXMethodDecl *MD,
7328 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7329 if (MD->size_overridden_methods() == 0)
7330 return Methods.count(MD->getCanonicalDecl());
7331 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7332 E = MD->end_overridden_methods();
7333 I != E; ++I)
7334 if (CheckMostOverridenMethods(*I, Methods))
7335 return true;
7336 return false;
7337 }
7338
7339public:
7340 /// Member lookup function that determines whether a given C++
7341 /// method overloads virtual methods in a base class without overriding any,
7342 /// to be used with CXXRecordDecl::lookupInBases().
7343 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7344 RecordDecl *BaseRecord =
7345 Specifier->getType()->getAs<RecordType>()->getDecl();
7346
7347 DeclarationName Name = Method->getDeclName();
7348 assert(Name.getNameKind() == DeclarationName::Identifier)((Name.getNameKind() == DeclarationName::Identifier) ? static_cast
<void> (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7348, __PRETTY_FUNCTION__))
;
7349
7350 bool foundSameNameMethod = false;
7351 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7352 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7353 Path.Decls = Path.Decls.slice(1)) {
7354 NamedDecl *D = Path.Decls.front();
7355 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7356 MD = MD->getCanonicalDecl();
7357 foundSameNameMethod = true;
7358 // Interested only in hidden virtual methods.
7359 if (!MD->isVirtual())
7360 continue;
7361 // If the method we are checking overrides a method from its base
7362 // don't warn about the other overloaded methods. Clang deviates from
7363 // GCC by only diagnosing overloads of inherited virtual functions that
7364 // do not override any other virtual functions in the base. GCC's
7365 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7366 // function from a base class. These cases may be better served by a
7367 // warning (not specific to virtual functions) on call sites when the
7368 // call would select a different function from the base class, were it
7369 // visible.
7370 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7371 if (!S->IsOverload(Method, MD, false))
7372 return true;
7373 // Collect the overload only if its hidden.
7374 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7375 overloadedMethods.push_back(MD);
7376 }
7377 }
7378
7379 if (foundSameNameMethod)
7380 OverloadedMethods.append(overloadedMethods.begin(),
7381 overloadedMethods.end());
7382 return foundSameNameMethod;
7383 }
7384};
7385} // end anonymous namespace
7386
7387/// \brief Add the most overriden methods from MD to Methods
7388static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7389 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7390 if (MD->size_overridden_methods() == 0)
7391 Methods.insert(MD->getCanonicalDecl());
7392 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7393 E = MD->end_overridden_methods();
7394 I != E; ++I)
7395 AddMostOverridenMethods(*I, Methods);
7396}
7397
7398/// \brief Check if a method overloads virtual methods in a base class without
7399/// overriding any.
7400void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7401 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7402 if (!MD->getDeclName().isIdentifier())
7403 return;
7404
7405 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7406 /*bool RecordPaths=*/false,
7407 /*bool DetectVirtual=*/false);
7408 FindHiddenVirtualMethod FHVM;
7409 FHVM.Method = MD;
7410 FHVM.S = this;
7411
7412 // Keep the base methods that were overriden or introduced in the subclass
7413 // by 'using' in a set. A base method not in this set is hidden.
7414 CXXRecordDecl *DC = MD->getParent();
7415 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7416 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7417 NamedDecl *ND = *I;
7418 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7419 ND = shad->getTargetDecl();
7420 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7421 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7422 }
7423
7424 if (DC->lookupInBases(FHVM, Paths))
7425 OverloadedMethods = FHVM.OverloadedMethods;
7426}
7427
7428void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7429 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7430 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7431 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7432 PartialDiagnostic PD = PDiag(
7433 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7434 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7435 Diag(overloadedMD->getLocation(), PD);
7436 }
7437}
7438
7439/// \brief Diagnose methods which overload virtual methods in a base class
7440/// without overriding any.
7441void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7442 if (MD->isInvalidDecl())
7443 return;
7444
7445 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7446 return;
7447
7448 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7449 FindHiddenVirtualMethods(MD, OverloadedMethods);
7450 if (!OverloadedMethods.empty()) {
7451 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7452 << MD << (OverloadedMethods.size() > 1);
7453
7454 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7455 }
7456}
7457
7458void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7459 Decl *TagDecl,
7460 SourceLocation LBrac,
7461 SourceLocation RBrac,
7462 AttributeList *AttrList) {
7463 if (!TagDecl)
7464 return;
7465
7466 AdjustDeclIfTemplate(TagDecl);
7467
7468 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7469 if (l->getKind() != AttributeList::AT_Visibility)
7470 continue;
7471 l->setInvalid();
7472 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7473 l->getName();
7474 }
7475
7476 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7477 // strict aliasing violation!
7478 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7479 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7480
7481 CheckCompletedCXXClass(
7482 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7483}
7484
7485/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7486/// special functions, such as the default constructor, copy
7487/// constructor, or destructor, to the given C++ class (C++
7488/// [special]p1). This routine can only be executed just before the
7489/// definition of the class is complete.
7490void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7491 if (ClassDecl->needsImplicitDefaultConstructor()) {
7492 ++ASTContext::NumImplicitDefaultConstructors;
7493
7494 if (ClassDecl->hasInheritedConstructor())
7495 DeclareImplicitDefaultConstructor(ClassDecl);
7496 }
7497
7498 if (ClassDecl->needsImplicitCopyConstructor()) {
7499 ++ASTContext::NumImplicitCopyConstructors;
7500
7501 // If the properties or semantics of the copy constructor couldn't be
7502 // determined while the class was being declared, force a declaration
7503 // of it now.
7504 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7505 ClassDecl->hasInheritedConstructor())
7506 DeclareImplicitCopyConstructor(ClassDecl);
7507 // For the MS ABI we need to know whether the copy ctor is deleted. A
7508 // prerequisite for deleting the implicit copy ctor is that the class has a
7509 // move ctor or move assignment that is either user-declared or whose
7510 // semantics are inherited from a subobject. FIXME: We should provide a more
7511 // direct way for CodeGen to ask whether the constructor was deleted.
7512 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7513 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7514 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7515 ClassDecl->hasUserDeclaredMoveAssignment() ||
7516 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7517 DeclareImplicitCopyConstructor(ClassDecl);
7518 }
7519
7520 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7521 ++ASTContext::NumImplicitMoveConstructors;
7522
7523 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7524 ClassDecl->hasInheritedConstructor())
7525 DeclareImplicitMoveConstructor(ClassDecl);
7526 }
7527
7528 if (ClassDecl->needsImplicitCopyAssignment()) {
7529 ++ASTContext::NumImplicitCopyAssignmentOperators;
7530
7531 // If we have a dynamic class, then the copy assignment operator may be
7532 // virtual, so we have to declare it immediately. This ensures that, e.g.,
7533 // it shows up in the right place in the vtable and that we diagnose
7534 // problems with the implicit exception specification.
7535 if (ClassDecl->isDynamicClass() ||
7536 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7537 ClassDecl->hasInheritedAssignment())
7538 DeclareImplicitCopyAssignment(ClassDecl);
7539 }
7540
7541 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7542 ++ASTContext::NumImplicitMoveAssignmentOperators;
7543
7544 // Likewise for the move assignment operator.
7545 if (ClassDecl->isDynamicClass() ||
7546 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7547 ClassDecl->hasInheritedAssignment())
7548 DeclareImplicitMoveAssignment(ClassDecl);
7549 }
7550
7551 if (ClassDecl->needsImplicitDestructor()) {
7552 ++ASTContext::NumImplicitDestructors;
7553
7554 // If we have a dynamic class, then the destructor may be virtual, so we
7555 // have to declare the destructor immediately. This ensures that, e.g., it
7556 // shows up in the right place in the vtable and that we diagnose problems
7557 // with the implicit exception specification.
7558 if (ClassDecl->isDynamicClass() ||
7559 ClassDecl->needsOverloadResolutionForDestructor())
7560 DeclareImplicitDestructor(ClassDecl);
7561 }
7562}
7563
7564unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7565 if (!D)
7566 return 0;
7567
7568 // The order of template parameters is not important here. All names
7569 // get added to the same scope.
7570 SmallVector<TemplateParameterList *, 4> ParameterLists;
7571
7572 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7573 D = TD->getTemplatedDecl();
7574
7575 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7576 ParameterLists.push_back(PSD->getTemplateParameters());
7577
7578 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7579 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7580 ParameterLists.push_back(DD->getTemplateParameterList(i));
7581
7582 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7583 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7584 ParameterLists.push_back(FTD->getTemplateParameters());
7585 }
7586 }
7587
7588 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7589 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7590 ParameterLists.push_back(TD->getTemplateParameterList(i));
7591
7592 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7593 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7594 ParameterLists.push_back(CTD->getTemplateParameters());
7595 }
7596 }
7597
7598 unsigned Count = 0;
7599 for (TemplateParameterList *Params : ParameterLists) {
7600 if (Params->size() > 0)
7601 // Ignore explicit specializations; they don't contribute to the template
7602 // depth.
7603 ++Count;
7604 for (NamedDecl *Param : *Params) {
7605 if (Param->getDeclName()) {
7606 S->AddDecl(Param);
7607 IdResolver.AddDecl(Param);
7608 }
7609 }
7610 }
7611
7612 return Count;
7613}
7614
7615void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7616 if (!RecordD) return;
7617 AdjustDeclIfTemplate(RecordD);
7618 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7619 PushDeclContext(S, Record);
7620}
7621
7622void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7623 if (!RecordD) return;
7624 PopDeclContext();
7625}
7626
7627/// This is used to implement the constant expression evaluation part of the
7628/// attribute enable_if extension. There is nothing in standard C++ which would
7629/// require reentering parameters.
7630void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7631 if (!Param)
7632 return;
7633
7634 S->AddDecl(Param);
7635 if (Param->getDeclName())
7636 IdResolver.AddDecl(Param);
7637}
7638
7639/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7640/// parsing a top-level (non-nested) C++ class, and we are now
7641/// parsing those parts of the given Method declaration that could
7642/// not be parsed earlier (C++ [class.mem]p2), such as default
7643/// arguments. This action should enter the scope of the given
7644/// Method declaration as if we had just parsed the qualified method
7645/// name. However, it should not bring the parameters into scope;
7646/// that will be performed by ActOnDelayedCXXMethodParameter.
7647void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7648}
7649
7650/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7651/// C++ method declaration. We're (re-)introducing the given
7652/// function parameter into scope for use in parsing later parts of
7653/// the method declaration. For example, we could see an
7654/// ActOnParamDefaultArgument event for this parameter.
7655void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7656 if (!ParamD)
7657 return;
7658
7659 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7660
7661 // If this parameter has an unparsed default argument, clear it out
7662 // to make way for the parsed default argument.
7663 if (Param->hasUnparsedDefaultArg())
7664 Param->setDefaultArg(nullptr);
7665
7666 S->AddDecl(Param);
7667 if (Param->getDeclName())
7668 IdResolver.AddDecl(Param);
7669}
7670
7671/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7672/// processing the delayed method declaration for Method. The method
7673/// declaration is now considered finished. There may be a separate
7674/// ActOnStartOfFunctionDef action later (not necessarily
7675/// immediately!) for this method, if it was also defined inside the
7676/// class body.
7677void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7678 if (!MethodD)
7679 return;
7680
7681 AdjustDeclIfTemplate(MethodD);
7682
7683 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7684
7685 // Now that we have our default arguments, check the constructor
7686 // again. It could produce additional diagnostics or affect whether
7687 // the class has implicitly-declared destructors, among other
7688 // things.
7689 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7690 CheckConstructor(Constructor);
7691
7692 // Check the default arguments, which we may have added.
7693 if (!Method->isInvalidDecl())
7694 CheckCXXDefaultArguments(Method);
7695}
7696
7697/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7698/// the well-formedness of the constructor declarator @p D with type @p
7699/// R. If there are any errors in the declarator, this routine will
7700/// emit diagnostics and set the invalid bit to true. In any case, the type
7701/// will be updated to reflect a well-formed type for the constructor and
7702/// returned.
7703QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7704 StorageClass &SC) {
7705 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7706
7707 // C++ [class.ctor]p3:
7708 // A constructor shall not be virtual (10.3) or static (9.4). A
7709 // constructor can be invoked for a const, volatile or const
7710 // volatile object. A constructor shall not be declared const,
7711 // volatile, or const volatile (9.3.2).
7712 if (isVirtual) {
7713 if (!D.isInvalidType())
7714 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7715 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7716 << SourceRange(D.getIdentifierLoc());
7717 D.setInvalidType();
7718 }
7719 if (SC == SC_Static) {
7720 if (!D.isInvalidType())
7721 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7722 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7723 << SourceRange(D.getIdentifierLoc());
7724 D.setInvalidType();
7725 SC = SC_None;
7726 }
7727
7728 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7729 diagnoseIgnoredQualifiers(
7730 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7731 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7732 D.getDeclSpec().getRestrictSpecLoc(),
7733 D.getDeclSpec().getAtomicSpecLoc());
7734 D.setInvalidType();
7735 }
7736
7737 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7738 if (FTI.TypeQuals != 0) {
7739 if (FTI.TypeQuals & Qualifiers::Const)
7740 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7741 << "const" << SourceRange(D.getIdentifierLoc());
7742 if (FTI.TypeQuals & Qualifiers::Volatile)
7743 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7744 << "volatile" << SourceRange(D.getIdentifierLoc());
7745 if (FTI.TypeQuals & Qualifiers::Restrict)
7746 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7747 << "restrict" << SourceRange(D.getIdentifierLoc());
7748 D.setInvalidType();
7749 }
7750
7751 // C++0x [class.ctor]p4:
7752 // A constructor shall not be declared with a ref-qualifier.
7753 if (FTI.hasRefQualifier()) {
7754 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7755 << FTI.RefQualifierIsLValueRef
7756 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7757 D.setInvalidType();
7758 }
7759
7760 // Rebuild the function type "R" without any type qualifiers (in
7761 // case any of the errors above fired) and with "void" as the
7762 // return type, since constructors don't have return types.
7763 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7764 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7765 return R;
7766
7767 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7768 EPI.TypeQuals = 0;
7769 EPI.RefQualifier = RQ_None;
7770
7771 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7772}
7773
7774/// CheckConstructor - Checks a fully-formed constructor for
7775/// well-formedness, issuing any diagnostics required. Returns true if
7776/// the constructor declarator is invalid.
7777void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7778 CXXRecordDecl *ClassDecl
7779 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7780 if (!ClassDecl)
7781 return Constructor->setInvalidDecl();
7782
7783 // C++ [class.copy]p3:
7784 // A declaration of a constructor for a class X is ill-formed if
7785 // its first parameter is of type (optionally cv-qualified) X and
7786 // either there are no other parameters or else all other
7787 // parameters have default arguments.
7788 if (!Constructor->isInvalidDecl() &&
7789 ((Constructor->getNumParams() == 1) ||
7790 (Constructor->getNumParams() > 1 &&
7791 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7792 Constructor->getTemplateSpecializationKind()
7793 != TSK_ImplicitInstantiation) {
7794 QualType ParamType = Constructor->getParamDecl(0)->getType();
7795 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7796 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7797 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7798 const char *ConstRef
7799 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7800 : " const &";
7801 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7802 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7803
7804 // FIXME: Rather that making the constructor invalid, we should endeavor
7805 // to fix the type.
7806 Constructor->setInvalidDecl();
7807 }
7808 }
7809}
7810
7811/// CheckDestructor - Checks a fully-formed destructor definition for
7812/// well-formedness, issuing any diagnostics required. Returns true
7813/// on error.
7814bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7815 CXXRecordDecl *RD = Destructor->getParent();
7816
7817 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7818 SourceLocation Loc;
7819
7820 if (!Destructor->isImplicit())
7821 Loc = Destructor->getLocation();
7822 else
7823 Loc = RD->getLocation();
7824
7825 // If we have a virtual destructor, look up the deallocation function
7826 if (FunctionDecl *OperatorDelete =
7827 FindDeallocationFunctionForDestructor(Loc, RD)) {
7828 MarkFunctionReferenced(Loc, OperatorDelete);
7829 Destructor->setOperatorDelete(OperatorDelete);
7830 }
7831 }
7832
7833 return false;
7834}
7835
7836/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7837/// the well-formednes of the destructor declarator @p D with type @p
7838/// R. If there are any errors in the declarator, this routine will
7839/// emit diagnostics and set the declarator to invalid. Even if this happens,
7840/// will be updated to reflect a well-formed type for the destructor and
7841/// returned.
7842QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7843 StorageClass& SC) {
7844 // C++ [class.dtor]p1:
7845 // [...] A typedef-name that names a class is a class-name
7846 // (7.1.3); however, a typedef-name that names a class shall not
7847 // be used as the identifier in the declarator for a destructor
7848 // declaration.
7849 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7850 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7851 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7852 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7853 else if (const TemplateSpecializationType *TST =
7854 DeclaratorType->getAs<TemplateSpecializationType>())
7855 if (TST->isTypeAlias())
7856 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7857 << DeclaratorType << 1;
7858
7859 // C++ [class.dtor]p2:
7860 // A destructor is used to destroy objects of its class type. A
7861 // destructor takes no parameters, and no return type can be
7862 // specified for it (not even void). The address of a destructor
7863 // shall not be taken. A destructor shall not be static. A
7864 // destructor can be invoked for a const, volatile or const
7865 // volatile object. A destructor shall not be declared const,
7866 // volatile or const volatile (9.3.2).
7867 if (SC == SC_Static) {
7868 if (!D.isInvalidType())
7869 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7870 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7871 << SourceRange(D.getIdentifierLoc())
7872 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7873
7874 SC = SC_None;
7875 }
7876 if (!D.isInvalidType()) {
7877 // Destructors don't have return types, but the parser will
7878 // happily parse something like:
7879 //
7880 // class X {
7881 // float ~X();
7882 // };
7883 //
7884 // The return type will be eliminated later.
7885 if (D.getDeclSpec().hasTypeSpecifier())
7886 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7887 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7888 << SourceRange(D.getIdentifierLoc());
7889 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7890 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7891 SourceLocation(),
7892 D.getDeclSpec().getConstSpecLoc(),
7893 D.getDeclSpec().getVolatileSpecLoc(),
7894 D.getDeclSpec().getRestrictSpecLoc(),
7895 D.getDeclSpec().getAtomicSpecLoc());
7896 D.setInvalidType();
7897 }
7898 }
7899
7900 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7901 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7902 if (FTI.TypeQuals & Qualifiers::Const)
7903 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7904 << "const" << SourceRange(D.getIdentifierLoc());
7905 if (FTI.TypeQuals & Qualifiers::Volatile)
7906 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7907 << "volatile" << SourceRange(D.getIdentifierLoc());
7908 if (FTI.TypeQuals & Qualifiers::Restrict)
7909 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7910 << "restrict" << SourceRange(D.getIdentifierLoc());
7911 D.setInvalidType();
7912 }
7913
7914 // C++0x [class.dtor]p2:
7915 // A destructor shall not be declared with a ref-qualifier.
7916 if (FTI.hasRefQualifier()) {
7917 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7918 << FTI.RefQualifierIsLValueRef
7919 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7920 D.setInvalidType();
7921 }
7922
7923 // Make sure we don't have any parameters.
7924 if (FTIHasNonVoidParameters(FTI)) {
7925 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7926
7927 // Delete the parameters.
7928 FTI.freeParams();
7929 D.setInvalidType();
7930 }
7931
7932 // Make sure the destructor isn't variadic.
7933 if (FTI.isVariadic) {
7934 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7935 D.setInvalidType();
7936 }
7937
7938 // Rebuild the function type "R" without any type qualifiers or
7939 // parameters (in case any of the errors above fired) and with
7940 // "void" as the return type, since destructors don't have return
7941 // types.
7942 if (!D.isInvalidType())
7943 return R;
7944
7945 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7946 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7947 EPI.Variadic = false;
7948 EPI.TypeQuals = 0;
7949 EPI.RefQualifier = RQ_None;
7950 return Context.getFunctionType(Context.VoidTy, None, EPI);
7951}
7952
7953static void extendLeft(SourceRange &R, SourceRange Before) {
7954 if (Before.isInvalid())
7955 return;
7956 R.setBegin(Before.getBegin());
7957 if (R.getEnd().isInvalid())
7958 R.setEnd(Before.getEnd());
7959}
7960
7961static void extendRight(SourceRange &R, SourceRange After) {
7962 if (After.isInvalid())
7963 return;
7964 if (R.getBegin().isInvalid())
7965 R.setBegin(After.getBegin());
7966 R.setEnd(After.getEnd());
7967}
7968
7969/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7970/// well-formednes of the conversion function declarator @p D with
7971/// type @p R. If there are any errors in the declarator, this routine
7972/// will emit diagnostics and return true. Otherwise, it will return
7973/// false. Either way, the type @p R will be updated to reflect a
7974/// well-formed type for the conversion operator.
7975void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7976 StorageClass& SC) {
7977 // C++ [class.conv.fct]p1:
7978 // Neither parameter types nor return type can be specified. The
7979 // type of a conversion function (8.3.5) is "function taking no
7980 // parameter returning conversion-type-id."
7981 if (SC == SC_Static) {
7982 if (!D.isInvalidType())
7983 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7984 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7985 << D.getName().getSourceRange();
7986 D.setInvalidType();
7987 SC = SC_None;
7988 }
7989
7990 TypeSourceInfo *ConvTSI = nullptr;
7991 QualType ConvType =
7992 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7993
7994 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7995 // Conversion functions don't have return types, but the parser will
7996 // happily parse something like:
7997 //
7998 // class X {
7999 // float operator bool();
8000 // };
8001 //
8002 // The return type will be changed later anyway.
8003 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8004 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8005 << SourceRange(D.getIdentifierLoc());
8006 D.setInvalidType();
8007 }
8008
8009 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8010
8011 // Make sure we don't have any parameters.
8012 if (Proto->getNumParams() > 0) {
8013 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8014
8015 // Delete the parameters.
8016 D.getFunctionTypeInfo().freeParams();
8017 D.setInvalidType();
8018 } else if (Proto->isVariadic()) {