Bug Summary

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

Annotated Source Code

[?] Use j/k keys for keyboard navigation

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