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/Sema/SemaInternal.h"
15 #include "clang/Sema/CXXFieldCollector.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/AST/ASTConsumer.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/ASTMutationListener.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/CXXInheritance.h"
25 #include "clang/AST/DeclVisitor.h"
26 #include "clang/AST/EvaluatedExprVisitor.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/RecordLayout.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/StmtVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/TypeOrdering.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Basic/PartialDiagnostic.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <map>
40 #include <set>
41
42 using namespace clang;
43
44 //===----------------------------------------------------------------------===//
45 // CheckDefaultArgumentVisitor
46 //===----------------------------------------------------------------------===//
47
48 namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
54 class CheckDefaultArgumentVisitor
55 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
56 Expr *DefaultArg;
57 Sema *S;
58
59 public:
CheckDefaultArgumentVisitor(Expr * defarg,Sema * s)60 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
61 : DefaultArg(defarg), S(s) {}
62
63 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
65 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
66 bool VisitLambdaExpr(LambdaExpr *Lambda);
67 };
68
69 /// VisitExpr - Visit all of the children of this expression.
VisitExpr(Expr * Node)70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
72 for (Stmt::child_range I = Node->children(); I; ++I)
73 IsInvalid |= Visit(*I);
74 return IsInvalid;
75 }
76
77 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
VisitDeclRefExpr(DeclRefExpr * DRE)80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
81 NamedDecl *Decl = DRE->getDecl();
82 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
91 return S->Diag(DRE->getLocStart(),
92 diag::err_param_default_argument_references_param)
93 << Param->getDeclName() << DefaultArg->getSourceRange();
94 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
95 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
98 if (VDecl->isLocalVarDecl())
99 return S->Diag(DRE->getLocStart(),
100 diag::err_param_default_argument_references_local)
101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
102 }
103
104 return false;
105 }
106
107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(CXXThisExpr * ThisE)108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
112 return S->Diag(ThisE->getLocStart(),
113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
115 }
116
VisitLambdaExpr(LambdaExpr * Lambda)117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
127 }
128
CalledDecl(SourceLocation CallLoc,CXXMethodDecl * Method)129 void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
131 // If we have an MSAny spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny)
133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
144 if (EST == EST_MSAny || EST == EST_None) {
145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
197 Exceptions.push_back(*E);
198 }
199
CalledExpr(Expr * E)200 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
201 if (!E || ComputedEST == EST_MSAny)
202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
225 if (Self->canThrow(E))
226 ComputedEST = EST_None;
227 }
228
229 bool
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)230 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
231 SourceLocation EqualLoc) {
232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
250 if (Result.isInvalid())
251 return true;
252 Arg = Result.takeAs<Expr>();
253
254 CheckImplicitConversions(Arg, EqualLoc);
255 Arg = MaybeCreateExprWithCleanups(Arg);
256
257 // Okay: add the default argument to the parameter
258 Param->setDefaultArg(Arg);
259
260 // We have already instantiated this parameter; provide each of the
261 // instantiations with the uninstantiated default argument.
262 UnparsedDefaultArgInstantiationsMap::iterator InstPos
263 = UnparsedDefaultArgInstantiations.find(Param);
264 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268 // We're done tracking this parameter's instantiations.
269 UnparsedDefaultArgInstantiations.erase(InstPos);
270 }
271
272 return false;
273 }
274
275 /// ActOnParamDefaultArgument - Check whether the default argument
276 /// provided for a function parameter is well-formed. If so, attach it
277 /// to the parameter declaration.
278 void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)279 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
280 Expr *DefaultArg) {
281 if (!param || !DefaultArg)
282 return;
283
284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
285 UnparsedDefaultArgLocs.erase(Param);
286
287 // Default arguments are only permitted in C++
288 if (!getLangOpts().CPlusPlus) {
289 Diag(EqualLoc, diag::err_param_default_argument)
290 << DefaultArg->getSourceRange();
291 Param->setInvalidDecl();
292 return;
293 }
294
295 // Check for unexpanded parameter packs.
296 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297 Param->setInvalidDecl();
298 return;
299 }
300
301 // Check that the default argument is well-formed
302 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303 if (DefaultArgChecker.Visit(DefaultArg)) {
304 Param->setInvalidDecl();
305 return;
306 }
307
308 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
309 }
310
311 /// ActOnParamUnparsedDefaultArgument - We've seen a default
312 /// argument for a function parameter, but we can't parse it yet
313 /// because we're inside a class definition. Note that this default
314 /// argument will be parsed later.
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)315 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
316 SourceLocation EqualLoc,
317 SourceLocation ArgLoc) {
318 if (!param)
319 return;
320
321 ParmVarDecl *Param = cast<ParmVarDecl>(param);
322 if (Param)
323 Param->setUnparsedDefaultArg();
324
325 UnparsedDefaultArgLocs[Param] = ArgLoc;
326 }
327
328 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329 /// the default argument for the parameter param failed.
ActOnParamDefaultArgumentError(Decl * param)330 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
331 if (!param)
332 return;
333
334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
335
336 Param->setInvalidDecl();
337
338 UnparsedDefaultArgLocs.erase(Param);
339 }
340
341 /// CheckExtraCXXDefaultArguments - Check for any extra default
342 /// arguments in the declarator, which is not a function declaration
343 /// or definition and therefore is not permitted to have default
344 /// arguments. This routine should be invoked for every declarator
345 /// that is not a function declaration or definition.
CheckExtraCXXDefaultArguments(Declarator & D)346 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347 // C++ [dcl.fct.default]p3
348 // A default argument expression shall be specified only in the
349 // parameter-declaration-clause of a function declaration or in a
350 // template-parameter (14.1). It shall not be specified for a
351 // parameter pack. If it is specified in a
352 // parameter-declaration-clause, it shall not occur within a
353 // declarator or abstract-declarator of a parameter-declaration.
354 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
355 DeclaratorChunk &chunk = D.getTypeObject(i);
356 if (chunk.Kind == DeclaratorChunk::Function) {
357 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358 ParmVarDecl *Param =
359 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
360 if (Param->hasUnparsedDefaultArg()) {
361 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364 delete Toks;
365 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
366 } else if (Param->getDefaultArg()) {
367 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368 << Param->getDefaultArg()->getSourceRange();
369 Param->setDefaultArg(0);
370 }
371 }
372 }
373 }
374 }
375
376 // MergeCXXFunctionDecl - Merge two declarations of the same C++
377 // function, once we already know that they have the same
378 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
379 // error, false otherwise.
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old,Scope * S)380 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381 Scope *S) {
382 bool Invalid = false;
383
384 // C++ [dcl.fct.default]p4:
385 // For non-template functions, default arguments can be added in
386 // later declarations of a function in the same
387 // scope. Declarations in different scopes have completely
388 // distinct sets of default arguments. That is, declarations in
389 // inner scopes do not acquire default arguments from
390 // declarations in outer scopes, and vice versa. In a given
391 // function declaration, all parameters subsequent to a
392 // parameter with a default argument shall have default
393 // arguments supplied in this or previous declarations. A
394 // default argument shall not be redefined by a later
395 // declaration (not even to the same value).
396 //
397 // C++ [dcl.fct.default]p6:
398 // Except for member functions of class templates, the default arguments
399 // in a member function definition that appears outside of the class
400 // definition are added to the set of default arguments provided by the
401 // member function declaration in the class definition.
402 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403 ParmVarDecl *OldParam = Old->getParamDecl(p);
404 ParmVarDecl *NewParam = New->getParamDecl(p);
405
406 bool OldParamHasDfl = OldParam->hasDefaultArg();
407 bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409 NamedDecl *ND = Old;
410 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411 // Ignore default parameters of old decl if they are not in
412 // the same scope.
413 OldParamHasDfl = false;
414
415 if (OldParamHasDfl && NewParamHasDfl) {
416
417 unsigned DiagDefaultParamID =
418 diag::err_param_default_argument_redefinition;
419
420 // MSVC accepts that default parameters be redefined for member functions
421 // of template class. The new default parameter's value is ignored.
422 Invalid = true;
423 if (getLangOpts().MicrosoftExt) {
424 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425 if (MD && MD->getParent()->getDescribedClassTemplate()) {
426 // Merge the old default argument into the new parameter.
427 NewParam->setHasInheritedDefaultArg();
428 if (OldParam->hasUninstantiatedDefaultArg())
429 NewParam->setUninstantiatedDefaultArg(
430 OldParam->getUninstantiatedDefaultArg());
431 else
432 NewParam->setDefaultArg(OldParam->getInit());
433 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
434 Invalid = false;
435 }
436 }
437
438 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439 // hint here. Alternatively, we could walk the type-source information
440 // for NewParam to find the last source location in the type... but it
441 // isn't worth the effort right now. This is the kind of test case that
442 // is hard to get right:
443 // int f(int);
444 // void g(int (*fp)(int) = f);
445 // void g(int (*fp)(int) = &f);
446 Diag(NewParam->getLocation(), DiagDefaultParamID)
447 << NewParam->getDefaultArgRange();
448
449 // Look for the function declaration where the default argument was
450 // actually written, which may be a declaration prior to Old.
451 for (FunctionDecl *Older = Old->getPreviousDecl();
452 Older; Older = Older->getPreviousDecl()) {
453 if (!Older->getParamDecl(p)->hasDefaultArg())
454 break;
455
456 OldParam = Older->getParamDecl(p);
457 }
458
459 Diag(OldParam->getLocation(), diag::note_previous_definition)
460 << OldParam->getDefaultArgRange();
461 } else if (OldParamHasDfl) {
462 // Merge the old default argument into the new parameter.
463 // It's important to use getInit() here; getDefaultArg()
464 // strips off any top-level ExprWithCleanups.
465 NewParam->setHasInheritedDefaultArg();
466 if (OldParam->hasUninstantiatedDefaultArg())
467 NewParam->setUninstantiatedDefaultArg(
468 OldParam->getUninstantiatedDefaultArg());
469 else
470 NewParam->setDefaultArg(OldParam->getInit());
471 } else if (NewParamHasDfl) {
472 if (New->getDescribedFunctionTemplate()) {
473 // Paragraph 4, quoted above, only applies to non-template functions.
474 Diag(NewParam->getLocation(),
475 diag::err_param_default_argument_template_redecl)
476 << NewParam->getDefaultArgRange();
477 Diag(Old->getLocation(), diag::note_template_prev_declaration)
478 << false;
479 } else if (New->getTemplateSpecializationKind()
480 != TSK_ImplicitInstantiation &&
481 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482 // C++ [temp.expr.spec]p21:
483 // Default function arguments shall not be specified in a declaration
484 // or a definition for one of the following explicit specializations:
485 // - the explicit specialization of a function template;
486 // - the explicit specialization of a member function template;
487 // - the explicit specialization of a member function of a class
488 // template where the class template specialization to which the
489 // member function specialization belongs is implicitly
490 // instantiated.
491 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493 << New->getDeclName()
494 << NewParam->getDefaultArgRange();
495 } else if (New->getDeclContext()->isDependentContext()) {
496 // C++ [dcl.fct.default]p6 (DR217):
497 // Default arguments for a member function of a class template shall
498 // be specified on the initial declaration of the member function
499 // within the class template.
500 //
501 // Reading the tea leaves a bit in DR217 and its reference to DR205
502 // leads me to the conclusion that one cannot add default function
503 // arguments for an out-of-line definition of a member function of a
504 // dependent type.
505 int WhichKind = 2;
506 if (CXXRecordDecl *Record
507 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508 if (Record->getDescribedClassTemplate())
509 WhichKind = 0;
510 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511 WhichKind = 1;
512 else
513 WhichKind = 2;
514 }
515
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_member_template_redecl)
518 << WhichKind
519 << NewParam->getDefaultArgRange();
520 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521 CXXSpecialMember NewSM = getSpecialMember(Ctor),
522 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523 if (NewSM != OldSM) {
524 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525 << NewParam->getDefaultArgRange() << NewSM;
526 Diag(Old->getLocation(), diag::note_previous_declaration_special)
527 << OldSM;
528 }
529 }
530 }
531 }
532
533 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
534 // template has a constexpr specifier then all its declarations shall
535 // contain the constexpr specifier.
536 if (New->isConstexpr() != Old->isConstexpr()) {
537 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538 << New << New->isConstexpr();
539 Diag(Old->getLocation(), diag::note_previous_declaration);
540 Invalid = true;
541 }
542
543 if (CheckEquivalentExceptionSpec(Old, New))
544 Invalid = true;
545
546 return Invalid;
547 }
548
549 /// \brief Merge the exception specifications of two variable declarations.
550 ///
551 /// This is called when there's a redeclaration of a VarDecl. The function
552 /// checks if the redeclaration might have an exception specification and
553 /// validates compatibility and merges the specs if necessary.
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)554 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555 // Shortcut if exceptions are disabled.
556 if (!getLangOpts().CXXExceptions)
557 return;
558
559 assert(Context.hasSameType(New->getType(), Old->getType()) &&
560 "Should only be called if types are otherwise the same.");
561
562 QualType NewType = New->getType();
563 QualType OldType = Old->getType();
564
565 // We're only interested in pointers and references to functions, as well
566 // as pointers to member functions.
567 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568 NewType = R->getPointeeType();
569 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571 NewType = P->getPointeeType();
572 OldType = OldType->getAs<PointerType>()->getPointeeType();
573 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574 NewType = M->getPointeeType();
575 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576 }
577
578 if (!NewType->isFunctionProtoType())
579 return;
580
581 // There's lots of special cases for functions. For function pointers, system
582 // libraries are hopefully not as broken so that we don't need these
583 // workarounds.
584 if (CheckEquivalentExceptionSpec(
585 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587 New->setInvalidDecl();
588 }
589 }
590
591 /// CheckCXXDefaultArguments - Verify that the default arguments for a
592 /// function declaration are well-formed according to C++
593 /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)594 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595 unsigned NumParams = FD->getNumParams();
596 unsigned p;
597
598 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599 isa<CXXMethodDecl>(FD) &&
600 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601
602 // Find first parameter with a default argument
603 for (p = 0; p < NumParams; ++p) {
604 ParmVarDecl *Param = FD->getParamDecl(p);
605 if (Param->hasDefaultArg()) {
606 // C++11 [expr.prim.lambda]p5:
607 // [...] Default arguments (8.3.6) shall not be specified in the
608 // parameter-declaration-clause of a lambda-declarator.
609 //
610 // FIXME: Core issue 974 strikes this sentence, we only provide an
611 // extension warning.
612 if (IsLambda)
613 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614 << Param->getDefaultArgRange();
615 break;
616 }
617 }
618
619 // C++ [dcl.fct.default]p4:
620 // In a given function declaration, all parameters
621 // subsequent to a parameter with a default argument shall
622 // have default arguments supplied in this or previous
623 // declarations. A default argument shall not be redefined
624 // by a later declaration (not even to the same value).
625 unsigned LastMissingDefaultArg = 0;
626 for (; p < NumParams; ++p) {
627 ParmVarDecl *Param = FD->getParamDecl(p);
628 if (!Param->hasDefaultArg()) {
629 if (Param->isInvalidDecl())
630 /* We already complained about this parameter. */;
631 else if (Param->getIdentifier())
632 Diag(Param->getLocation(),
633 diag::err_param_default_argument_missing_name)
634 << Param->getIdentifier();
635 else
636 Diag(Param->getLocation(),
637 diag::err_param_default_argument_missing);
638
639 LastMissingDefaultArg = p;
640 }
641 }
642
643 if (LastMissingDefaultArg > 0) {
644 // Some default arguments were missing. Clear out all of the
645 // default arguments up to (and including) the last missing
646 // default argument, so that we leave the function parameters
647 // in a semantically valid state.
648 for (p = 0; p <= LastMissingDefaultArg; ++p) {
649 ParmVarDecl *Param = FD->getParamDecl(p);
650 if (Param->hasDefaultArg()) {
651 Param->setDefaultArg(0);
652 }
653 }
654 }
655 }
656
657 // CheckConstexprParameterTypes - Check whether a function's parameter types
658 // are all literal types. If so, return true. If not, produce a suitable
659 // diagnostic and return false.
CheckConstexprParameterTypes(Sema & SemaRef,const FunctionDecl * FD)660 static bool CheckConstexprParameterTypes(Sema &SemaRef,
661 const FunctionDecl *FD) {
662 unsigned ArgIndex = 0;
663 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667 SourceLocation ParamLoc = PD->getLocation();
668 if (!(*i)->isDependentType() &&
669 SemaRef.RequireLiteralType(ParamLoc, *i,
670 diag::err_constexpr_non_literal_param,
671 ArgIndex+1, PD->getSourceRange(),
672 isa<CXXConstructorDecl>(FD)))
673 return false;
674 }
675 return true;
676 }
677
678 /// \brief Get diagnostic %select index for tag kind for
679 /// record diagnostic message.
680 /// WARNING: Indexes apply to particular diagnostics only!
681 ///
682 /// \returns diagnostic %select index.
getRecordDiagFromTagKind(TagTypeKind Tag)683 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
684 switch (Tag) {
685 case TTK_Struct: return 0;
686 case TTK_Interface: return 1;
687 case TTK_Class: return 2;
688 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
689 }
690 }
691
692 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
693 // the requirements of a constexpr function definition or a constexpr
694 // constructor definition. If so, return true. If not, produce appropriate
695 // diagnostics and return false.
696 //
697 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
CheckConstexprFunctionDecl(const FunctionDecl * NewFD)698 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
699 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
700 if (MD && MD->isInstance()) {
701 // C++11 [dcl.constexpr]p4:
702 // The definition of a constexpr constructor shall satisfy the following
703 // constraints:
704 // - the class shall not have any virtual base classes;
705 const CXXRecordDecl *RD = MD->getParent();
706 if (RD->getNumVBases()) {
707 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
708 << isa<CXXConstructorDecl>(NewFD)
709 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
710 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
711 E = RD->vbases_end(); I != E; ++I)
712 Diag(I->getLocStart(),
713 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
714 return false;
715 }
716 }
717
718 if (!isa<CXXConstructorDecl>(NewFD)) {
719 // C++11 [dcl.constexpr]p3:
720 // The definition of a constexpr function shall satisfy the following
721 // constraints:
722 // - it shall not be virtual;
723 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
724 if (Method && Method->isVirtual()) {
725 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
726
727 // If it's not obvious why this function is virtual, find an overridden
728 // function which uses the 'virtual' keyword.
729 const CXXMethodDecl *WrittenVirtual = Method;
730 while (!WrittenVirtual->isVirtualAsWritten())
731 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
732 if (WrittenVirtual != Method)
733 Diag(WrittenVirtual->getLocation(),
734 diag::note_overridden_virtual_function);
735 return false;
736 }
737
738 // - its return type shall be a literal type;
739 QualType RT = NewFD->getResultType();
740 if (!RT->isDependentType() &&
741 RequireLiteralType(NewFD->getLocation(), RT,
742 diag::err_constexpr_non_literal_return))
743 return false;
744 }
745
746 // - each of its parameter types shall be a literal type;
747 if (!CheckConstexprParameterTypes(*this, NewFD))
748 return false;
749
750 return true;
751 }
752
753 /// Check the given declaration statement is legal within a constexpr function
754 /// body. C++0x [dcl.constexpr]p3,p4.
755 ///
756 /// \return true if the body is OK, false if we have diagnosed a problem.
CheckConstexprDeclStmt(Sema & SemaRef,const FunctionDecl * Dcl,DeclStmt * DS)757 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
758 DeclStmt *DS) {
759 // C++0x [dcl.constexpr]p3 and p4:
760 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
761 // contain only
762 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
763 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
764 switch ((*DclIt)->getKind()) {
765 case Decl::StaticAssert:
766 case Decl::Using:
767 case Decl::UsingShadow:
768 case Decl::UsingDirective:
769 case Decl::UnresolvedUsingTypename:
770 // - static_assert-declarations
771 // - using-declarations,
772 // - using-directives,
773 continue;
774
775 case Decl::Typedef:
776 case Decl::TypeAlias: {
777 // - typedef declarations and alias-declarations that do not define
778 // classes or enumerations,
779 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
780 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
781 // Don't allow variably-modified types in constexpr functions.
782 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
783 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
784 << TL.getSourceRange() << TL.getType()
785 << isa<CXXConstructorDecl>(Dcl);
786 return false;
787 }
788 continue;
789 }
790
791 case Decl::Enum:
792 case Decl::CXXRecord:
793 // As an extension, we allow the declaration (but not the definition) of
794 // classes and enumerations in all declarations, not just in typedef and
795 // alias declarations.
796 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
797 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
798 << isa<CXXConstructorDecl>(Dcl);
799 return false;
800 }
801 continue;
802
803 case Decl::Var:
804 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
805 << isa<CXXConstructorDecl>(Dcl);
806 return false;
807
808 default:
809 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
810 << isa<CXXConstructorDecl>(Dcl);
811 return false;
812 }
813 }
814
815 return true;
816 }
817
818 /// Check that the given field is initialized within a constexpr constructor.
819 ///
820 /// \param Dcl The constexpr constructor being checked.
821 /// \param Field The field being checked. This may be a member of an anonymous
822 /// struct or union nested within the class being checked.
823 /// \param Inits All declarations, including anonymous struct/union members and
824 /// indirect members, for which any initialization was provided.
825 /// \param Diagnosed Set to true if an error is produced.
CheckConstexprCtorInitializer(Sema & SemaRef,const FunctionDecl * Dcl,FieldDecl * Field,llvm::SmallSet<Decl *,16> & Inits,bool & Diagnosed)826 static void CheckConstexprCtorInitializer(Sema &SemaRef,
827 const FunctionDecl *Dcl,
828 FieldDecl *Field,
829 llvm::SmallSet<Decl*, 16> &Inits,
830 bool &Diagnosed) {
831 if (Field->isUnnamedBitfield())
832 return;
833
834 if (Field->isAnonymousStructOrUnion() &&
835 Field->getType()->getAsCXXRecordDecl()->isEmpty())
836 return;
837
838 if (!Inits.count(Field)) {
839 if (!Diagnosed) {
840 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
841 Diagnosed = true;
842 }
843 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
844 } else if (Field->isAnonymousStructOrUnion()) {
845 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
846 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
847 I != E; ++I)
848 // If an anonymous union contains an anonymous struct of which any member
849 // is initialized, all members must be initialized.
850 if (!RD->isUnion() || Inits.count(*I))
851 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
852 }
853 }
854
855 /// Check the body for the given constexpr function declaration only contains
856 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
857 ///
858 /// \return true if the body is OK, false if we have diagnosed a problem.
CheckConstexprFunctionBody(const FunctionDecl * Dcl,Stmt * Body)859 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
860 if (isa<CXXTryStmt>(Body)) {
861 // C++11 [dcl.constexpr]p3:
862 // The definition of a constexpr function shall satisfy the following
863 // constraints: [...]
864 // - its function-body shall be = delete, = default, or a
865 // compound-statement
866 //
867 // C++11 [dcl.constexpr]p4:
868 // In the definition of a constexpr constructor, [...]
869 // - its function-body shall not be a function-try-block;
870 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
871 << isa<CXXConstructorDecl>(Dcl);
872 return false;
873 }
874
875 // - its function-body shall be [...] a compound-statement that contains only
876 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
877
878 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
879 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
880 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
881 switch ((*BodyIt)->getStmtClass()) {
882 case Stmt::NullStmtClass:
883 // - null statements,
884 continue;
885
886 case Stmt::DeclStmtClass:
887 // - static_assert-declarations
888 // - using-declarations,
889 // - using-directives,
890 // - typedef declarations and alias-declarations that do not define
891 // classes or enumerations,
892 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
893 return false;
894 continue;
895
896 case Stmt::ReturnStmtClass:
897 // - and exactly one return statement;
898 if (isa<CXXConstructorDecl>(Dcl))
899 break;
900
901 ReturnStmts.push_back((*BodyIt)->getLocStart());
902 continue;
903
904 default:
905 break;
906 }
907
908 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
909 << isa<CXXConstructorDecl>(Dcl);
910 return false;
911 }
912
913 if (const CXXConstructorDecl *Constructor
914 = dyn_cast<CXXConstructorDecl>(Dcl)) {
915 const CXXRecordDecl *RD = Constructor->getParent();
916 // DR1359:
917 // - every non-variant non-static data member and base class sub-object
918 // shall be initialized;
919 // - if the class is a non-empty union, or for each non-empty anonymous
920 // union member of a non-union class, exactly one non-static data member
921 // shall be initialized;
922 if (RD->isUnion()) {
923 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
924 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
925 return false;
926 }
927 } else if (!Constructor->isDependentContext() &&
928 !Constructor->isDelegatingConstructor()) {
929 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
930
931 // Skip detailed checking if we have enough initializers, and we would
932 // allow at most one initializer per member.
933 bool AnyAnonStructUnionMembers = false;
934 unsigned Fields = 0;
935 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
936 E = RD->field_end(); I != E; ++I, ++Fields) {
937 if (I->isAnonymousStructOrUnion()) {
938 AnyAnonStructUnionMembers = true;
939 break;
940 }
941 }
942 if (AnyAnonStructUnionMembers ||
943 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
944 // Check initialization of non-static data members. Base classes are
945 // always initialized so do not need to be checked. Dependent bases
946 // might not have initializers in the member initializer list.
947 llvm::SmallSet<Decl*, 16> Inits;
948 for (CXXConstructorDecl::init_const_iterator
949 I = Constructor->init_begin(), E = Constructor->init_end();
950 I != E; ++I) {
951 if (FieldDecl *FD = (*I)->getMember())
952 Inits.insert(FD);
953 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
954 Inits.insert(ID->chain_begin(), ID->chain_end());
955 }
956
957 bool Diagnosed = false;
958 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
959 E = RD->field_end(); I != E; ++I)
960 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
961 if (Diagnosed)
962 return false;
963 }
964 }
965 } else {
966 if (ReturnStmts.empty()) {
967 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
968 return false;
969 }
970 if (ReturnStmts.size() > 1) {
971 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
972 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
973 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
974 return false;
975 }
976 }
977
978 // C++11 [dcl.constexpr]p5:
979 // if no function argument values exist such that the function invocation
980 // substitution would produce a constant expression, the program is
981 // ill-formed; no diagnostic required.
982 // C++11 [dcl.constexpr]p3:
983 // - every constructor call and implicit conversion used in initializing the
984 // return value shall be one of those allowed in a constant expression.
985 // C++11 [dcl.constexpr]p4:
986 // - every constructor involved in initializing non-static data members and
987 // base class sub-objects shall be a constexpr constructor.
988 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
989 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
990 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
991 << isa<CXXConstructorDecl>(Dcl);
992 for (size_t I = 0, N = Diags.size(); I != N; ++I)
993 Diag(Diags[I].first, Diags[I].second);
994 return false;
995 }
996
997 return true;
998 }
999
1000 /// isCurrentClassName - Determine whether the identifier II is the
1001 /// name of the class type currently being defined. In the case of
1002 /// nested classes, this will only return true if II is the name of
1003 /// the innermost class.
isCurrentClassName(const IdentifierInfo & II,Scope *,const CXXScopeSpec * SS)1004 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1005 const CXXScopeSpec *SS) {
1006 assert(getLangOpts().CPlusPlus && "No class names in C!");
1007
1008 CXXRecordDecl *CurDecl;
1009 if (SS && SS->isSet() && !SS->isInvalid()) {
1010 DeclContext *DC = computeDeclContext(*SS, true);
1011 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1012 } else
1013 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1014
1015 if (CurDecl && CurDecl->getIdentifier())
1016 return &II == CurDecl->getIdentifier();
1017 else
1018 return false;
1019 }
1020
1021 /// \brief Check the validity of a C++ base class specifier.
1022 ///
1023 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1024 /// and returns NULL otherwise.
1025 CXXBaseSpecifier *
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)1026 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1027 SourceRange SpecifierRange,
1028 bool Virtual, AccessSpecifier Access,
1029 TypeSourceInfo *TInfo,
1030 SourceLocation EllipsisLoc) {
1031 QualType BaseType = TInfo->getType();
1032
1033 // C++ [class.union]p1:
1034 // A union shall not have base classes.
1035 if (Class->isUnion()) {
1036 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1037 << SpecifierRange;
1038 return 0;
1039 }
1040
1041 if (EllipsisLoc.isValid() &&
1042 !TInfo->getType()->containsUnexpandedParameterPack()) {
1043 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1044 << TInfo->getTypeLoc().getSourceRange();
1045 EllipsisLoc = SourceLocation();
1046 }
1047
1048 if (BaseType->isDependentType())
1049 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1050 Class->getTagKind() == TTK_Class,
1051 Access, TInfo, EllipsisLoc);
1052
1053 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1054
1055 // Base specifiers must be record types.
1056 if (!BaseType->isRecordType()) {
1057 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1058 return 0;
1059 }
1060
1061 // C++ [class.union]p1:
1062 // A union shall not be used as a base class.
1063 if (BaseType->isUnionType()) {
1064 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1065 return 0;
1066 }
1067
1068 // C++ [class.derived]p2:
1069 // The class-name in a base-specifier shall not be an incompletely
1070 // defined class.
1071 if (RequireCompleteType(BaseLoc, BaseType,
1072 diag::err_incomplete_base_class, SpecifierRange)) {
1073 Class->setInvalidDecl();
1074 return 0;
1075 }
1076
1077 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1078 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1079 assert(BaseDecl && "Record type has no declaration");
1080 BaseDecl = BaseDecl->getDefinition();
1081 assert(BaseDecl && "Base type is not incomplete, but has no definition");
1082 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1083 assert(CXXBaseDecl && "Base type is not a C++ type");
1084
1085 // C++ [class]p3:
1086 // If a class is marked final and it appears as a base-type-specifier in
1087 // base-clause, the program is ill-formed.
1088 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1089 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1090 << CXXBaseDecl->getDeclName();
1091 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1092 << CXXBaseDecl->getDeclName();
1093 return 0;
1094 }
1095
1096 if (BaseDecl->isInvalidDecl())
1097 Class->setInvalidDecl();
1098
1099 // Create the base specifier.
1100 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1101 Class->getTagKind() == TTK_Class,
1102 Access, TInfo, EllipsisLoc);
1103 }
1104
1105 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1106 /// one entry in the base class list of a class specifier, for
1107 /// example:
1108 /// class foo : public bar, virtual private baz {
1109 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1110 BaseResult
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)1111 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1112 bool Virtual, AccessSpecifier Access,
1113 ParsedType basetype, SourceLocation BaseLoc,
1114 SourceLocation EllipsisLoc) {
1115 if (!classdecl)
1116 return true;
1117
1118 AdjustDeclIfTemplate(classdecl);
1119 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1120 if (!Class)
1121 return true;
1122
1123 TypeSourceInfo *TInfo = 0;
1124 GetTypeFromParser(basetype, &TInfo);
1125
1126 if (EllipsisLoc.isInvalid() &&
1127 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1128 UPPC_BaseType))
1129 return true;
1130
1131 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1132 Virtual, Access, TInfo,
1133 EllipsisLoc))
1134 return BaseSpec;
1135 else
1136 Class->setInvalidDecl();
1137
1138 return true;
1139 }
1140
1141 /// \brief Performs the actual work of attaching the given base class
1142 /// specifiers to a C++ class.
AttachBaseSpecifiers(CXXRecordDecl * Class,CXXBaseSpecifier ** Bases,unsigned NumBases)1143 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1144 unsigned NumBases) {
1145 if (NumBases == 0)
1146 return false;
1147
1148 // Used to keep track of which base types we have already seen, so
1149 // that we can properly diagnose redundant direct base types. Note
1150 // that the key is always the unqualified canonical type of the base
1151 // class.
1152 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1153
1154 // Copy non-redundant base specifiers into permanent storage.
1155 unsigned NumGoodBases = 0;
1156 bool Invalid = false;
1157 for (unsigned idx = 0; idx < NumBases; ++idx) {
1158 QualType NewBaseType
1159 = Context.getCanonicalType(Bases[idx]->getType());
1160 NewBaseType = NewBaseType.getLocalUnqualifiedType();
1161
1162 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1163 if (KnownBase) {
1164 // C++ [class.mi]p3:
1165 // A class shall not be specified as a direct base class of a
1166 // derived class more than once.
1167 Diag(Bases[idx]->getLocStart(),
1168 diag::err_duplicate_base_class)
1169 << KnownBase->getType()
1170 << Bases[idx]->getSourceRange();
1171
1172 // Delete the duplicate base class specifier; we're going to
1173 // overwrite its pointer later.
1174 Context.Deallocate(Bases[idx]);
1175
1176 Invalid = true;
1177 } else {
1178 // Okay, add this new base class.
1179 KnownBase = Bases[idx];
1180 Bases[NumGoodBases++] = Bases[idx];
1181 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
1182 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1183 if (RD->hasAttr<WeakAttr>())
1184 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1185 }
1186 }
1187
1188 // Attach the remaining base class specifiers to the derived class.
1189 Class->setBases(Bases, NumGoodBases);
1190
1191 // Delete the remaining (good) base class specifiers, since their
1192 // data has been copied into the CXXRecordDecl.
1193 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1194 Context.Deallocate(Bases[idx]);
1195
1196 return Invalid;
1197 }
1198
1199 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1200 /// class, after checking whether there are any duplicate base
1201 /// classes.
ActOnBaseSpecifiers(Decl * ClassDecl,CXXBaseSpecifier ** Bases,unsigned NumBases)1202 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1203 unsigned NumBases) {
1204 if (!ClassDecl || !Bases || !NumBases)
1205 return;
1206
1207 AdjustDeclIfTemplate(ClassDecl);
1208 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1209 (CXXBaseSpecifier**)(Bases), NumBases);
1210 }
1211
GetClassForType(QualType T)1212 static CXXRecordDecl *GetClassForType(QualType T) {
1213 if (const RecordType *RT = T->getAs<RecordType>())
1214 return cast<CXXRecordDecl>(RT->getDecl());
1215 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1216 return ICT->getDecl();
1217 else
1218 return 0;
1219 }
1220
1221 /// \brief Determine whether the type \p Derived is a C++ class that is
1222 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base)1223 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1224 if (!getLangOpts().CPlusPlus)
1225 return false;
1226
1227 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1228 if (!DerivedRD)
1229 return false;
1230
1231 CXXRecordDecl *BaseRD = GetClassForType(Base);
1232 if (!BaseRD)
1233 return false;
1234
1235 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1236 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1237 }
1238
1239 /// \brief Determine whether the type \p Derived is a C++ class that is
1240 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base,CXXBasePaths & Paths)1241 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1242 if (!getLangOpts().CPlusPlus)
1243 return false;
1244
1245 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1246 if (!DerivedRD)
1247 return false;
1248
1249 CXXRecordDecl *BaseRD = GetClassForType(Base);
1250 if (!BaseRD)
1251 return false;
1252
1253 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1254 }
1255
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)1256 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1257 CXXCastPath &BasePathArray) {
1258 assert(BasePathArray.empty() && "Base path array must be empty!");
1259 assert(Paths.isRecordingPaths() && "Must record paths!");
1260
1261 const CXXBasePath &Path = Paths.front();
1262
1263 // We first go backward and check if we have a virtual base.
1264 // FIXME: It would be better if CXXBasePath had the base specifier for
1265 // the nearest virtual base.
1266 unsigned Start = 0;
1267 for (unsigned I = Path.size(); I != 0; --I) {
1268 if (Path[I - 1].Base->isVirtual()) {
1269 Start = I - 1;
1270 break;
1271 }
1272 }
1273
1274 // Now add all bases.
1275 for (unsigned I = Start, E = Path.size(); I != E; ++I)
1276 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1277 }
1278
1279 /// \brief Determine whether the given base path includes a virtual
1280 /// base class.
BasePathInvolvesVirtualBase(const CXXCastPath & BasePath)1281 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1282 for (CXXCastPath::const_iterator B = BasePath.begin(),
1283 BEnd = BasePath.end();
1284 B != BEnd; ++B)
1285 if ((*B)->isVirtual())
1286 return true;
1287
1288 return false;
1289 }
1290
1291 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1292 /// conversion (where Derived and Base are class types) is
1293 /// well-formed, meaning that the conversion is unambiguous (and
1294 /// that all of the base classes are accessible). Returns true
1295 /// and emits a diagnostic if the code is ill-formed, returns false
1296 /// otherwise. Loc is the location where this routine should point to
1297 /// if there is an error, and Range is the source range to highlight
1298 /// if there is an error.
1299 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbigiousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath)1300 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1301 unsigned InaccessibleBaseID,
1302 unsigned AmbigiousBaseConvID,
1303 SourceLocation Loc, SourceRange Range,
1304 DeclarationName Name,
1305 CXXCastPath *BasePath) {
1306 // First, determine whether the path from Derived to Base is
1307 // ambiguous. This is slightly more expensive than checking whether
1308 // the Derived to Base conversion exists, because here we need to
1309 // explore multiple paths to determine if there is an ambiguity.
1310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1311 /*DetectVirtual=*/false);
1312 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1313 assert(DerivationOkay &&
1314 "Can only be used with a derived-to-base conversion");
1315 (void)DerivationOkay;
1316
1317 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1318 if (InaccessibleBaseID) {
1319 // Check that the base class can be accessed.
1320 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1321 InaccessibleBaseID)) {
1322 case AR_inaccessible:
1323 return true;
1324 case AR_accessible:
1325 case AR_dependent:
1326 case AR_delayed:
1327 break;
1328 }
1329 }
1330
1331 // Build a base path if necessary.
1332 if (BasePath)
1333 BuildBasePathArray(Paths, *BasePath);
1334 return false;
1335 }
1336
1337 // We know that the derived-to-base conversion is ambiguous, and
1338 // we're going to produce a diagnostic. Perform the derived-to-base
1339 // search just one more time to compute all of the possible paths so
1340 // that we can print them out. This is more expensive than any of
1341 // the previous derived-to-base checks we've done, but at this point
1342 // performance isn't as much of an issue.
1343 Paths.clear();
1344 Paths.setRecordingPaths(true);
1345 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1346 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1347 (void)StillOkay;
1348
1349 // Build up a textual representation of the ambiguous paths, e.g.,
1350 // D -> B -> A, that will be used to illustrate the ambiguous
1351 // conversions in the diagnostic. We only print one of the paths
1352 // to each base class subobject.
1353 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1354
1355 Diag(Loc, AmbigiousBaseConvID)
1356 << Derived << Base << PathDisplayStr << Range << Name;
1357 return true;
1358 }
1359
1360 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)1361 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1362 SourceLocation Loc, SourceRange Range,
1363 CXXCastPath *BasePath,
1364 bool IgnoreAccess) {
1365 return CheckDerivedToBaseConversion(Derived, Base,
1366 IgnoreAccess ? 0
1367 : diag::err_upcast_to_inaccessible_base,
1368 diag::err_ambiguous_derived_to_base_conv,
1369 Loc, Range, DeclarationName(),
1370 BasePath);
1371 }
1372
1373
1374 /// @brief Builds a string representing ambiguous paths from a
1375 /// specific derived class to different subobjects of the same base
1376 /// class.
1377 ///
1378 /// This function builds a string that can be used in error messages
1379 /// to show the different paths that one can take through the
1380 /// inheritance hierarchy to go from the derived class to different
1381 /// subobjects of a base class. The result looks something like this:
1382 /// @code
1383 /// struct D -> struct B -> struct A
1384 /// struct D -> struct C -> struct A
1385 /// @endcode
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)1386 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1387 std::string PathDisplayStr;
1388 std::set<unsigned> DisplayedPaths;
1389 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1390 Path != Paths.end(); ++Path) {
1391 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1392 // We haven't displayed a path to this particular base
1393 // class subobject yet.
1394 PathDisplayStr += "\n ";
1395 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1396 for (CXXBasePath::const_iterator Element = Path->begin();
1397 Element != Path->end(); ++Element)
1398 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1399 }
1400 }
1401
1402 return PathDisplayStr;
1403 }
1404
1405 //===----------------------------------------------------------------------===//
1406 // C++ class member Handling
1407 //===----------------------------------------------------------------------===//
1408
1409 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc,AttributeList * Attrs)1410 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1411 SourceLocation ASLoc,
1412 SourceLocation ColonLoc,
1413 AttributeList *Attrs) {
1414 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1415 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1416 ASLoc, ColonLoc);
1417 CurContext->addHiddenDecl(ASDecl);
1418 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1419 }
1420
1421 /// CheckOverrideControl - Check C++11 override control semantics.
CheckOverrideControl(Decl * D)1422 void Sema::CheckOverrideControl(Decl *D) {
1423 if (D->isInvalidDecl())
1424 return;
1425
1426 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1427
1428 // Do we know which functions this declaration might be overriding?
1429 bool OverridesAreKnown = !MD ||
1430 (!MD->getParent()->hasAnyDependentBases() &&
1431 !MD->getType()->isDependentType());
1432
1433 if (!MD || !MD->isVirtual()) {
1434 if (OverridesAreKnown) {
1435 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1436 Diag(OA->getLocation(),
1437 diag::override_keyword_only_allowed_on_virtual_member_functions)
1438 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1439 D->dropAttr<OverrideAttr>();
1440 }
1441 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1442 Diag(FA->getLocation(),
1443 diag::override_keyword_only_allowed_on_virtual_member_functions)
1444 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1445 D->dropAttr<FinalAttr>();
1446 }
1447 }
1448 return;
1449 }
1450
1451 if (!OverridesAreKnown)
1452 return;
1453
1454 // C++11 [class.virtual]p5:
1455 // If a virtual function is marked with the virt-specifier override and
1456 // does not override a member function of a base class, the program is
1457 // ill-formed.
1458 bool HasOverriddenMethods =
1459 MD->begin_overridden_methods() != MD->end_overridden_methods();
1460 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1461 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1462 << MD->getDeclName();
1463 }
1464
1465 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1466 /// function overrides a virtual member function marked 'final', according to
1467 /// C++11 [class.virtual]p4.
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)1468 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1469 const CXXMethodDecl *Old) {
1470 if (!Old->hasAttr<FinalAttr>())
1471 return false;
1472
1473 Diag(New->getLocation(), diag::err_final_function_overridden)
1474 << New->getDeclName();
1475 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1476 return true;
1477 }
1478
InitializationHasSideEffects(const FieldDecl & FD)1479 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1480 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1481 // FIXME: Destruction of ObjC lifetime types has side-effects.
1482 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1483 return !RD->isCompleteDefinition() ||
1484 !RD->hasTrivialDefaultConstructor() ||
1485 !RD->hasTrivialDestructor();
1486 return false;
1487 }
1488
1489 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1490 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1491 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1492 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1493 /// present (but parsing it has been deferred).
1494 Decl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,Expr * BW,const VirtSpecifiers & VS,InClassInitStyle InitStyle)1495 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1496 MultiTemplateParamsArg TemplateParameterLists,
1497 Expr *BW, const VirtSpecifiers &VS,
1498 InClassInitStyle InitStyle) {
1499 const DeclSpec &DS = D.getDeclSpec();
1500 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1501 DeclarationName Name = NameInfo.getName();
1502 SourceLocation Loc = NameInfo.getLoc();
1503
1504 // For anonymous bitfields, the location should point to the type.
1505 if (Loc.isInvalid())
1506 Loc = D.getLocStart();
1507
1508 Expr *BitWidth = static_cast<Expr*>(BW);
1509
1510 assert(isa<CXXRecordDecl>(CurContext));
1511 assert(!DS.isFriendSpecified());
1512
1513 bool isFunc = D.isDeclarationOfFunction();
1514
1515 // C++ 9.2p6: A member shall not be declared to have automatic storage
1516 // duration (auto, register) or with the extern storage-class-specifier.
1517 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1518 // data members and cannot be applied to names declared const or static,
1519 // and cannot be applied to reference members.
1520 switch (DS.getStorageClassSpec()) {
1521 case DeclSpec::SCS_unspecified:
1522 case DeclSpec::SCS_typedef:
1523 case DeclSpec::SCS_static:
1524 // FALL THROUGH.
1525 break;
1526 case DeclSpec::SCS_mutable:
1527 if (isFunc) {
1528 if (DS.getStorageClassSpecLoc().isValid())
1529 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1530 else
1531 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1532
1533 // FIXME: It would be nicer if the keyword was ignored only for this
1534 // declarator. Otherwise we could get follow-up errors.
1535 D.getMutableDeclSpec().ClearStorageClassSpecs();
1536 }
1537 break;
1538 default:
1539 if (DS.getStorageClassSpecLoc().isValid())
1540 Diag(DS.getStorageClassSpecLoc(),
1541 diag::err_storageclass_invalid_for_member);
1542 else
1543 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1544 D.getMutableDeclSpec().ClearStorageClassSpecs();
1545 }
1546
1547 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1548 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1549 !isFunc);
1550
1551 Decl *Member;
1552 if (isInstField) {
1553 CXXScopeSpec &SS = D.getCXXScopeSpec();
1554
1555 // Data members must have identifiers for names.
1556 if (!Name.isIdentifier()) {
1557 Diag(Loc, diag::err_bad_variable_name)
1558 << Name;
1559 return 0;
1560 }
1561
1562 IdentifierInfo *II = Name.getAsIdentifierInfo();
1563
1564 // Member field could not be with "template" keyword.
1565 // So TemplateParameterLists should be empty in this case.
1566 if (TemplateParameterLists.size()) {
1567 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1568 if (TemplateParams->size()) {
1569 // There is no such thing as a member field template.
1570 Diag(D.getIdentifierLoc(), diag::err_template_member)
1571 << II
1572 << SourceRange(TemplateParams->getTemplateLoc(),
1573 TemplateParams->getRAngleLoc());
1574 } else {
1575 // There is an extraneous 'template<>' for this member.
1576 Diag(TemplateParams->getTemplateLoc(),
1577 diag::err_template_member_noparams)
1578 << II
1579 << SourceRange(TemplateParams->getTemplateLoc(),
1580 TemplateParams->getRAngleLoc());
1581 }
1582 return 0;
1583 }
1584
1585 if (SS.isSet() && !SS.isInvalid()) {
1586 // The user provided a superfluous scope specifier inside a class
1587 // definition:
1588 //
1589 // class X {
1590 // int X::member;
1591 // };
1592 if (DeclContext *DC = computeDeclContext(SS, false))
1593 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1594 else
1595 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1596 << Name << SS.getRange();
1597
1598 SS.clear();
1599 }
1600
1601 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1602 InitStyle, AS);
1603 assert(Member && "HandleField never returns null");
1604 } else {
1605 assert(InitStyle == ICIS_NoInit);
1606
1607 Member = HandleDeclarator(S, D, TemplateParameterLists);
1608 if (!Member) {
1609 return 0;
1610 }
1611
1612 // Non-instance-fields can't have a bitfield.
1613 if (BitWidth) {
1614 if (Member->isInvalidDecl()) {
1615 // don't emit another diagnostic.
1616 } else if (isa<VarDecl>(Member)) {
1617 // C++ 9.6p3: A bit-field shall not be a static member.
1618 // "static member 'A' cannot be a bit-field"
1619 Diag(Loc, diag::err_static_not_bitfield)
1620 << Name << BitWidth->getSourceRange();
1621 } else if (isa<TypedefDecl>(Member)) {
1622 // "typedef member 'x' cannot be a bit-field"
1623 Diag(Loc, diag::err_typedef_not_bitfield)
1624 << Name << BitWidth->getSourceRange();
1625 } else {
1626 // A function typedef ("typedef int f(); f a;").
1627 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1628 Diag(Loc, diag::err_not_integral_type_bitfield)
1629 << Name << cast<ValueDecl>(Member)->getType()
1630 << BitWidth->getSourceRange();
1631 }
1632
1633 BitWidth = 0;
1634 Member->setInvalidDecl();
1635 }
1636
1637 Member->setAccess(AS);
1638
1639 // If we have declared a member function template, set the access of the
1640 // templated declaration as well.
1641 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1642 FunTmpl->getTemplatedDecl()->setAccess(AS);
1643 }
1644
1645 if (VS.isOverrideSpecified())
1646 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1647 if (VS.isFinalSpecified())
1648 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1649
1650 if (VS.getLastLocation().isValid()) {
1651 // Update the end location of a method that has a virt-specifiers.
1652 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1653 MD->setRangeEnd(VS.getLastLocation());
1654 }
1655
1656 CheckOverrideControl(Member);
1657
1658 assert((Name || isInstField) && "No identifier for non-field ?");
1659
1660 if (isInstField) {
1661 FieldDecl *FD = cast<FieldDecl>(Member);
1662 FieldCollector->Add(FD);
1663
1664 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1665 FD->getLocation())
1666 != DiagnosticsEngine::Ignored) {
1667 // Remember all explicit private FieldDecls that have a name, no side
1668 // effects and are not part of a dependent type declaration.
1669 if (!FD->isImplicit() && FD->getDeclName() &&
1670 FD->getAccess() == AS_private &&
1671 !FD->hasAttr<UnusedAttr>() &&
1672 !FD->getParent()->isDependentContext() &&
1673 !InitializationHasSideEffects(*FD))
1674 UnusedPrivateFields.insert(FD);
1675 }
1676 }
1677
1678 return Member;
1679 }
1680
1681 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1682 /// in-class initializer for a non-static C++ class member, and after
1683 /// instantiating an in-class initializer in a class template. Such actions
1684 /// are deferred until the class is complete.
1685 void
ActOnCXXInClassMemberInitializer(Decl * D,SourceLocation InitLoc,Expr * InitExpr)1686 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1687 Expr *InitExpr) {
1688 FieldDecl *FD = cast<FieldDecl>(D);
1689 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1690 "must set init style when field is created");
1691
1692 if (!InitExpr) {
1693 FD->setInvalidDecl();
1694 FD->removeInClassInitializer();
1695 return;
1696 }
1697
1698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1699 FD->setInvalidDecl();
1700 FD->removeInClassInitializer();
1701 return;
1702 }
1703
1704 ExprResult Init = InitExpr;
1705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1706 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1707 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1708 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1709 }
1710 Expr **Inits = &InitExpr;
1711 unsigned NumInits = 1;
1712 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1713 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1714 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1715 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1716 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1717 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1718 if (Init.isInvalid()) {
1719 FD->setInvalidDecl();
1720 return;
1721 }
1722
1723 CheckImplicitConversions(Init.get(), InitLoc);
1724 }
1725
1726 // C++0x [class.base.init]p7:
1727 // The initialization of each base and member constitutes a
1728 // full-expression.
1729 Init = MaybeCreateExprWithCleanups(Init);
1730 if (Init.isInvalid()) {
1731 FD->setInvalidDecl();
1732 return;
1733 }
1734
1735 InitExpr = Init.release();
1736
1737 FD->setInClassInitializer(InitExpr);
1738 }
1739
1740 /// \brief Find the direct and/or virtual base specifiers that
1741 /// correspond to the given base type, for use in base initialization
1742 /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)1743 static bool FindBaseInitializer(Sema &SemaRef,
1744 CXXRecordDecl *ClassDecl,
1745 QualType BaseType,
1746 const CXXBaseSpecifier *&DirectBaseSpec,
1747 const CXXBaseSpecifier *&VirtualBaseSpec) {
1748 // First, check for a direct base class.
1749 DirectBaseSpec = 0;
1750 for (CXXRecordDecl::base_class_const_iterator Base
1751 = ClassDecl->bases_begin();
1752 Base != ClassDecl->bases_end(); ++Base) {
1753 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1754 // We found a direct base of this type. That's what we're
1755 // initializing.
1756 DirectBaseSpec = &*Base;
1757 break;
1758 }
1759 }
1760
1761 // Check for a virtual base class.
1762 // FIXME: We might be able to short-circuit this if we know in advance that
1763 // there are no virtual bases.
1764 VirtualBaseSpec = 0;
1765 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1766 // We haven't found a base yet; search the class hierarchy for a
1767 // virtual base class.
1768 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1769 /*DetectVirtual=*/false);
1770 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1771 BaseType, Paths)) {
1772 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1773 Path != Paths.end(); ++Path) {
1774 if (Path->back().Base->isVirtual()) {
1775 VirtualBaseSpec = Path->back().Base;
1776 break;
1777 }
1778 }
1779 }
1780 }
1781
1782 return DirectBaseSpec || VirtualBaseSpec;
1783 }
1784
1785 /// \brief Handle a C++ member initializer using braced-init-list syntax.
1786 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * InitList,SourceLocation EllipsisLoc)1787 Sema::ActOnMemInitializer(Decl *ConstructorD,
1788 Scope *S,
1789 CXXScopeSpec &SS,
1790 IdentifierInfo *MemberOrBase,
1791 ParsedType TemplateTypeTy,
1792 const DeclSpec &DS,
1793 SourceLocation IdLoc,
1794 Expr *InitList,
1795 SourceLocation EllipsisLoc) {
1796 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1797 DS, IdLoc, InitList,
1798 EllipsisLoc);
1799 }
1800
1801 /// \brief Handle a C++ member initializer using parentheses syntax.
1802 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc,SourceLocation EllipsisLoc)1803 Sema::ActOnMemInitializer(Decl *ConstructorD,
1804 Scope *S,
1805 CXXScopeSpec &SS,
1806 IdentifierInfo *MemberOrBase,
1807 ParsedType TemplateTypeTy,
1808 const DeclSpec &DS,
1809 SourceLocation IdLoc,
1810 SourceLocation LParenLoc,
1811 Expr **Args, unsigned NumArgs,
1812 SourceLocation RParenLoc,
1813 SourceLocation EllipsisLoc) {
1814 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
1815 llvm::makeArrayRef(Args, NumArgs),
1816 RParenLoc);
1817 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1818 DS, IdLoc, List, EllipsisLoc);
1819 }
1820
1821 namespace {
1822
1823 // Callback to only accept typo corrections that can be a valid C++ member
1824 // intializer: either a non-static field member or a base class.
1825 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1826 public:
MemInitializerValidatorCCC(CXXRecordDecl * ClassDecl)1827 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1828 : ClassDecl(ClassDecl) {}
1829
ValidateCandidate(const TypoCorrection & candidate)1830 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1831 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1832 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1833 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1834 else
1835 return isa<TypeDecl>(ND);
1836 }
1837 return false;
1838 }
1839
1840 private:
1841 CXXRecordDecl *ClassDecl;
1842 };
1843
1844 }
1845
1846 /// \brief Handle a C++ member initializer.
1847 MemInitResult
BuildMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * Init,SourceLocation EllipsisLoc)1848 Sema::BuildMemInitializer(Decl *ConstructorD,
1849 Scope *S,
1850 CXXScopeSpec &SS,
1851 IdentifierInfo *MemberOrBase,
1852 ParsedType TemplateTypeTy,
1853 const DeclSpec &DS,
1854 SourceLocation IdLoc,
1855 Expr *Init,
1856 SourceLocation EllipsisLoc) {
1857 if (!ConstructorD)
1858 return true;
1859
1860 AdjustDeclIfTemplate(ConstructorD);
1861
1862 CXXConstructorDecl *Constructor
1863 = dyn_cast<CXXConstructorDecl>(ConstructorD);
1864 if (!Constructor) {
1865 // The user wrote a constructor initializer on a function that is
1866 // not a C++ constructor. Ignore the error for now, because we may
1867 // have more member initializers coming; we'll diagnose it just
1868 // once in ActOnMemInitializers.
1869 return true;
1870 }
1871
1872 CXXRecordDecl *ClassDecl = Constructor->getParent();
1873
1874 // C++ [class.base.init]p2:
1875 // Names in a mem-initializer-id are looked up in the scope of the
1876 // constructor's class and, if not found in that scope, are looked
1877 // up in the scope containing the constructor's definition.
1878 // [Note: if the constructor's class contains a member with the
1879 // same name as a direct or virtual base class of the class, a
1880 // mem-initializer-id naming the member or base class and composed
1881 // of a single identifier refers to the class member. A
1882 // mem-initializer-id for the hidden base class may be specified
1883 // using a qualified name. ]
1884 if (!SS.getScopeRep() && !TemplateTypeTy) {
1885 // Look for a member, first.
1886 DeclContext::lookup_result Result
1887 = ClassDecl->lookup(MemberOrBase);
1888 if (Result.first != Result.second) {
1889 ValueDecl *Member;
1890 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1891 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
1892 if (EllipsisLoc.isValid())
1893 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1894 << MemberOrBase
1895 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
1896
1897 return BuildMemberInitializer(Member, Init, IdLoc);
1898 }
1899 }
1900 }
1901 // It didn't name a member, so see if it names a class.
1902 QualType BaseType;
1903 TypeSourceInfo *TInfo = 0;
1904
1905 if (TemplateTypeTy) {
1906 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1907 } else if (DS.getTypeSpecType() == TST_decltype) {
1908 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
1909 } else {
1910 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1911 LookupParsedName(R, S, &SS);
1912
1913 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1914 if (!TyD) {
1915 if (R.isAmbiguous()) return true;
1916
1917 // We don't want access-control diagnostics here.
1918 R.suppressDiagnostics();
1919
1920 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1921 bool NotUnknownSpecialization = false;
1922 DeclContext *DC = computeDeclContext(SS, false);
1923 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1924 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1925
1926 if (!NotUnknownSpecialization) {
1927 // When the scope specifier can refer to a member of an unknown
1928 // specialization, we take it as a type name.
1929 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1930 SS.getWithLocInContext(Context),
1931 *MemberOrBase, IdLoc);
1932 if (BaseType.isNull())
1933 return true;
1934
1935 R.clear();
1936 R.setLookupName(MemberOrBase);
1937 }
1938 }
1939
1940 // If no results were found, try to correct typos.
1941 TypoCorrection Corr;
1942 MemInitializerValidatorCCC Validator(ClassDecl);
1943 if (R.empty() && BaseType.isNull() &&
1944 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1945 Validator, ClassDecl))) {
1946 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1947 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
1948 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1949 // We have found a non-static data member with a similar
1950 // name to what was typed; complain and initialize that
1951 // member.
1952 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1953 << MemberOrBase << true << CorrectedQuotedStr
1954 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1955 Diag(Member->getLocation(), diag::note_previous_decl)
1956 << CorrectedQuotedStr;
1957
1958 return BuildMemberInitializer(Member, Init, IdLoc);
1959 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1960 const CXXBaseSpecifier *DirectBaseSpec;
1961 const CXXBaseSpecifier *VirtualBaseSpec;
1962 if (FindBaseInitializer(*this, ClassDecl,
1963 Context.getTypeDeclType(Type),
1964 DirectBaseSpec, VirtualBaseSpec)) {
1965 // We have found a direct or virtual base class with a
1966 // similar name to what was typed; complain and initialize
1967 // that base class.
1968 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1969 << MemberOrBase << false << CorrectedQuotedStr
1970 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1971
1972 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1973 : VirtualBaseSpec;
1974 Diag(BaseSpec->getLocStart(),
1975 diag::note_base_class_specified_here)
1976 << BaseSpec->getType()
1977 << BaseSpec->getSourceRange();
1978
1979 TyD = Type;
1980 }
1981 }
1982 }
1983
1984 if (!TyD && BaseType.isNull()) {
1985 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1986 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
1987 return true;
1988 }
1989 }
1990
1991 if (BaseType.isNull()) {
1992 BaseType = Context.getTypeDeclType(TyD);
1993 if (SS.isSet()) {
1994 NestedNameSpecifier *Qualifier =
1995 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1996
1997 // FIXME: preserve source range information
1998 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1999 }
2000 }
2001 }
2002
2003 if (!TInfo)
2004 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2005
2006 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2007 }
2008
2009 /// Checks a member initializer expression for cases where reference (or
2010 /// pointer) members are bound to by-value parameters (or their addresses).
CheckForDanglingReferenceOrPointer(Sema & S,ValueDecl * Member,Expr * Init,SourceLocation IdLoc)2011 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2012 Expr *Init,
2013 SourceLocation IdLoc) {
2014 QualType MemberTy = Member->getType();
2015
2016 // We only handle pointers and references currently.
2017 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2018 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2019 return;
2020
2021 const bool IsPointer = MemberTy->isPointerType();
2022 if (IsPointer) {
2023 if (const UnaryOperator *Op
2024 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2025 // The only case we're worried about with pointers requires taking the
2026 // address.
2027 if (Op->getOpcode() != UO_AddrOf)
2028 return;
2029
2030 Init = Op->getSubExpr();
2031 } else {
2032 // We only handle address-of expression initializers for pointers.
2033 return;
2034 }
2035 }
2036
2037 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2038 // Taking the address of a temporary will be diagnosed as a hard error.
2039 if (IsPointer)
2040 return;
2041
2042 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2043 << Member << Init->getSourceRange();
2044 } else if (const DeclRefExpr *DRE
2045 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2046 // We only warn when referring to a non-reference parameter declaration.
2047 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2048 if (!Parameter || Parameter->getType()->isReferenceType())
2049 return;
2050
2051 S.Diag(Init->getExprLoc(),
2052 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2053 : diag::warn_bind_ref_member_to_parameter)
2054 << Member << Parameter << Init->getSourceRange();
2055 } else {
2056 // Other initializers are fine.
2057 return;
2058 }
2059
2060 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2061 << (unsigned)IsPointer;
2062 }
2063
2064 namespace {
2065 class UninitializedFieldVisitor
2066 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2067 Sema &S;
2068 ValueDecl *VD;
2069 public:
2070 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema & S,ValueDecl * VD)2071 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2072 S(S), VD(VD) {
2073 }
2074
HandleExpr(Expr * E)2075 void HandleExpr(Expr *E) {
2076 if (!E) return;
2077
2078 // Expressions like x(x) sometimes lack the surrounding expressions
2079 // but need to be checked anyways.
2080 HandleValue(E);
2081 Visit(E);
2082 }
2083
HandleValue(Expr * E)2084 void HandleValue(Expr *E) {
2085 E = E->IgnoreParens();
2086
2087 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2088 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2089 return;
2090 Expr *Base = E;
2091 while (isa<MemberExpr>(Base)) {
2092 ME = dyn_cast<MemberExpr>(Base);
2093 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2094 if (VarD->hasGlobalStorage())
2095 return;
2096 Base = ME->getBase();
2097 }
2098
2099 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2100 unsigned diag = VD->getType()->isReferenceType()
2101 ? diag::warn_reference_field_is_uninit
2102 : diag::warn_field_is_uninit;
2103 S.Diag(ME->getExprLoc(), diag);
2104 return;
2105 }
2106 }
2107
2108 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2109 HandleValue(CO->getTrueExpr());
2110 HandleValue(CO->getFalseExpr());
2111 return;
2112 }
2113
2114 if (BinaryConditionalOperator *BCO =
2115 dyn_cast<BinaryConditionalOperator>(E)) {
2116 HandleValue(BCO->getCommon());
2117 HandleValue(BCO->getFalseExpr());
2118 return;
2119 }
2120
2121 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2122 switch (BO->getOpcode()) {
2123 default:
2124 return;
2125 case(BO_PtrMemD):
2126 case(BO_PtrMemI):
2127 HandleValue(BO->getLHS());
2128 return;
2129 case(BO_Comma):
2130 HandleValue(BO->getRHS());
2131 return;
2132 }
2133 }
2134 }
2135
VisitImplicitCastExpr(ImplicitCastExpr * E)2136 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2137 if (E->getCastKind() == CK_LValueToRValue)
2138 HandleValue(E->getSubExpr());
2139
2140 Inherited::VisitImplicitCastExpr(E);
2141 }
2142
VisitCXXMemberCallExpr(CXXMemberCallExpr * E)2143 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2144 Expr *Callee = E->getCallee();
2145 if (isa<MemberExpr>(Callee))
2146 HandleValue(Callee);
2147
2148 Inherited::VisitCXXMemberCallExpr(E);
2149 }
2150 };
CheckInitExprContainsUninitializedFields(Sema & S,Expr * E,ValueDecl * VD)2151 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2152 ValueDecl *VD) {
2153 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2154 }
2155 } // namespace
2156
2157 MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr * Init,SourceLocation IdLoc)2158 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2159 SourceLocation IdLoc) {
2160 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2161 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2162 assert((DirectMember || IndirectMember) &&
2163 "Member must be a FieldDecl or IndirectFieldDecl");
2164
2165 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2166 return true;
2167
2168 if (Member->isInvalidDecl())
2169 return true;
2170
2171 // Diagnose value-uses of fields to initialize themselves, e.g.
2172 // foo(foo)
2173 // where foo is not also a parameter to the constructor.
2174 // TODO: implement -Wuninitialized and fold this into that framework.
2175 Expr **Args;
2176 unsigned NumArgs;
2177 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2178 Args = ParenList->getExprs();
2179 NumArgs = ParenList->getNumExprs();
2180 } else {
2181 InitListExpr *InitList = cast<InitListExpr>(Init);
2182 Args = InitList->getInits();
2183 NumArgs = InitList->getNumInits();
2184 }
2185
2186 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2187 != DiagnosticsEngine::Ignored)
2188 for (unsigned i = 0; i < NumArgs; ++i)
2189 // FIXME: Warn about the case when other fields are used before being
2190 // uninitialized. For example, let this field be the i'th field. When
2191 // initializing the i'th field, throw a warning if any of the >= i'th
2192 // fields are used, as they are not yet initialized.
2193 // Right now we are only handling the case where the i'th field uses
2194 // itself in its initializer.
2195 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2196
2197 SourceRange InitRange = Init->getSourceRange();
2198
2199 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2200 // Can't check initialization for a member of dependent type or when
2201 // any of the arguments are type-dependent expressions.
2202 DiscardCleanupsInEvaluationContext();
2203 } else {
2204 bool InitList = false;
2205 if (isa<InitListExpr>(Init)) {
2206 InitList = true;
2207 Args = &Init;
2208 NumArgs = 1;
2209
2210 if (isStdInitializerList(Member->getType(), 0)) {
2211 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2212 << /*at end of ctor*/1 << InitRange;
2213 }
2214 }
2215
2216 // Initialize the member.
2217 InitializedEntity MemberEntity =
2218 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2219 : InitializedEntity::InitializeMember(IndirectMember, 0);
2220 InitializationKind Kind =
2221 InitList ? InitializationKind::CreateDirectList(IdLoc)
2222 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2223 InitRange.getEnd());
2224
2225 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2226 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2227 MultiExprArg(Args, NumArgs),
2228 0);
2229 if (MemberInit.isInvalid())
2230 return true;
2231
2232 CheckImplicitConversions(MemberInit.get(),
2233 InitRange.getBegin());
2234
2235 // C++0x [class.base.init]p7:
2236 // The initialization of each base and member constitutes a
2237 // full-expression.
2238 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2239 if (MemberInit.isInvalid())
2240 return true;
2241
2242 // If we are in a dependent context, template instantiation will
2243 // perform this type-checking again. Just save the arguments that we
2244 // received.
2245 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2246 // of the information that we have about the member
2247 // initializer. However, deconstructing the ASTs is a dicey process,
2248 // and this approach is far more likely to get the corner cases right.
2249 if (CurContext->isDependentContext()) {
2250 // The existing Init will do fine.
2251 } else {
2252 Init = MemberInit.get();
2253 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2254 }
2255 }
2256
2257 if (DirectMember) {
2258 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2259 InitRange.getBegin(), Init,
2260 InitRange.getEnd());
2261 } else {
2262 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2263 InitRange.getBegin(), Init,
2264 InitRange.getEnd());
2265 }
2266 }
2267
2268 MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr * Init,CXXRecordDecl * ClassDecl)2269 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2270 CXXRecordDecl *ClassDecl) {
2271 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2272 if (!LangOpts.CPlusPlus0x)
2273 return Diag(NameLoc, diag::err_delegating_ctor)
2274 << TInfo->getTypeLoc().getLocalSourceRange();
2275 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2276
2277 bool InitList = true;
2278 Expr **Args = &Init;
2279 unsigned NumArgs = 1;
2280 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2281 InitList = false;
2282 Args = ParenList->getExprs();
2283 NumArgs = ParenList->getNumExprs();
2284 }
2285
2286 SourceRange InitRange = Init->getSourceRange();
2287 // Initialize the object.
2288 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2289 QualType(ClassDecl->getTypeForDecl(), 0));
2290 InitializationKind Kind =
2291 InitList ? InitializationKind::CreateDirectList(NameLoc)
2292 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2293 InitRange.getEnd());
2294 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2295 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2296 MultiExprArg(Args, NumArgs),
2297 0);
2298 if (DelegationInit.isInvalid())
2299 return true;
2300
2301 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2302 "Delegating constructor with no target?");
2303
2304 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2305
2306 // C++0x [class.base.init]p7:
2307 // The initialization of each base and member constitutes a
2308 // full-expression.
2309 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2310 if (DelegationInit.isInvalid())
2311 return true;
2312
2313 // If we are in a dependent context, template instantiation will
2314 // perform this type-checking again. Just save the arguments that we
2315 // received in a ParenListExpr.
2316 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2317 // of the information that we have about the base
2318 // initializer. However, deconstructing the ASTs is a dicey process,
2319 // and this approach is far more likely to get the corner cases right.
2320 if (CurContext->isDependentContext())
2321 DelegationInit = Owned(Init);
2322
2323 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2324 DelegationInit.takeAs<Expr>(),
2325 InitRange.getEnd());
2326 }
2327
2328 MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr * Init,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)2329 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2330 Expr *Init, CXXRecordDecl *ClassDecl,
2331 SourceLocation EllipsisLoc) {
2332 SourceLocation BaseLoc
2333 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2334
2335 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2336 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2337 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2338
2339 // C++ [class.base.init]p2:
2340 // [...] Unless the mem-initializer-id names a nonstatic data
2341 // member of the constructor's class or a direct or virtual base
2342 // of that class, the mem-initializer is ill-formed. A
2343 // mem-initializer-list can initialize a base class using any
2344 // name that denotes that base class type.
2345 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2346
2347 SourceRange InitRange = Init->getSourceRange();
2348 if (EllipsisLoc.isValid()) {
2349 // This is a pack expansion.
2350 if (!BaseType->containsUnexpandedParameterPack()) {
2351 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2352 << SourceRange(BaseLoc, InitRange.getEnd());
2353
2354 EllipsisLoc = SourceLocation();
2355 }
2356 } else {
2357 // Check for any unexpanded parameter packs.
2358 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2359 return true;
2360
2361 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2362 return true;
2363 }
2364
2365 // Check for direct and virtual base classes.
2366 const CXXBaseSpecifier *DirectBaseSpec = 0;
2367 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2368 if (!Dependent) {
2369 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2370 BaseType))
2371 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2372
2373 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2374 VirtualBaseSpec);
2375
2376 // C++ [base.class.init]p2:
2377 // Unless the mem-initializer-id names a nonstatic data member of the
2378 // constructor's class or a direct or virtual base of that class, the
2379 // mem-initializer is ill-formed.
2380 if (!DirectBaseSpec && !VirtualBaseSpec) {
2381 // If the class has any dependent bases, then it's possible that
2382 // one of those types will resolve to the same type as
2383 // BaseType. Therefore, just treat this as a dependent base
2384 // class initialization. FIXME: Should we try to check the
2385 // initialization anyway? It seems odd.
2386 if (ClassDecl->hasAnyDependentBases())
2387 Dependent = true;
2388 else
2389 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2390 << BaseType << Context.getTypeDeclType(ClassDecl)
2391 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2392 }
2393 }
2394
2395 if (Dependent) {
2396 DiscardCleanupsInEvaluationContext();
2397
2398 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2399 /*IsVirtual=*/false,
2400 InitRange.getBegin(), Init,
2401 InitRange.getEnd(), EllipsisLoc);
2402 }
2403
2404 // C++ [base.class.init]p2:
2405 // If a mem-initializer-id is ambiguous because it designates both
2406 // a direct non-virtual base class and an inherited virtual base
2407 // class, the mem-initializer is ill-formed.
2408 if (DirectBaseSpec && VirtualBaseSpec)
2409 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2410 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2411
2412 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2413 if (!BaseSpec)
2414 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2415
2416 // Initialize the base.
2417 bool InitList = true;
2418 Expr **Args = &Init;
2419 unsigned NumArgs = 1;
2420 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2421 InitList = false;
2422 Args = ParenList->getExprs();
2423 NumArgs = ParenList->getNumExprs();
2424 }
2425
2426 InitializedEntity BaseEntity =
2427 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2428 InitializationKind Kind =
2429 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2430 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2431 InitRange.getEnd());
2432 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2433 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2434 MultiExprArg(Args, NumArgs), 0);
2435 if (BaseInit.isInvalid())
2436 return true;
2437
2438 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2439
2440 // C++0x [class.base.init]p7:
2441 // The initialization of each base and member constitutes a
2442 // full-expression.
2443 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2444 if (BaseInit.isInvalid())
2445 return true;
2446
2447 // If we are in a dependent context, template instantiation will
2448 // perform this type-checking again. Just save the arguments that we
2449 // received in a ParenListExpr.
2450 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2451 // of the information that we have about the base
2452 // initializer. However, deconstructing the ASTs is a dicey process,
2453 // and this approach is far more likely to get the corner cases right.
2454 if (CurContext->isDependentContext())
2455 BaseInit = Owned(Init);
2456
2457 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2458 BaseSpec->isVirtual(),
2459 InitRange.getBegin(),
2460 BaseInit.takeAs<Expr>(),
2461 InitRange.getEnd(), EllipsisLoc);
2462 }
2463
2464 // Create a static_cast\<T&&>(expr).
CastForMoving(Sema & SemaRef,Expr * E)2465 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2466 QualType ExprType = E->getType();
2467 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2468 SourceLocation ExprLoc = E->getLocStart();
2469 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2470 TargetType, ExprLoc);
2471
2472 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2473 SourceRange(ExprLoc, ExprLoc),
2474 E->getSourceRange()).take();
2475 }
2476
2477 /// ImplicitInitializerKind - How an implicit base or member initializer should
2478 /// initialize its base or member.
2479 enum ImplicitInitializerKind {
2480 IIK_Default,
2481 IIK_Copy,
2482 IIK_Move
2483 };
2484
2485 static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)2486 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2487 ImplicitInitializerKind ImplicitInitKind,
2488 CXXBaseSpecifier *BaseSpec,
2489 bool IsInheritedVirtualBase,
2490 CXXCtorInitializer *&CXXBaseInit) {
2491 InitializedEntity InitEntity
2492 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2493 IsInheritedVirtualBase);
2494
2495 ExprResult BaseInit;
2496
2497 switch (ImplicitInitKind) {
2498 case IIK_Default: {
2499 InitializationKind InitKind
2500 = InitializationKind::CreateDefault(Constructor->getLocation());
2501 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2502 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2503 break;
2504 }
2505
2506 case IIK_Move:
2507 case IIK_Copy: {
2508 bool Moving = ImplicitInitKind == IIK_Move;
2509 ParmVarDecl *Param = Constructor->getParamDecl(0);
2510 QualType ParamType = Param->getType().getNonReferenceType();
2511
2512 Expr *CopyCtorArg =
2513 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2514 SourceLocation(), Param, false,
2515 Constructor->getLocation(), ParamType,
2516 VK_LValue, 0);
2517
2518 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2519
2520 // Cast to the base class to avoid ambiguities.
2521 QualType ArgTy =
2522 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2523 ParamType.getQualifiers());
2524
2525 if (Moving) {
2526 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2527 }
2528
2529 CXXCastPath BasePath;
2530 BasePath.push_back(BaseSpec);
2531 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2532 CK_UncheckedDerivedToBase,
2533 Moving ? VK_XValue : VK_LValue,
2534 &BasePath).take();
2535
2536 InitializationKind InitKind
2537 = InitializationKind::CreateDirect(Constructor->getLocation(),
2538 SourceLocation(), SourceLocation());
2539 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2540 &CopyCtorArg, 1);
2541 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2542 MultiExprArg(&CopyCtorArg, 1));
2543 break;
2544 }
2545 }
2546
2547 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2548 if (BaseInit.isInvalid())
2549 return true;
2550
2551 CXXBaseInit =
2552 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2553 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2554 SourceLocation()),
2555 BaseSpec->isVirtual(),
2556 SourceLocation(),
2557 BaseInit.takeAs<Expr>(),
2558 SourceLocation(),
2559 SourceLocation());
2560
2561 return false;
2562 }
2563
RefersToRValueRef(Expr * MemRef)2564 static bool RefersToRValueRef(Expr *MemRef) {
2565 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2566 return Referenced->getType()->isRValueReferenceType();
2567 }
2568
2569 static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,IndirectFieldDecl * Indirect,CXXCtorInitializer * & CXXMemberInit)2570 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2571 ImplicitInitializerKind ImplicitInitKind,
2572 FieldDecl *Field, IndirectFieldDecl *Indirect,
2573 CXXCtorInitializer *&CXXMemberInit) {
2574 if (Field->isInvalidDecl())
2575 return true;
2576
2577 SourceLocation Loc = Constructor->getLocation();
2578
2579 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2580 bool Moving = ImplicitInitKind == IIK_Move;
2581 ParmVarDecl *Param = Constructor->getParamDecl(0);
2582 QualType ParamType = Param->getType().getNonReferenceType();
2583
2584 // Suppress copying zero-width bitfields.
2585 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2586 return false;
2587
2588 Expr *MemberExprBase =
2589 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2590 SourceLocation(), Param, false,
2591 Loc, ParamType, VK_LValue, 0);
2592
2593 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2594
2595 if (Moving) {
2596 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2597 }
2598
2599 // Build a reference to this field within the parameter.
2600 CXXScopeSpec SS;
2601 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2602 Sema::LookupMemberName);
2603 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2604 : cast<ValueDecl>(Field), AS_public);
2605 MemberLookup.resolveKind();
2606 ExprResult CtorArg
2607 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2608 ParamType, Loc,
2609 /*IsArrow=*/false,
2610 SS,
2611 /*TemplateKWLoc=*/SourceLocation(),
2612 /*FirstQualifierInScope=*/0,
2613 MemberLookup,
2614 /*TemplateArgs=*/0);
2615 if (CtorArg.isInvalid())
2616 return true;
2617
2618 // C++11 [class.copy]p15:
2619 // - if a member m has rvalue reference type T&&, it is direct-initialized
2620 // with static_cast<T&&>(x.m);
2621 if (RefersToRValueRef(CtorArg.get())) {
2622 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2623 }
2624
2625 // When the field we are copying is an array, create index variables for
2626 // each dimension of the array. We use these index variables to subscript
2627 // the source array, and other clients (e.g., CodeGen) will perform the
2628 // necessary iteration with these index variables.
2629 SmallVector<VarDecl *, 4> IndexVariables;
2630 QualType BaseType = Field->getType();
2631 QualType SizeType = SemaRef.Context.getSizeType();
2632 bool InitializingArray = false;
2633 while (const ConstantArrayType *Array
2634 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2635 InitializingArray = true;
2636 // Create the iteration variable for this array index.
2637 IdentifierInfo *IterationVarName = 0;
2638 {
2639 SmallString<8> Str;
2640 llvm::raw_svector_ostream OS(Str);
2641 OS << "__i" << IndexVariables.size();
2642 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2643 }
2644 VarDecl *IterationVar
2645 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2646 IterationVarName, SizeType,
2647 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2648 SC_None, SC_None);
2649 IndexVariables.push_back(IterationVar);
2650
2651 // Create a reference to the iteration variable.
2652 ExprResult IterationVarRef
2653 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2654 assert(!IterationVarRef.isInvalid() &&
2655 "Reference to invented variable cannot fail!");
2656 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2657 assert(!IterationVarRef.isInvalid() &&
2658 "Conversion of invented variable cannot fail!");
2659
2660 // Subscript the array with this iteration variable.
2661 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2662 IterationVarRef.take(),
2663 Loc);
2664 if (CtorArg.isInvalid())
2665 return true;
2666
2667 BaseType = Array->getElementType();
2668 }
2669
2670 // The array subscript expression is an lvalue, which is wrong for moving.
2671 if (Moving && InitializingArray)
2672 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2673
2674 // Construct the entity that we will be initializing. For an array, this
2675 // will be first element in the array, which may require several levels
2676 // of array-subscript entities.
2677 SmallVector<InitializedEntity, 4> Entities;
2678 Entities.reserve(1 + IndexVariables.size());
2679 if (Indirect)
2680 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2681 else
2682 Entities.push_back(InitializedEntity::InitializeMember(Field));
2683 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2684 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2685 0,
2686 Entities.back()));
2687
2688 // Direct-initialize to use the copy constructor.
2689 InitializationKind InitKind =
2690 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2691
2692 Expr *CtorArgE = CtorArg.takeAs<Expr>();
2693 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2694 &CtorArgE, 1);
2695
2696 ExprResult MemberInit
2697 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2698 MultiExprArg(&CtorArgE, 1));
2699 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2700 if (MemberInit.isInvalid())
2701 return true;
2702
2703 if (Indirect) {
2704 assert(IndexVariables.size() == 0 &&
2705 "Indirect field improperly initialized");
2706 CXXMemberInit
2707 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2708 Loc, Loc,
2709 MemberInit.takeAs<Expr>(),
2710 Loc);
2711 } else
2712 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2713 Loc, MemberInit.takeAs<Expr>(),
2714 Loc,
2715 IndexVariables.data(),
2716 IndexVariables.size());
2717 return false;
2718 }
2719
2720 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2721
2722 QualType FieldBaseElementType =
2723 SemaRef.Context.getBaseElementType(Field->getType());
2724
2725 if (FieldBaseElementType->isRecordType()) {
2726 InitializedEntity InitEntity
2727 = Indirect? InitializedEntity::InitializeMember(Indirect)
2728 : InitializedEntity::InitializeMember(Field);
2729 InitializationKind InitKind =
2730 InitializationKind::CreateDefault(Loc);
2731
2732 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2733 ExprResult MemberInit =
2734 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2735
2736 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2737 if (MemberInit.isInvalid())
2738 return true;
2739
2740 if (Indirect)
2741 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2742 Indirect, Loc,
2743 Loc,
2744 MemberInit.get(),
2745 Loc);
2746 else
2747 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2748 Field, Loc, Loc,
2749 MemberInit.get(),
2750 Loc);
2751 return false;
2752 }
2753
2754 if (!Field->getParent()->isUnion()) {
2755 if (FieldBaseElementType->isReferenceType()) {
2756 SemaRef.Diag(Constructor->getLocation(),
2757 diag::err_uninitialized_member_in_ctor)
2758 << (int)Constructor->isImplicit()
2759 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2760 << 0 << Field->getDeclName();
2761 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2762 return true;
2763 }
2764
2765 if (FieldBaseElementType.isConstQualified()) {
2766 SemaRef.Diag(Constructor->getLocation(),
2767 diag::err_uninitialized_member_in_ctor)
2768 << (int)Constructor->isImplicit()
2769 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2770 << 1 << Field->getDeclName();
2771 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2772 return true;
2773 }
2774 }
2775
2776 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2777 FieldBaseElementType->isObjCRetainableType() &&
2778 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2779 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2780 // ARC:
2781 // Default-initialize Objective-C pointers to NULL.
2782 CXXMemberInit
2783 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2784 Loc, Loc,
2785 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2786 Loc);
2787 return false;
2788 }
2789
2790 // Nothing to initialize.
2791 CXXMemberInit = 0;
2792 return false;
2793 }
2794
2795 namespace {
2796 struct BaseAndFieldInfo {
2797 Sema &S;
2798 CXXConstructorDecl *Ctor;
2799 bool AnyErrorsInInits;
2800 ImplicitInitializerKind IIK;
2801 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2802 SmallVector<CXXCtorInitializer*, 8> AllToInit;
2803
BaseAndFieldInfo__anon8123c3a80411::BaseAndFieldInfo2804 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2805 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2806 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2807 if (Generated && Ctor->isCopyConstructor())
2808 IIK = IIK_Copy;
2809 else if (Generated && Ctor->isMoveConstructor())
2810 IIK = IIK_Move;
2811 else
2812 IIK = IIK_Default;
2813 }
2814
isImplicitCopyOrMove__anon8123c3a80411::BaseAndFieldInfo2815 bool isImplicitCopyOrMove() const {
2816 switch (IIK) {
2817 case IIK_Copy:
2818 case IIK_Move:
2819 return true;
2820
2821 case IIK_Default:
2822 return false;
2823 }
2824
2825 llvm_unreachable("Invalid ImplicitInitializerKind!");
2826 }
2827
addFieldInitializer__anon8123c3a80411::BaseAndFieldInfo2828 bool addFieldInitializer(CXXCtorInitializer *Init) {
2829 AllToInit.push_back(Init);
2830
2831 // Check whether this initializer makes the field "used".
2832 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2833 S.UnusedPrivateFields.remove(Init->getAnyMember());
2834
2835 return false;
2836 }
2837 };
2838 }
2839
2840 /// \brief Determine whether the given indirect field declaration is somewhere
2841 /// within an anonymous union.
isWithinAnonymousUnion(IndirectFieldDecl * F)2842 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2843 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2844 CEnd = F->chain_end();
2845 C != CEnd; ++C)
2846 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2847 if (Record->isUnion())
2848 return true;
2849
2850 return false;
2851 }
2852
2853 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
2854 /// array type.
isIncompleteOrZeroLengthArrayType(ASTContext & Context,QualType T)2855 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2856 if (T->isIncompleteArrayType())
2857 return true;
2858
2859 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2860 if (!ArrayT->getSize())
2861 return true;
2862
2863 T = ArrayT->getElementType();
2864 }
2865
2866 return false;
2867 }
2868
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Field,IndirectFieldDecl * Indirect=0)2869 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2870 FieldDecl *Field,
2871 IndirectFieldDecl *Indirect = 0) {
2872
2873 // Overwhelmingly common case: we have a direct initializer for this field.
2874 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2875 return Info.addFieldInitializer(Init);
2876
2877 // C++11 [class.base.init]p8: if the entity is a non-static data member that
2878 // has a brace-or-equal-initializer, the entity is initialized as specified
2879 // in [dcl.init].
2880 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
2881 CXXCtorInitializer *Init;
2882 if (Indirect)
2883 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2884 SourceLocation(),
2885 SourceLocation(), 0,
2886 SourceLocation());
2887 else
2888 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2889 SourceLocation(),
2890 SourceLocation(), 0,
2891 SourceLocation());
2892 return Info.addFieldInitializer(Init);
2893 }
2894
2895 // Don't build an implicit initializer for union members if none was
2896 // explicitly specified.
2897 if (Field->getParent()->isUnion() ||
2898 (Indirect && isWithinAnonymousUnion(Indirect)))
2899 return false;
2900
2901 // Don't initialize incomplete or zero-length arrays.
2902 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2903 return false;
2904
2905 // Don't try to build an implicit initializer if there were semantic
2906 // errors in any of the initializers (and therefore we might be
2907 // missing some that the user actually wrote).
2908 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2909 return false;
2910
2911 CXXCtorInitializer *Init = 0;
2912 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2913 Indirect, Init))
2914 return true;
2915
2916 if (!Init)
2917 return false;
2918
2919 return Info.addFieldInitializer(Init);
2920 }
2921
2922 bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)2923 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2924 CXXCtorInitializer *Initializer) {
2925 assert(Initializer->isDelegatingInitializer());
2926 Constructor->setNumCtorInitializers(1);
2927 CXXCtorInitializer **initializer =
2928 new (Context) CXXCtorInitializer*[1];
2929 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2930 Constructor->setCtorInitializers(initializer);
2931
2932 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2933 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
2934 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2935 }
2936
2937 DelegatingCtorDecls.push_back(Constructor);
2938
2939 return false;
2940 }
2941
SetCtorInitializers(CXXConstructorDecl * Constructor,CXXCtorInitializer ** Initializers,unsigned NumInitializers,bool AnyErrors)2942 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2943 CXXCtorInitializer **Initializers,
2944 unsigned NumInitializers,
2945 bool AnyErrors) {
2946 if (Constructor->isDependentContext()) {
2947 // Just store the initializers as written, they will be checked during
2948 // instantiation.
2949 if (NumInitializers > 0) {
2950 Constructor->setNumCtorInitializers(NumInitializers);
2951 CXXCtorInitializer **baseOrMemberInitializers =
2952 new (Context) CXXCtorInitializer*[NumInitializers];
2953 memcpy(baseOrMemberInitializers, Initializers,
2954 NumInitializers * sizeof(CXXCtorInitializer*));
2955 Constructor->setCtorInitializers(baseOrMemberInitializers);
2956 }
2957
2958 return false;
2959 }
2960
2961 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2962
2963 // We need to build the initializer AST according to order of construction
2964 // and not what user specified in the Initializers list.
2965 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2966 if (!ClassDecl)
2967 return true;
2968
2969 bool HadError = false;
2970
2971 for (unsigned i = 0; i < NumInitializers; i++) {
2972 CXXCtorInitializer *Member = Initializers[i];
2973
2974 if (Member->isBaseInitializer())
2975 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2976 else
2977 Info.AllBaseFields[Member->getAnyMember()] = Member;
2978 }
2979
2980 // Keep track of the direct virtual bases.
2981 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2982 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2983 E = ClassDecl->bases_end(); I != E; ++I) {
2984 if (I->isVirtual())
2985 DirectVBases.insert(I);
2986 }
2987
2988 // Push virtual bases before others.
2989 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2990 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2991
2992 if (CXXCtorInitializer *Value
2993 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2994 Info.AllToInit.push_back(Value);
2995 } else if (!AnyErrors) {
2996 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2997 CXXCtorInitializer *CXXBaseInit;
2998 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2999 VBase, IsInheritedVirtualBase,
3000 CXXBaseInit)) {
3001 HadError = true;
3002 continue;
3003 }
3004
3005 Info.AllToInit.push_back(CXXBaseInit);
3006 }
3007 }
3008
3009 // Non-virtual bases.
3010 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3011 E = ClassDecl->bases_end(); Base != E; ++Base) {
3012 // Virtuals are in the virtual base list and already constructed.
3013 if (Base->isVirtual())
3014 continue;
3015
3016 if (CXXCtorInitializer *Value
3017 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3018 Info.AllToInit.push_back(Value);
3019 } else if (!AnyErrors) {
3020 CXXCtorInitializer *CXXBaseInit;
3021 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3022 Base, /*IsInheritedVirtualBase=*/false,
3023 CXXBaseInit)) {
3024 HadError = true;
3025 continue;
3026 }
3027
3028 Info.AllToInit.push_back(CXXBaseInit);
3029 }
3030 }
3031
3032 // Fields.
3033 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3034 MemEnd = ClassDecl->decls_end();
3035 Mem != MemEnd; ++Mem) {
3036 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3037 // C++ [class.bit]p2:
3038 // A declaration for a bit-field that omits the identifier declares an
3039 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3040 // initialized.
3041 if (F->isUnnamedBitfield())
3042 continue;
3043
3044 // If we're not generating the implicit copy/move constructor, then we'll
3045 // handle anonymous struct/union fields based on their individual
3046 // indirect fields.
3047 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3048 continue;
3049
3050 if (CollectFieldInitializer(*this, Info, F))
3051 HadError = true;
3052 continue;
3053 }
3054
3055 // Beyond this point, we only consider default initialization.
3056 if (Info.IIK != IIK_Default)
3057 continue;
3058
3059 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3060 if (F->getType()->isIncompleteArrayType()) {
3061 assert(ClassDecl->hasFlexibleArrayMember() &&
3062 "Incomplete array type is not valid");
3063 continue;
3064 }
3065
3066 // Initialize each field of an anonymous struct individually.
3067 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3068 HadError = true;
3069
3070 continue;
3071 }
3072 }
3073
3074 NumInitializers = Info.AllToInit.size();
3075 if (NumInitializers > 0) {
3076 Constructor->setNumCtorInitializers(NumInitializers);
3077 CXXCtorInitializer **baseOrMemberInitializers =
3078 new (Context) CXXCtorInitializer*[NumInitializers];
3079 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3080 NumInitializers * sizeof(CXXCtorInitializer*));
3081 Constructor->setCtorInitializers(baseOrMemberInitializers);
3082
3083 // Constructors implicitly reference the base and member
3084 // destructors.
3085 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3086 Constructor->getParent());
3087 }
3088
3089 return HadError;
3090 }
3091
GetKeyForTopLevelField(FieldDecl * Field)3092 static void *GetKeyForTopLevelField(FieldDecl *Field) {
3093 // For anonymous unions, use the class declaration as the key.
3094 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3095 if (RT->getDecl()->isAnonymousStructOrUnion())
3096 return static_cast<void *>(RT->getDecl());
3097 }
3098 return static_cast<void *>(Field);
3099 }
3100
GetKeyForBase(ASTContext & Context,QualType BaseType)3101 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3102 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3103 }
3104
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)3105 static void *GetKeyForMember(ASTContext &Context,
3106 CXXCtorInitializer *Member) {
3107 if (!Member->isAnyMemberInitializer())
3108 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3109
3110 // For fields injected into the class via declaration of an anonymous union,
3111 // use its anonymous union class declaration as the unique key.
3112 FieldDecl *Field = Member->getAnyMember();
3113
3114 // If the field is a member of an anonymous struct or union, our key
3115 // is the anonymous record decl that's a direct child of the class.
3116 RecordDecl *RD = Field->getParent();
3117 if (RD->isAnonymousStructOrUnion()) {
3118 while (true) {
3119 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3120 if (Parent->isAnonymousStructOrUnion())
3121 RD = Parent;
3122 else
3123 break;
3124 }
3125
3126 return static_cast<void *>(RD);
3127 }
3128
3129 return static_cast<void *>(Field);
3130 }
3131
3132 static void
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,CXXCtorInitializer ** Inits,unsigned NumInits)3133 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3134 const CXXConstructorDecl *Constructor,
3135 CXXCtorInitializer **Inits,
3136 unsigned NumInits) {
3137 if (Constructor->getDeclContext()->isDependentContext())
3138 return;
3139
3140 // Don't check initializers order unless the warning is enabled at the
3141 // location of at least one initializer.
3142 bool ShouldCheckOrder = false;
3143 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3144 CXXCtorInitializer *Init = Inits[InitIndex];
3145 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3146 Init->getSourceLocation())
3147 != DiagnosticsEngine::Ignored) {
3148 ShouldCheckOrder = true;
3149 break;
3150 }
3151 }
3152 if (!ShouldCheckOrder)
3153 return;
3154
3155 // Build the list of bases and members in the order that they'll
3156 // actually be initialized. The explicit initializers should be in
3157 // this same order but may be missing things.
3158 SmallVector<const void*, 32> IdealInitKeys;
3159
3160 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3161
3162 // 1. Virtual bases.
3163 for (CXXRecordDecl::base_class_const_iterator VBase =
3164 ClassDecl->vbases_begin(),
3165 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3166 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3167
3168 // 2. Non-virtual bases.
3169 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3170 E = ClassDecl->bases_end(); Base != E; ++Base) {
3171 if (Base->isVirtual())
3172 continue;
3173 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3174 }
3175
3176 // 3. Direct fields.
3177 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3178 E = ClassDecl->field_end(); Field != E; ++Field) {
3179 if (Field->isUnnamedBitfield())
3180 continue;
3181
3182 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3183 }
3184
3185 unsigned NumIdealInits = IdealInitKeys.size();
3186 unsigned IdealIndex = 0;
3187
3188 CXXCtorInitializer *PrevInit = 0;
3189 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3190 CXXCtorInitializer *Init = Inits[InitIndex];
3191 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3192
3193 // Scan forward to try to find this initializer in the idealized
3194 // initializers list.
3195 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3196 if (InitKey == IdealInitKeys[IdealIndex])
3197 break;
3198
3199 // If we didn't find this initializer, it must be because we
3200 // scanned past it on a previous iteration. That can only
3201 // happen if we're out of order; emit a warning.
3202 if (IdealIndex == NumIdealInits && PrevInit) {
3203 Sema::SemaDiagnosticBuilder D =
3204 SemaRef.Diag(PrevInit->getSourceLocation(),
3205 diag::warn_initializer_out_of_order);
3206
3207 if (PrevInit->isAnyMemberInitializer())
3208 D << 0 << PrevInit->getAnyMember()->getDeclName();
3209 else
3210 D << 1 << PrevInit->getTypeSourceInfo()->getType();
3211
3212 if (Init->isAnyMemberInitializer())
3213 D << 0 << Init->getAnyMember()->getDeclName();
3214 else
3215 D << 1 << Init->getTypeSourceInfo()->getType();
3216
3217 // Move back to the initializer's location in the ideal list.
3218 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3219 if (InitKey == IdealInitKeys[IdealIndex])
3220 break;
3221
3222 assert(IdealIndex != NumIdealInits &&
3223 "initializer not found in initializer list");
3224 }
3225
3226 PrevInit = Init;
3227 }
3228 }
3229
3230 namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)3231 bool CheckRedundantInit(Sema &S,
3232 CXXCtorInitializer *Init,
3233 CXXCtorInitializer *&PrevInit) {
3234 if (!PrevInit) {
3235 PrevInit = Init;
3236 return false;
3237 }
3238
3239 if (FieldDecl *Field = Init->getMember())
3240 S.Diag(Init->getSourceLocation(),
3241 diag::err_multiple_mem_initialization)
3242 << Field->getDeclName()
3243 << Init->getSourceRange();
3244 else {
3245 const Type *BaseClass = Init->getBaseClass();
3246 assert(BaseClass && "neither field nor base");
3247 S.Diag(Init->getSourceLocation(),
3248 diag::err_multiple_base_initialization)
3249 << QualType(BaseClass, 0)
3250 << Init->getSourceRange();
3251 }
3252 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3253 << 0 << PrevInit->getSourceRange();
3254
3255 return true;
3256 }
3257
3258 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3259 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3260
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)3261 bool CheckRedundantUnionInit(Sema &S,
3262 CXXCtorInitializer *Init,
3263 RedundantUnionMap &Unions) {
3264 FieldDecl *Field = Init->getAnyMember();
3265 RecordDecl *Parent = Field->getParent();
3266 NamedDecl *Child = Field;
3267
3268 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3269 if (Parent->isUnion()) {
3270 UnionEntry &En = Unions[Parent];
3271 if (En.first && En.first != Child) {
3272 S.Diag(Init->getSourceLocation(),
3273 diag::err_multiple_mem_union_initialization)
3274 << Field->getDeclName()
3275 << Init->getSourceRange();
3276 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3277 << 0 << En.second->getSourceRange();
3278 return true;
3279 }
3280 if (!En.first) {
3281 En.first = Child;
3282 En.second = Init;
3283 }
3284 if (!Parent->isAnonymousStructOrUnion())
3285 return false;
3286 }
3287
3288 Child = Parent;
3289 Parent = cast<RecordDecl>(Parent->getDeclContext());
3290 }
3291
3292 return false;
3293 }
3294 }
3295
3296 /// ActOnMemInitializers - Handle the member initializers for a constructor.
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,CXXCtorInitializer ** meminits,unsigned NumMemInits,bool AnyErrors)3297 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3298 SourceLocation ColonLoc,
3299 CXXCtorInitializer **meminits,
3300 unsigned NumMemInits,
3301 bool AnyErrors) {
3302 if (!ConstructorDecl)
3303 return;
3304
3305 AdjustDeclIfTemplate(ConstructorDecl);
3306
3307 CXXConstructorDecl *Constructor
3308 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3309
3310 if (!Constructor) {
3311 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3312 return;
3313 }
3314
3315 CXXCtorInitializer **MemInits =
3316 reinterpret_cast<CXXCtorInitializer **>(meminits);
3317
3318 // Mapping for the duplicate initializers check.
3319 // For member initializers, this is keyed with a FieldDecl*.
3320 // For base initializers, this is keyed with a Type*.
3321 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3322
3323 // Mapping for the inconsistent anonymous-union initializers check.
3324 RedundantUnionMap MemberUnions;
3325
3326 bool HadError = false;
3327 for (unsigned i = 0; i < NumMemInits; i++) {
3328 CXXCtorInitializer *Init = MemInits[i];
3329
3330 // Set the source order index.
3331 Init->setSourceOrder(i);
3332
3333 if (Init->isAnyMemberInitializer()) {
3334 FieldDecl *Field = Init->getAnyMember();
3335 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3336 CheckRedundantUnionInit(*this, Init, MemberUnions))
3337 HadError = true;
3338 } else if (Init->isBaseInitializer()) {
3339 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3340 if (CheckRedundantInit(*this, Init, Members[Key]))
3341 HadError = true;
3342 } else {
3343 assert(Init->isDelegatingInitializer());
3344 // This must be the only initializer
3345 if (i != 0 || NumMemInits > 1) {
3346 Diag(MemInits[0]->getSourceLocation(),
3347 diag::err_delegating_initializer_alone)
3348 << MemInits[0]->getSourceRange();
3349 HadError = true;
3350 // We will treat this as being the only initializer.
3351 }
3352 SetDelegatingInitializer(Constructor, MemInits[i]);
3353 // Return immediately as the initializer is set.
3354 return;
3355 }
3356 }
3357
3358 if (HadError)
3359 return;
3360
3361 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3362
3363 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3364 }
3365
3366 void
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)3367 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3368 CXXRecordDecl *ClassDecl) {
3369 // Ignore dependent contexts. Also ignore unions, since their members never
3370 // have destructors implicitly called.
3371 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3372 return;
3373
3374 // FIXME: all the access-control diagnostics are positioned on the
3375 // field/base declaration. That's probably good; that said, the
3376 // user might reasonably want to know why the destructor is being
3377 // emitted, and we currently don't say.
3378
3379 // Non-static data members.
3380 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3381 E = ClassDecl->field_end(); I != E; ++I) {
3382 FieldDecl *Field = *I;
3383 if (Field->isInvalidDecl())
3384 continue;
3385
3386 // Don't destroy incomplete or zero-length arrays.
3387 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3388 continue;
3389
3390 QualType FieldType = Context.getBaseElementType(Field->getType());
3391
3392 const RecordType* RT = FieldType->getAs<RecordType>();
3393 if (!RT)
3394 continue;
3395
3396 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3397 if (FieldClassDecl->isInvalidDecl())
3398 continue;
3399 if (FieldClassDecl->hasIrrelevantDestructor())
3400 continue;
3401 // The destructor for an implicit anonymous union member is never invoked.
3402 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3403 continue;
3404
3405 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3406 assert(Dtor && "No dtor found for FieldClassDecl!");
3407 CheckDestructorAccess(Field->getLocation(), Dtor,
3408 PDiag(diag::err_access_dtor_field)
3409 << Field->getDeclName()
3410 << FieldType);
3411
3412 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3413 DiagnoseUseOfDecl(Dtor, Location);
3414 }
3415
3416 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3417
3418 // Bases.
3419 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3420 E = ClassDecl->bases_end(); Base != E; ++Base) {
3421 // Bases are always records in a well-formed non-dependent class.
3422 const RecordType *RT = Base->getType()->getAs<RecordType>();
3423
3424 // Remember direct virtual bases.
3425 if (Base->isVirtual())
3426 DirectVirtualBases.insert(RT);
3427
3428 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3429 // If our base class is invalid, we probably can't get its dtor anyway.
3430 if (BaseClassDecl->isInvalidDecl())
3431 continue;
3432 if (BaseClassDecl->hasIrrelevantDestructor())
3433 continue;
3434
3435 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3436 assert(Dtor && "No dtor found for BaseClassDecl!");
3437
3438 // FIXME: caret should be on the start of the class name
3439 CheckDestructorAccess(Base->getLocStart(), Dtor,
3440 PDiag(diag::err_access_dtor_base)
3441 << Base->getType()
3442 << Base->getSourceRange(),
3443 Context.getTypeDeclType(ClassDecl));
3444
3445 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3446 DiagnoseUseOfDecl(Dtor, Location);
3447 }
3448
3449 // Virtual bases.
3450 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3451 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3452
3453 // Bases are always records in a well-formed non-dependent class.
3454 const RecordType *RT = VBase->getType()->castAs<RecordType>();
3455
3456 // Ignore direct virtual bases.
3457 if (DirectVirtualBases.count(RT))
3458 continue;
3459
3460 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3461 // If our base class is invalid, we probably can't get its dtor anyway.
3462 if (BaseClassDecl->isInvalidDecl())
3463 continue;
3464 if (BaseClassDecl->hasIrrelevantDestructor())
3465 continue;
3466
3467 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3468 assert(Dtor && "No dtor found for BaseClassDecl!");
3469 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3470 PDiag(diag::err_access_dtor_vbase)
3471 << VBase->getType(),
3472 Context.getTypeDeclType(ClassDecl));
3473
3474 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3475 DiagnoseUseOfDecl(Dtor, Location);
3476 }
3477 }
3478
ActOnDefaultCtorInitializers(Decl * CDtorDecl)3479 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3480 if (!CDtorDecl)
3481 return;
3482
3483 if (CXXConstructorDecl *Constructor
3484 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3485 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3486 }
3487
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,AbstractDiagSelID SelID)3488 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3489 unsigned DiagID, AbstractDiagSelID SelID) {
3490 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3491 unsigned DiagID;
3492 AbstractDiagSelID SelID;
3493
3494 public:
3495 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3496 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3497
3498 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3499 if (Suppressed) return;
3500 if (SelID == -1)
3501 S.Diag(Loc, DiagID) << T;
3502 else
3503 S.Diag(Loc, DiagID) << SelID << T;
3504 }
3505 } Diagnoser(DiagID, SelID);
3506
3507 return RequireNonAbstractType(Loc, T, Diagnoser);
3508 }
3509
RequireNonAbstractType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)3510 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3511 TypeDiagnoser &Diagnoser) {
3512 if (!getLangOpts().CPlusPlus)
3513 return false;
3514
3515 if (const ArrayType *AT = Context.getAsArrayType(T))
3516 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3517
3518 if (const PointerType *PT = T->getAs<PointerType>()) {
3519 // Find the innermost pointer type.
3520 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3521 PT = T;
3522
3523 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3524 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3525 }
3526
3527 const RecordType *RT = T->getAs<RecordType>();
3528 if (!RT)
3529 return false;
3530
3531 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3532
3533 // We can't answer whether something is abstract until it has a
3534 // definition. If it's currently being defined, we'll walk back
3535 // over all the declarations when we have a full definition.
3536 const CXXRecordDecl *Def = RD->getDefinition();
3537 if (!Def || Def->isBeingDefined())
3538 return false;
3539
3540 if (!RD->isAbstract())
3541 return false;
3542
3543 Diagnoser.diagnose(*this, Loc, T);
3544 DiagnoseAbstractType(RD);
3545
3546 return true;
3547 }
3548
DiagnoseAbstractType(const CXXRecordDecl * RD)3549 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3550 // Check if we've already emitted the list of pure virtual functions
3551 // for this class.
3552 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3553 return;
3554
3555 CXXFinalOverriderMap FinalOverriders;
3556 RD->getFinalOverriders(FinalOverriders);
3557
3558 // Keep a set of seen pure methods so we won't diagnose the same method
3559 // more than once.
3560 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3561
3562 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3563 MEnd = FinalOverriders.end();
3564 M != MEnd;
3565 ++M) {
3566 for (OverridingMethods::iterator SO = M->second.begin(),
3567 SOEnd = M->second.end();
3568 SO != SOEnd; ++SO) {
3569 // C++ [class.abstract]p4:
3570 // A class is abstract if it contains or inherits at least one
3571 // pure virtual function for which the final overrider is pure
3572 // virtual.
3573
3574 //
3575 if (SO->second.size() != 1)
3576 continue;
3577
3578 if (!SO->second.front().Method->isPure())
3579 continue;
3580
3581 if (!SeenPureMethods.insert(SO->second.front().Method))
3582 continue;
3583
3584 Diag(SO->second.front().Method->getLocation(),
3585 diag::note_pure_virtual_function)
3586 << SO->second.front().Method->getDeclName() << RD->getDeclName();
3587 }
3588 }
3589
3590 if (!PureVirtualClassDiagSet)
3591 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3592 PureVirtualClassDiagSet->insert(RD);
3593 }
3594
3595 namespace {
3596 struct AbstractUsageInfo {
3597 Sema &S;
3598 CXXRecordDecl *Record;
3599 CanQualType AbstractType;
3600 bool Invalid;
3601
AbstractUsageInfo__anon8123c3a80611::AbstractUsageInfo3602 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3603 : S(S), Record(Record),
3604 AbstractType(S.Context.getCanonicalType(
3605 S.Context.getTypeDeclType(Record))),
3606 Invalid(false) {}
3607
DiagnoseAbstractType__anon8123c3a80611::AbstractUsageInfo3608 void DiagnoseAbstractType() {
3609 if (Invalid) return;
3610 S.DiagnoseAbstractType(Record);
3611 Invalid = true;
3612 }
3613
3614 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3615 };
3616
3617 struct CheckAbstractUsage {
3618 AbstractUsageInfo &Info;
3619 const NamedDecl *Ctx;
3620
CheckAbstractUsage__anon8123c3a80611::CheckAbstractUsage3621 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3622 : Info(Info), Ctx(Ctx) {}
3623
Visit__anon8123c3a80611::CheckAbstractUsage3624 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3625 switch (TL.getTypeLocClass()) {
3626 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3627 #define TYPELOC(CLASS, PARENT) \
3628 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3629 #include "clang/AST/TypeLocNodes.def"
3630 }
3631 }
3632
Check__anon8123c3a80611::CheckAbstractUsage3633 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3634 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3635 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3636 if (!TL.getArg(I))
3637 continue;
3638
3639 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3640 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3641 }
3642 }
3643
Check__anon8123c3a80611::CheckAbstractUsage3644 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3645 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3646 }
3647
Check__anon8123c3a80611::CheckAbstractUsage3648 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3649 // Visit the type parameters from a permissive context.
3650 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3651 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3652 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3653 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3654 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3655 // TODO: other template argument types?
3656 }
3657 }
3658
3659 // Visit pointee types from a permissive context.
3660 #define CheckPolymorphic(Type) \
3661 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3662 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3663 }
3664 CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anon8123c3a80611::CheckAbstractUsage3665 CheckPolymorphic(ReferenceTypeLoc)
3666 CheckPolymorphic(MemberPointerTypeLoc)
3667 CheckPolymorphic(BlockPointerTypeLoc)
3668 CheckPolymorphic(AtomicTypeLoc)
3669
3670 /// Handle all the types we haven't given a more specific
3671 /// implementation for above.
3672 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3673 // Every other kind of type that we haven't called out already
3674 // that has an inner type is either (1) sugar or (2) contains that
3675 // inner type in some way as a subobject.
3676 if (TypeLoc Next = TL.getNextTypeLoc())
3677 return Visit(Next, Sel);
3678
3679 // If there's no inner type and we're in a permissive context,
3680 // don't diagnose.
3681 if (Sel == Sema::AbstractNone) return;
3682
3683 // Check whether the type matches the abstract type.
3684 QualType T = TL.getType();
3685 if (T->isArrayType()) {
3686 Sel = Sema::AbstractArrayType;
3687 T = Info.S.Context.getBaseElementType(T);
3688 }
3689 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3690 if (CT != Info.AbstractType) return;
3691
3692 // It matched; do some magic.
3693 if (Sel == Sema::AbstractArrayType) {
3694 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3695 << T << TL.getSourceRange();
3696 } else {
3697 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3698 << Sel << T << TL.getSourceRange();
3699 }
3700 Info.DiagnoseAbstractType();
3701 }
3702 };
3703
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)3704 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3705 Sema::AbstractDiagSelID Sel) {
3706 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3707 }
3708
3709 }
3710
3711 /// Check for invalid uses of an abstract type in a method declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXMethodDecl * MD)3712 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3713 CXXMethodDecl *MD) {
3714 // No need to do the check on definitions, which require that
3715 // the return/param types be complete.
3716 if (MD->doesThisDeclarationHaveABody())
3717 return;
3718
3719 // For safety's sake, just ignore it if we don't have type source
3720 // information. This should never happen for non-implicit methods,
3721 // but...
3722 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3723 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3724 }
3725
3726 /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)3727 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3728 CXXRecordDecl *RD) {
3729 for (CXXRecordDecl::decl_iterator
3730 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3731 Decl *D = *I;
3732 if (D->isImplicit()) continue;
3733
3734 // Methods and method templates.
3735 if (isa<CXXMethodDecl>(D)) {
3736 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3737 } else if (isa<FunctionTemplateDecl>(D)) {
3738 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3739 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3740
3741 // Fields and static variables.
3742 } else if (isa<FieldDecl>(D)) {
3743 FieldDecl *FD = cast<FieldDecl>(D);
3744 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3745 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3746 } else if (isa<VarDecl>(D)) {
3747 VarDecl *VD = cast<VarDecl>(D);
3748 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3749 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3750
3751 // Nested classes and class templates.
3752 } else if (isa<CXXRecordDecl>(D)) {
3753 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3754 } else if (isa<ClassTemplateDecl>(D)) {
3755 CheckAbstractClassUsage(Info,
3756 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3757 }
3758 }
3759 }
3760
3761 /// \brief Perform semantic checks on a class definition that has been
3762 /// completing, introducing implicitly-declared members, checking for
3763 /// abstract types, etc.
CheckCompletedCXXClass(CXXRecordDecl * Record)3764 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3765 if (!Record)
3766 return;
3767
3768 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3769 AbstractUsageInfo Info(*this, Record);
3770 CheckAbstractClassUsage(Info, Record);
3771 }
3772
3773 // If this is not an aggregate type and has no user-declared constructor,
3774 // complain about any non-static data members of reference or const scalar
3775 // type, since they will never get initializers.
3776 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3777 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3778 !Record->isLambda()) {
3779 bool Complained = false;
3780 for (RecordDecl::field_iterator F = Record->field_begin(),
3781 FEnd = Record->field_end();
3782 F != FEnd; ++F) {
3783 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3784 continue;
3785
3786 if (F->getType()->isReferenceType() ||
3787 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3788 if (!Complained) {
3789 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3790 << Record->getTagKind() << Record;
3791 Complained = true;
3792 }
3793
3794 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3795 << F->getType()->isReferenceType()
3796 << F->getDeclName();
3797 }
3798 }
3799 }
3800
3801 if (Record->isDynamicClass() && !Record->isDependentType())
3802 DynamicClasses.push_back(Record);
3803
3804 if (Record->getIdentifier()) {
3805 // C++ [class.mem]p13:
3806 // If T is the name of a class, then each of the following shall have a
3807 // name different from T:
3808 // - every member of every anonymous union that is a member of class T.
3809 //
3810 // C++ [class.mem]p14:
3811 // In addition, if class T has a user-declared constructor (12.1), every
3812 // non-static data member of class T shall have a name different from T.
3813 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3814 R.first != R.second; ++R.first) {
3815 NamedDecl *D = *R.first;
3816 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3817 isa<IndirectFieldDecl>(D)) {
3818 Diag(D->getLocation(), diag::err_member_name_of_class)
3819 << D->getDeclName();
3820 break;
3821 }
3822 }
3823 }
3824
3825 // Warn if the class has virtual methods but non-virtual public destructor.
3826 if (Record->isPolymorphic() && !Record->isDependentType()) {
3827 CXXDestructorDecl *dtor = Record->getDestructor();
3828 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3829 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3830 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3831 }
3832
3833 // See if a method overloads virtual methods in a base
3834 /// class without overriding any.
3835 if (!Record->isDependentType()) {
3836 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3837 MEnd = Record->method_end();
3838 M != MEnd; ++M) {
3839 if (!M->isStatic())
3840 DiagnoseHiddenVirtualMethods(Record, *M);
3841 }
3842 }
3843
3844 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3845 // function that is not a constructor declares that member function to be
3846 // const. [...] The class of which that function is a member shall be
3847 // a literal type.
3848 //
3849 // If the class has virtual bases, any constexpr members will already have
3850 // been diagnosed by the checks performed on the member declaration, so
3851 // suppress this (less useful) diagnostic.
3852 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3853 !Record->isLiteral() && !Record->getNumVBases()) {
3854 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3855 MEnd = Record->method_end();
3856 M != MEnd; ++M) {
3857 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3858 switch (Record->getTemplateSpecializationKind()) {
3859 case TSK_ImplicitInstantiation:
3860 case TSK_ExplicitInstantiationDeclaration:
3861 case TSK_ExplicitInstantiationDefinition:
3862 // If a template instantiates to a non-literal type, but its members
3863 // instantiate to constexpr functions, the template is technically
3864 // ill-formed, but we allow it for sanity.
3865 continue;
3866
3867 case TSK_Undeclared:
3868 case TSK_ExplicitSpecialization:
3869 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
3870 diag::err_constexpr_method_non_literal);
3871 break;
3872 }
3873
3874 // Only produce one error per class.
3875 break;
3876 }
3877 }
3878 }
3879
3880 // Declare inherited constructors. We do this eagerly here because:
3881 // - The standard requires an eager diagnostic for conflicting inherited
3882 // constructors from different classes.
3883 // - The lazy declaration of the other implicit constructors is so as to not
3884 // waste space and performance on classes that are not meant to be
3885 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3886 // have inherited constructors.
3887 DeclareInheritedConstructors(Record);
3888 }
3889
CheckExplicitlyDefaultedMethods(CXXRecordDecl * Record)3890 void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3891 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3892 ME = Record->method_end();
3893 MI != ME; ++MI)
3894 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
3895 CheckExplicitlyDefaultedSpecialMember(*MI);
3896 }
3897
3898 /// Is the special member function which would be selected to perform the
3899 /// specified operation on the specified class type a constexpr constructor?
specialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg)3900 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3901 Sema::CXXSpecialMember CSM,
3902 bool ConstArg) {
3903 Sema::SpecialMemberOverloadResult *SMOR =
3904 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3905 false, false, false, false);
3906 if (!SMOR || !SMOR->getMethod())
3907 // A constructor we wouldn't select can't be "involved in initializing"
3908 // anything.
3909 return true;
3910 return SMOR->getMethod()->isConstexpr();
3911 }
3912
3913 /// Determine whether the specified special member function would be constexpr
3914 /// if it were implicitly defined.
defaultedSpecialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg)3915 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3916 Sema::CXXSpecialMember CSM,
3917 bool ConstArg) {
3918 if (!S.getLangOpts().CPlusPlus0x)
3919 return false;
3920
3921 // C++11 [dcl.constexpr]p4:
3922 // In the definition of a constexpr constructor [...]
3923 switch (CSM) {
3924 case Sema::CXXDefaultConstructor:
3925 // Since default constructor lookup is essentially trivial (and cannot
3926 // involve, for instance, template instantiation), we compute whether a
3927 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3928 //
3929 // This is important for performance; we need to know whether the default
3930 // constructor is constexpr to determine whether the type is a literal type.
3931 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3932
3933 case Sema::CXXCopyConstructor:
3934 case Sema::CXXMoveConstructor:
3935 // For copy or move constructors, we need to perform overload resolution.
3936 break;
3937
3938 case Sema::CXXCopyAssignment:
3939 case Sema::CXXMoveAssignment:
3940 case Sema::CXXDestructor:
3941 case Sema::CXXInvalid:
3942 return false;
3943 }
3944
3945 // -- if the class is a non-empty union, or for each non-empty anonymous
3946 // union member of a non-union class, exactly one non-static data member
3947 // shall be initialized; [DR1359]
3948 //
3949 // If we squint, this is guaranteed, since exactly one non-static data member
3950 // will be initialized (if the constructor isn't deleted), we just don't know
3951 // which one.
3952 if (ClassDecl->isUnion())
3953 return true;
3954
3955 // -- the class shall not have any virtual base classes;
3956 if (ClassDecl->getNumVBases())
3957 return false;
3958
3959 // -- every constructor involved in initializing [...] base class
3960 // sub-objects shall be a constexpr constructor;
3961 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3962 BEnd = ClassDecl->bases_end();
3963 B != BEnd; ++B) {
3964 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3965 if (!BaseType) continue;
3966
3967 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3968 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3969 return false;
3970 }
3971
3972 // -- every constructor involved in initializing non-static data members
3973 // [...] shall be a constexpr constructor;
3974 // -- every non-static data member and base class sub-object shall be
3975 // initialized
3976 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3977 FEnd = ClassDecl->field_end();
3978 F != FEnd; ++F) {
3979 if (F->isInvalidDecl())
3980 continue;
3981 if (const RecordType *RecordTy =
3982 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
3983 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3984 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3985 return false;
3986 }
3987 }
3988
3989 // All OK, it's constexpr!
3990 return true;
3991 }
3992
3993 static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema & S,SourceLocation Loc,CXXMethodDecl * MD)3994 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3995 switch (S.getSpecialMember(MD)) {
3996 case Sema::CXXDefaultConstructor:
3997 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
3998 case Sema::CXXCopyConstructor:
3999 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4000 case Sema::CXXCopyAssignment:
4001 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4002 case Sema::CXXMoveConstructor:
4003 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4004 case Sema::CXXMoveAssignment:
4005 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4006 case Sema::CXXDestructor:
4007 return S.ComputeDefaultedDtorExceptionSpec(MD);
4008 case Sema::CXXInvalid:
4009 break;
4010 }
4011 llvm_unreachable("only special members have implicit exception specs");
4012 }
4013
4014 static void
updateExceptionSpec(Sema & S,FunctionDecl * FD,const FunctionProtoType * FPT,const Sema::ImplicitExceptionSpecification & ExceptSpec)4015 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4016 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4017 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4018 ExceptSpec.getEPI(EPI);
4019 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4020 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4021 FPT->getNumArgs(), EPI));
4022 FD->setType(QualType(NewFPT, 0));
4023 }
4024
EvaluateImplicitExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)4025 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4026 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4027 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4028 return;
4029
4030 // Evaluate the exception specification.
4031 ImplicitExceptionSpecification ExceptSpec =
4032 computeImplicitExceptionSpec(*this, Loc, MD);
4033
4034 // Update the type of the special member to use it.
4035 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4036
4037 // A user-provided destructor can be defined outside the class. When that
4038 // happens, be sure to update the exception specification on both
4039 // declarations.
4040 const FunctionProtoType *CanonicalFPT =
4041 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4042 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4043 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4044 CanonicalFPT, ExceptSpec);
4045 }
4046
4047 static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4048 static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4049
CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl * MD)4050 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4051 CXXRecordDecl *RD = MD->getParent();
4052 CXXSpecialMember CSM = getSpecialMember(MD);
4053
4054 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4055 "not an explicitly-defaulted special member");
4056
4057 // Whether this was the first-declared instance of the constructor.
4058 // This affects whether we implicitly add an exception spec and constexpr.
4059 bool First = MD == MD->getCanonicalDecl();
4060
4061 bool HadError = false;
4062
4063 // C++11 [dcl.fct.def.default]p1:
4064 // A function that is explicitly defaulted shall
4065 // -- be a special member function (checked elsewhere),
4066 // -- have the same type (except for ref-qualifiers, and except that a
4067 // copy operation can take a non-const reference) as an implicit
4068 // declaration, and
4069 // -- not have default arguments.
4070 unsigned ExpectedParams = 1;
4071 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4072 ExpectedParams = 0;
4073 if (MD->getNumParams() != ExpectedParams) {
4074 // This also checks for default arguments: a copy or move constructor with a
4075 // default argument is classified as a default constructor, and assignment
4076 // operations and destructors can't have default arguments.
4077 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4078 << CSM << MD->getSourceRange();
4079 HadError = true;
4080 }
4081
4082 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4083
4084 // Compute argument constness, constexpr, and triviality.
4085 bool CanHaveConstParam = false;
4086 bool Trivial;
4087 switch (CSM) {
4088 case CXXDefaultConstructor:
4089 Trivial = RD->hasTrivialDefaultConstructor();
4090 break;
4091 case CXXCopyConstructor:
4092 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
4093 Trivial = RD->hasTrivialCopyConstructor();
4094 break;
4095 case CXXCopyAssignment:
4096 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
4097 Trivial = RD->hasTrivialCopyAssignment();
4098 break;
4099 case CXXMoveConstructor:
4100 Trivial = RD->hasTrivialMoveConstructor();
4101 break;
4102 case CXXMoveAssignment:
4103 Trivial = RD->hasTrivialMoveAssignment();
4104 break;
4105 case CXXDestructor:
4106 Trivial = RD->hasTrivialDestructor();
4107 break;
4108 case CXXInvalid:
4109 llvm_unreachable("non-special member explicitly defaulted!");
4110 }
4111
4112 QualType ReturnType = Context.VoidTy;
4113 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4114 // Check for return type matching.
4115 ReturnType = Type->getResultType();
4116 QualType ExpectedReturnType =
4117 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4118 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4119 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4120 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4121 HadError = true;
4122 }
4123
4124 // A defaulted special member cannot have cv-qualifiers.
4125 if (Type->getTypeQuals()) {
4126 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4127 << (CSM == CXXMoveAssignment);
4128 HadError = true;
4129 }
4130 }
4131
4132 // Check for parameter type matching.
4133 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4134 bool HasConstParam = false;
4135 if (ExpectedParams && ArgType->isReferenceType()) {
4136 // Argument must be reference to possibly-const T.
4137 QualType ReferentType = ArgType->getPointeeType();
4138 HasConstParam = ReferentType.isConstQualified();
4139
4140 if (ReferentType.isVolatileQualified()) {
4141 Diag(MD->getLocation(),
4142 diag::err_defaulted_special_member_volatile_param) << CSM;
4143 HadError = true;
4144 }
4145
4146 if (HasConstParam && !CanHaveConstParam) {
4147 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4148 Diag(MD->getLocation(),
4149 diag::err_defaulted_special_member_copy_const_param)
4150 << (CSM == CXXCopyAssignment);
4151 // FIXME: Explain why this special member can't be const.
4152 } else {
4153 Diag(MD->getLocation(),
4154 diag::err_defaulted_special_member_move_const_param)
4155 << (CSM == CXXMoveAssignment);
4156 }
4157 HadError = true;
4158 }
4159
4160 // If a function is explicitly defaulted on its first declaration, it shall
4161 // have the same parameter type as if it had been implicitly declared.
4162 // (Presumably this is to prevent it from being trivial?)
4163 if (!HasConstParam && CanHaveConstParam && First)
4164 Diag(MD->getLocation(),
4165 diag::err_defaulted_special_member_copy_non_const_param)
4166 << (CSM == CXXCopyAssignment);
4167 } else if (ExpectedParams) {
4168 // A copy assignment operator can take its argument by value, but a
4169 // defaulted one cannot.
4170 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4171 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4172 HadError = true;
4173 }
4174
4175 // Rebuild the type with the implicit exception specification added, if we
4176 // are going to need it.
4177 const FunctionProtoType *ImplicitType = 0;
4178 if (First || Type->hasExceptionSpec()) {
4179 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4180 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4181 ImplicitType = cast<FunctionProtoType>(
4182 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4183 }
4184
4185 // C++11 [dcl.fct.def.default]p2:
4186 // An explicitly-defaulted function may be declared constexpr only if it
4187 // would have been implicitly declared as constexpr,
4188 // Do not apply this rule to members of class templates, since core issue 1358
4189 // makes such functions always instantiate to constexpr functions. For
4190 // non-constructors, this is checked elsewhere.
4191 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4192 HasConstParam);
4193 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4194 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4195 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4196 // FIXME: Explain why the constructor can't be constexpr.
4197 HadError = true;
4198 }
4199 // and may have an explicit exception-specification only if it is compatible
4200 // with the exception-specification on the implicit declaration.
4201 if (Type->hasExceptionSpec() &&
4202 CheckEquivalentExceptionSpec(
4203 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4204 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4205 HadError = true;
4206
4207 // If a function is explicitly defaulted on its first declaration,
4208 if (First) {
4209 // -- it is implicitly considered to be constexpr if the implicit
4210 // definition would be,
4211 MD->setConstexpr(Constexpr);
4212
4213 // -- it is implicitly considered to have the same exception-specification
4214 // as if it had been implicitly declared,
4215 MD->setType(QualType(ImplicitType, 0));
4216
4217 // Such a function is also trivial if the implicitly-declared function
4218 // would have been.
4219 MD->setTrivial(Trivial);
4220 }
4221
4222 if (ShouldDeleteSpecialMember(MD, CSM)) {
4223 if (First) {
4224 MD->setDeletedAsWritten();
4225 } else {
4226 // C++11 [dcl.fct.def.default]p4:
4227 // [For a] user-provided explicitly-defaulted function [...] if such a
4228 // function is implicitly defined as deleted, the program is ill-formed.
4229 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4230 HadError = true;
4231 }
4232 }
4233
4234 if (HadError)
4235 MD->setInvalidDecl();
4236 }
4237
4238 namespace {
4239 struct SpecialMemberDeletionInfo {
4240 Sema &S;
4241 CXXMethodDecl *MD;
4242 Sema::CXXSpecialMember CSM;
4243 bool Diagnose;
4244
4245 // Properties of the special member, computed for convenience.
4246 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4247 SourceLocation Loc;
4248
4249 bool AllFieldsAreConst;
4250
SpecialMemberDeletionInfo__anon8123c3a80711::SpecialMemberDeletionInfo4251 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4252 Sema::CXXSpecialMember CSM, bool Diagnose)
4253 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4254 IsConstructor(false), IsAssignment(false), IsMove(false),
4255 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4256 AllFieldsAreConst(true) {
4257 switch (CSM) {
4258 case Sema::CXXDefaultConstructor:
4259 case Sema::CXXCopyConstructor:
4260 IsConstructor = true;
4261 break;
4262 case Sema::CXXMoveConstructor:
4263 IsConstructor = true;
4264 IsMove = true;
4265 break;
4266 case Sema::CXXCopyAssignment:
4267 IsAssignment = true;
4268 break;
4269 case Sema::CXXMoveAssignment:
4270 IsAssignment = true;
4271 IsMove = true;
4272 break;
4273 case Sema::CXXDestructor:
4274 break;
4275 case Sema::CXXInvalid:
4276 llvm_unreachable("invalid special member kind");
4277 }
4278
4279 if (MD->getNumParams()) {
4280 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4281 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4282 }
4283 }
4284
inUnion__anon8123c3a80711::SpecialMemberDeletionInfo4285 bool inUnion() const { return MD->getParent()->isUnion(); }
4286
4287 /// Look up the corresponding special member in the given class.
lookupIn__anon8123c3a80711::SpecialMemberDeletionInfo4288 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4289 unsigned Quals) {
4290 unsigned TQ = MD->getTypeQualifiers();
4291 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4292 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4293 Quals = 0;
4294 return S.LookupSpecialMember(Class, CSM,
4295 ConstArg || (Quals & Qualifiers::Const),
4296 VolatileArg || (Quals & Qualifiers::Volatile),
4297 MD->getRefQualifier() == RQ_RValue,
4298 TQ & Qualifiers::Const,
4299 TQ & Qualifiers::Volatile);
4300 }
4301
4302 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4303
4304 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4305 bool shouldDeleteForField(FieldDecl *FD);
4306 bool shouldDeleteForAllConstMembers();
4307
4308 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4309 unsigned Quals);
4310 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4311 Sema::SpecialMemberOverloadResult *SMOR,
4312 bool IsDtorCallInCtor);
4313
4314 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4315 };
4316 }
4317
4318 /// Is the given special member inaccessible when used on the given
4319 /// sub-object.
isAccessible(Subobject Subobj,CXXMethodDecl * target)4320 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4321 CXXMethodDecl *target) {
4322 /// If we're operating on a base class, the object type is the
4323 /// type of this special member.
4324 QualType objectTy;
4325 AccessSpecifier access = target->getAccess();
4326 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4327 objectTy = S.Context.getTypeDeclType(MD->getParent());
4328 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4329
4330 // If we're operating on a field, the object type is the type of the field.
4331 } else {
4332 objectTy = S.Context.getTypeDeclType(target->getParent());
4333 }
4334
4335 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4336 }
4337
4338 /// Check whether we should delete a special member due to the implicit
4339 /// definition containing a call to a special member of a subobject.
shouldDeleteForSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult * SMOR,bool IsDtorCallInCtor)4340 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4341 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4342 bool IsDtorCallInCtor) {
4343 CXXMethodDecl *Decl = SMOR->getMethod();
4344 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4345
4346 int DiagKind = -1;
4347
4348 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4349 DiagKind = !Decl ? 0 : 1;
4350 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4351 DiagKind = 2;
4352 else if (!isAccessible(Subobj, Decl))
4353 DiagKind = 3;
4354 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4355 !Decl->isTrivial()) {
4356 // A member of a union must have a trivial corresponding special member.
4357 // As a weird special case, a destructor call from a union's constructor
4358 // must be accessible and non-deleted, but need not be trivial. Such a
4359 // destructor is never actually called, but is semantically checked as
4360 // if it were.
4361 DiagKind = 4;
4362 }
4363
4364 if (DiagKind == -1)
4365 return false;
4366
4367 if (Diagnose) {
4368 if (Field) {
4369 S.Diag(Field->getLocation(),
4370 diag::note_deleted_special_member_class_subobject)
4371 << CSM << MD->getParent() << /*IsField*/true
4372 << Field << DiagKind << IsDtorCallInCtor;
4373 } else {
4374 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4375 S.Diag(Base->getLocStart(),
4376 diag::note_deleted_special_member_class_subobject)
4377 << CSM << MD->getParent() << /*IsField*/false
4378 << Base->getType() << DiagKind << IsDtorCallInCtor;
4379 }
4380
4381 if (DiagKind == 1)
4382 S.NoteDeletedFunction(Decl);
4383 // FIXME: Explain inaccessibility if DiagKind == 3.
4384 }
4385
4386 return true;
4387 }
4388
4389 /// Check whether we should delete a special member function due to having a
4390 /// direct or virtual base class or non-static data member of class type M.
shouldDeleteForClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)4391 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4392 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4393 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4394
4395 // C++11 [class.ctor]p5:
4396 // -- any direct or virtual base class, or non-static data member with no
4397 // brace-or-equal-initializer, has class type M (or array thereof) and
4398 // either M has no default constructor or overload resolution as applied
4399 // to M's default constructor results in an ambiguity or in a function
4400 // that is deleted or inaccessible
4401 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4402 // -- a direct or virtual base class B that cannot be copied/moved because
4403 // overload resolution, as applied to B's corresponding special member,
4404 // results in an ambiguity or a function that is deleted or inaccessible
4405 // from the defaulted special member
4406 // C++11 [class.dtor]p5:
4407 // -- any direct or virtual base class [...] has a type with a destructor
4408 // that is deleted or inaccessible
4409 if (!(CSM == Sema::CXXDefaultConstructor &&
4410 Field && Field->hasInClassInitializer()) &&
4411 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4412 return true;
4413
4414 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4415 // -- any direct or virtual base class or non-static data member has a
4416 // type with a destructor that is deleted or inaccessible
4417 if (IsConstructor) {
4418 Sema::SpecialMemberOverloadResult *SMOR =
4419 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4420 false, false, false, false, false);
4421 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4422 return true;
4423 }
4424
4425 return false;
4426 }
4427
4428 /// Check whether we should delete a special member function due to the class
4429 /// having a particular direct or virtual base class.
shouldDeleteForBase(CXXBaseSpecifier * Base)4430 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4431 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4432 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4433 }
4434
4435 /// Check whether we should delete a special member function due to the class
4436 /// having a particular non-static data member.
shouldDeleteForField(FieldDecl * FD)4437 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4438 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4439 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4440
4441 if (CSM == Sema::CXXDefaultConstructor) {
4442 // For a default constructor, all references must be initialized in-class
4443 // and, if a union, it must have a non-const member.
4444 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4445 if (Diagnose)
4446 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4447 << MD->getParent() << FD << FieldType << /*Reference*/0;
4448 return true;
4449 }
4450 // C++11 [class.ctor]p5: any non-variant non-static data member of
4451 // const-qualified type (or array thereof) with no
4452 // brace-or-equal-initializer does not have a user-provided default
4453 // constructor.
4454 if (!inUnion() && FieldType.isConstQualified() &&
4455 !FD->hasInClassInitializer() &&
4456 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4457 if (Diagnose)
4458 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4459 << MD->getParent() << FD << FD->getType() << /*Const*/1;
4460 return true;
4461 }
4462
4463 if (inUnion() && !FieldType.isConstQualified())
4464 AllFieldsAreConst = false;
4465 } else if (CSM == Sema::CXXCopyConstructor) {
4466 // For a copy constructor, data members must not be of rvalue reference
4467 // type.
4468 if (FieldType->isRValueReferenceType()) {
4469 if (Diagnose)
4470 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4471 << MD->getParent() << FD << FieldType;
4472 return true;
4473 }
4474 } else if (IsAssignment) {
4475 // For an assignment operator, data members must not be of reference type.
4476 if (FieldType->isReferenceType()) {
4477 if (Diagnose)
4478 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4479 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4480 return true;
4481 }
4482 if (!FieldRecord && FieldType.isConstQualified()) {
4483 // C++11 [class.copy]p23:
4484 // -- a non-static data member of const non-class type (or array thereof)
4485 if (Diagnose)
4486 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4487 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4488 return true;
4489 }
4490 }
4491
4492 if (FieldRecord) {
4493 // Some additional restrictions exist on the variant members.
4494 if (!inUnion() && FieldRecord->isUnion() &&
4495 FieldRecord->isAnonymousStructOrUnion()) {
4496 bool AllVariantFieldsAreConst = true;
4497
4498 // FIXME: Handle anonymous unions declared within anonymous unions.
4499 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4500 UE = FieldRecord->field_end();
4501 UI != UE; ++UI) {
4502 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4503
4504 if (!UnionFieldType.isConstQualified())
4505 AllVariantFieldsAreConst = false;
4506
4507 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4508 if (UnionFieldRecord &&
4509 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4510 UnionFieldType.getCVRQualifiers()))
4511 return true;
4512 }
4513
4514 // At least one member in each anonymous union must be non-const
4515 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4516 FieldRecord->field_begin() != FieldRecord->field_end()) {
4517 if (Diagnose)
4518 S.Diag(FieldRecord->getLocation(),
4519 diag::note_deleted_default_ctor_all_const)
4520 << MD->getParent() << /*anonymous union*/1;
4521 return true;
4522 }
4523
4524 // Don't check the implicit member of the anonymous union type.
4525 // This is technically non-conformant, but sanity demands it.
4526 return false;
4527 }
4528
4529 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4530 FieldType.getCVRQualifiers()))
4531 return true;
4532 }
4533
4534 return false;
4535 }
4536
4537 /// C++11 [class.ctor] p5:
4538 /// A defaulted default constructor for a class X is defined as deleted if
4539 /// X is a union and all of its variant members are of const-qualified type.
shouldDeleteForAllConstMembers()4540 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4541 // This is a silly definition, because it gives an empty union a deleted
4542 // default constructor. Don't do that.
4543 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4544 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4545 if (Diagnose)
4546 S.Diag(MD->getParent()->getLocation(),
4547 diag::note_deleted_default_ctor_all_const)
4548 << MD->getParent() << /*not anonymous union*/0;
4549 return true;
4550 }
4551 return false;
4552 }
4553
4554 /// Determine whether a defaulted special member function should be defined as
4555 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4556 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
ShouldDeleteSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM,bool Diagnose)4557 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4558 bool Diagnose) {
4559 if (MD->isInvalidDecl())
4560 return false;
4561 CXXRecordDecl *RD = MD->getParent();
4562 assert(!RD->isDependentType() && "do deletion after instantiation");
4563 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4564 return false;
4565
4566 // C++11 [expr.lambda.prim]p19:
4567 // The closure type associated with a lambda-expression has a
4568 // deleted (8.4.3) default constructor and a deleted copy
4569 // assignment operator.
4570 if (RD->isLambda() &&
4571 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4572 if (Diagnose)
4573 Diag(RD->getLocation(), diag::note_lambda_decl);
4574 return true;
4575 }
4576
4577 // For an anonymous struct or union, the copy and assignment special members
4578 // will never be used, so skip the check. For an anonymous union declared at
4579 // namespace scope, the constructor and destructor are used.
4580 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4581 RD->isAnonymousStructOrUnion())
4582 return false;
4583
4584 // C++11 [class.copy]p7, p18:
4585 // If the class definition declares a move constructor or move assignment
4586 // operator, an implicitly declared copy constructor or copy assignment
4587 // operator is defined as deleted.
4588 if (MD->isImplicit() &&
4589 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4590 CXXMethodDecl *UserDeclaredMove = 0;
4591
4592 // In Microsoft mode, a user-declared move only causes the deletion of the
4593 // corresponding copy operation, not both copy operations.
4594 if (RD->hasUserDeclaredMoveConstructor() &&
4595 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4596 if (!Diagnose) return true;
4597 UserDeclaredMove = RD->getMoveConstructor();
4598 assert(UserDeclaredMove);
4599 } else if (RD->hasUserDeclaredMoveAssignment() &&
4600 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4601 if (!Diagnose) return true;
4602 UserDeclaredMove = RD->getMoveAssignmentOperator();
4603 assert(UserDeclaredMove);
4604 }
4605
4606 if (UserDeclaredMove) {
4607 Diag(UserDeclaredMove->getLocation(),
4608 diag::note_deleted_copy_user_declared_move)
4609 << (CSM == CXXCopyAssignment) << RD
4610 << UserDeclaredMove->isMoveAssignmentOperator();
4611 return true;
4612 }
4613 }
4614
4615 // Do access control from the special member function
4616 ContextRAII MethodContext(*this, MD);
4617
4618 // C++11 [class.dtor]p5:
4619 // -- for a virtual destructor, lookup of the non-array deallocation function
4620 // results in an ambiguity or in a function that is deleted or inaccessible
4621 if (CSM == CXXDestructor && MD->isVirtual()) {
4622 FunctionDecl *OperatorDelete = 0;
4623 DeclarationName Name =
4624 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4625 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4626 OperatorDelete, false)) {
4627 if (Diagnose)
4628 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4629 return true;
4630 }
4631 }
4632
4633 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4634
4635 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4636 BE = RD->bases_end(); BI != BE; ++BI)
4637 if (!BI->isVirtual() &&
4638 SMI.shouldDeleteForBase(BI))
4639 return true;
4640
4641 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4642 BE = RD->vbases_end(); BI != BE; ++BI)
4643 if (SMI.shouldDeleteForBase(BI))
4644 return true;
4645
4646 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4647 FE = RD->field_end(); FI != FE; ++FI)
4648 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4649 SMI.shouldDeleteForField(*FI))
4650 return true;
4651
4652 if (SMI.shouldDeleteForAllConstMembers())
4653 return true;
4654
4655 return false;
4656 }
4657
4658 /// \brief Data used with FindHiddenVirtualMethod
4659 namespace {
4660 struct FindHiddenVirtualMethodData {
4661 Sema *S;
4662 CXXMethodDecl *Method;
4663 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4664 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4665 };
4666 }
4667
4668 /// \brief Member lookup function that determines whether a given C++
4669 /// method overloads virtual methods in a base class without overriding any,
4670 /// to be used with CXXRecordDecl::lookupInBases().
FindHiddenVirtualMethod(const CXXBaseSpecifier * Specifier,CXXBasePath & Path,void * UserData)4671 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4672 CXXBasePath &Path,
4673 void *UserData) {
4674 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4675
4676 FindHiddenVirtualMethodData &Data
4677 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4678
4679 DeclarationName Name = Data.Method->getDeclName();
4680 assert(Name.getNameKind() == DeclarationName::Identifier);
4681
4682 bool foundSameNameMethod = false;
4683 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4684 for (Path.Decls = BaseRecord->lookup(Name);
4685 Path.Decls.first != Path.Decls.second;
4686 ++Path.Decls.first) {
4687 NamedDecl *D = *Path.Decls.first;
4688 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4689 MD = MD->getCanonicalDecl();
4690 foundSameNameMethod = true;
4691 // Interested only in hidden virtual methods.
4692 if (!MD->isVirtual())
4693 continue;
4694 // If the method we are checking overrides a method from its base
4695 // don't warn about the other overloaded methods.
4696 if (!Data.S->IsOverload(Data.Method, MD, false))
4697 return true;
4698 // Collect the overload only if its hidden.
4699 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4700 overloadedMethods.push_back(MD);
4701 }
4702 }
4703
4704 if (foundSameNameMethod)
4705 Data.OverloadedMethods.append(overloadedMethods.begin(),
4706 overloadedMethods.end());
4707 return foundSameNameMethod;
4708 }
4709
4710 /// \brief See if a method overloads virtual methods in a base class without
4711 /// overriding any.
DiagnoseHiddenVirtualMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)4712 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4713 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4714 MD->getLocation()) == DiagnosticsEngine::Ignored)
4715 return;
4716 if (!MD->getDeclName().isIdentifier())
4717 return;
4718
4719 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4720 /*bool RecordPaths=*/false,
4721 /*bool DetectVirtual=*/false);
4722 FindHiddenVirtualMethodData Data;
4723 Data.Method = MD;
4724 Data.S = this;
4725
4726 // Keep the base methods that were overriden or introduced in the subclass
4727 // by 'using' in a set. A base method not in this set is hidden.
4728 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4729 res.first != res.second; ++res.first) {
4730 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4731 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4732 E = MD->end_overridden_methods();
4733 I != E; ++I)
4734 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4735 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4736 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4737 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4738 }
4739
4740 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4741 !Data.OverloadedMethods.empty()) {
4742 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4743 << MD << (Data.OverloadedMethods.size() > 1);
4744
4745 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4746 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4747 Diag(overloadedMD->getLocation(),
4748 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4749 }
4750 }
4751 }
4752
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,AttributeList * AttrList)4753 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4754 Decl *TagDecl,
4755 SourceLocation LBrac,
4756 SourceLocation RBrac,
4757 AttributeList *AttrList) {
4758 if (!TagDecl)
4759 return;
4760
4761 AdjustDeclIfTemplate(TagDecl);
4762
4763 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4764 if (l->getKind() != AttributeList::AT_Visibility)
4765 continue;
4766 l->setInvalid();
4767 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4768 l->getName();
4769 }
4770
4771 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4772 // strict aliasing violation!
4773 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4774 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4775
4776 CheckCompletedCXXClass(
4777 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4778 }
4779
4780 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4781 /// special functions, such as the default constructor, copy
4782 /// constructor, or destructor, to the given C++ class (C++
4783 /// [special]p1). This routine can only be executed just before the
4784 /// definition of the class is complete.
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)4785 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4786 if (!ClassDecl->hasUserDeclaredConstructor())
4787 ++ASTContext::NumImplicitDefaultConstructors;
4788
4789 if (!ClassDecl->hasUserDeclaredCopyConstructor())
4790 ++ASTContext::NumImplicitCopyConstructors;
4791
4792 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4793 ++ASTContext::NumImplicitMoveConstructors;
4794
4795 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4796 ++ASTContext::NumImplicitCopyAssignmentOperators;
4797
4798 // If we have a dynamic class, then the copy assignment operator may be
4799 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4800 // it shows up in the right place in the vtable and that we diagnose
4801 // problems with the implicit exception specification.
4802 if (ClassDecl->isDynamicClass())
4803 DeclareImplicitCopyAssignment(ClassDecl);
4804 }
4805
4806 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
4807 ++ASTContext::NumImplicitMoveAssignmentOperators;
4808
4809 // Likewise for the move assignment operator.
4810 if (ClassDecl->isDynamicClass())
4811 DeclareImplicitMoveAssignment(ClassDecl);
4812 }
4813
4814 if (!ClassDecl->hasUserDeclaredDestructor()) {
4815 ++ASTContext::NumImplicitDestructors;
4816
4817 // If we have a dynamic class, then the destructor may be virtual, so we
4818 // have to declare the destructor immediately. This ensures that, e.g., it
4819 // shows up in the right place in the vtable and that we diagnose problems
4820 // with the implicit exception specification.
4821 if (ClassDecl->isDynamicClass())
4822 DeclareImplicitDestructor(ClassDecl);
4823 }
4824 }
4825
ActOnReenterDeclaratorTemplateScope(Scope * S,DeclaratorDecl * D)4826 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4827 if (!D)
4828 return;
4829
4830 int NumParamList = D->getNumTemplateParameterLists();
4831 for (int i = 0; i < NumParamList; i++) {
4832 TemplateParameterList* Params = D->getTemplateParameterList(i);
4833 for (TemplateParameterList::iterator Param = Params->begin(),
4834 ParamEnd = Params->end();
4835 Param != ParamEnd; ++Param) {
4836 NamedDecl *Named = cast<NamedDecl>(*Param);
4837 if (Named->getDeclName()) {
4838 S->AddDecl(Named);
4839 IdResolver.AddDecl(Named);
4840 }
4841 }
4842 }
4843 }
4844
ActOnReenterTemplateScope(Scope * S,Decl * D)4845 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4846 if (!D)
4847 return;
4848
4849 TemplateParameterList *Params = 0;
4850 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4851 Params = Template->getTemplateParameters();
4852 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4853 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4854 Params = PartialSpec->getTemplateParameters();
4855 else
4856 return;
4857
4858 for (TemplateParameterList::iterator Param = Params->begin(),
4859 ParamEnd = Params->end();
4860 Param != ParamEnd; ++Param) {
4861 NamedDecl *Named = cast<NamedDecl>(*Param);
4862 if (Named->getDeclName()) {
4863 S->AddDecl(Named);
4864 IdResolver.AddDecl(Named);
4865 }
4866 }
4867 }
4868
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)4869 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4870 if (!RecordD) return;
4871 AdjustDeclIfTemplate(RecordD);
4872 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4873 PushDeclContext(S, Record);
4874 }
4875
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)4876 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4877 if (!RecordD) return;
4878 PopDeclContext();
4879 }
4880
4881 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
4882 /// parsing a top-level (non-nested) C++ class, and we are now
4883 /// parsing those parts of the given Method declaration that could
4884 /// not be parsed earlier (C++ [class.mem]p2), such as default
4885 /// arguments. This action should enter the scope of the given
4886 /// Method declaration as if we had just parsed the qualified method
4887 /// name. However, it should not bring the parameters into scope;
4888 /// that will be performed by ActOnDelayedCXXMethodParameter.
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)4889 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4890 }
4891
4892 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
4893 /// C++ method declaration. We're (re-)introducing the given
4894 /// function parameter into scope for use in parsing later parts of
4895 /// the method declaration. For example, we could see an
4896 /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)4897 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4898 if (!ParamD)
4899 return;
4900
4901 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4902
4903 // If this parameter has an unparsed default argument, clear it out
4904 // to make way for the parsed default argument.
4905 if (Param->hasUnparsedDefaultArg())
4906 Param->setDefaultArg(0);
4907
4908 S->AddDecl(Param);
4909 if (Param->getDeclName())
4910 IdResolver.AddDecl(Param);
4911 }
4912
4913 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4914 /// processing the delayed method declaration for Method. The method
4915 /// declaration is now considered finished. There may be a separate
4916 /// ActOnStartOfFunctionDef action later (not necessarily
4917 /// immediately!) for this method, if it was also defined inside the
4918 /// class body.
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)4919 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4920 if (!MethodD)
4921 return;
4922
4923 AdjustDeclIfTemplate(MethodD);
4924
4925 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4926
4927 // Now that we have our default arguments, check the constructor
4928 // again. It could produce additional diagnostics or affect whether
4929 // the class has implicitly-declared destructors, among other
4930 // things.
4931 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4932 CheckConstructor(Constructor);
4933
4934 // Check the default arguments, which we may have added.
4935 if (!Method->isInvalidDecl())
4936 CheckCXXDefaultArguments(Method);
4937 }
4938
4939 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4940 /// the well-formedness of the constructor declarator @p D with type @p
4941 /// R. If there are any errors in the declarator, this routine will
4942 /// emit diagnostics and set the invalid bit to true. In any case, the type
4943 /// will be updated to reflect a well-formed type for the constructor and
4944 /// returned.
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)4945 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4946 StorageClass &SC) {
4947 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4948
4949 // C++ [class.ctor]p3:
4950 // A constructor shall not be virtual (10.3) or static (9.4). A
4951 // constructor can be invoked for a const, volatile or const
4952 // volatile object. A constructor shall not be declared const,
4953 // volatile, or const volatile (9.3.2).
4954 if (isVirtual) {
4955 if (!D.isInvalidType())
4956 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4957 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4958 << SourceRange(D.getIdentifierLoc());
4959 D.setInvalidType();
4960 }
4961 if (SC == SC_Static) {
4962 if (!D.isInvalidType())
4963 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4964 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4965 << SourceRange(D.getIdentifierLoc());
4966 D.setInvalidType();
4967 SC = SC_None;
4968 }
4969
4970 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4971 if (FTI.TypeQuals != 0) {
4972 if (FTI.TypeQuals & Qualifiers::Const)
4973 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4974 << "const" << SourceRange(D.getIdentifierLoc());
4975 if (FTI.TypeQuals & Qualifiers::Volatile)
4976 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4977 << "volatile" << SourceRange(D.getIdentifierLoc());
4978 if (FTI.TypeQuals & Qualifiers::Restrict)
4979 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4980 << "restrict" << SourceRange(D.getIdentifierLoc());
4981 D.setInvalidType();
4982 }
4983
4984 // C++0x [class.ctor]p4:
4985 // A constructor shall not be declared with a ref-qualifier.
4986 if (FTI.hasRefQualifier()) {
4987 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4988 << FTI.RefQualifierIsLValueRef
4989 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4990 D.setInvalidType();
4991 }
4992
4993 // Rebuild the function type "R" without any type qualifiers (in
4994 // case any of the errors above fired) and with "void" as the
4995 // return type, since constructors don't have return types.
4996 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4997 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4998 return R;
4999
5000 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5001 EPI.TypeQuals = 0;
5002 EPI.RefQualifier = RQ_None;
5003
5004 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5005 Proto->getNumArgs(), EPI);
5006 }
5007
5008 /// CheckConstructor - Checks a fully-formed constructor for
5009 /// well-formedness, issuing any diagnostics required. Returns true if
5010 /// the constructor declarator is invalid.
CheckConstructor(CXXConstructorDecl * Constructor)5011 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5012 CXXRecordDecl *ClassDecl
5013 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5014 if (!ClassDecl)
5015 return Constructor->setInvalidDecl();
5016
5017 // C++ [class.copy]p3:
5018 // A declaration of a constructor for a class X is ill-formed if
5019 // its first parameter is of type (optionally cv-qualified) X and
5020 // either there are no other parameters or else all other
5021 // parameters have default arguments.
5022 if (!Constructor->isInvalidDecl() &&
5023 ((Constructor->getNumParams() == 1) ||
5024 (Constructor->getNumParams() > 1 &&
5025 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5026 Constructor->getTemplateSpecializationKind()
5027 != TSK_ImplicitInstantiation) {
5028 QualType ParamType = Constructor->getParamDecl(0)->getType();
5029 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5030 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5031 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5032 const char *ConstRef
5033 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5034 : " const &";
5035 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5036 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5037
5038 // FIXME: Rather that making the constructor invalid, we should endeavor
5039 // to fix the type.
5040 Constructor->setInvalidDecl();
5041 }
5042 }
5043 }
5044
5045 /// CheckDestructor - Checks a fully-formed destructor definition for
5046 /// well-formedness, issuing any diagnostics required. Returns true
5047 /// on error.
CheckDestructor(CXXDestructorDecl * Destructor)5048 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5049 CXXRecordDecl *RD = Destructor->getParent();
5050
5051 if (Destructor->isVirtual()) {
5052 SourceLocation Loc;
5053
5054 if (!Destructor->isImplicit())
5055 Loc = Destructor->getLocation();
5056 else
5057 Loc = RD->getLocation();
5058
5059 // If we have a virtual destructor, look up the deallocation function
5060 FunctionDecl *OperatorDelete = 0;
5061 DeclarationName Name =
5062 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5063 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5064 return true;
5065
5066 MarkFunctionReferenced(Loc, OperatorDelete);
5067
5068 Destructor->setOperatorDelete(OperatorDelete);
5069 }
5070
5071 return false;
5072 }
5073
5074 static inline bool
FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo & FTI)5075 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5076 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5077 FTI.ArgInfo[0].Param &&
5078 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5079 }
5080
5081 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5082 /// the well-formednes of the destructor declarator @p D with type @p
5083 /// R. If there are any errors in the declarator, this routine will
5084 /// emit diagnostics and set the declarator to invalid. Even if this happens,
5085 /// will be updated to reflect a well-formed type for the destructor and
5086 /// returned.
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)5087 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5088 StorageClass& SC) {
5089 // C++ [class.dtor]p1:
5090 // [...] A typedef-name that names a class is a class-name
5091 // (7.1.3); however, a typedef-name that names a class shall not
5092 // be used as the identifier in the declarator for a destructor
5093 // declaration.
5094 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5095 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5096 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5097 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5098 else if (const TemplateSpecializationType *TST =
5099 DeclaratorType->getAs<TemplateSpecializationType>())
5100 if (TST->isTypeAlias())
5101 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5102 << DeclaratorType << 1;
5103
5104 // C++ [class.dtor]p2:
5105 // A destructor is used to destroy objects of its class type. A
5106 // destructor takes no parameters, and no return type can be
5107 // specified for it (not even void). The address of a destructor
5108 // shall not be taken. A destructor shall not be static. A
5109 // destructor can be invoked for a const, volatile or const
5110 // volatile object. A destructor shall not be declared const,
5111 // volatile or const volatile (9.3.2).
5112 if (SC == SC_Static) {
5113 if (!D.isInvalidType())
5114 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5115 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5116 << SourceRange(D.getIdentifierLoc())
5117 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5118
5119 SC = SC_None;
5120 }
5121 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5122 // Destructors don't have return types, but the parser will
5123 // happily parse something like:
5124 //
5125 // class X {
5126 // float ~X();
5127 // };
5128 //
5129 // The return type will be eliminated later.
5130 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5131 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5132 << SourceRange(D.getIdentifierLoc());
5133 }
5134
5135 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5136 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5137 if (FTI.TypeQuals & Qualifiers::Const)
5138 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5139 << "const" << SourceRange(D.getIdentifierLoc());
5140 if (FTI.TypeQuals & Qualifiers::Volatile)
5141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5142 << "volatile" << SourceRange(D.getIdentifierLoc());
5143 if (FTI.TypeQuals & Qualifiers::Restrict)
5144 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5145 << "restrict" << SourceRange(D.getIdentifierLoc());
5146 D.setInvalidType();
5147 }
5148
5149 // C++0x [class.dtor]p2:
5150 // A destructor shall not be declared with a ref-qualifier.
5151 if (FTI.hasRefQualifier()) {
5152 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5153 << FTI.RefQualifierIsLValueRef
5154 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5155 D.setInvalidType();
5156 }
5157
5158 // Make sure we don't have any parameters.
5159 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5160 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5161
5162 // Delete the parameters.
5163 FTI.freeArgs();
5164 D.setInvalidType();
5165 }
5166
5167 // Make sure the destructor isn't variadic.
5168 if (FTI.isVariadic) {
5169 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5170 D.setInvalidType();
5171 }
5172
5173 // Rebuild the function type "R" without any type qualifiers or
5174 // parameters (in case any of the errors above fired) and with
5175 // "void" as the return type, since destructors don't have return
5176 // types.
5177 if (!D.isInvalidType())
5178 return R;
5179
5180 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5181 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5182 EPI.Variadic = false;
5183 EPI.TypeQuals = 0;
5184 EPI.RefQualifier = RQ_None;
5185 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5186 }
5187
5188 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5189 /// well-formednes of the conversion function declarator @p D with
5190 /// type @p R. If there are any errors in the declarator, this routine
5191 /// will emit diagnostics and return true. Otherwise, it will return
5192 /// false. Either way, the type @p R will be updated to reflect a
5193 /// well-formed type for the conversion operator.
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)5194 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5195 StorageClass& SC) {
5196 // C++ [class.conv.fct]p1:
5197 // Neither parameter types nor return type can be specified. The
5198 // type of a conversion function (8.3.5) is "function taking no
5199 // parameter returning conversion-type-id."
5200 if (SC == SC_Static) {
5201 if (!D.isInvalidType())
5202 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5203 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5204 << SourceRange(D.getIdentifierLoc());
5205 D.setInvalidType();
5206 SC = SC_None;
5207 }
5208
5209 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5210
5211 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5212 // Conversion functions don't have return types, but the parser will
5213 // happily parse something like:
5214 //
5215 // class X {
5216 // float operator bool();
5217 // };
5218 //
5219 // The return type will be changed later anyway.
5220 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5221 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5222 << SourceRange(D.getIdentifierLoc());
5223 D.setInvalidType();
5224 }
5225
5226 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5227
5228 // Make sure we don't have any parameters.
5229 if (Proto->getNumArgs() > 0) {
5230 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5231
5232 // Delete the parameters.
5233 D.getFunctionTypeInfo().freeArgs();
5234 D.setInvalidType();
5235 } else if (Proto->isVariadic()) {
5236 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5237 D.setInvalidType();
5238 }
5239
5240 // Diagnose "&operator bool()" and other such nonsense. This
5241 // is actually a gcc extension which we don't support.
5242 if (Proto->getResultType() != ConvType) {
5243 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5244 << Proto->getResultType();
5245 D.setInvalidType();
5246 ConvType = Proto->getResultType();
5247 }
5248
5249 // C++ [class.conv.fct]p4:
5250 // The conversion-type-id shall not represent a function type nor
5251 // an array type.
5252 if (ConvType->isArrayType()) {
5253 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5254 ConvType = Context.getPointerType(ConvType);
5255 D.setInvalidType();
5256 } else if (ConvType->isFunctionType()) {
5257 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5258 ConvType = Context.getPointerType(ConvType);
5259 D.setInvalidType();
5260 }
5261
5262 // Rebuild the function type "R" without any parameters (in case any
5263 // of the errors above fired) and with the conversion type as the
5264 // return type.
5265 if (D.isInvalidType())
5266 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5267
5268 // C++0x explicit conversion operators.
5269 if (D.getDeclSpec().isExplicitSpecified())
5270 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5271 getLangOpts().CPlusPlus0x ?
5272 diag::warn_cxx98_compat_explicit_conversion_functions :
5273 diag::ext_explicit_conversion_functions)
5274 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5275 }
5276
5277 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5278 /// the declaration of the given C++ conversion function. This routine
5279 /// is responsible for recording the conversion function in the C++
5280 /// class, if possible.
ActOnConversionDeclarator(CXXConversionDecl * Conversion)5281 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5282 assert(Conversion && "Expected to receive a conversion function declaration");
5283
5284 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5285
5286 // Make sure we aren't redeclaring the conversion function.
5287 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5288
5289 // C++ [class.conv.fct]p1:
5290 // [...] A conversion function is never used to convert a
5291 // (possibly cv-qualified) object to the (possibly cv-qualified)
5292 // same object type (or a reference to it), to a (possibly
5293 // cv-qualified) base class of that type (or a reference to it),
5294 // or to (possibly cv-qualified) void.
5295 // FIXME: Suppress this warning if the conversion function ends up being a
5296 // virtual function that overrides a virtual function in a base class.
5297 QualType ClassType
5298 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5299 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5300 ConvType = ConvTypeRef->getPointeeType();
5301 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5302 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5303 /* Suppress diagnostics for instantiations. */;
5304 else if (ConvType->isRecordType()) {
5305 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5306 if (ConvType == ClassType)
5307 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5308 << ClassType;
5309 else if (IsDerivedFrom(ClassType, ConvType))
5310 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5311 << ClassType << ConvType;
5312 } else if (ConvType->isVoidType()) {
5313 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5314 << ClassType << ConvType;
5315 }
5316
5317 if (FunctionTemplateDecl *ConversionTemplate
5318 = Conversion->getDescribedFunctionTemplate())
5319 return ConversionTemplate;
5320
5321 return Conversion;
5322 }
5323
5324 //===----------------------------------------------------------------------===//
5325 // Namespace Handling
5326 //===----------------------------------------------------------------------===//
5327
5328
5329
5330 /// ActOnStartNamespaceDef - This is called at the start of a namespace
5331 /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,AttributeList * AttrList)5332 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5333 SourceLocation InlineLoc,
5334 SourceLocation NamespaceLoc,
5335 SourceLocation IdentLoc,
5336 IdentifierInfo *II,
5337 SourceLocation LBrace,
5338 AttributeList *AttrList) {
5339 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5340 // For anonymous namespace, take the location of the left brace.
5341 SourceLocation Loc = II ? IdentLoc : LBrace;
5342 bool IsInline = InlineLoc.isValid();
5343 bool IsInvalid = false;
5344 bool IsStd = false;
5345 bool AddToKnown = false;
5346 Scope *DeclRegionScope = NamespcScope->getParent();
5347
5348 NamespaceDecl *PrevNS = 0;
5349 if (II) {
5350 // C++ [namespace.def]p2:
5351 // The identifier in an original-namespace-definition shall not
5352 // have been previously defined in the declarative region in
5353 // which the original-namespace-definition appears. The
5354 // identifier in an original-namespace-definition is the name of
5355 // the namespace. Subsequently in that declarative region, it is
5356 // treated as an original-namespace-name.
5357 //
5358 // Since namespace names are unique in their scope, and we don't
5359 // look through using directives, just look for any ordinary names.
5360
5361 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5362 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5363 Decl::IDNS_Namespace;
5364 NamedDecl *PrevDecl = 0;
5365 for (DeclContext::lookup_result R
5366 = CurContext->getRedeclContext()->lookup(II);
5367 R.first != R.second; ++R.first) {
5368 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5369 PrevDecl = *R.first;
5370 break;
5371 }
5372 }
5373
5374 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5375
5376 if (PrevNS) {
5377 // This is an extended namespace definition.
5378 if (IsInline != PrevNS->isInline()) {
5379 // inline-ness must match
5380 if (PrevNS->isInline()) {
5381 // The user probably just forgot the 'inline', so suggest that it
5382 // be added back.
5383 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5384 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5385 } else {
5386 Diag(Loc, diag::err_inline_namespace_mismatch)
5387 << IsInline;
5388 }
5389 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5390
5391 IsInline = PrevNS->isInline();
5392 }
5393 } else if (PrevDecl) {
5394 // This is an invalid name redefinition.
5395 Diag(Loc, diag::err_redefinition_different_kind)
5396 << II;
5397 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5398 IsInvalid = true;
5399 // Continue on to push Namespc as current DeclContext and return it.
5400 } else if (II->isStr("std") &&
5401 CurContext->getRedeclContext()->isTranslationUnit()) {
5402 // This is the first "real" definition of the namespace "std", so update
5403 // our cache of the "std" namespace to point at this definition.
5404 PrevNS = getStdNamespace();
5405 IsStd = true;
5406 AddToKnown = !IsInline;
5407 } else {
5408 // We've seen this namespace for the first time.
5409 AddToKnown = !IsInline;
5410 }
5411 } else {
5412 // Anonymous namespaces.
5413
5414 // Determine whether the parent already has an anonymous namespace.
5415 DeclContext *Parent = CurContext->getRedeclContext();
5416 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5417 PrevNS = TU->getAnonymousNamespace();
5418 } else {
5419 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5420 PrevNS = ND->getAnonymousNamespace();
5421 }
5422
5423 if (PrevNS && IsInline != PrevNS->isInline()) {
5424 // inline-ness must match
5425 Diag(Loc, diag::err_inline_namespace_mismatch)
5426 << IsInline;
5427 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5428
5429 // Recover by ignoring the new namespace's inline status.
5430 IsInline = PrevNS->isInline();
5431 }
5432 }
5433
5434 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5435 StartLoc, Loc, II, PrevNS);
5436 if (IsInvalid)
5437 Namespc->setInvalidDecl();
5438
5439 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5440
5441 // FIXME: Should we be merging attributes?
5442 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5443 PushNamespaceVisibilityAttr(Attr, Loc);
5444
5445 if (IsStd)
5446 StdNamespace = Namespc;
5447 if (AddToKnown)
5448 KnownNamespaces[Namespc] = false;
5449
5450 if (II) {
5451 PushOnScopeChains(Namespc, DeclRegionScope);
5452 } else {
5453 // Link the anonymous namespace into its parent.
5454 DeclContext *Parent = CurContext->getRedeclContext();
5455 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5456 TU->setAnonymousNamespace(Namespc);
5457 } else {
5458 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5459 }
5460
5461 CurContext->addDecl(Namespc);
5462
5463 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5464 // behaves as if it were replaced by
5465 // namespace unique { /* empty body */ }
5466 // using namespace unique;
5467 // namespace unique { namespace-body }
5468 // where all occurrences of 'unique' in a translation unit are
5469 // replaced by the same identifier and this identifier differs
5470 // from all other identifiers in the entire program.
5471
5472 // We just create the namespace with an empty name and then add an
5473 // implicit using declaration, just like the standard suggests.
5474 //
5475 // CodeGen enforces the "universally unique" aspect by giving all
5476 // declarations semantically contained within an anonymous
5477 // namespace internal linkage.
5478
5479 if (!PrevNS) {
5480 UsingDirectiveDecl* UD
5481 = UsingDirectiveDecl::Create(Context, CurContext,
5482 /* 'using' */ LBrace,
5483 /* 'namespace' */ SourceLocation(),
5484 /* qualifier */ NestedNameSpecifierLoc(),
5485 /* identifier */ SourceLocation(),
5486 Namespc,
5487 /* Ancestor */ CurContext);
5488 UD->setImplicit();
5489 CurContext->addDecl(UD);
5490 }
5491 }
5492
5493 ActOnDocumentableDecl(Namespc);
5494
5495 // Although we could have an invalid decl (i.e. the namespace name is a
5496 // redefinition), push it as current DeclContext and try to continue parsing.
5497 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5498 // for the namespace has the declarations that showed up in that particular
5499 // namespace definition.
5500 PushDeclContext(NamespcScope, Namespc);
5501 return Namespc;
5502 }
5503
5504 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5505 /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)5506 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5507 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5508 return AD->getNamespace();
5509 return dyn_cast_or_null<NamespaceDecl>(D);
5510 }
5511
5512 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5513 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)5514 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5515 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5516 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5517 Namespc->setRBraceLoc(RBrace);
5518 PopDeclContext();
5519 if (Namespc->hasAttr<VisibilityAttr>())
5520 PopPragmaVisibility(true, RBrace);
5521 }
5522
getStdBadAlloc() const5523 CXXRecordDecl *Sema::getStdBadAlloc() const {
5524 return cast_or_null<CXXRecordDecl>(
5525 StdBadAlloc.get(Context.getExternalSource()));
5526 }
5527
getStdNamespace() const5528 NamespaceDecl *Sema::getStdNamespace() const {
5529 return cast_or_null<NamespaceDecl>(
5530 StdNamespace.get(Context.getExternalSource()));
5531 }
5532
5533 /// \brief Retrieve the special "std" namespace, which may require us to
5534 /// implicitly define the namespace.
getOrCreateStdNamespace()5535 NamespaceDecl *Sema::getOrCreateStdNamespace() {
5536 if (!StdNamespace) {
5537 // The "std" namespace has not yet been defined, so build one implicitly.
5538 StdNamespace = NamespaceDecl::Create(Context,
5539 Context.getTranslationUnitDecl(),
5540 /*Inline=*/false,
5541 SourceLocation(), SourceLocation(),
5542 &PP.getIdentifierTable().get("std"),
5543 /*PrevDecl=*/0);
5544 getStdNamespace()->setImplicit(true);
5545 }
5546
5547 return getStdNamespace();
5548 }
5549
isStdInitializerList(QualType Ty,QualType * Element)5550 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5551 assert(getLangOpts().CPlusPlus &&
5552 "Looking for std::initializer_list outside of C++.");
5553
5554 // We're looking for implicit instantiations of
5555 // template <typename E> class std::initializer_list.
5556
5557 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5558 return false;
5559
5560 ClassTemplateDecl *Template = 0;
5561 const TemplateArgument *Arguments = 0;
5562
5563 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5564
5565 ClassTemplateSpecializationDecl *Specialization =
5566 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5567 if (!Specialization)
5568 return false;
5569
5570 Template = Specialization->getSpecializedTemplate();
5571 Arguments = Specialization->getTemplateArgs().data();
5572 } else if (const TemplateSpecializationType *TST =
5573 Ty->getAs<TemplateSpecializationType>()) {
5574 Template = dyn_cast_or_null<ClassTemplateDecl>(
5575 TST->getTemplateName().getAsTemplateDecl());
5576 Arguments = TST->getArgs();
5577 }
5578 if (!Template)
5579 return false;
5580
5581 if (!StdInitializerList) {
5582 // Haven't recognized std::initializer_list yet, maybe this is it.
5583 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5584 if (TemplateClass->getIdentifier() !=
5585 &PP.getIdentifierTable().get("initializer_list") ||
5586 !getStdNamespace()->InEnclosingNamespaceSetOf(
5587 TemplateClass->getDeclContext()))
5588 return false;
5589 // This is a template called std::initializer_list, but is it the right
5590 // template?
5591 TemplateParameterList *Params = Template->getTemplateParameters();
5592 if (Params->getMinRequiredArguments() != 1)
5593 return false;
5594 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5595 return false;
5596
5597 // It's the right template.
5598 StdInitializerList = Template;
5599 }
5600
5601 if (Template != StdInitializerList)
5602 return false;
5603
5604 // This is an instance of std::initializer_list. Find the argument type.
5605 if (Element)
5606 *Element = Arguments[0].getAsType();
5607 return true;
5608 }
5609
LookupStdInitializerList(Sema & S,SourceLocation Loc)5610 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5611 NamespaceDecl *Std = S.getStdNamespace();
5612 if (!Std) {
5613 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5614 return 0;
5615 }
5616
5617 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5618 Loc, Sema::LookupOrdinaryName);
5619 if (!S.LookupQualifiedName(Result, Std)) {
5620 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5621 return 0;
5622 }
5623 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5624 if (!Template) {
5625 Result.suppressDiagnostics();
5626 // We found something weird. Complain about the first thing we found.
5627 NamedDecl *Found = *Result.begin();
5628 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5629 return 0;
5630 }
5631
5632 // We found some template called std::initializer_list. Now verify that it's
5633 // correct.
5634 TemplateParameterList *Params = Template->getTemplateParameters();
5635 if (Params->getMinRequiredArguments() != 1 ||
5636 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5637 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5638 return 0;
5639 }
5640
5641 return Template;
5642 }
5643
BuildStdInitializerList(QualType Element,SourceLocation Loc)5644 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5645 if (!StdInitializerList) {
5646 StdInitializerList = LookupStdInitializerList(*this, Loc);
5647 if (!StdInitializerList)
5648 return QualType();
5649 }
5650
5651 TemplateArgumentListInfo Args(Loc, Loc);
5652 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5653 Context.getTrivialTypeSourceInfo(Element,
5654 Loc)));
5655 return Context.getCanonicalType(
5656 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5657 }
5658
isInitListConstructor(const CXXConstructorDecl * Ctor)5659 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5660 // C++ [dcl.init.list]p2:
5661 // A constructor is an initializer-list constructor if its first parameter
5662 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5663 // std::initializer_list<E> for some type E, and either there are no other
5664 // parameters or else all other parameters have default arguments.
5665 if (Ctor->getNumParams() < 1 ||
5666 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5667 return false;
5668
5669 QualType ArgType = Ctor->getParamDecl(0)->getType();
5670 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5671 ArgType = RT->getPointeeType().getUnqualifiedType();
5672
5673 return isStdInitializerList(ArgType, 0);
5674 }
5675
5676 /// \brief Determine whether a using statement is in a context where it will be
5677 /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)5678 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5679 switch (CurContext->getDeclKind()) {
5680 case Decl::TranslationUnit:
5681 return true;
5682 case Decl::LinkageSpec:
5683 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5684 default:
5685 return false;
5686 }
5687 }
5688
5689 namespace {
5690
5691 // Callback to only accept typo corrections that are namespaces.
5692 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5693 public:
ValidateCandidate(const TypoCorrection & candidate)5694 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5695 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5696 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5697 }
5698 return false;
5699 }
5700 };
5701
5702 }
5703
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)5704 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5705 CXXScopeSpec &SS,
5706 SourceLocation IdentLoc,
5707 IdentifierInfo *Ident) {
5708 NamespaceValidatorCCC Validator;
5709 R.clear();
5710 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5711 R.getLookupKind(), Sc, &SS,
5712 Validator)) {
5713 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5714 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5715 if (DeclContext *DC = S.computeDeclContext(SS, false))
5716 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5717 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5718 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5719 else
5720 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5721 << Ident << CorrectedQuotedStr
5722 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5723
5724 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5725 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5726
5727 R.addDecl(Corrected.getCorrectionDecl());
5728 return true;
5729 }
5730 return false;
5731 }
5732
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,AttributeList * AttrList)5733 Decl *Sema::ActOnUsingDirective(Scope *S,
5734 SourceLocation UsingLoc,
5735 SourceLocation NamespcLoc,
5736 CXXScopeSpec &SS,
5737 SourceLocation IdentLoc,
5738 IdentifierInfo *NamespcName,
5739 AttributeList *AttrList) {
5740 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5741 assert(NamespcName && "Invalid NamespcName.");
5742 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5743
5744 // This can only happen along a recovery path.
5745 while (S->getFlags() & Scope::TemplateParamScope)
5746 S = S->getParent();
5747 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5748
5749 UsingDirectiveDecl *UDir = 0;
5750 NestedNameSpecifier *Qualifier = 0;
5751 if (SS.isSet())
5752 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5753
5754 // Lookup namespace name.
5755 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5756 LookupParsedName(R, S, &SS);
5757 if (R.isAmbiguous())
5758 return 0;
5759
5760 if (R.empty()) {
5761 R.clear();
5762 // Allow "using namespace std;" or "using namespace ::std;" even if
5763 // "std" hasn't been defined yet, for GCC compatibility.
5764 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5765 NamespcName->isStr("std")) {
5766 Diag(IdentLoc, diag::ext_using_undefined_std);
5767 R.addDecl(getOrCreateStdNamespace());
5768 R.resolveKind();
5769 }
5770 // Otherwise, attempt typo correction.
5771 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5772 }
5773
5774 if (!R.empty()) {
5775 NamedDecl *Named = R.getFoundDecl();
5776 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5777 && "expected namespace decl");
5778 // C++ [namespace.udir]p1:
5779 // A using-directive specifies that the names in the nominated
5780 // namespace can be used in the scope in which the
5781 // using-directive appears after the using-directive. During
5782 // unqualified name lookup (3.4.1), the names appear as if they
5783 // were declared in the nearest enclosing namespace which
5784 // contains both the using-directive and the nominated
5785 // namespace. [Note: in this context, "contains" means "contains
5786 // directly or indirectly". ]
5787
5788 // Find enclosing context containing both using-directive and
5789 // nominated namespace.
5790 NamespaceDecl *NS = getNamespaceDecl(Named);
5791 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5792 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5793 CommonAncestor = CommonAncestor->getParent();
5794
5795 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5796 SS.getWithLocInContext(Context),
5797 IdentLoc, Named, CommonAncestor);
5798
5799 if (IsUsingDirectiveInToplevelContext(CurContext) &&
5800 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5801 Diag(IdentLoc, diag::warn_using_directive_in_header);
5802 }
5803
5804 PushUsingDirective(S, UDir);
5805 } else {
5806 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5807 }
5808
5809 // FIXME: We ignore attributes for now.
5810 return UDir;
5811 }
5812
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)5813 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5814 // If the scope has an associated entity and the using directive is at
5815 // namespace or translation unit scope, add the UsingDirectiveDecl into
5816 // its lookup structure so qualified name lookup can find it.
5817 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5818 if (Ctx && !Ctx->isFunctionOrMethod())
5819 Ctx->addDecl(UDir);
5820 else
5821 // Otherwise, it is at block sope. The using-directives will affect lookup
5822 // only to the end of the scope.
5823 S->PushUsingDirective(UDir);
5824 }
5825
5826
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,bool HasUsingKeyword,SourceLocation UsingLoc,CXXScopeSpec & SS,UnqualifiedId & Name,AttributeList * AttrList,bool IsTypeName,SourceLocation TypenameLoc)5827 Decl *Sema::ActOnUsingDeclaration(Scope *S,
5828 AccessSpecifier AS,
5829 bool HasUsingKeyword,
5830 SourceLocation UsingLoc,
5831 CXXScopeSpec &SS,
5832 UnqualifiedId &Name,
5833 AttributeList *AttrList,
5834 bool IsTypeName,
5835 SourceLocation TypenameLoc) {
5836 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5837
5838 switch (Name.getKind()) {
5839 case UnqualifiedId::IK_ImplicitSelfParam:
5840 case UnqualifiedId::IK_Identifier:
5841 case UnqualifiedId::IK_OperatorFunctionId:
5842 case UnqualifiedId::IK_LiteralOperatorId:
5843 case UnqualifiedId::IK_ConversionFunctionId:
5844 break;
5845
5846 case UnqualifiedId::IK_ConstructorName:
5847 case UnqualifiedId::IK_ConstructorTemplateId:
5848 // C++11 inheriting constructors.
5849 Diag(Name.getLocStart(),
5850 getLangOpts().CPlusPlus0x ?
5851 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5852 // instead once inheriting constructors work.
5853 diag::err_using_decl_constructor_unsupported :
5854 diag::err_using_decl_constructor)
5855 << SS.getRange();
5856
5857 if (getLangOpts().CPlusPlus0x) break;
5858
5859 return 0;
5860
5861 case UnqualifiedId::IK_DestructorName:
5862 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5863 << SS.getRange();
5864 return 0;
5865
5866 case UnqualifiedId::IK_TemplateId:
5867 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5868 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5869 return 0;
5870 }
5871
5872 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5873 DeclarationName TargetName = TargetNameInfo.getName();
5874 if (!TargetName)
5875 return 0;
5876
5877 // Warn about using declarations.
5878 // TODO: store that the declaration was written without 'using' and
5879 // talk about access decls instead of using decls in the
5880 // diagnostics.
5881 if (!HasUsingKeyword) {
5882 UsingLoc = Name.getLocStart();
5883
5884 Diag(UsingLoc, diag::warn_access_decl_deprecated)
5885 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5886 }
5887
5888 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5889 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5890 return 0;
5891
5892 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5893 TargetNameInfo, AttrList,
5894 /* IsInstantiation */ false,
5895 IsTypeName, TypenameLoc);
5896 if (UD)
5897 PushOnScopeChains(UD, S, /*AddToContext*/ false);
5898
5899 return UD;
5900 }
5901
5902 /// \brief Determine whether a using declaration considers the given
5903 /// declarations as "equivalent", e.g., if they are redeclarations of
5904 /// the same entity or are both typedefs of the same type.
5905 static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2,bool & SuppressRedeclaration)5906 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5907 bool &SuppressRedeclaration) {
5908 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5909 SuppressRedeclaration = false;
5910 return true;
5911 }
5912
5913 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5914 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5915 SuppressRedeclaration = true;
5916 return Context.hasSameType(TD1->getUnderlyingType(),
5917 TD2->getUnderlyingType());
5918 }
5919
5920 return false;
5921 }
5922
5923
5924 /// Determines whether to create a using shadow decl for a particular
5925 /// decl, given the set of decls existing prior to this using lookup.
CheckUsingShadowDecl(UsingDecl * Using,NamedDecl * Orig,const LookupResult & Previous)5926 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5927 const LookupResult &Previous) {
5928 // Diagnose finding a decl which is not from a base class of the
5929 // current class. We do this now because there are cases where this
5930 // function will silently decide not to build a shadow decl, which
5931 // will pre-empt further diagnostics.
5932 //
5933 // We don't need to do this in C++0x because we do the check once on
5934 // the qualifier.
5935 //
5936 // FIXME: diagnose the following if we care enough:
5937 // struct A { int foo; };
5938 // struct B : A { using A::foo; };
5939 // template <class T> struct C : A {};
5940 // template <class T> struct D : C<T> { using B::foo; } // <---
5941 // This is invalid (during instantiation) in C++03 because B::foo
5942 // resolves to the using decl in B, which is not a base class of D<T>.
5943 // We can't diagnose it immediately because C<T> is an unknown
5944 // specialization. The UsingShadowDecl in D<T> then points directly
5945 // to A::foo, which will look well-formed when we instantiate.
5946 // The right solution is to not collapse the shadow-decl chain.
5947 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
5948 DeclContext *OrigDC = Orig->getDeclContext();
5949
5950 // Handle enums and anonymous structs.
5951 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5952 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5953 while (OrigRec->isAnonymousStructOrUnion())
5954 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5955
5956 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5957 if (OrigDC == CurContext) {
5958 Diag(Using->getLocation(),
5959 diag::err_using_decl_nested_name_specifier_is_current_class)
5960 << Using->getQualifierLoc().getSourceRange();
5961 Diag(Orig->getLocation(), diag::note_using_decl_target);
5962 return true;
5963 }
5964
5965 Diag(Using->getQualifierLoc().getBeginLoc(),
5966 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5967 << Using->getQualifier()
5968 << cast<CXXRecordDecl>(CurContext)
5969 << Using->getQualifierLoc().getSourceRange();
5970 Diag(Orig->getLocation(), diag::note_using_decl_target);
5971 return true;
5972 }
5973 }
5974
5975 if (Previous.empty()) return false;
5976
5977 NamedDecl *Target = Orig;
5978 if (isa<UsingShadowDecl>(Target))
5979 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5980
5981 // If the target happens to be one of the previous declarations, we
5982 // don't have a conflict.
5983 //
5984 // FIXME: but we might be increasing its access, in which case we
5985 // should redeclare it.
5986 NamedDecl *NonTag = 0, *Tag = 0;
5987 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5988 I != E; ++I) {
5989 NamedDecl *D = (*I)->getUnderlyingDecl();
5990 bool Result;
5991 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5992 return Result;
5993
5994 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5995 }
5996
5997 if (Target->isFunctionOrFunctionTemplate()) {
5998 FunctionDecl *FD;
5999 if (isa<FunctionTemplateDecl>(Target))
6000 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6001 else
6002 FD = cast<FunctionDecl>(Target);
6003
6004 NamedDecl *OldDecl = 0;
6005 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6006 case Ovl_Overload:
6007 return false;
6008
6009 case Ovl_NonFunction:
6010 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6011 break;
6012
6013 // We found a decl with the exact signature.
6014 case Ovl_Match:
6015 // If we're in a record, we want to hide the target, so we
6016 // return true (without a diagnostic) to tell the caller not to
6017 // build a shadow decl.
6018 if (CurContext->isRecord())
6019 return true;
6020
6021 // If we're not in a record, this is an error.
6022 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6023 break;
6024 }
6025
6026 Diag(Target->getLocation(), diag::note_using_decl_target);
6027 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6028 return true;
6029 }
6030
6031 // Target is not a function.
6032
6033 if (isa<TagDecl>(Target)) {
6034 // No conflict between a tag and a non-tag.
6035 if (!Tag) return false;
6036
6037 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6038 Diag(Target->getLocation(), diag::note_using_decl_target);
6039 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6040 return true;
6041 }
6042
6043 // No conflict between a tag and a non-tag.
6044 if (!NonTag) return false;
6045
6046 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6047 Diag(Target->getLocation(), diag::note_using_decl_target);
6048 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6049 return true;
6050 }
6051
6052 /// Builds a shadow declaration corresponding to a 'using' declaration.
BuildUsingShadowDecl(Scope * S,UsingDecl * UD,NamedDecl * Orig)6053 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6054 UsingDecl *UD,
6055 NamedDecl *Orig) {
6056
6057 // If we resolved to another shadow declaration, just coalesce them.
6058 NamedDecl *Target = Orig;
6059 if (isa<UsingShadowDecl>(Target)) {
6060 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6061 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6062 }
6063
6064 UsingShadowDecl *Shadow
6065 = UsingShadowDecl::Create(Context, CurContext,
6066 UD->getLocation(), UD, Target);
6067 UD->addShadowDecl(Shadow);
6068
6069 Shadow->setAccess(UD->getAccess());
6070 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6071 Shadow->setInvalidDecl();
6072
6073 if (S)
6074 PushOnScopeChains(Shadow, S);
6075 else
6076 CurContext->addDecl(Shadow);
6077
6078
6079 return Shadow;
6080 }
6081
6082 /// Hides a using shadow declaration. This is required by the current
6083 /// using-decl implementation when a resolvable using declaration in a
6084 /// class is followed by a declaration which would hide or override
6085 /// one or more of the using decl's targets; for example:
6086 ///
6087 /// struct Base { void foo(int); };
6088 /// struct Derived : Base {
6089 /// using Base::foo;
6090 /// void foo(int);
6091 /// };
6092 ///
6093 /// The governing language is C++03 [namespace.udecl]p12:
6094 ///
6095 /// When a using-declaration brings names from a base class into a
6096 /// derived class scope, member functions in the derived class
6097 /// override and/or hide member functions with the same name and
6098 /// parameter types in a base class (rather than conflicting).
6099 ///
6100 /// There are two ways to implement this:
6101 /// (1) optimistically create shadow decls when they're not hidden
6102 /// by existing declarations, or
6103 /// (2) don't create any shadow decls (or at least don't make them
6104 /// visible) until we've fully parsed/instantiated the class.
6105 /// The problem with (1) is that we might have to retroactively remove
6106 /// a shadow decl, which requires several O(n) operations because the
6107 /// decl structures are (very reasonably) not designed for removal.
6108 /// (2) avoids this but is very fiddly and phase-dependent.
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)6109 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6110 if (Shadow->getDeclName().getNameKind() ==
6111 DeclarationName::CXXConversionFunctionName)
6112 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6113
6114 // Remove it from the DeclContext...
6115 Shadow->getDeclContext()->removeDecl(Shadow);
6116
6117 // ...and the scope, if applicable...
6118 if (S) {
6119 S->RemoveDecl(Shadow);
6120 IdResolver.RemoveDecl(Shadow);
6121 }
6122
6123 // ...and the using decl.
6124 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6125
6126 // TODO: complain somehow if Shadow was used. It shouldn't
6127 // be possible for this to happen, because...?
6128 }
6129
6130 /// Builds a using declaration.
6131 ///
6132 /// \param IsInstantiation - Whether this call arises from an
6133 /// instantiation of an unresolved using declaration. We treat
6134 /// the lookup differently for these declarations.
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,AttributeList * AttrList,bool IsInstantiation,bool IsTypeName,SourceLocation TypenameLoc)6135 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6136 SourceLocation UsingLoc,
6137 CXXScopeSpec &SS,
6138 const DeclarationNameInfo &NameInfo,
6139 AttributeList *AttrList,
6140 bool IsInstantiation,
6141 bool IsTypeName,
6142 SourceLocation TypenameLoc) {
6143 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6144 SourceLocation IdentLoc = NameInfo.getLoc();
6145 assert(IdentLoc.isValid() && "Invalid TargetName location.");
6146
6147 // FIXME: We ignore attributes for now.
6148
6149 if (SS.isEmpty()) {
6150 Diag(IdentLoc, diag::err_using_requires_qualname);
6151 return 0;
6152 }
6153
6154 // Do the redeclaration lookup in the current scope.
6155 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6156 ForRedeclaration);
6157 Previous.setHideTags(false);
6158 if (S) {
6159 LookupName(Previous, S);
6160
6161 // It is really dumb that we have to do this.
6162 LookupResult::Filter F = Previous.makeFilter();
6163 while (F.hasNext()) {
6164 NamedDecl *D = F.next();
6165 if (!isDeclInScope(D, CurContext, S))
6166 F.erase();
6167 }
6168 F.done();
6169 } else {
6170 assert(IsInstantiation && "no scope in non-instantiation");
6171 assert(CurContext->isRecord() && "scope not record in instantiation");
6172 LookupQualifiedName(Previous, CurContext);
6173 }
6174
6175 // Check for invalid redeclarations.
6176 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6177 return 0;
6178
6179 // Check for bad qualifiers.
6180 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6181 return 0;
6182
6183 DeclContext *LookupContext = computeDeclContext(SS);
6184 NamedDecl *D;
6185 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6186 if (!LookupContext) {
6187 if (IsTypeName) {
6188 // FIXME: not all declaration name kinds are legal here
6189 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6190 UsingLoc, TypenameLoc,
6191 QualifierLoc,
6192 IdentLoc, NameInfo.getName());
6193 } else {
6194 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6195 QualifierLoc, NameInfo);
6196 }
6197 } else {
6198 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6199 NameInfo, IsTypeName);
6200 }
6201 D->setAccess(AS);
6202 CurContext->addDecl(D);
6203
6204 if (!LookupContext) return D;
6205 UsingDecl *UD = cast<UsingDecl>(D);
6206
6207 if (RequireCompleteDeclContext(SS, LookupContext)) {
6208 UD->setInvalidDecl();
6209 return UD;
6210 }
6211
6212 // The normal rules do not apply to inheriting constructor declarations.
6213 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6214 if (CheckInheritingConstructorUsingDecl(UD))
6215 UD->setInvalidDecl();
6216 return UD;
6217 }
6218
6219 // Otherwise, look up the target name.
6220
6221 LookupResult R(*this, NameInfo, LookupOrdinaryName);
6222
6223 // Unlike most lookups, we don't always want to hide tag
6224 // declarations: tag names are visible through the using declaration
6225 // even if hidden by ordinary names, *except* in a dependent context
6226 // where it's important for the sanity of two-phase lookup.
6227 if (!IsInstantiation)
6228 R.setHideTags(false);
6229
6230 // For the purposes of this lookup, we have a base object type
6231 // equal to that of the current context.
6232 if (CurContext->isRecord()) {
6233 R.setBaseObjectType(
6234 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6235 }
6236
6237 LookupQualifiedName(R, LookupContext);
6238
6239 if (R.empty()) {
6240 Diag(IdentLoc, diag::err_no_member)
6241 << NameInfo.getName() << LookupContext << SS.getRange();
6242 UD->setInvalidDecl();
6243 return UD;
6244 }
6245
6246 if (R.isAmbiguous()) {
6247 UD->setInvalidDecl();
6248 return UD;
6249 }
6250
6251 if (IsTypeName) {
6252 // If we asked for a typename and got a non-type decl, error out.
6253 if (!R.getAsSingle<TypeDecl>()) {
6254 Diag(IdentLoc, diag::err_using_typename_non_type);
6255 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6256 Diag((*I)->getUnderlyingDecl()->getLocation(),
6257 diag::note_using_decl_target);
6258 UD->setInvalidDecl();
6259 return UD;
6260 }
6261 } else {
6262 // If we asked for a non-typename and we got a type, error out,
6263 // but only if this is an instantiation of an unresolved using
6264 // decl. Otherwise just silently find the type name.
6265 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6266 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6267 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6268 UD->setInvalidDecl();
6269 return UD;
6270 }
6271 }
6272
6273 // C++0x N2914 [namespace.udecl]p6:
6274 // A using-declaration shall not name a namespace.
6275 if (R.getAsSingle<NamespaceDecl>()) {
6276 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6277 << SS.getRange();
6278 UD->setInvalidDecl();
6279 return UD;
6280 }
6281
6282 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6283 if (!CheckUsingShadowDecl(UD, *I, Previous))
6284 BuildUsingShadowDecl(S, UD, *I);
6285 }
6286
6287 return UD;
6288 }
6289
6290 /// Additional checks for a using declaration referring to a constructor name.
CheckInheritingConstructorUsingDecl(UsingDecl * UD)6291 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6292 assert(!UD->isTypeName() && "expecting a constructor name");
6293
6294 const Type *SourceType = UD->getQualifier()->getAsType();
6295 assert(SourceType &&
6296 "Using decl naming constructor doesn't have type in scope spec.");
6297 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6298
6299 // Check whether the named type is a direct base class.
6300 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6301 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6302 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6303 BaseIt != BaseE; ++BaseIt) {
6304 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6305 if (CanonicalSourceType == BaseType)
6306 break;
6307 if (BaseIt->getType()->isDependentType())
6308 break;
6309 }
6310
6311 if (BaseIt == BaseE) {
6312 // Did not find SourceType in the bases.
6313 Diag(UD->getUsingLocation(),
6314 diag::err_using_decl_constructor_not_in_direct_base)
6315 << UD->getNameInfo().getSourceRange()
6316 << QualType(SourceType, 0) << TargetClass;
6317 return true;
6318 }
6319
6320 if (!CurContext->isDependentContext())
6321 BaseIt->setInheritConstructors();
6322
6323 return false;
6324 }
6325
6326 /// Checks that the given using declaration is not an invalid
6327 /// redeclaration. Note that this is checking only for the using decl
6328 /// itself, not for any ill-formedness among the UsingShadowDecls.
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool isTypeName,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)6329 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6330 bool isTypeName,
6331 const CXXScopeSpec &SS,
6332 SourceLocation NameLoc,
6333 const LookupResult &Prev) {
6334 // C++03 [namespace.udecl]p8:
6335 // C++0x [namespace.udecl]p10:
6336 // A using-declaration is a declaration and can therefore be used
6337 // repeatedly where (and only where) multiple declarations are
6338 // allowed.
6339 //
6340 // That's in non-member contexts.
6341 if (!CurContext->getRedeclContext()->isRecord())
6342 return false;
6343
6344 NestedNameSpecifier *Qual
6345 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6346
6347 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6348 NamedDecl *D = *I;
6349
6350 bool DTypename;
6351 NestedNameSpecifier *DQual;
6352 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6353 DTypename = UD->isTypeName();
6354 DQual = UD->getQualifier();
6355 } else if (UnresolvedUsingValueDecl *UD
6356 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6357 DTypename = false;
6358 DQual = UD->getQualifier();
6359 } else if (UnresolvedUsingTypenameDecl *UD
6360 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6361 DTypename = true;
6362 DQual = UD->getQualifier();
6363 } else continue;
6364
6365 // using decls differ if one says 'typename' and the other doesn't.
6366 // FIXME: non-dependent using decls?
6367 if (isTypeName != DTypename) continue;
6368
6369 // using decls differ if they name different scopes (but note that
6370 // template instantiation can cause this check to trigger when it
6371 // didn't before instantiation).
6372 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6373 Context.getCanonicalNestedNameSpecifier(DQual))
6374 continue;
6375
6376 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6377 Diag(D->getLocation(), diag::note_using_decl) << 1;
6378 return true;
6379 }
6380
6381 return false;
6382 }
6383
6384
6385 /// Checks that the given nested-name qualifier used in a using decl
6386 /// in the current context is appropriately related to the current
6387 /// scope. If an error is found, diagnoses it and returns true.
CheckUsingDeclQualifier(SourceLocation UsingLoc,const CXXScopeSpec & SS,SourceLocation NameLoc)6388 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6389 const CXXScopeSpec &SS,
6390 SourceLocation NameLoc) {
6391 DeclContext *NamedContext = computeDeclContext(SS);
6392
6393 if (!CurContext->isRecord()) {
6394 // C++03 [namespace.udecl]p3:
6395 // C++0x [namespace.udecl]p8:
6396 // A using-declaration for a class member shall be a member-declaration.
6397
6398 // If we weren't able to compute a valid scope, it must be a
6399 // dependent class scope.
6400 if (!NamedContext || NamedContext->isRecord()) {
6401 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6402 << SS.getRange();
6403 return true;
6404 }
6405
6406 // Otherwise, everything is known to be fine.
6407 return false;
6408 }
6409
6410 // The current scope is a record.
6411
6412 // If the named context is dependent, we can't decide much.
6413 if (!NamedContext) {
6414 // FIXME: in C++0x, we can diagnose if we can prove that the
6415 // nested-name-specifier does not refer to a base class, which is
6416 // still possible in some cases.
6417
6418 // Otherwise we have to conservatively report that things might be
6419 // okay.
6420 return false;
6421 }
6422
6423 if (!NamedContext->isRecord()) {
6424 // Ideally this would point at the last name in the specifier,
6425 // but we don't have that level of source info.
6426 Diag(SS.getRange().getBegin(),
6427 diag::err_using_decl_nested_name_specifier_is_not_class)
6428 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6429 return true;
6430 }
6431
6432 if (!NamedContext->isDependentContext() &&
6433 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6434 return true;
6435
6436 if (getLangOpts().CPlusPlus0x) {
6437 // C++0x [namespace.udecl]p3:
6438 // In a using-declaration used as a member-declaration, the
6439 // nested-name-specifier shall name a base class of the class
6440 // being defined.
6441
6442 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6443 cast<CXXRecordDecl>(NamedContext))) {
6444 if (CurContext == NamedContext) {
6445 Diag(NameLoc,
6446 diag::err_using_decl_nested_name_specifier_is_current_class)
6447 << SS.getRange();
6448 return true;
6449 }
6450
6451 Diag(SS.getRange().getBegin(),
6452 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6453 << (NestedNameSpecifier*) SS.getScopeRep()
6454 << cast<CXXRecordDecl>(CurContext)
6455 << SS.getRange();
6456 return true;
6457 }
6458
6459 return false;
6460 }
6461
6462 // C++03 [namespace.udecl]p4:
6463 // A using-declaration used as a member-declaration shall refer
6464 // to a member of a base class of the class being defined [etc.].
6465
6466 // Salient point: SS doesn't have to name a base class as long as
6467 // lookup only finds members from base classes. Therefore we can
6468 // diagnose here only if we can prove that that can't happen,
6469 // i.e. if the class hierarchies provably don't intersect.
6470
6471 // TODO: it would be nice if "definitely valid" results were cached
6472 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6473 // need to be repeated.
6474
6475 struct UserData {
6476 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6477
6478 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6479 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6480 Data->Bases.insert(Base);
6481 return true;
6482 }
6483
6484 bool hasDependentBases(const CXXRecordDecl *Class) {
6485 return !Class->forallBases(collect, this);
6486 }
6487
6488 /// Returns true if the base is dependent or is one of the
6489 /// accumulated base classes.
6490 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6491 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6492 return !Data->Bases.count(Base);
6493 }
6494
6495 bool mightShareBases(const CXXRecordDecl *Class) {
6496 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6497 }
6498 };
6499
6500 UserData Data;
6501
6502 // Returns false if we find a dependent base.
6503 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6504 return false;
6505
6506 // Returns false if the class has a dependent base or if it or one
6507 // of its bases is present in the base set of the current context.
6508 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6509 return false;
6510
6511 Diag(SS.getRange().getBegin(),
6512 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6513 << (NestedNameSpecifier*) SS.getScopeRep()
6514 << cast<CXXRecordDecl>(CurContext)
6515 << SS.getRange();
6516
6517 return true;
6518 }
6519
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,TypeResult Type)6520 Decl *Sema::ActOnAliasDeclaration(Scope *S,
6521 AccessSpecifier AS,
6522 MultiTemplateParamsArg TemplateParamLists,
6523 SourceLocation UsingLoc,
6524 UnqualifiedId &Name,
6525 TypeResult Type) {
6526 // Skip up to the relevant declaration scope.
6527 while (S->getFlags() & Scope::TemplateParamScope)
6528 S = S->getParent();
6529 assert((S->getFlags() & Scope::DeclScope) &&
6530 "got alias-declaration outside of declaration scope");
6531
6532 if (Type.isInvalid())
6533 return 0;
6534
6535 bool Invalid = false;
6536 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6537 TypeSourceInfo *TInfo = 0;
6538 GetTypeFromParser(Type.get(), &TInfo);
6539
6540 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6541 return 0;
6542
6543 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6544 UPPC_DeclarationType)) {
6545 Invalid = true;
6546 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6547 TInfo->getTypeLoc().getBeginLoc());
6548 }
6549
6550 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6551 LookupName(Previous, S);
6552
6553 // Warn about shadowing the name of a template parameter.
6554 if (Previous.isSingleResult() &&
6555 Previous.getFoundDecl()->isTemplateParameter()) {
6556 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6557 Previous.clear();
6558 }
6559
6560 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6561 "name in alias declaration must be an identifier");
6562 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6563 Name.StartLocation,
6564 Name.Identifier, TInfo);
6565
6566 NewTD->setAccess(AS);
6567
6568 if (Invalid)
6569 NewTD->setInvalidDecl();
6570
6571 CheckTypedefForVariablyModifiedType(S, NewTD);
6572 Invalid |= NewTD->isInvalidDecl();
6573
6574 bool Redeclaration = false;
6575
6576 NamedDecl *NewND;
6577 if (TemplateParamLists.size()) {
6578 TypeAliasTemplateDecl *OldDecl = 0;
6579 TemplateParameterList *OldTemplateParams = 0;
6580
6581 if (TemplateParamLists.size() != 1) {
6582 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6583 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6584 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
6585 }
6586 TemplateParameterList *TemplateParams = TemplateParamLists[0];
6587
6588 // Only consider previous declarations in the same scope.
6589 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6590 /*ExplicitInstantiationOrSpecialization*/false);
6591 if (!Previous.empty()) {
6592 Redeclaration = true;
6593
6594 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6595 if (!OldDecl && !Invalid) {
6596 Diag(UsingLoc, diag::err_redefinition_different_kind)
6597 << Name.Identifier;
6598
6599 NamedDecl *OldD = Previous.getRepresentativeDecl();
6600 if (OldD->getLocation().isValid())
6601 Diag(OldD->getLocation(), diag::note_previous_definition);
6602
6603 Invalid = true;
6604 }
6605
6606 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6607 if (TemplateParameterListsAreEqual(TemplateParams,
6608 OldDecl->getTemplateParameters(),
6609 /*Complain=*/true,
6610 TPL_TemplateMatch))
6611 OldTemplateParams = OldDecl->getTemplateParameters();
6612 else
6613 Invalid = true;
6614
6615 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6616 if (!Invalid &&
6617 !Context.hasSameType(OldTD->getUnderlyingType(),
6618 NewTD->getUnderlyingType())) {
6619 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6620 // but we can't reasonably accept it.
6621 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6622 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6623 if (OldTD->getLocation().isValid())
6624 Diag(OldTD->getLocation(), diag::note_previous_definition);
6625 Invalid = true;
6626 }
6627 }
6628 }
6629
6630 // Merge any previous default template arguments into our parameters,
6631 // and check the parameter list.
6632 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6633 TPC_TypeAliasTemplate))
6634 return 0;
6635
6636 TypeAliasTemplateDecl *NewDecl =
6637 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6638 Name.Identifier, TemplateParams,
6639 NewTD);
6640
6641 NewDecl->setAccess(AS);
6642
6643 if (Invalid)
6644 NewDecl->setInvalidDecl();
6645 else if (OldDecl)
6646 NewDecl->setPreviousDeclaration(OldDecl);
6647
6648 NewND = NewDecl;
6649 } else {
6650 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6651 NewND = NewTD;
6652 }
6653
6654 if (!Redeclaration)
6655 PushOnScopeChains(NewND, S);
6656
6657 ActOnDocumentableDecl(NewND);
6658 return NewND;
6659 }
6660
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)6661 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6662 SourceLocation NamespaceLoc,
6663 SourceLocation AliasLoc,
6664 IdentifierInfo *Alias,
6665 CXXScopeSpec &SS,
6666 SourceLocation IdentLoc,
6667 IdentifierInfo *Ident) {
6668
6669 // Lookup the namespace name.
6670 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6671 LookupParsedName(R, S, &SS);
6672
6673 // Check if we have a previous declaration with the same name.
6674 NamedDecl *PrevDecl
6675 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6676 ForRedeclaration);
6677 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6678 PrevDecl = 0;
6679
6680 if (PrevDecl) {
6681 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6682 // We already have an alias with the same name that points to the same
6683 // namespace, so don't create a new one.
6684 // FIXME: At some point, we'll want to create the (redundant)
6685 // declaration to maintain better source information.
6686 if (!R.isAmbiguous() && !R.empty() &&
6687 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6688 return 0;
6689 }
6690
6691 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6692 diag::err_redefinition_different_kind;
6693 Diag(AliasLoc, DiagID) << Alias;
6694 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6695 return 0;
6696 }
6697
6698 if (R.isAmbiguous())
6699 return 0;
6700
6701 if (R.empty()) {
6702 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6703 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6704 return 0;
6705 }
6706 }
6707
6708 NamespaceAliasDecl *AliasDecl =
6709 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6710 Alias, SS.getWithLocInContext(Context),
6711 IdentLoc, R.getFoundDecl());
6712
6713 PushOnScopeChains(AliasDecl, S);
6714 return AliasDecl;
6715 }
6716
6717 namespace {
6718 /// \brief Scoped object used to handle the state changes required in Sema
6719 /// to implicitly define the body of a C++ member function;
6720 class ImplicitlyDefinedFunctionScope {
6721 Sema &S;
6722 Sema::ContextRAII SavedContext;
6723
6724 public:
ImplicitlyDefinedFunctionScope(Sema & S,CXXMethodDecl * Method)6725 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6726 : S(S), SavedContext(S, Method)
6727 {
6728 S.PushFunctionScope();
6729 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6730 }
6731
~ImplicitlyDefinedFunctionScope()6732 ~ImplicitlyDefinedFunctionScope() {
6733 S.PopExpressionEvaluationContext();
6734 S.PopFunctionScopeInfo();
6735 }
6736 };
6737 }
6738
6739 Sema::ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)6740 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6741 CXXMethodDecl *MD) {
6742 CXXRecordDecl *ClassDecl = MD->getParent();
6743
6744 // C++ [except.spec]p14:
6745 // An implicitly declared special member function (Clause 12) shall have an
6746 // exception-specification. [...]
6747 ImplicitExceptionSpecification ExceptSpec(*this);
6748 if (ClassDecl->isInvalidDecl())
6749 return ExceptSpec;
6750
6751 // Direct base-class constructors.
6752 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6753 BEnd = ClassDecl->bases_end();
6754 B != BEnd; ++B) {
6755 if (B->isVirtual()) // Handled below.
6756 continue;
6757
6758 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6759 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6760 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6761 // If this is a deleted function, add it anyway. This might be conformant
6762 // with the standard. This might not. I'm not sure. It might not matter.
6763 if (Constructor)
6764 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6765 }
6766 }
6767
6768 // Virtual base-class constructors.
6769 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6770 BEnd = ClassDecl->vbases_end();
6771 B != BEnd; ++B) {
6772 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6773 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6774 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6775 // If this is a deleted function, add it anyway. This might be conformant
6776 // with the standard. This might not. I'm not sure. It might not matter.
6777 if (Constructor)
6778 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6779 }
6780 }
6781
6782 // Field constructors.
6783 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6784 FEnd = ClassDecl->field_end();
6785 F != FEnd; ++F) {
6786 if (F->hasInClassInitializer()) {
6787 if (Expr *E = F->getInClassInitializer())
6788 ExceptSpec.CalledExpr(E);
6789 else if (!F->isInvalidDecl())
6790 // DR1351:
6791 // If the brace-or-equal-initializer of a non-static data member
6792 // invokes a defaulted default constructor of its class or of an
6793 // enclosing class in a potentially evaluated subexpression, the
6794 // program is ill-formed.
6795 //
6796 // This resolution is unworkable: the exception specification of the
6797 // default constructor can be needed in an unevaluated context, in
6798 // particular, in the operand of a noexcept-expression, and we can be
6799 // unable to compute an exception specification for an enclosed class.
6800 //
6801 // We do not allow an in-class initializer to require the evaluation
6802 // of the exception specification for any in-class initializer whose
6803 // definition is not lexically complete.
6804 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
6805 } else if (const RecordType *RecordTy
6806 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6807 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6808 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6809 // If this is a deleted function, add it anyway. This might be conformant
6810 // with the standard. This might not. I'm not sure. It might not matter.
6811 // In particular, the problem is that this function never gets called. It
6812 // might just be ill-formed because this function attempts to refer to
6813 // a deleted function here.
6814 if (Constructor)
6815 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
6816 }
6817 }
6818
6819 return ExceptSpec;
6820 }
6821
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)6822 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6823 CXXRecordDecl *ClassDecl) {
6824 // C++ [class.ctor]p5:
6825 // A default constructor for a class X is a constructor of class X
6826 // that can be called without an argument. If there is no
6827 // user-declared constructor for class X, a default constructor is
6828 // implicitly declared. An implicitly-declared default constructor
6829 // is an inline public member of its class.
6830 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6831 "Should not build implicit default constructor!");
6832
6833 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6834 CXXDefaultConstructor,
6835 false);
6836
6837 // Create the actual constructor declaration.
6838 CanQualType ClassType
6839 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6840 SourceLocation ClassLoc = ClassDecl->getLocation();
6841 DeclarationName Name
6842 = Context.DeclarationNames.getCXXConstructorName(ClassType);
6843 DeclarationNameInfo NameInfo(Name, ClassLoc);
6844 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6845 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
6846 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6847 Constexpr);
6848 DefaultCon->setAccess(AS_public);
6849 DefaultCon->setDefaulted();
6850 DefaultCon->setImplicit();
6851 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6852
6853 // Build an exception specification pointing back at this constructor.
6854 FunctionProtoType::ExtProtoInfo EPI;
6855 EPI.ExceptionSpecType = EST_Unevaluated;
6856 EPI.ExceptionSpecDecl = DefaultCon;
6857 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6858
6859 // Note that we have declared this constructor.
6860 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6861
6862 if (Scope *S = getScopeForContext(ClassDecl))
6863 PushOnScopeChains(DefaultCon, S, false);
6864 ClassDecl->addDecl(DefaultCon);
6865
6866 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6867 DefaultCon->setDeletedAsWritten();
6868
6869 return DefaultCon;
6870 }
6871
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)6872 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6873 CXXConstructorDecl *Constructor) {
6874 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6875 !Constructor->doesThisDeclarationHaveABody() &&
6876 !Constructor->isDeleted()) &&
6877 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6878
6879 CXXRecordDecl *ClassDecl = Constructor->getParent();
6880 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6881
6882 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6883 DiagnosticErrorTrap Trap(Diags);
6884 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6885 Trap.hasErrorOccurred()) {
6886 Diag(CurrentLocation, diag::note_member_synthesized_at)
6887 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6888 Constructor->setInvalidDecl();
6889 return;
6890 }
6891
6892 SourceLocation Loc = Constructor->getLocation();
6893 Constructor->setBody(new (Context) CompoundStmt(Loc));
6894
6895 Constructor->setUsed();
6896 MarkVTableUsed(CurrentLocation, ClassDecl);
6897
6898 if (ASTMutationListener *L = getASTMutationListener()) {
6899 L->CompletedImplicitDefinition(Constructor);
6900 }
6901 }
6902
ActOnFinishDelayedMemberInitializers(Decl * D)6903 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6904 if (!D) return;
6905 AdjustDeclIfTemplate(D);
6906
6907 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6908
6909 if (!ClassDecl->isDependentType())
6910 CheckExplicitlyDefaultedMethods(ClassDecl);
6911 }
6912
DeclareInheritedConstructors(CXXRecordDecl * ClassDecl)6913 void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6914 // We start with an initial pass over the base classes to collect those that
6915 // inherit constructors from. If there are none, we can forgo all further
6916 // processing.
6917 typedef SmallVector<const RecordType *, 4> BasesVector;
6918 BasesVector BasesToInheritFrom;
6919 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6920 BaseE = ClassDecl->bases_end();
6921 BaseIt != BaseE; ++BaseIt) {
6922 if (BaseIt->getInheritConstructors()) {
6923 QualType Base = BaseIt->getType();
6924 if (Base->isDependentType()) {
6925 // If we inherit constructors from anything that is dependent, just
6926 // abort processing altogether. We'll get another chance for the
6927 // instantiations.
6928 return;
6929 }
6930 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6931 }
6932 }
6933 if (BasesToInheritFrom.empty())
6934 return;
6935
6936 // Now collect the constructors that we already have in the current class.
6937 // Those take precedence over inherited constructors.
6938 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6939 // unless there is a user-declared constructor with the same signature in
6940 // the class where the using-declaration appears.
6941 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6942 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6943 CtorE = ClassDecl->ctor_end();
6944 CtorIt != CtorE; ++CtorIt) {
6945 ExistingConstructors.insert(
6946 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6947 }
6948
6949 DeclarationName CreatedCtorName =
6950 Context.DeclarationNames.getCXXConstructorName(
6951 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6952
6953 // Now comes the true work.
6954 // First, we keep a map from constructor types to the base that introduced
6955 // them. Needed for finding conflicting constructors. We also keep the
6956 // actually inserted declarations in there, for pretty diagnostics.
6957 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6958 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6959 ConstructorToSourceMap InheritedConstructors;
6960 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6961 BaseE = BasesToInheritFrom.end();
6962 BaseIt != BaseE; ++BaseIt) {
6963 const RecordType *Base = *BaseIt;
6964 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6965 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6966 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6967 CtorE = BaseDecl->ctor_end();
6968 CtorIt != CtorE; ++CtorIt) {
6969 // Find the using declaration for inheriting this base's constructors.
6970 // FIXME: Don't perform name lookup just to obtain a source location!
6971 DeclarationName Name =
6972 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6973 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6974 LookupQualifiedName(Result, CurContext);
6975 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
6976 SourceLocation UsingLoc = UD ? UD->getLocation() :
6977 ClassDecl->getLocation();
6978
6979 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6980 // from the class X named in the using-declaration consists of actual
6981 // constructors and notional constructors that result from the
6982 // transformation of defaulted parameters as follows:
6983 // - all non-template default constructors of X, and
6984 // - for each non-template constructor of X that has at least one
6985 // parameter with a default argument, the set of constructors that
6986 // results from omitting any ellipsis parameter specification and
6987 // successively omitting parameters with a default argument from the
6988 // end of the parameter-type-list.
6989 CXXConstructorDecl *BaseCtor = *CtorIt;
6990 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6991 const FunctionProtoType *BaseCtorType =
6992 BaseCtor->getType()->getAs<FunctionProtoType>();
6993
6994 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6995 maxParams = BaseCtor->getNumParams();
6996 params <= maxParams; ++params) {
6997 // Skip default constructors. They're never inherited.
6998 if (params == 0)
6999 continue;
7000 // Skip copy and move constructors for the same reason.
7001 if (CanBeCopyOrMove && params == 1)
7002 continue;
7003
7004 // Build up a function type for this particular constructor.
7005 // FIXME: The working paper does not consider that the exception spec
7006 // for the inheriting constructor might be larger than that of the
7007 // source. This code doesn't yet, either. When it does, this code will
7008 // need to be delayed until after exception specifications and in-class
7009 // member initializers are attached.
7010 const Type *NewCtorType;
7011 if (params == maxParams)
7012 NewCtorType = BaseCtorType;
7013 else {
7014 SmallVector<QualType, 16> Args;
7015 for (unsigned i = 0; i < params; ++i) {
7016 Args.push_back(BaseCtorType->getArgType(i));
7017 }
7018 FunctionProtoType::ExtProtoInfo ExtInfo =
7019 BaseCtorType->getExtProtoInfo();
7020 ExtInfo.Variadic = false;
7021 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7022 Args.data(), params, ExtInfo)
7023 .getTypePtr();
7024 }
7025 const Type *CanonicalNewCtorType =
7026 Context.getCanonicalType(NewCtorType);
7027
7028 // Now that we have the type, first check if the class already has a
7029 // constructor with this signature.
7030 if (ExistingConstructors.count(CanonicalNewCtorType))
7031 continue;
7032
7033 // Then we check if we have already declared an inherited constructor
7034 // with this signature.
7035 std::pair<ConstructorToSourceMap::iterator, bool> result =
7036 InheritedConstructors.insert(std::make_pair(
7037 CanonicalNewCtorType,
7038 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7039 if (!result.second) {
7040 // Already in the map. If it came from a different class, that's an
7041 // error. Not if it's from the same.
7042 CanQualType PreviousBase = result.first->second.first;
7043 if (CanonicalBase != PreviousBase) {
7044 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7045 const CXXConstructorDecl *PrevBaseCtor =
7046 PrevCtor->getInheritedConstructor();
7047 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7048
7049 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7050 Diag(BaseCtor->getLocation(),
7051 diag::note_using_decl_constructor_conflict_current_ctor);
7052 Diag(PrevBaseCtor->getLocation(),
7053 diag::note_using_decl_constructor_conflict_previous_ctor);
7054 Diag(PrevCtor->getLocation(),
7055 diag::note_using_decl_constructor_conflict_previous_using);
7056 }
7057 continue;
7058 }
7059
7060 // OK, we're there, now add the constructor.
7061 // C++0x [class.inhctor]p8: [...] that would be performed by a
7062 // user-written inline constructor [...]
7063 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7064 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7065 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7066 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7067 /*ImplicitlyDeclared=*/true,
7068 // FIXME: Due to a defect in the standard, we treat inherited
7069 // constructors as constexpr even if that makes them ill-formed.
7070 /*Constexpr=*/BaseCtor->isConstexpr());
7071 NewCtor->setAccess(BaseCtor->getAccess());
7072
7073 // Build up the parameter decls and add them.
7074 SmallVector<ParmVarDecl *, 16> ParamDecls;
7075 for (unsigned i = 0; i < params; ++i) {
7076 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7077 UsingLoc, UsingLoc,
7078 /*IdentifierInfo=*/0,
7079 BaseCtorType->getArgType(i),
7080 /*TInfo=*/0, SC_None,
7081 SC_None, /*DefaultArg=*/0));
7082 }
7083 NewCtor->setParams(ParamDecls);
7084 NewCtor->setInheritedConstructor(BaseCtor);
7085
7086 ClassDecl->addDecl(NewCtor);
7087 result.first->second.second = NewCtor;
7088 }
7089 }
7090 }
7091 }
7092
7093 Sema::ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl * MD)7094 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7095 CXXRecordDecl *ClassDecl = MD->getParent();
7096
7097 // C++ [except.spec]p14:
7098 // An implicitly declared special member function (Clause 12) shall have
7099 // an exception-specification.
7100 ImplicitExceptionSpecification ExceptSpec(*this);
7101 if (ClassDecl->isInvalidDecl())
7102 return ExceptSpec;
7103
7104 // Direct base-class destructors.
7105 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7106 BEnd = ClassDecl->bases_end();
7107 B != BEnd; ++B) {
7108 if (B->isVirtual()) // Handled below.
7109 continue;
7110
7111 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7112 ExceptSpec.CalledDecl(B->getLocStart(),
7113 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7114 }
7115
7116 // Virtual base-class destructors.
7117 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7118 BEnd = ClassDecl->vbases_end();
7119 B != BEnd; ++B) {
7120 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7121 ExceptSpec.CalledDecl(B->getLocStart(),
7122 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7123 }
7124
7125 // Field destructors.
7126 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7127 FEnd = ClassDecl->field_end();
7128 F != FEnd; ++F) {
7129 if (const RecordType *RecordTy
7130 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7131 ExceptSpec.CalledDecl(F->getLocation(),
7132 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7133 }
7134
7135 return ExceptSpec;
7136 }
7137
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)7138 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7139 // C++ [class.dtor]p2:
7140 // If a class has no user-declared destructor, a destructor is
7141 // declared implicitly. An implicitly-declared destructor is an
7142 // inline public member of its class.
7143
7144 // Create the actual destructor declaration.
7145 CanQualType ClassType
7146 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7147 SourceLocation ClassLoc = ClassDecl->getLocation();
7148 DeclarationName Name
7149 = Context.DeclarationNames.getCXXDestructorName(ClassType);
7150 DeclarationNameInfo NameInfo(Name, ClassLoc);
7151 CXXDestructorDecl *Destructor
7152 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7153 QualType(), 0, /*isInline=*/true,
7154 /*isImplicitlyDeclared=*/true);
7155 Destructor->setAccess(AS_public);
7156 Destructor->setDefaulted();
7157 Destructor->setImplicit();
7158 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7159
7160 // Build an exception specification pointing back at this destructor.
7161 FunctionProtoType::ExtProtoInfo EPI;
7162 EPI.ExceptionSpecType = EST_Unevaluated;
7163 EPI.ExceptionSpecDecl = Destructor;
7164 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7165
7166 // Note that we have declared this destructor.
7167 ++ASTContext::NumImplicitDestructorsDeclared;
7168
7169 // Introduce this destructor into its scope.
7170 if (Scope *S = getScopeForContext(ClassDecl))
7171 PushOnScopeChains(Destructor, S, false);
7172 ClassDecl->addDecl(Destructor);
7173
7174 AddOverriddenMethods(ClassDecl, Destructor);
7175
7176 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7177 Destructor->setDeletedAsWritten();
7178
7179 return Destructor;
7180 }
7181
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)7182 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7183 CXXDestructorDecl *Destructor) {
7184 assert((Destructor->isDefaulted() &&
7185 !Destructor->doesThisDeclarationHaveABody() &&
7186 !Destructor->isDeleted()) &&
7187 "DefineImplicitDestructor - call it for implicit default dtor");
7188 CXXRecordDecl *ClassDecl = Destructor->getParent();
7189 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7190
7191 if (Destructor->isInvalidDecl())
7192 return;
7193
7194 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7195
7196 DiagnosticErrorTrap Trap(Diags);
7197 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7198 Destructor->getParent());
7199
7200 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7201 Diag(CurrentLocation, diag::note_member_synthesized_at)
7202 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7203
7204 Destructor->setInvalidDecl();
7205 return;
7206 }
7207
7208 SourceLocation Loc = Destructor->getLocation();
7209 Destructor->setBody(new (Context) CompoundStmt(Loc));
7210 Destructor->setImplicitlyDefined(true);
7211 Destructor->setUsed();
7212 MarkVTableUsed(CurrentLocation, ClassDecl);
7213
7214 if (ASTMutationListener *L = getASTMutationListener()) {
7215 L->CompletedImplicitDefinition(Destructor);
7216 }
7217 }
7218
7219 /// \brief Perform any semantic analysis which needs to be delayed until all
7220 /// pending class member declarations have been parsed.
ActOnFinishCXXMemberDecls()7221 void Sema::ActOnFinishCXXMemberDecls() {
7222 // Perform any deferred checking of exception specifications for virtual
7223 // destructors.
7224 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7225 i != e; ++i) {
7226 const CXXDestructorDecl *Dtor =
7227 DelayedDestructorExceptionSpecChecks[i].first;
7228 assert(!Dtor->getParent()->isDependentType() &&
7229 "Should not ever add destructors of templates into the list.");
7230 CheckOverridingFunctionExceptionSpec(Dtor,
7231 DelayedDestructorExceptionSpecChecks[i].second);
7232 }
7233 DelayedDestructorExceptionSpecChecks.clear();
7234 }
7235
AdjustDestructorExceptionSpec(CXXRecordDecl * ClassDecl,CXXDestructorDecl * Destructor)7236 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7237 CXXDestructorDecl *Destructor) {
7238 assert(getLangOpts().CPlusPlus0x &&
7239 "adjusting dtor exception specs was introduced in c++11");
7240
7241 // C++11 [class.dtor]p3:
7242 // A declaration of a destructor that does not have an exception-
7243 // specification is implicitly considered to have the same exception-
7244 // specification as an implicit declaration.
7245 const FunctionProtoType *DtorType = Destructor->getType()->
7246 getAs<FunctionProtoType>();
7247 if (DtorType->hasExceptionSpec())
7248 return;
7249
7250 // Replace the destructor's type, building off the existing one. Fortunately,
7251 // the only thing of interest in the destructor type is its extended info.
7252 // The return and arguments are fixed.
7253 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7254 EPI.ExceptionSpecType = EST_Unevaluated;
7255 EPI.ExceptionSpecDecl = Destructor;
7256 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7257
7258 // FIXME: If the destructor has a body that could throw, and the newly created
7259 // spec doesn't allow exceptions, we should emit a warning, because this
7260 // change in behavior can break conforming C++03 programs at runtime.
7261 // However, we don't have a body or an exception specification yet, so it
7262 // needs to be done somewhere else.
7263 }
7264
7265 /// \brief Builds a statement that copies/moves the given entity from \p From to
7266 /// \c To.
7267 ///
7268 /// This routine is used to copy/move the members of a class with an
7269 /// implicitly-declared copy/move assignment operator. When the entities being
7270 /// copied are arrays, this routine builds for loops to copy them.
7271 ///
7272 /// \param S The Sema object used for type-checking.
7273 ///
7274 /// \param Loc The location where the implicit copy/move is being generated.
7275 ///
7276 /// \param T The type of the expressions being copied/moved. Both expressions
7277 /// must have this type.
7278 ///
7279 /// \param To The expression we are copying/moving to.
7280 ///
7281 /// \param From The expression we are copying/moving from.
7282 ///
7283 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7284 /// Otherwise, it's a non-static member subobject.
7285 ///
7286 /// \param Copying Whether we're copying or moving.
7287 ///
7288 /// \param Depth Internal parameter recording the depth of the recursion.
7289 ///
7290 /// \returns A statement or a loop that copies the expressions.
7291 static StmtResult
BuildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,Expr * To,Expr * From,bool CopyingBaseSubobject,bool Copying,unsigned Depth=0)7292 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7293 Expr *To, Expr *From,
7294 bool CopyingBaseSubobject, bool Copying,
7295 unsigned Depth = 0) {
7296 // C++0x [class.copy]p28:
7297 // Each subobject is assigned in the manner appropriate to its type:
7298 //
7299 // - if the subobject is of class type, as if by a call to operator= with
7300 // the subobject as the object expression and the corresponding
7301 // subobject of x as a single function argument (as if by explicit
7302 // qualification; that is, ignoring any possible virtual overriding
7303 // functions in more derived classes);
7304 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7305 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7306
7307 // Look for operator=.
7308 DeclarationName Name
7309 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7310 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7311 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7312
7313 // Filter out any result that isn't a copy/move-assignment operator.
7314 LookupResult::Filter F = OpLookup.makeFilter();
7315 while (F.hasNext()) {
7316 NamedDecl *D = F.next();
7317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7318 if (Method->isCopyAssignmentOperator() ||
7319 (!Copying && Method->isMoveAssignmentOperator()))
7320 continue;
7321
7322 F.erase();
7323 }
7324 F.done();
7325
7326 // Suppress the protected check (C++ [class.protected]) for each of the
7327 // assignment operators we found. This strange dance is required when
7328 // we're assigning via a base classes's copy-assignment operator. To
7329 // ensure that we're getting the right base class subobject (without
7330 // ambiguities), we need to cast "this" to that subobject type; to
7331 // ensure that we don't go through the virtual call mechanism, we need
7332 // to qualify the operator= name with the base class (see below). However,
7333 // this means that if the base class has a protected copy assignment
7334 // operator, the protected member access check will fail. So, we
7335 // rewrite "protected" access to "public" access in this case, since we
7336 // know by construction that we're calling from a derived class.
7337 if (CopyingBaseSubobject) {
7338 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7339 L != LEnd; ++L) {
7340 if (L.getAccess() == AS_protected)
7341 L.setAccess(AS_public);
7342 }
7343 }
7344
7345 // Create the nested-name-specifier that will be used to qualify the
7346 // reference to operator=; this is required to suppress the virtual
7347 // call mechanism.
7348 CXXScopeSpec SS;
7349 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7350 SS.MakeTrivial(S.Context,
7351 NestedNameSpecifier::Create(S.Context, 0, false,
7352 CanonicalT),
7353 Loc);
7354
7355 // Create the reference to operator=.
7356 ExprResult OpEqualRef
7357 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7358 /*TemplateKWLoc=*/SourceLocation(),
7359 /*FirstQualifierInScope=*/0,
7360 OpLookup,
7361 /*TemplateArgs=*/0,
7362 /*SuppressQualifierCheck=*/true);
7363 if (OpEqualRef.isInvalid())
7364 return StmtError();
7365
7366 // Build the call to the assignment operator.
7367
7368 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7369 OpEqualRef.takeAs<Expr>(),
7370 Loc, &From, 1, Loc);
7371 if (Call.isInvalid())
7372 return StmtError();
7373
7374 return S.Owned(Call.takeAs<Stmt>());
7375 }
7376
7377 // - if the subobject is of scalar type, the built-in assignment
7378 // operator is used.
7379 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7380 if (!ArrayTy) {
7381 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7382 if (Assignment.isInvalid())
7383 return StmtError();
7384
7385 return S.Owned(Assignment.takeAs<Stmt>());
7386 }
7387
7388 // - if the subobject is an array, each element is assigned, in the
7389 // manner appropriate to the element type;
7390
7391 // Construct a loop over the array bounds, e.g.,
7392 //
7393 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7394 //
7395 // that will copy each of the array elements.
7396 QualType SizeType = S.Context.getSizeType();
7397
7398 // Create the iteration variable.
7399 IdentifierInfo *IterationVarName = 0;
7400 {
7401 SmallString<8> Str;
7402 llvm::raw_svector_ostream OS(Str);
7403 OS << "__i" << Depth;
7404 IterationVarName = &S.Context.Idents.get(OS.str());
7405 }
7406 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7407 IterationVarName, SizeType,
7408 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7409 SC_None, SC_None);
7410
7411 // Initialize the iteration variable to zero.
7412 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7413 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7414
7415 // Create a reference to the iteration variable; we'll use this several
7416 // times throughout.
7417 Expr *IterationVarRef
7418 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7419 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7420 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7421 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7422
7423 // Create the DeclStmt that holds the iteration variable.
7424 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7425
7426 // Create the comparison against the array bound.
7427 llvm::APInt Upper
7428 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7429 Expr *Comparison
7430 = new (S.Context) BinaryOperator(IterationVarRefRVal,
7431 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7432 BO_NE, S.Context.BoolTy,
7433 VK_RValue, OK_Ordinary, Loc);
7434
7435 // Create the pre-increment of the iteration variable.
7436 Expr *Increment
7437 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7438 VK_LValue, OK_Ordinary, Loc);
7439
7440 // Subscript the "from" and "to" expressions with the iteration variable.
7441 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7442 IterationVarRefRVal,
7443 Loc));
7444 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7445 IterationVarRefRVal,
7446 Loc));
7447 if (!Copying) // Cast to rvalue
7448 From = CastForMoving(S, From);
7449
7450 // Build the copy/move for an individual element of the array.
7451 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7452 To, From, CopyingBaseSubobject,
7453 Copying, Depth + 1);
7454 if (Copy.isInvalid())
7455 return StmtError();
7456
7457 // Construct the loop that copies all elements of this array.
7458 return S.ActOnForStmt(Loc, Loc, InitStmt,
7459 S.MakeFullExpr(Comparison),
7460 0, S.MakeFullExpr(Increment),
7461 Loc, Copy.take());
7462 }
7463
7464 /// Determine whether an implicit copy assignment operator for ClassDecl has a
7465 /// const argument.
7466 /// FIXME: It ought to be possible to store this on the record.
isImplicitCopyAssignmentArgConst(Sema & S,CXXRecordDecl * ClassDecl)7467 static bool isImplicitCopyAssignmentArgConst(Sema &S,
7468 CXXRecordDecl *ClassDecl) {
7469 if (ClassDecl->isInvalidDecl())
7470 return true;
7471
7472 // C++ [class.copy]p10:
7473 // If the class definition does not explicitly declare a copy
7474 // assignment operator, one is declared implicitly.
7475 // The implicitly-defined copy assignment operator for a class X
7476 // will have the form
7477 //
7478 // X& X::operator=(const X&)
7479 //
7480 // if
7481 // -- each direct base class B of X has a copy assignment operator
7482 // whose parameter is of type const B&, const volatile B& or B,
7483 // and
7484 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7485 BaseEnd = ClassDecl->bases_end();
7486 Base != BaseEnd; ++Base) {
7487 // We'll handle this below
7488 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
7489 continue;
7490
7491 assert(!Base->getType()->isDependentType() &&
7492 "Cannot generate implicit members for class with dependent bases.");
7493 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7494 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7495 return false;
7496 }
7497
7498 // In C++11, the above citation has "or virtual" added
7499 if (S.getLangOpts().CPlusPlus0x) {
7500 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7501 BaseEnd = ClassDecl->vbases_end();
7502 Base != BaseEnd; ++Base) {
7503 assert(!Base->getType()->isDependentType() &&
7504 "Cannot generate implicit members for class with dependent bases.");
7505 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7506 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7507 false, 0))
7508 return false;
7509 }
7510 }
7511
7512 // -- for all the nonstatic data members of X that are of a class
7513 // type M (or array thereof), each such class type has a copy
7514 // assignment operator whose parameter is of type const M&,
7515 // const volatile M& or M.
7516 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7517 FieldEnd = ClassDecl->field_end();
7518 Field != FieldEnd; ++Field) {
7519 QualType FieldType = S.Context.getBaseElementType(Field->getType());
7520 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7521 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7522 false, 0))
7523 return false;
7524 }
7525
7526 // Otherwise, the implicitly declared copy assignment operator will
7527 // have the form
7528 //
7529 // X& X::operator=(X&)
7530
7531 return true;
7532 }
7533
7534 Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl * MD)7535 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7536 CXXRecordDecl *ClassDecl = MD->getParent();
7537
7538 ImplicitExceptionSpecification ExceptSpec(*this);
7539 if (ClassDecl->isInvalidDecl())
7540 return ExceptSpec;
7541
7542 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7543 assert(T->getNumArgs() == 1 && "not a copy assignment op");
7544 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7545
7546 // C++ [except.spec]p14:
7547 // An implicitly declared special member function (Clause 12) shall have an
7548 // exception-specification. [...]
7549
7550 // It is unspecified whether or not an implicit copy assignment operator
7551 // attempts to deduplicate calls to assignment operators of virtual bases are
7552 // made. As such, this exception specification is effectively unspecified.
7553 // Based on a similar decision made for constness in C++0x, we're erring on
7554 // the side of assuming such calls to be made regardless of whether they
7555 // actually happen.
7556 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7557 BaseEnd = ClassDecl->bases_end();
7558 Base != BaseEnd; ++Base) {
7559 if (Base->isVirtual())
7560 continue;
7561
7562 CXXRecordDecl *BaseClassDecl
7563 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7564 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7565 ArgQuals, false, 0))
7566 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7567 }
7568
7569 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7570 BaseEnd = ClassDecl->vbases_end();
7571 Base != BaseEnd; ++Base) {
7572 CXXRecordDecl *BaseClassDecl
7573 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7574 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7575 ArgQuals, false, 0))
7576 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7577 }
7578
7579 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7580 FieldEnd = ClassDecl->field_end();
7581 Field != FieldEnd;
7582 ++Field) {
7583 QualType FieldType = Context.getBaseElementType(Field->getType());
7584 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7585 if (CXXMethodDecl *CopyAssign =
7586 LookupCopyingAssignment(FieldClassDecl,
7587 ArgQuals | FieldType.getCVRQualifiers(),
7588 false, 0))
7589 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
7590 }
7591 }
7592
7593 return ExceptSpec;
7594 }
7595
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)7596 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7597 // Note: The following rules are largely analoguous to the copy
7598 // constructor rules. Note that virtual bases are not taken into account
7599 // for determining the argument type of the operator. Note also that
7600 // operators taking an object instead of a reference are allowed.
7601
7602 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7603 QualType RetType = Context.getLValueReferenceType(ArgType);
7604 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
7605 ArgType = ArgType.withConst();
7606 ArgType = Context.getLValueReferenceType(ArgType);
7607
7608 // An implicitly-declared copy assignment operator is an inline public
7609 // member of its class.
7610 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7611 SourceLocation ClassLoc = ClassDecl->getLocation();
7612 DeclarationNameInfo NameInfo(Name, ClassLoc);
7613 CXXMethodDecl *CopyAssignment
7614 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
7615 /*TInfo=*/0, /*isStatic=*/false,
7616 /*StorageClassAsWritten=*/SC_None,
7617 /*isInline=*/true, /*isConstexpr=*/false,
7618 SourceLocation());
7619 CopyAssignment->setAccess(AS_public);
7620 CopyAssignment->setDefaulted();
7621 CopyAssignment->setImplicit();
7622 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7623
7624 // Build an exception specification pointing back at this member.
7625 FunctionProtoType::ExtProtoInfo EPI;
7626 EPI.ExceptionSpecType = EST_Unevaluated;
7627 EPI.ExceptionSpecDecl = CopyAssignment;
7628 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7629
7630 // Add the parameter to the operator.
7631 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7632 ClassLoc, ClassLoc, /*Id=*/0,
7633 ArgType, /*TInfo=*/0,
7634 SC_None,
7635 SC_None, 0);
7636 CopyAssignment->setParams(FromParam);
7637
7638 // Note that we have added this copy-assignment operator.
7639 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7640
7641 if (Scope *S = getScopeForContext(ClassDecl))
7642 PushOnScopeChains(CopyAssignment, S, false);
7643 ClassDecl->addDecl(CopyAssignment);
7644
7645 // C++0x [class.copy]p19:
7646 // .... If the class definition does not explicitly declare a copy
7647 // assignment operator, there is no user-declared move constructor, and
7648 // there is no user-declared move assignment operator, a copy assignment
7649 // operator is implicitly declared as defaulted.
7650 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7651 CopyAssignment->setDeletedAsWritten();
7652
7653 AddOverriddenMethods(ClassDecl, CopyAssignment);
7654 return CopyAssignment;
7655 }
7656
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)7657 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7658 CXXMethodDecl *CopyAssignOperator) {
7659 assert((CopyAssignOperator->isDefaulted() &&
7660 CopyAssignOperator->isOverloadedOperator() &&
7661 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7662 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7663 !CopyAssignOperator->isDeleted()) &&
7664 "DefineImplicitCopyAssignment called for wrong function");
7665
7666 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7667
7668 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7669 CopyAssignOperator->setInvalidDecl();
7670 return;
7671 }
7672
7673 CopyAssignOperator->setUsed();
7674
7675 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7676 DiagnosticErrorTrap Trap(Diags);
7677
7678 // C++0x [class.copy]p30:
7679 // The implicitly-defined or explicitly-defaulted copy assignment operator
7680 // for a non-union class X performs memberwise copy assignment of its
7681 // subobjects. The direct base classes of X are assigned first, in the
7682 // order of their declaration in the base-specifier-list, and then the
7683 // immediate non-static data members of X are assigned, in the order in
7684 // which they were declared in the class definition.
7685
7686 // The statements that form the synthesized function body.
7687 SmallVector<Stmt*, 8> Statements;
7688
7689 // The parameter for the "other" object, which we are copying from.
7690 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7691 Qualifiers OtherQuals = Other->getType().getQualifiers();
7692 QualType OtherRefType = Other->getType();
7693 if (const LValueReferenceType *OtherRef
7694 = OtherRefType->getAs<LValueReferenceType>()) {
7695 OtherRefType = OtherRef->getPointeeType();
7696 OtherQuals = OtherRefType.getQualifiers();
7697 }
7698
7699 // Our location for everything implicitly-generated.
7700 SourceLocation Loc = CopyAssignOperator->getLocation();
7701
7702 // Construct a reference to the "other" object. We'll be using this
7703 // throughout the generated ASTs.
7704 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7705 assert(OtherRef && "Reference to parameter cannot fail!");
7706
7707 // Construct the "this" pointer. We'll be using this throughout the generated
7708 // ASTs.
7709 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7710 assert(This && "Reference to this cannot fail!");
7711
7712 // Assign base classes.
7713 bool Invalid = false;
7714 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7715 E = ClassDecl->bases_end(); Base != E; ++Base) {
7716 // Form the assignment:
7717 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7718 QualType BaseType = Base->getType().getUnqualifiedType();
7719 if (!BaseType->isRecordType()) {
7720 Invalid = true;
7721 continue;
7722 }
7723
7724 CXXCastPath BasePath;
7725 BasePath.push_back(Base);
7726
7727 // Construct the "from" expression, which is an implicit cast to the
7728 // appropriately-qualified base type.
7729 Expr *From = OtherRef;
7730 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7731 CK_UncheckedDerivedToBase,
7732 VK_LValue, &BasePath).take();
7733
7734 // Dereference "this".
7735 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7736
7737 // Implicitly cast "this" to the appropriately-qualified base type.
7738 To = ImpCastExprToType(To.take(),
7739 Context.getCVRQualifiedType(BaseType,
7740 CopyAssignOperator->getTypeQualifiers()),
7741 CK_UncheckedDerivedToBase,
7742 VK_LValue, &BasePath);
7743
7744 // Build the copy.
7745 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7746 To.get(), From,
7747 /*CopyingBaseSubobject=*/true,
7748 /*Copying=*/true);
7749 if (Copy.isInvalid()) {
7750 Diag(CurrentLocation, diag::note_member_synthesized_at)
7751 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7752 CopyAssignOperator->setInvalidDecl();
7753 return;
7754 }
7755
7756 // Success! Record the copy.
7757 Statements.push_back(Copy.takeAs<Expr>());
7758 }
7759
7760 // \brief Reference to the __builtin_memcpy function.
7761 Expr *BuiltinMemCpyRef = 0;
7762 // \brief Reference to the __builtin_objc_memmove_collectable function.
7763 Expr *CollectableMemCpyRef = 0;
7764
7765 // Assign non-static members.
7766 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7767 FieldEnd = ClassDecl->field_end();
7768 Field != FieldEnd; ++Field) {
7769 if (Field->isUnnamedBitfield())
7770 continue;
7771
7772 // Check for members of reference type; we can't copy those.
7773 if (Field->getType()->isReferenceType()) {
7774 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7775 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7776 Diag(Field->getLocation(), diag::note_declared_at);
7777 Diag(CurrentLocation, diag::note_member_synthesized_at)
7778 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7779 Invalid = true;
7780 continue;
7781 }
7782
7783 // Check for members of const-qualified, non-class type.
7784 QualType BaseType = Context.getBaseElementType(Field->getType());
7785 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7786 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7787 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7788 Diag(Field->getLocation(), diag::note_declared_at);
7789 Diag(CurrentLocation, diag::note_member_synthesized_at)
7790 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7791 Invalid = true;
7792 continue;
7793 }
7794
7795 // Suppress assigning zero-width bitfields.
7796 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7797 continue;
7798
7799 QualType FieldType = Field->getType().getNonReferenceType();
7800 if (FieldType->isIncompleteArrayType()) {
7801 assert(ClassDecl->hasFlexibleArrayMember() &&
7802 "Incomplete array type is not valid");
7803 continue;
7804 }
7805
7806 // Build references to the field in the object we're copying from and to.
7807 CXXScopeSpec SS; // Intentionally empty
7808 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7809 LookupMemberName);
7810 MemberLookup.addDecl(*Field);
7811 MemberLookup.resolveKind();
7812 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7813 Loc, /*IsArrow=*/false,
7814 SS, SourceLocation(), 0,
7815 MemberLookup, 0);
7816 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7817 Loc, /*IsArrow=*/true,
7818 SS, SourceLocation(), 0,
7819 MemberLookup, 0);
7820 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7821 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7822
7823 // If the field should be copied with __builtin_memcpy rather than via
7824 // explicit assignments, do so. This optimization only applies for arrays
7825 // of scalars and arrays of class type with trivial copy-assignment
7826 // operators.
7827 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7828 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7829 // Compute the size of the memory buffer to be copied.
7830 QualType SizeType = Context.getSizeType();
7831 llvm::APInt Size(Context.getTypeSize(SizeType),
7832 Context.getTypeSizeInChars(BaseType).getQuantity());
7833 for (const ConstantArrayType *Array
7834 = Context.getAsConstantArrayType(FieldType);
7835 Array;
7836 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7837 llvm::APInt ArraySize
7838 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7839 Size *= ArraySize;
7840 }
7841
7842 // Take the address of the field references for "from" and "to".
7843 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7844 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7845
7846 bool NeedsCollectableMemCpy =
7847 (BaseType->isRecordType() &&
7848 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7849
7850 if (NeedsCollectableMemCpy) {
7851 if (!CollectableMemCpyRef) {
7852 // Create a reference to the __builtin_objc_memmove_collectable function.
7853 LookupResult R(*this,
7854 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7855 Loc, LookupOrdinaryName);
7856 LookupName(R, TUScope, true);
7857
7858 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7859 if (!CollectableMemCpy) {
7860 // Something went horribly wrong earlier, and we will have
7861 // complained about it.
7862 Invalid = true;
7863 continue;
7864 }
7865
7866 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7867 Context.BuiltinFnTy,
7868 VK_RValue, Loc, 0).take();
7869 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7870 }
7871 }
7872 // Create a reference to the __builtin_memcpy builtin function.
7873 else if (!BuiltinMemCpyRef) {
7874 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7875 LookupOrdinaryName);
7876 LookupName(R, TUScope, true);
7877
7878 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7879 if (!BuiltinMemCpy) {
7880 // Something went horribly wrong earlier, and we will have complained
7881 // about it.
7882 Invalid = true;
7883 continue;
7884 }
7885
7886 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7887 Context.BuiltinFnTy,
7888 VK_RValue, Loc, 0).take();
7889 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7890 }
7891
7892 SmallVector<Expr*, 8> CallArgs;
7893 CallArgs.push_back(To.takeAs<Expr>());
7894 CallArgs.push_back(From.takeAs<Expr>());
7895 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7896 ExprResult Call = ExprError();
7897 if (NeedsCollectableMemCpy)
7898 Call = ActOnCallExpr(/*Scope=*/0,
7899 CollectableMemCpyRef,
7900 Loc, CallArgs,
7901 Loc);
7902 else
7903 Call = ActOnCallExpr(/*Scope=*/0,
7904 BuiltinMemCpyRef,
7905 Loc, CallArgs,
7906 Loc);
7907
7908 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7909 Statements.push_back(Call.takeAs<Expr>());
7910 continue;
7911 }
7912
7913 // Build the copy of this field.
7914 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7915 To.get(), From.get(),
7916 /*CopyingBaseSubobject=*/false,
7917 /*Copying=*/true);
7918 if (Copy.isInvalid()) {
7919 Diag(CurrentLocation, diag::note_member_synthesized_at)
7920 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7921 CopyAssignOperator->setInvalidDecl();
7922 return;
7923 }
7924
7925 // Success! Record the copy.
7926 Statements.push_back(Copy.takeAs<Stmt>());
7927 }
7928
7929 if (!Invalid) {
7930 // Add a "return *this;"
7931 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7932
7933 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7934 if (Return.isInvalid())
7935 Invalid = true;
7936 else {
7937 Statements.push_back(Return.takeAs<Stmt>());
7938
7939 if (Trap.hasErrorOccurred()) {
7940 Diag(CurrentLocation, diag::note_member_synthesized_at)
7941 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7942 Invalid = true;
7943 }
7944 }
7945 }
7946
7947 if (Invalid) {
7948 CopyAssignOperator->setInvalidDecl();
7949 return;
7950 }
7951
7952 StmtResult Body;
7953 {
7954 CompoundScopeRAII CompoundScope(*this);
7955 Body = ActOnCompoundStmt(Loc, Loc, Statements,
7956 /*isStmtExpr=*/false);
7957 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7958 }
7959 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7960
7961 if (ASTMutationListener *L = getASTMutationListener()) {
7962 L->CompletedImplicitDefinition(CopyAssignOperator);
7963 }
7964 }
7965
7966 Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl * MD)7967 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7968 CXXRecordDecl *ClassDecl = MD->getParent();
7969
7970 ImplicitExceptionSpecification ExceptSpec(*this);
7971 if (ClassDecl->isInvalidDecl())
7972 return ExceptSpec;
7973
7974 // C++0x [except.spec]p14:
7975 // An implicitly declared special member function (Clause 12) shall have an
7976 // exception-specification. [...]
7977
7978 // It is unspecified whether or not an implicit move assignment operator
7979 // attempts to deduplicate calls to assignment operators of virtual bases are
7980 // made. As such, this exception specification is effectively unspecified.
7981 // Based on a similar decision made for constness in C++0x, we're erring on
7982 // the side of assuming such calls to be made regardless of whether they
7983 // actually happen.
7984 // Note that a move constructor is not implicitly declared when there are
7985 // virtual bases, but it can still be user-declared and explicitly defaulted.
7986 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7987 BaseEnd = ClassDecl->bases_end();
7988 Base != BaseEnd; ++Base) {
7989 if (Base->isVirtual())
7990 continue;
7991
7992 CXXRecordDecl *BaseClassDecl
7993 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7994 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7995 0, false, 0))
7996 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
7997 }
7998
7999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8000 BaseEnd = ClassDecl->vbases_end();
8001 Base != BaseEnd; ++Base) {
8002 CXXRecordDecl *BaseClassDecl
8003 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8004 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8005 0, false, 0))
8006 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8007 }
8008
8009 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8010 FieldEnd = ClassDecl->field_end();
8011 Field != FieldEnd;
8012 ++Field) {
8013 QualType FieldType = Context.getBaseElementType(Field->getType());
8014 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8015 if (CXXMethodDecl *MoveAssign =
8016 LookupMovingAssignment(FieldClassDecl,
8017 FieldType.getCVRQualifiers(),
8018 false, 0))
8019 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8020 }
8021 }
8022
8023 return ExceptSpec;
8024 }
8025
8026 /// Determine whether the class type has any direct or indirect virtual base
8027 /// classes which have a non-trivial move assignment operator.
8028 static bool
hasVirtualBaseWithNonTrivialMoveAssignment(Sema & S,CXXRecordDecl * ClassDecl)8029 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8030 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8031 BaseEnd = ClassDecl->vbases_end();
8032 Base != BaseEnd; ++Base) {
8033 CXXRecordDecl *BaseClass =
8034 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8035
8036 // Try to declare the move assignment. If it would be deleted, then the
8037 // class does not have a non-trivial move assignment.
8038 if (BaseClass->needsImplicitMoveAssignment())
8039 S.DeclareImplicitMoveAssignment(BaseClass);
8040
8041 // If the class has both a trivial move assignment and a non-trivial move
8042 // assignment, hasTrivialMoveAssignment() is false.
8043 if (BaseClass->hasDeclaredMoveAssignment() &&
8044 !BaseClass->hasTrivialMoveAssignment())
8045 return true;
8046 }
8047
8048 return false;
8049 }
8050
8051 /// Determine whether the given type either has a move constructor or is
8052 /// trivially copyable.
8053 static bool
hasMoveOrIsTriviallyCopyable(Sema & S,QualType Type,bool IsConstructor)8054 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8055 Type = S.Context.getBaseElementType(Type);
8056
8057 // FIXME: Technically, non-trivially-copyable non-class types, such as
8058 // reference types, are supposed to return false here, but that appears
8059 // to be a standard defect.
8060 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8061 if (!ClassDecl || !ClassDecl->getDefinition())
8062 return true;
8063
8064 if (Type.isTriviallyCopyableType(S.Context))
8065 return true;
8066
8067 if (IsConstructor) {
8068 if (ClassDecl->needsImplicitMoveConstructor())
8069 S.DeclareImplicitMoveConstructor(ClassDecl);
8070 return ClassDecl->hasDeclaredMoveConstructor();
8071 }
8072
8073 if (ClassDecl->needsImplicitMoveAssignment())
8074 S.DeclareImplicitMoveAssignment(ClassDecl);
8075 return ClassDecl->hasDeclaredMoveAssignment();
8076 }
8077
8078 /// Determine whether all non-static data members and direct or virtual bases
8079 /// of class \p ClassDecl have either a move operation, or are trivially
8080 /// copyable.
subobjectsHaveMoveOrTrivialCopy(Sema & S,CXXRecordDecl * ClassDecl,bool IsConstructor)8081 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8082 bool IsConstructor) {
8083 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8084 BaseEnd = ClassDecl->bases_end();
8085 Base != BaseEnd; ++Base) {
8086 if (Base->isVirtual())
8087 continue;
8088
8089 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8090 return false;
8091 }
8092
8093 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8094 BaseEnd = ClassDecl->vbases_end();
8095 Base != BaseEnd; ++Base) {
8096 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8097 return false;
8098 }
8099
8100 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8101 FieldEnd = ClassDecl->field_end();
8102 Field != FieldEnd; ++Field) {
8103 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8104 return false;
8105 }
8106
8107 return true;
8108 }
8109
DeclareImplicitMoveAssignment(CXXRecordDecl * ClassDecl)8110 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8111 // C++11 [class.copy]p20:
8112 // If the definition of a class X does not explicitly declare a move
8113 // assignment operator, one will be implicitly declared as defaulted
8114 // if and only if:
8115 //
8116 // - [first 4 bullets]
8117 assert(ClassDecl->needsImplicitMoveAssignment());
8118
8119 // [Checked after we build the declaration]
8120 // - the move assignment operator would not be implicitly defined as
8121 // deleted,
8122
8123 // [DR1402]:
8124 // - X has no direct or indirect virtual base class with a non-trivial
8125 // move assignment operator, and
8126 // - each of X's non-static data members and direct or virtual base classes
8127 // has a type that either has a move assignment operator or is trivially
8128 // copyable.
8129 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8130 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8131 ClassDecl->setFailedImplicitMoveAssignment();
8132 return 0;
8133 }
8134
8135 // Note: The following rules are largely analoguous to the move
8136 // constructor rules.
8137
8138 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8139 QualType RetType = Context.getLValueReferenceType(ArgType);
8140 ArgType = Context.getRValueReferenceType(ArgType);
8141
8142 // An implicitly-declared move assignment operator is an inline public
8143 // member of its class.
8144 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8145 SourceLocation ClassLoc = ClassDecl->getLocation();
8146 DeclarationNameInfo NameInfo(Name, ClassLoc);
8147 CXXMethodDecl *MoveAssignment
8148 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8149 /*TInfo=*/0, /*isStatic=*/false,
8150 /*StorageClassAsWritten=*/SC_None,
8151 /*isInline=*/true,
8152 /*isConstexpr=*/false,
8153 SourceLocation());
8154 MoveAssignment->setAccess(AS_public);
8155 MoveAssignment->setDefaulted();
8156 MoveAssignment->setImplicit();
8157 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8158
8159 // Build an exception specification pointing back at this member.
8160 FunctionProtoType::ExtProtoInfo EPI;
8161 EPI.ExceptionSpecType = EST_Unevaluated;
8162 EPI.ExceptionSpecDecl = MoveAssignment;
8163 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8164
8165 // Add the parameter to the operator.
8166 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8167 ClassLoc, ClassLoc, /*Id=*/0,
8168 ArgType, /*TInfo=*/0,
8169 SC_None,
8170 SC_None, 0);
8171 MoveAssignment->setParams(FromParam);
8172
8173 // Note that we have added this copy-assignment operator.
8174 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8175
8176 // C++0x [class.copy]p9:
8177 // If the definition of a class X does not explicitly declare a move
8178 // assignment operator, one will be implicitly declared as defaulted if and
8179 // only if:
8180 // [...]
8181 // - the move assignment operator would not be implicitly defined as
8182 // deleted.
8183 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8184 // Cache this result so that we don't try to generate this over and over
8185 // on every lookup, leaking memory and wasting time.
8186 ClassDecl->setFailedImplicitMoveAssignment();
8187 return 0;
8188 }
8189
8190 if (Scope *S = getScopeForContext(ClassDecl))
8191 PushOnScopeChains(MoveAssignment, S, false);
8192 ClassDecl->addDecl(MoveAssignment);
8193
8194 AddOverriddenMethods(ClassDecl, MoveAssignment);
8195 return MoveAssignment;
8196 }
8197
DefineImplicitMoveAssignment(SourceLocation CurrentLocation,CXXMethodDecl * MoveAssignOperator)8198 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8199 CXXMethodDecl *MoveAssignOperator) {
8200 assert((MoveAssignOperator->isDefaulted() &&
8201 MoveAssignOperator->isOverloadedOperator() &&
8202 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8203 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8204 !MoveAssignOperator->isDeleted()) &&
8205 "DefineImplicitMoveAssignment called for wrong function");
8206
8207 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8208
8209 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8210 MoveAssignOperator->setInvalidDecl();
8211 return;
8212 }
8213
8214 MoveAssignOperator->setUsed();
8215
8216 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8217 DiagnosticErrorTrap Trap(Diags);
8218
8219 // C++0x [class.copy]p28:
8220 // The implicitly-defined or move assignment operator for a non-union class
8221 // X performs memberwise move assignment of its subobjects. The direct base
8222 // classes of X are assigned first, in the order of their declaration in the
8223 // base-specifier-list, and then the immediate non-static data members of X
8224 // are assigned, in the order in which they were declared in the class
8225 // definition.
8226
8227 // The statements that form the synthesized function body.
8228 SmallVector<Stmt*, 8> Statements;
8229
8230 // The parameter for the "other" object, which we are move from.
8231 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8232 QualType OtherRefType = Other->getType()->
8233 getAs<RValueReferenceType>()->getPointeeType();
8234 assert(OtherRefType.getQualifiers() == 0 &&
8235 "Bad argument type of defaulted move assignment");
8236
8237 // Our location for everything implicitly-generated.
8238 SourceLocation Loc = MoveAssignOperator->getLocation();
8239
8240 // Construct a reference to the "other" object. We'll be using this
8241 // throughout the generated ASTs.
8242 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8243 assert(OtherRef && "Reference to parameter cannot fail!");
8244 // Cast to rvalue.
8245 OtherRef = CastForMoving(*this, OtherRef);
8246
8247 // Construct the "this" pointer. We'll be using this throughout the generated
8248 // ASTs.
8249 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8250 assert(This && "Reference to this cannot fail!");
8251
8252 // Assign base classes.
8253 bool Invalid = false;
8254 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8255 E = ClassDecl->bases_end(); Base != E; ++Base) {
8256 // Form the assignment:
8257 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8258 QualType BaseType = Base->getType().getUnqualifiedType();
8259 if (!BaseType->isRecordType()) {
8260 Invalid = true;
8261 continue;
8262 }
8263
8264 CXXCastPath BasePath;
8265 BasePath.push_back(Base);
8266
8267 // Construct the "from" expression, which is an implicit cast to the
8268 // appropriately-qualified base type.
8269 Expr *From = OtherRef;
8270 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8271 VK_XValue, &BasePath).take();
8272
8273 // Dereference "this".
8274 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8275
8276 // Implicitly cast "this" to the appropriately-qualified base type.
8277 To = ImpCastExprToType(To.take(),
8278 Context.getCVRQualifiedType(BaseType,
8279 MoveAssignOperator->getTypeQualifiers()),
8280 CK_UncheckedDerivedToBase,
8281 VK_LValue, &BasePath);
8282
8283 // Build the move.
8284 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8285 To.get(), From,
8286 /*CopyingBaseSubobject=*/true,
8287 /*Copying=*/false);
8288 if (Move.isInvalid()) {
8289 Diag(CurrentLocation, diag::note_member_synthesized_at)
8290 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8291 MoveAssignOperator->setInvalidDecl();
8292 return;
8293 }
8294
8295 // Success! Record the move.
8296 Statements.push_back(Move.takeAs<Expr>());
8297 }
8298
8299 // \brief Reference to the __builtin_memcpy function.
8300 Expr *BuiltinMemCpyRef = 0;
8301 // \brief Reference to the __builtin_objc_memmove_collectable function.
8302 Expr *CollectableMemCpyRef = 0;
8303
8304 // Assign non-static members.
8305 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8306 FieldEnd = ClassDecl->field_end();
8307 Field != FieldEnd; ++Field) {
8308 if (Field->isUnnamedBitfield())
8309 continue;
8310
8311 // Check for members of reference type; we can't move those.
8312 if (Field->getType()->isReferenceType()) {
8313 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8314 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8315 Diag(Field->getLocation(), diag::note_declared_at);
8316 Diag(CurrentLocation, diag::note_member_synthesized_at)
8317 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8318 Invalid = true;
8319 continue;
8320 }
8321
8322 // Check for members of const-qualified, non-class type.
8323 QualType BaseType = Context.getBaseElementType(Field->getType());
8324 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8325 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8326 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8327 Diag(Field->getLocation(), diag::note_declared_at);
8328 Diag(CurrentLocation, diag::note_member_synthesized_at)
8329 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8330 Invalid = true;
8331 continue;
8332 }
8333
8334 // Suppress assigning zero-width bitfields.
8335 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8336 continue;
8337
8338 QualType FieldType = Field->getType().getNonReferenceType();
8339 if (FieldType->isIncompleteArrayType()) {
8340 assert(ClassDecl->hasFlexibleArrayMember() &&
8341 "Incomplete array type is not valid");
8342 continue;
8343 }
8344
8345 // Build references to the field in the object we're copying from and to.
8346 CXXScopeSpec SS; // Intentionally empty
8347 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8348 LookupMemberName);
8349 MemberLookup.addDecl(*Field);
8350 MemberLookup.resolveKind();
8351 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8352 Loc, /*IsArrow=*/false,
8353 SS, SourceLocation(), 0,
8354 MemberLookup, 0);
8355 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8356 Loc, /*IsArrow=*/true,
8357 SS, SourceLocation(), 0,
8358 MemberLookup, 0);
8359 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8360 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8361
8362 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8363 "Member reference with rvalue base must be rvalue except for reference "
8364 "members, which aren't allowed for move assignment.");
8365
8366 // If the field should be copied with __builtin_memcpy rather than via
8367 // explicit assignments, do so. This optimization only applies for arrays
8368 // of scalars and arrays of class type with trivial move-assignment
8369 // operators.
8370 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8371 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8372 // Compute the size of the memory buffer to be copied.
8373 QualType SizeType = Context.getSizeType();
8374 llvm::APInt Size(Context.getTypeSize(SizeType),
8375 Context.getTypeSizeInChars(BaseType).getQuantity());
8376 for (const ConstantArrayType *Array
8377 = Context.getAsConstantArrayType(FieldType);
8378 Array;
8379 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8380 llvm::APInt ArraySize
8381 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8382 Size *= ArraySize;
8383 }
8384
8385 // Take the address of the field references for "from" and "to". We
8386 // directly construct UnaryOperators here because semantic analysis
8387 // does not permit us to take the address of an xvalue.
8388 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8389 Context.getPointerType(From.get()->getType()),
8390 VK_RValue, OK_Ordinary, Loc);
8391 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8392 Context.getPointerType(To.get()->getType()),
8393 VK_RValue, OK_Ordinary, Loc);
8394
8395 bool NeedsCollectableMemCpy =
8396 (BaseType->isRecordType() &&
8397 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8398
8399 if (NeedsCollectableMemCpy) {
8400 if (!CollectableMemCpyRef) {
8401 // Create a reference to the __builtin_objc_memmove_collectable function.
8402 LookupResult R(*this,
8403 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8404 Loc, LookupOrdinaryName);
8405 LookupName(R, TUScope, true);
8406
8407 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8408 if (!CollectableMemCpy) {
8409 // Something went horribly wrong earlier, and we will have
8410 // complained about it.
8411 Invalid = true;
8412 continue;
8413 }
8414
8415 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8416 Context.BuiltinFnTy,
8417 VK_RValue, Loc, 0).take();
8418 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8419 }
8420 }
8421 // Create a reference to the __builtin_memcpy builtin function.
8422 else if (!BuiltinMemCpyRef) {
8423 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8424 LookupOrdinaryName);
8425 LookupName(R, TUScope, true);
8426
8427 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8428 if (!BuiltinMemCpy) {
8429 // Something went horribly wrong earlier, and we will have complained
8430 // about it.
8431 Invalid = true;
8432 continue;
8433 }
8434
8435 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8436 Context.BuiltinFnTy,
8437 VK_RValue, Loc, 0).take();
8438 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8439 }
8440
8441 SmallVector<Expr*, 8> CallArgs;
8442 CallArgs.push_back(To.takeAs<Expr>());
8443 CallArgs.push_back(From.takeAs<Expr>());
8444 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8445 ExprResult Call = ExprError();
8446 if (NeedsCollectableMemCpy)
8447 Call = ActOnCallExpr(/*Scope=*/0,
8448 CollectableMemCpyRef,
8449 Loc, CallArgs,
8450 Loc);
8451 else
8452 Call = ActOnCallExpr(/*Scope=*/0,
8453 BuiltinMemCpyRef,
8454 Loc, CallArgs,
8455 Loc);
8456
8457 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8458 Statements.push_back(Call.takeAs<Expr>());
8459 continue;
8460 }
8461
8462 // Build the move of this field.
8463 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8464 To.get(), From.get(),
8465 /*CopyingBaseSubobject=*/false,
8466 /*Copying=*/false);
8467 if (Move.isInvalid()) {
8468 Diag(CurrentLocation, diag::note_member_synthesized_at)
8469 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8470 MoveAssignOperator->setInvalidDecl();
8471 return;
8472 }
8473
8474 // Success! Record the copy.
8475 Statements.push_back(Move.takeAs<Stmt>());
8476 }
8477
8478 if (!Invalid) {
8479 // Add a "return *this;"
8480 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8481
8482 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8483 if (Return.isInvalid())
8484 Invalid = true;
8485 else {
8486 Statements.push_back(Return.takeAs<Stmt>());
8487
8488 if (Trap.hasErrorOccurred()) {
8489 Diag(CurrentLocation, diag::note_member_synthesized_at)
8490 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8491 Invalid = true;
8492 }
8493 }
8494 }
8495
8496 if (Invalid) {
8497 MoveAssignOperator->setInvalidDecl();
8498 return;
8499 }
8500
8501 StmtResult Body;
8502 {
8503 CompoundScopeRAII CompoundScope(*this);
8504 Body = ActOnCompoundStmt(Loc, Loc, Statements,
8505 /*isStmtExpr=*/false);
8506 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8507 }
8508 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8509
8510 if (ASTMutationListener *L = getASTMutationListener()) {
8511 L->CompletedImplicitDefinition(MoveAssignOperator);
8512 }
8513 }
8514
8515 /// Determine whether an implicit copy constructor for ClassDecl has a const
8516 /// argument.
8517 /// FIXME: It ought to be possible to store this on the record.
isImplicitCopyCtorArgConst(Sema & S,CXXRecordDecl * ClassDecl)8518 static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
8519 if (ClassDecl->isInvalidDecl())
8520 return true;
8521
8522 // C++ [class.copy]p5:
8523 // The implicitly-declared copy constructor for a class X will
8524 // have the form
8525 //
8526 // X::X(const X&)
8527 //
8528 // if
8529 // -- each direct or virtual base class B of X has a copy
8530 // constructor whose first parameter is of type const B& or
8531 // const volatile B&, and
8532 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8533 BaseEnd = ClassDecl->bases_end();
8534 Base != BaseEnd; ++Base) {
8535 // Virtual bases are handled below.
8536 if (Base->isVirtual())
8537 continue;
8538
8539 CXXRecordDecl *BaseClassDecl
8540 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8541 // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8542 // ambiguous, we should still produce a constructor with a const-qualified
8543 // parameter.
8544 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8545 return false;
8546 }
8547
8548 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8549 BaseEnd = ClassDecl->vbases_end();
8550 Base != BaseEnd; ++Base) {
8551 CXXRecordDecl *BaseClassDecl
8552 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8553 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8554 return false;
8555 }
8556
8557 // -- for all the nonstatic data members of X that are of a
8558 // class type M (or array thereof), each such class type
8559 // has a copy constructor whose first parameter is of type
8560 // const M& or const volatile M&.
8561 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8562 FieldEnd = ClassDecl->field_end();
8563 Field != FieldEnd; ++Field) {
8564 QualType FieldType = S.Context.getBaseElementType(Field->getType());
8565 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8566 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8567 return false;
8568 }
8569 }
8570
8571 // Otherwise, the implicitly declared copy constructor will have
8572 // the form
8573 //
8574 // X::X(X&)
8575
8576 return true;
8577 }
8578
8579 Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl * MD)8580 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8581 CXXRecordDecl *ClassDecl = MD->getParent();
8582
8583 ImplicitExceptionSpecification ExceptSpec(*this);
8584 if (ClassDecl->isInvalidDecl())
8585 return ExceptSpec;
8586
8587 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8588 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8589 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8590
8591 // C++ [except.spec]p14:
8592 // An implicitly declared special member function (Clause 12) shall have an
8593 // exception-specification. [...]
8594 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8595 BaseEnd = ClassDecl->bases_end();
8596 Base != BaseEnd;
8597 ++Base) {
8598 // Virtual bases are handled below.
8599 if (Base->isVirtual())
8600 continue;
8601
8602 CXXRecordDecl *BaseClassDecl
8603 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8604 if (CXXConstructorDecl *CopyConstructor =
8605 LookupCopyingConstructor(BaseClassDecl, Quals))
8606 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8607 }
8608 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8609 BaseEnd = ClassDecl->vbases_end();
8610 Base != BaseEnd;
8611 ++Base) {
8612 CXXRecordDecl *BaseClassDecl
8613 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8614 if (CXXConstructorDecl *CopyConstructor =
8615 LookupCopyingConstructor(BaseClassDecl, Quals))
8616 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8617 }
8618 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8619 FieldEnd = ClassDecl->field_end();
8620 Field != FieldEnd;
8621 ++Field) {
8622 QualType FieldType = Context.getBaseElementType(Field->getType());
8623 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8624 if (CXXConstructorDecl *CopyConstructor =
8625 LookupCopyingConstructor(FieldClassDecl,
8626 Quals | FieldType.getCVRQualifiers()))
8627 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
8628 }
8629 }
8630
8631 return ExceptSpec;
8632 }
8633
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)8634 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8635 CXXRecordDecl *ClassDecl) {
8636 // C++ [class.copy]p4:
8637 // If the class definition does not explicitly declare a copy
8638 // constructor, one is declared implicitly.
8639
8640 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8641 QualType ArgType = ClassType;
8642 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
8643 if (Const)
8644 ArgType = ArgType.withConst();
8645 ArgType = Context.getLValueReferenceType(ArgType);
8646
8647 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8648 CXXCopyConstructor,
8649 Const);
8650
8651 DeclarationName Name
8652 = Context.DeclarationNames.getCXXConstructorName(
8653 Context.getCanonicalType(ClassType));
8654 SourceLocation ClassLoc = ClassDecl->getLocation();
8655 DeclarationNameInfo NameInfo(Name, ClassLoc);
8656
8657 // An implicitly-declared copy constructor is an inline public
8658 // member of its class.
8659 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8660 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8661 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8662 Constexpr);
8663 CopyConstructor->setAccess(AS_public);
8664 CopyConstructor->setDefaulted();
8665 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8666
8667 // Build an exception specification pointing back at this member.
8668 FunctionProtoType::ExtProtoInfo EPI;
8669 EPI.ExceptionSpecType = EST_Unevaluated;
8670 EPI.ExceptionSpecDecl = CopyConstructor;
8671 CopyConstructor->setType(
8672 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8673
8674 // Note that we have declared this constructor.
8675 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8676
8677 // Add the parameter to the constructor.
8678 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8679 ClassLoc, ClassLoc,
8680 /*IdentifierInfo=*/0,
8681 ArgType, /*TInfo=*/0,
8682 SC_None,
8683 SC_None, 0);
8684 CopyConstructor->setParams(FromParam);
8685
8686 if (Scope *S = getScopeForContext(ClassDecl))
8687 PushOnScopeChains(CopyConstructor, S, false);
8688 ClassDecl->addDecl(CopyConstructor);
8689
8690 // C++11 [class.copy]p8:
8691 // ... If the class definition does not explicitly declare a copy
8692 // constructor, there is no user-declared move constructor, and there is no
8693 // user-declared move assignment operator, a copy constructor is implicitly
8694 // declared as defaulted.
8695 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8696 CopyConstructor->setDeletedAsWritten();
8697
8698 return CopyConstructor;
8699 }
8700
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)8701 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8702 CXXConstructorDecl *CopyConstructor) {
8703 assert((CopyConstructor->isDefaulted() &&
8704 CopyConstructor->isCopyConstructor() &&
8705 !CopyConstructor->doesThisDeclarationHaveABody() &&
8706 !CopyConstructor->isDeleted()) &&
8707 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8708
8709 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8710 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8711
8712 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8713 DiagnosticErrorTrap Trap(Diags);
8714
8715 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8716 Trap.hasErrorOccurred()) {
8717 Diag(CurrentLocation, diag::note_member_synthesized_at)
8718 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8719 CopyConstructor->setInvalidDecl();
8720 } else {
8721 Sema::CompoundScopeRAII CompoundScope(*this);
8722 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8723 CopyConstructor->getLocation(),
8724 MultiStmtArg(),
8725 /*isStmtExpr=*/false)
8726 .takeAs<Stmt>());
8727 CopyConstructor->setImplicitlyDefined(true);
8728 }
8729
8730 CopyConstructor->setUsed();
8731 if (ASTMutationListener *L = getASTMutationListener()) {
8732 L->CompletedImplicitDefinition(CopyConstructor);
8733 }
8734 }
8735
8736 Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl * MD)8737 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8738 CXXRecordDecl *ClassDecl = MD->getParent();
8739
8740 // C++ [except.spec]p14:
8741 // An implicitly declared special member function (Clause 12) shall have an
8742 // exception-specification. [...]
8743 ImplicitExceptionSpecification ExceptSpec(*this);
8744 if (ClassDecl->isInvalidDecl())
8745 return ExceptSpec;
8746
8747 // Direct base-class constructors.
8748 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8749 BEnd = ClassDecl->bases_end();
8750 B != BEnd; ++B) {
8751 if (B->isVirtual()) // Handled below.
8752 continue;
8753
8754 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8755 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8756 CXXConstructorDecl *Constructor =
8757 LookupMovingConstructor(BaseClassDecl, 0);
8758 // If this is a deleted function, add it anyway. This might be conformant
8759 // with the standard. This might not. I'm not sure. It might not matter.
8760 if (Constructor)
8761 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8762 }
8763 }
8764
8765 // Virtual base-class constructors.
8766 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8767 BEnd = ClassDecl->vbases_end();
8768 B != BEnd; ++B) {
8769 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8770 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8771 CXXConstructorDecl *Constructor =
8772 LookupMovingConstructor(BaseClassDecl, 0);
8773 // If this is a deleted function, add it anyway. This might be conformant
8774 // with the standard. This might not. I'm not sure. It might not matter.
8775 if (Constructor)
8776 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8777 }
8778 }
8779
8780 // Field constructors.
8781 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8782 FEnd = ClassDecl->field_end();
8783 F != FEnd; ++F) {
8784 QualType FieldType = Context.getBaseElementType(F->getType());
8785 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8786 CXXConstructorDecl *Constructor =
8787 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
8788 // If this is a deleted function, add it anyway. This might be conformant
8789 // with the standard. This might not. I'm not sure. It might not matter.
8790 // In particular, the problem is that this function never gets called. It
8791 // might just be ill-formed because this function attempts to refer to
8792 // a deleted function here.
8793 if (Constructor)
8794 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8795 }
8796 }
8797
8798 return ExceptSpec;
8799 }
8800
DeclareImplicitMoveConstructor(CXXRecordDecl * ClassDecl)8801 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8802 CXXRecordDecl *ClassDecl) {
8803 // C++11 [class.copy]p9:
8804 // If the definition of a class X does not explicitly declare a move
8805 // constructor, one will be implicitly declared as defaulted if and only if:
8806 //
8807 // - [first 4 bullets]
8808 assert(ClassDecl->needsImplicitMoveConstructor());
8809
8810 // [Checked after we build the declaration]
8811 // - the move assignment operator would not be implicitly defined as
8812 // deleted,
8813
8814 // [DR1402]:
8815 // - each of X's non-static data members and direct or virtual base classes
8816 // has a type that either has a move constructor or is trivially copyable.
8817 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8818 ClassDecl->setFailedImplicitMoveConstructor();
8819 return 0;
8820 }
8821
8822 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8823 QualType ArgType = Context.getRValueReferenceType(ClassType);
8824
8825 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8826 CXXMoveConstructor,
8827 false);
8828
8829 DeclarationName Name
8830 = Context.DeclarationNames.getCXXConstructorName(
8831 Context.getCanonicalType(ClassType));
8832 SourceLocation ClassLoc = ClassDecl->getLocation();
8833 DeclarationNameInfo NameInfo(Name, ClassLoc);
8834
8835 // C++0x [class.copy]p11:
8836 // An implicitly-declared copy/move constructor is an inline public
8837 // member of its class.
8838 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8839 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8840 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8841 Constexpr);
8842 MoveConstructor->setAccess(AS_public);
8843 MoveConstructor->setDefaulted();
8844 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8845
8846 // Build an exception specification pointing back at this member.
8847 FunctionProtoType::ExtProtoInfo EPI;
8848 EPI.ExceptionSpecType = EST_Unevaluated;
8849 EPI.ExceptionSpecDecl = MoveConstructor;
8850 MoveConstructor->setType(
8851 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8852
8853 // Add the parameter to the constructor.
8854 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8855 ClassLoc, ClassLoc,
8856 /*IdentifierInfo=*/0,
8857 ArgType, /*TInfo=*/0,
8858 SC_None,
8859 SC_None, 0);
8860 MoveConstructor->setParams(FromParam);
8861
8862 // C++0x [class.copy]p9:
8863 // If the definition of a class X does not explicitly declare a move
8864 // constructor, one will be implicitly declared as defaulted if and only if:
8865 // [...]
8866 // - the move constructor would not be implicitly defined as deleted.
8867 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8868 // Cache this result so that we don't try to generate this over and over
8869 // on every lookup, leaking memory and wasting time.
8870 ClassDecl->setFailedImplicitMoveConstructor();
8871 return 0;
8872 }
8873
8874 // Note that we have declared this constructor.
8875 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8876
8877 if (Scope *S = getScopeForContext(ClassDecl))
8878 PushOnScopeChains(MoveConstructor, S, false);
8879 ClassDecl->addDecl(MoveConstructor);
8880
8881 return MoveConstructor;
8882 }
8883
DefineImplicitMoveConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * MoveConstructor)8884 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8885 CXXConstructorDecl *MoveConstructor) {
8886 assert((MoveConstructor->isDefaulted() &&
8887 MoveConstructor->isMoveConstructor() &&
8888 !MoveConstructor->doesThisDeclarationHaveABody() &&
8889 !MoveConstructor->isDeleted()) &&
8890 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8891
8892 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8893 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8894
8895 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8896 DiagnosticErrorTrap Trap(Diags);
8897
8898 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8899 Trap.hasErrorOccurred()) {
8900 Diag(CurrentLocation, diag::note_member_synthesized_at)
8901 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8902 MoveConstructor->setInvalidDecl();
8903 } else {
8904 Sema::CompoundScopeRAII CompoundScope(*this);
8905 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8906 MoveConstructor->getLocation(),
8907 MultiStmtArg(),
8908 /*isStmtExpr=*/false)
8909 .takeAs<Stmt>());
8910 MoveConstructor->setImplicitlyDefined(true);
8911 }
8912
8913 MoveConstructor->setUsed();
8914
8915 if (ASTMutationListener *L = getASTMutationListener()) {
8916 L->CompletedImplicitDefinition(MoveConstructor);
8917 }
8918 }
8919
isImplicitlyDeleted(FunctionDecl * FD)8920 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8921 return FD->isDeleted() &&
8922 (FD->isDefaulted() || FD->isImplicit()) &&
8923 isa<CXXMethodDecl>(FD);
8924 }
8925
8926 /// \brief Mark the call operator of the given lambda closure type as "used".
markLambdaCallOperatorUsed(Sema & S,CXXRecordDecl * Lambda)8927 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8928 CXXMethodDecl *CallOperator
8929 = cast<CXXMethodDecl>(
8930 *Lambda->lookup(
8931 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
8932 CallOperator->setReferenced();
8933 CallOperator->setUsed();
8934 }
8935
DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)8936 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8937 SourceLocation CurrentLocation,
8938 CXXConversionDecl *Conv)
8939 {
8940 CXXRecordDecl *Lambda = Conv->getParent();
8941
8942 // Make sure that the lambda call operator is marked used.
8943 markLambdaCallOperatorUsed(*this, Lambda);
8944
8945 Conv->setUsed();
8946
8947 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8948 DiagnosticErrorTrap Trap(Diags);
8949
8950 // Return the address of the __invoke function.
8951 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8952 CXXMethodDecl *Invoke
8953 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8954 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8955 VK_LValue, Conv->getLocation()).take();
8956 assert(FunctionRef && "Can't refer to __invoke function?");
8957 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8958 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8959 Conv->getLocation(),
8960 Conv->getLocation()));
8961
8962 // Fill in the __invoke function with a dummy implementation. IR generation
8963 // will fill in the actual details.
8964 Invoke->setUsed();
8965 Invoke->setReferenced();
8966 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
8967
8968 if (ASTMutationListener *L = getASTMutationListener()) {
8969 L->CompletedImplicitDefinition(Conv);
8970 L->CompletedImplicitDefinition(Invoke);
8971 }
8972 }
8973
DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)8974 void Sema::DefineImplicitLambdaToBlockPointerConversion(
8975 SourceLocation CurrentLocation,
8976 CXXConversionDecl *Conv)
8977 {
8978 Conv->setUsed();
8979
8980 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8981 DiagnosticErrorTrap Trap(Diags);
8982
8983 // Copy-initialize the lambda object as needed to capture it.
8984 Expr *This = ActOnCXXThis(CurrentLocation).take();
8985 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
8986
8987 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8988 Conv->getLocation(),
8989 Conv, DerefThis);
8990
8991 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8992 // behavior. Note that only the general conversion function does this
8993 // (since it's unusable otherwise); in the case where we inline the
8994 // block literal, it has block literal lifetime semantics.
8995 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
8996 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8997 CK_CopyAndAutoreleaseBlockObject,
8998 BuildBlock.get(), 0, VK_RValue);
8999
9000 if (BuildBlock.isInvalid()) {
9001 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9002 Conv->setInvalidDecl();
9003 return;
9004 }
9005
9006 // Create the return statement that returns the block from the conversion
9007 // function.
9008 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9009 if (Return.isInvalid()) {
9010 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9011 Conv->setInvalidDecl();
9012 return;
9013 }
9014
9015 // Set the body of the conversion function.
9016 Stmt *ReturnS = Return.take();
9017 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9018 Conv->getLocation(),
9019 Conv->getLocation()));
9020
9021 // We're done; notify the mutation listener, if any.
9022 if (ASTMutationListener *L = getASTMutationListener()) {
9023 L->CompletedImplicitDefinition(Conv);
9024 }
9025 }
9026
9027 /// \brief Determine whether the given list arguments contains exactly one
9028 /// "real" (non-default) argument.
hasOneRealArgument(MultiExprArg Args)9029 static bool hasOneRealArgument(MultiExprArg Args) {
9030 switch (Args.size()) {
9031 case 0:
9032 return false;
9033
9034 default:
9035 if (!Args[1]->isDefaultArgument())
9036 return false;
9037
9038 // fall through
9039 case 1:
9040 return !Args[0]->isDefaultArgument();
9041 }
9042
9043 return false;
9044 }
9045
9046 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)9047 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9048 CXXConstructorDecl *Constructor,
9049 MultiExprArg ExprArgs,
9050 bool HadMultipleCandidates,
9051 bool RequiresZeroInit,
9052 unsigned ConstructKind,
9053 SourceRange ParenRange) {
9054 bool Elidable = false;
9055
9056 // C++0x [class.copy]p34:
9057 // When certain criteria are met, an implementation is allowed to
9058 // omit the copy/move construction of a class object, even if the
9059 // copy/move constructor and/or destructor for the object have
9060 // side effects. [...]
9061 // - when a temporary class object that has not been bound to a
9062 // reference (12.2) would be copied/moved to a class object
9063 // with the same cv-unqualified type, the copy/move operation
9064 // can be omitted by constructing the temporary object
9065 // directly into the target of the omitted copy/move
9066 if (ConstructKind == CXXConstructExpr::CK_Complete &&
9067 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9068 Expr *SubExpr = ExprArgs[0];
9069 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9070 }
9071
9072 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9073 Elidable, ExprArgs, HadMultipleCandidates,
9074 RequiresZeroInit, ConstructKind, ParenRange);
9075 }
9076
9077 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
9078 /// including handling of its default argument expressions.
9079 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)9080 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9081 CXXConstructorDecl *Constructor, bool Elidable,
9082 MultiExprArg ExprArgs,
9083 bool HadMultipleCandidates,
9084 bool RequiresZeroInit,
9085 unsigned ConstructKind,
9086 SourceRange ParenRange) {
9087 MarkFunctionReferenced(ConstructLoc, Constructor);
9088 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9089 Constructor, Elidable, ExprArgs,
9090 HadMultipleCandidates, /*FIXME*/false,
9091 RequiresZeroInit,
9092 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9093 ParenRange));
9094 }
9095
InitializeVarWithConstructor(VarDecl * VD,CXXConstructorDecl * Constructor,MultiExprArg Exprs,bool HadMultipleCandidates)9096 bool Sema::InitializeVarWithConstructor(VarDecl *VD,
9097 CXXConstructorDecl *Constructor,
9098 MultiExprArg Exprs,
9099 bool HadMultipleCandidates) {
9100 // FIXME: Provide the correct paren SourceRange when available.
9101 ExprResult TempResult =
9102 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
9103 Exprs, HadMultipleCandidates, false,
9104 CXXConstructExpr::CK_Complete, SourceRange());
9105 if (TempResult.isInvalid())
9106 return true;
9107
9108 Expr *Temp = TempResult.takeAs<Expr>();
9109 CheckImplicitConversions(Temp, VD->getLocation());
9110 MarkFunctionReferenced(VD->getLocation(), Constructor);
9111 Temp = MaybeCreateExprWithCleanups(Temp);
9112 VD->setInit(Temp);
9113
9114 return false;
9115 }
9116
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)9117 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9118 if (VD->isInvalidDecl()) return;
9119
9120 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9121 if (ClassDecl->isInvalidDecl()) return;
9122 if (ClassDecl->hasIrrelevantDestructor()) return;
9123 if (ClassDecl->isDependentContext()) return;
9124
9125 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9126 MarkFunctionReferenced(VD->getLocation(), Destructor);
9127 CheckDestructorAccess(VD->getLocation(), Destructor,
9128 PDiag(diag::err_access_dtor_var)
9129 << VD->getDeclName()
9130 << VD->getType());
9131 DiagnoseUseOfDecl(Destructor, VD->getLocation());
9132
9133 if (!VD->hasGlobalStorage()) return;
9134
9135 // Emit warning for non-trivial dtor in global scope (a real global,
9136 // class-static, function-static).
9137 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9138
9139 // TODO: this should be re-enabled for static locals by !CXAAtExit
9140 if (!VD->isStaticLocal())
9141 Diag(VD->getLocation(), diag::warn_global_destructor);
9142 }
9143
9144 /// \brief Given a constructor and the set of arguments provided for the
9145 /// constructor, convert the arguments and add any required default arguments
9146 /// to form a proper call to this constructor.
9147 ///
9148 /// \returns true if an error occurred, false otherwise.
9149 bool
CompleteConstructorCall(CXXConstructorDecl * Constructor,MultiExprArg ArgsPtr,SourceLocation Loc,SmallVectorImpl<Expr * > & ConvertedArgs,bool AllowExplicit)9150 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9151 MultiExprArg ArgsPtr,
9152 SourceLocation Loc,
9153 SmallVectorImpl<Expr*> &ConvertedArgs,
9154 bool AllowExplicit) {
9155 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9156 unsigned NumArgs = ArgsPtr.size();
9157 Expr **Args = ArgsPtr.data();
9158
9159 const FunctionProtoType *Proto
9160 = Constructor->getType()->getAs<FunctionProtoType>();
9161 assert(Proto && "Constructor without a prototype?");
9162 unsigned NumArgsInProto = Proto->getNumArgs();
9163
9164 // If too few arguments are available, we'll fill in the rest with defaults.
9165 if (NumArgs < NumArgsInProto)
9166 ConvertedArgs.reserve(NumArgsInProto);
9167 else
9168 ConvertedArgs.reserve(NumArgs);
9169
9170 VariadicCallType CallType =
9171 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9172 SmallVector<Expr *, 8> AllArgs;
9173 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9174 Proto, 0, Args, NumArgs, AllArgs,
9175 CallType, AllowExplicit);
9176 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9177
9178 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9179
9180 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9181 Proto, Loc);
9182
9183 return Invalid;
9184 }
9185
9186 static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)9187 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9188 const FunctionDecl *FnDecl) {
9189 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9190 if (isa<NamespaceDecl>(DC)) {
9191 return SemaRef.Diag(FnDecl->getLocation(),
9192 diag::err_operator_new_delete_declared_in_namespace)
9193 << FnDecl->getDeclName();
9194 }
9195
9196 if (isa<TranslationUnitDecl>(DC) &&
9197 FnDecl->getStorageClass() == SC_Static) {
9198 return SemaRef.Diag(FnDecl->getLocation(),
9199 diag::err_operator_new_delete_declared_static)
9200 << FnDecl->getDeclName();
9201 }
9202
9203 return false;
9204 }
9205
9206 static inline bool
CheckOperatorNewDeleteTypes(Sema & SemaRef,const FunctionDecl * FnDecl,CanQualType ExpectedResultType,CanQualType ExpectedFirstParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)9207 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9208 CanQualType ExpectedResultType,
9209 CanQualType ExpectedFirstParamType,
9210 unsigned DependentParamTypeDiag,
9211 unsigned InvalidParamTypeDiag) {
9212 QualType ResultType =
9213 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9214
9215 // Check that the result type is not dependent.
9216 if (ResultType->isDependentType())
9217 return SemaRef.Diag(FnDecl->getLocation(),
9218 diag::err_operator_new_delete_dependent_result_type)
9219 << FnDecl->getDeclName() << ExpectedResultType;
9220
9221 // Check that the result type is what we expect.
9222 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9223 return SemaRef.Diag(FnDecl->getLocation(),
9224 diag::err_operator_new_delete_invalid_result_type)
9225 << FnDecl->getDeclName() << ExpectedResultType;
9226
9227 // A function template must have at least 2 parameters.
9228 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9229 return SemaRef.Diag(FnDecl->getLocation(),
9230 diag::err_operator_new_delete_template_too_few_parameters)
9231 << FnDecl->getDeclName();
9232
9233 // The function decl must have at least 1 parameter.
9234 if (FnDecl->getNumParams() == 0)
9235 return SemaRef.Diag(FnDecl->getLocation(),
9236 diag::err_operator_new_delete_too_few_parameters)
9237 << FnDecl->getDeclName();
9238
9239 // Check the first parameter type is not dependent.
9240 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9241 if (FirstParamType->isDependentType())
9242 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9243 << FnDecl->getDeclName() << ExpectedFirstParamType;
9244
9245 // Check that the first parameter type is what we expect.
9246 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9247 ExpectedFirstParamType)
9248 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9249 << FnDecl->getDeclName() << ExpectedFirstParamType;
9250
9251 return false;
9252 }
9253
9254 static bool
CheckOperatorNewDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)9255 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9256 // C++ [basic.stc.dynamic.allocation]p1:
9257 // A program is ill-formed if an allocation function is declared in a
9258 // namespace scope other than global scope or declared static in global
9259 // scope.
9260 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9261 return true;
9262
9263 CanQualType SizeTy =
9264 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9265
9266 // C++ [basic.stc.dynamic.allocation]p1:
9267 // The return type shall be void*. The first parameter shall have type
9268 // std::size_t.
9269 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9270 SizeTy,
9271 diag::err_operator_new_dependent_param_type,
9272 diag::err_operator_new_param_type))
9273 return true;
9274
9275 // C++ [basic.stc.dynamic.allocation]p1:
9276 // The first parameter shall not have an associated default argument.
9277 if (FnDecl->getParamDecl(0)->hasDefaultArg())
9278 return SemaRef.Diag(FnDecl->getLocation(),
9279 diag::err_operator_new_default_arg)
9280 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9281
9282 return false;
9283 }
9284
9285 static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)9286 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9287 // C++ [basic.stc.dynamic.deallocation]p1:
9288 // A program is ill-formed if deallocation functions are declared in a
9289 // namespace scope other than global scope or declared static in global
9290 // scope.
9291 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9292 return true;
9293
9294 // C++ [basic.stc.dynamic.deallocation]p2:
9295 // Each deallocation function shall return void and its first parameter
9296 // shall be void*.
9297 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9298 SemaRef.Context.VoidPtrTy,
9299 diag::err_operator_delete_dependent_param_type,
9300 diag::err_operator_delete_param_type))
9301 return true;
9302
9303 return false;
9304 }
9305
9306 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
9307 /// of this overloaded operator is well-formed. If so, returns false;
9308 /// otherwise, emits appropriate diagnostics and returns true.
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)9309 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9310 assert(FnDecl && FnDecl->isOverloadedOperator() &&
9311 "Expected an overloaded operator declaration");
9312
9313 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9314
9315 // C++ [over.oper]p5:
9316 // The allocation and deallocation functions, operator new,
9317 // operator new[], operator delete and operator delete[], are
9318 // described completely in 3.7.3. The attributes and restrictions
9319 // found in the rest of this subclause do not apply to them unless
9320 // explicitly stated in 3.7.3.
9321 if (Op == OO_Delete || Op == OO_Array_Delete)
9322 return CheckOperatorDeleteDeclaration(*this, FnDecl);
9323
9324 if (Op == OO_New || Op == OO_Array_New)
9325 return CheckOperatorNewDeclaration(*this, FnDecl);
9326
9327 // C++ [over.oper]p6:
9328 // An operator function shall either be a non-static member
9329 // function or be a non-member function and have at least one
9330 // parameter whose type is a class, a reference to a class, an
9331 // enumeration, or a reference to an enumeration.
9332 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9333 if (MethodDecl->isStatic())
9334 return Diag(FnDecl->getLocation(),
9335 diag::err_operator_overload_static) << FnDecl->getDeclName();
9336 } else {
9337 bool ClassOrEnumParam = false;
9338 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9339 ParamEnd = FnDecl->param_end();
9340 Param != ParamEnd; ++Param) {
9341 QualType ParamType = (*Param)->getType().getNonReferenceType();
9342 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9343 ParamType->isEnumeralType()) {
9344 ClassOrEnumParam = true;
9345 break;
9346 }
9347 }
9348
9349 if (!ClassOrEnumParam)
9350 return Diag(FnDecl->getLocation(),
9351 diag::err_operator_overload_needs_class_or_enum)
9352 << FnDecl->getDeclName();
9353 }
9354
9355 // C++ [over.oper]p8:
9356 // An operator function cannot have default arguments (8.3.6),
9357 // except where explicitly stated below.
9358 //
9359 // Only the function-call operator allows default arguments
9360 // (C++ [over.call]p1).
9361 if (Op != OO_Call) {
9362 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9363 Param != FnDecl->param_end(); ++Param) {
9364 if ((*Param)->hasDefaultArg())
9365 return Diag((*Param)->getLocation(),
9366 diag::err_operator_overload_default_arg)
9367 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9368 }
9369 }
9370
9371 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9372 { false, false, false }
9373 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9374 , { Unary, Binary, MemberOnly }
9375 #include "clang/Basic/OperatorKinds.def"
9376 };
9377
9378 bool CanBeUnaryOperator = OperatorUses[Op][0];
9379 bool CanBeBinaryOperator = OperatorUses[Op][1];
9380 bool MustBeMemberOperator = OperatorUses[Op][2];
9381
9382 // C++ [over.oper]p8:
9383 // [...] Operator functions cannot have more or fewer parameters
9384 // than the number required for the corresponding operator, as
9385 // described in the rest of this subclause.
9386 unsigned NumParams = FnDecl->getNumParams()
9387 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9388 if (Op != OO_Call &&
9389 ((NumParams == 1 && !CanBeUnaryOperator) ||
9390 (NumParams == 2 && !CanBeBinaryOperator) ||
9391 (NumParams < 1) || (NumParams > 2))) {
9392 // We have the wrong number of parameters.
9393 unsigned ErrorKind;
9394 if (CanBeUnaryOperator && CanBeBinaryOperator) {
9395 ErrorKind = 2; // 2 -> unary or binary.
9396 } else if (CanBeUnaryOperator) {
9397 ErrorKind = 0; // 0 -> unary
9398 } else {
9399 assert(CanBeBinaryOperator &&
9400 "All non-call overloaded operators are unary or binary!");
9401 ErrorKind = 1; // 1 -> binary
9402 }
9403
9404 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9405 << FnDecl->getDeclName() << NumParams << ErrorKind;
9406 }
9407
9408 // Overloaded operators other than operator() cannot be variadic.
9409 if (Op != OO_Call &&
9410 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9411 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9412 << FnDecl->getDeclName();
9413 }
9414
9415 // Some operators must be non-static member functions.
9416 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9417 return Diag(FnDecl->getLocation(),
9418 diag::err_operator_overload_must_be_member)
9419 << FnDecl->getDeclName();
9420 }
9421
9422 // C++ [over.inc]p1:
9423 // The user-defined function called operator++ implements the
9424 // prefix and postfix ++ operator. If this function is a member
9425 // function with no parameters, or a non-member function with one
9426 // parameter of class or enumeration type, it defines the prefix
9427 // increment operator ++ for objects of that type. If the function
9428 // is a member function with one parameter (which shall be of type
9429 // int) or a non-member function with two parameters (the second
9430 // of which shall be of type int), it defines the postfix
9431 // increment operator ++ for objects of that type.
9432 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9433 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9434 bool ParamIsInt = false;
9435 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9436 ParamIsInt = BT->getKind() == BuiltinType::Int;
9437
9438 if (!ParamIsInt)
9439 return Diag(LastParam->getLocation(),
9440 diag::err_operator_overload_post_incdec_must_be_int)
9441 << LastParam->getType() << (Op == OO_MinusMinus);
9442 }
9443
9444 return false;
9445 }
9446
9447 /// CheckLiteralOperatorDeclaration - Check whether the declaration
9448 /// of this literal operator function is well-formed. If so, returns
9449 /// false; otherwise, emits appropriate diagnostics and returns true.
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)9450 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9451 if (isa<CXXMethodDecl>(FnDecl)) {
9452 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9453 << FnDecl->getDeclName();
9454 return true;
9455 }
9456
9457 if (FnDecl->isExternC()) {
9458 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9459 return true;
9460 }
9461
9462 bool Valid = false;
9463
9464 // This might be the definition of a literal operator template.
9465 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9466 // This might be a specialization of a literal operator template.
9467 if (!TpDecl)
9468 TpDecl = FnDecl->getPrimaryTemplate();
9469
9470 // template <char...> type operator "" name() is the only valid template
9471 // signature, and the only valid signature with no parameters.
9472 if (TpDecl) {
9473 if (FnDecl->param_size() == 0) {
9474 // Must have only one template parameter
9475 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9476 if (Params->size() == 1) {
9477 NonTypeTemplateParmDecl *PmDecl =
9478 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9479
9480 // The template parameter must be a char parameter pack.
9481 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9482 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9483 Valid = true;
9484 }
9485 }
9486 } else if (FnDecl->param_size()) {
9487 // Check the first parameter
9488 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9489
9490 QualType T = (*Param)->getType().getUnqualifiedType();
9491
9492 // unsigned long long int, long double, and any character type are allowed
9493 // as the only parameters.
9494 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9495 Context.hasSameType(T, Context.LongDoubleTy) ||
9496 Context.hasSameType(T, Context.CharTy) ||
9497 Context.hasSameType(T, Context.WCharTy) ||
9498 Context.hasSameType(T, Context.Char16Ty) ||
9499 Context.hasSameType(T, Context.Char32Ty)) {
9500 if (++Param == FnDecl->param_end())
9501 Valid = true;
9502 goto FinishedParams;
9503 }
9504
9505 // Otherwise it must be a pointer to const; let's strip those qualifiers.
9506 const PointerType *PT = T->getAs<PointerType>();
9507 if (!PT)
9508 goto FinishedParams;
9509 T = PT->getPointeeType();
9510 if (!T.isConstQualified() || T.isVolatileQualified())
9511 goto FinishedParams;
9512 T = T.getUnqualifiedType();
9513
9514 // Move on to the second parameter;
9515 ++Param;
9516
9517 // If there is no second parameter, the first must be a const char *
9518 if (Param == FnDecl->param_end()) {
9519 if (Context.hasSameType(T, Context.CharTy))
9520 Valid = true;
9521 goto FinishedParams;
9522 }
9523
9524 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9525 // are allowed as the first parameter to a two-parameter function
9526 if (!(Context.hasSameType(T, Context.CharTy) ||
9527 Context.hasSameType(T, Context.WCharTy) ||
9528 Context.hasSameType(T, Context.Char16Ty) ||
9529 Context.hasSameType(T, Context.Char32Ty)))
9530 goto FinishedParams;
9531
9532 // The second and final parameter must be an std::size_t
9533 T = (*Param)->getType().getUnqualifiedType();
9534 if (Context.hasSameType(T, Context.getSizeType()) &&
9535 ++Param == FnDecl->param_end())
9536 Valid = true;
9537 }
9538
9539 // FIXME: This diagnostic is absolutely terrible.
9540 FinishedParams:
9541 if (!Valid) {
9542 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9543 << FnDecl->getDeclName();
9544 return true;
9545 }
9546
9547 // A parameter-declaration-clause containing a default argument is not
9548 // equivalent to any of the permitted forms.
9549 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9550 ParamEnd = FnDecl->param_end();
9551 Param != ParamEnd; ++Param) {
9552 if ((*Param)->hasDefaultArg()) {
9553 Diag((*Param)->getDefaultArgRange().getBegin(),
9554 diag::err_literal_operator_default_argument)
9555 << (*Param)->getDefaultArgRange();
9556 break;
9557 }
9558 }
9559
9560 StringRef LiteralName
9561 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9562 if (LiteralName[0] != '_') {
9563 // C++11 [usrlit.suffix]p1:
9564 // Literal suffix identifiers that do not start with an underscore
9565 // are reserved for future standardization.
9566 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9567 }
9568
9569 return false;
9570 }
9571
9572 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9573 /// linkage specification, including the language and (if present)
9574 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9575 /// the location of the language string literal, which is provided
9576 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9577 /// the '{' brace. Otherwise, this linkage specification does not
9578 /// have any braces.
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,SourceLocation LangLoc,StringRef Lang,SourceLocation LBraceLoc)9579 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9580 SourceLocation LangLoc,
9581 StringRef Lang,
9582 SourceLocation LBraceLoc) {
9583 LinkageSpecDecl::LanguageIDs Language;
9584 if (Lang == "\"C\"")
9585 Language = LinkageSpecDecl::lang_c;
9586 else if (Lang == "\"C++\"")
9587 Language = LinkageSpecDecl::lang_cxx;
9588 else {
9589 Diag(LangLoc, diag::err_bad_language);
9590 return 0;
9591 }
9592
9593 // FIXME: Add all the various semantics of linkage specifications
9594
9595 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9596 ExternLoc, LangLoc, Language);
9597 CurContext->addDecl(D);
9598 PushDeclContext(S, D);
9599 return D;
9600 }
9601
9602 /// ActOnFinishLinkageSpecification - Complete the definition of
9603 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
9604 /// valid, it's the position of the closing '}' brace in a linkage
9605 /// specification that uses braces.
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)9606 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9607 Decl *LinkageSpec,
9608 SourceLocation RBraceLoc) {
9609 if (LinkageSpec) {
9610 if (RBraceLoc.isValid()) {
9611 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9612 LSDecl->setRBraceLoc(RBraceLoc);
9613 }
9614 PopDeclContext();
9615 }
9616 return LinkageSpec;
9617 }
9618
9619 /// \brief Perform semantic analysis for the variable declaration that
9620 /// occurs within a C++ catch clause, returning the newly-created
9621 /// variable.
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,IdentifierInfo * Name)9622 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9623 TypeSourceInfo *TInfo,
9624 SourceLocation StartLoc,
9625 SourceLocation Loc,
9626 IdentifierInfo *Name) {
9627 bool Invalid = false;
9628 QualType ExDeclType = TInfo->getType();
9629
9630 // Arrays and functions decay.
9631 if (ExDeclType->isArrayType())
9632 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9633 else if (ExDeclType->isFunctionType())
9634 ExDeclType = Context.getPointerType(ExDeclType);
9635
9636 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9637 // The exception-declaration shall not denote a pointer or reference to an
9638 // incomplete type, other than [cv] void*.
9639 // N2844 forbids rvalue references.
9640 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9641 Diag(Loc, diag::err_catch_rvalue_ref);
9642 Invalid = true;
9643 }
9644
9645 QualType BaseType = ExDeclType;
9646 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9647 unsigned DK = diag::err_catch_incomplete;
9648 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9649 BaseType = Ptr->getPointeeType();
9650 Mode = 1;
9651 DK = diag::err_catch_incomplete_ptr;
9652 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9653 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9654 BaseType = Ref->getPointeeType();
9655 Mode = 2;
9656 DK = diag::err_catch_incomplete_ref;
9657 }
9658 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9659 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9660 Invalid = true;
9661
9662 if (!Invalid && !ExDeclType->isDependentType() &&
9663 RequireNonAbstractType(Loc, ExDeclType,
9664 diag::err_abstract_type_in_decl,
9665 AbstractVariableType))
9666 Invalid = true;
9667
9668 // Only the non-fragile NeXT runtime currently supports C++ catches
9669 // of ObjC types, and no runtime supports catching ObjC types by value.
9670 if (!Invalid && getLangOpts().ObjC1) {
9671 QualType T = ExDeclType;
9672 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9673 T = RT->getPointeeType();
9674
9675 if (T->isObjCObjectType()) {
9676 Diag(Loc, diag::err_objc_object_catch);
9677 Invalid = true;
9678 } else if (T->isObjCObjectPointerType()) {
9679 // FIXME: should this be a test for macosx-fragile specifically?
9680 if (getLangOpts().ObjCRuntime.isFragile())
9681 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9682 }
9683 }
9684
9685 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9686 ExDeclType, TInfo, SC_None, SC_None);
9687 ExDecl->setExceptionVariable(true);
9688
9689 // In ARC, infer 'retaining' for variables of retainable type.
9690 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9691 Invalid = true;
9692
9693 if (!Invalid && !ExDeclType->isDependentType()) {
9694 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9695 // C++ [except.handle]p16:
9696 // The object declared in an exception-declaration or, if the
9697 // exception-declaration does not specify a name, a temporary (12.2) is
9698 // copy-initialized (8.5) from the exception object. [...]
9699 // The object is destroyed when the handler exits, after the destruction
9700 // of any automatic objects initialized within the handler.
9701 //
9702 // We just pretend to initialize the object with itself, then make sure
9703 // it can be destroyed later.
9704 QualType initType = ExDeclType;
9705
9706 InitializedEntity entity =
9707 InitializedEntity::InitializeVariable(ExDecl);
9708 InitializationKind initKind =
9709 InitializationKind::CreateCopy(Loc, SourceLocation());
9710
9711 Expr *opaqueValue =
9712 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9713 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9714 ExprResult result = sequence.Perform(*this, entity, initKind,
9715 MultiExprArg(&opaqueValue, 1));
9716 if (result.isInvalid())
9717 Invalid = true;
9718 else {
9719 // If the constructor used was non-trivial, set this as the
9720 // "initializer".
9721 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9722 if (!construct->getConstructor()->isTrivial()) {
9723 Expr *init = MaybeCreateExprWithCleanups(construct);
9724 ExDecl->setInit(init);
9725 }
9726
9727 // And make sure it's destructable.
9728 FinalizeVarWithDestructor(ExDecl, recordType);
9729 }
9730 }
9731 }
9732
9733 if (Invalid)
9734 ExDecl->setInvalidDecl();
9735
9736 return ExDecl;
9737 }
9738
9739 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9740 /// handler.
ActOnExceptionDeclarator(Scope * S,Declarator & D)9741 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9743 bool Invalid = D.isInvalidType();
9744
9745 // Check for unexpanded parameter packs.
9746 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9747 UPPC_ExceptionType)) {
9748 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9749 D.getIdentifierLoc());
9750 Invalid = true;
9751 }
9752
9753 IdentifierInfo *II = D.getIdentifier();
9754 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9755 LookupOrdinaryName,
9756 ForRedeclaration)) {
9757 // The scope should be freshly made just for us. There is just no way
9758 // it contains any previous declaration.
9759 assert(!S->isDeclScope(PrevDecl));
9760 if (PrevDecl->isTemplateParameter()) {
9761 // Maybe we will complain about the shadowed template parameter.
9762 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9763 PrevDecl = 0;
9764 }
9765 }
9766
9767 if (D.getCXXScopeSpec().isSet() && !Invalid) {
9768 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9769 << D.getCXXScopeSpec().getRange();
9770 Invalid = true;
9771 }
9772
9773 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9774 D.getLocStart(),
9775 D.getIdentifierLoc(),
9776 D.getIdentifier());
9777 if (Invalid)
9778 ExDecl->setInvalidDecl();
9779
9780 // Add the exception declaration into this scope.
9781 if (II)
9782 PushOnScopeChains(ExDecl, S);
9783 else
9784 CurContext->addDecl(ExDecl);
9785
9786 ProcessDeclAttributes(S, ExDecl, D);
9787 return ExDecl;
9788 }
9789
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr,SourceLocation RParenLoc)9790 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9791 Expr *AssertExpr,
9792 Expr *AssertMessageExpr,
9793 SourceLocation RParenLoc) {
9794 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
9795
9796 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9797 return 0;
9798
9799 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9800 AssertMessage, RParenLoc, false);
9801 }
9802
BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,StringLiteral * AssertMessage,SourceLocation RParenLoc,bool Failed)9803 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9804 Expr *AssertExpr,
9805 StringLiteral *AssertMessage,
9806 SourceLocation RParenLoc,
9807 bool Failed) {
9808 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9809 !Failed) {
9810 // In a static_assert-declaration, the constant-expression shall be a
9811 // constant expression that can be contextually converted to bool.
9812 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9813 if (Converted.isInvalid())
9814 Failed = true;
9815
9816 llvm::APSInt Cond;
9817 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
9818 diag::err_static_assert_expression_is_not_constant,
9819 /*AllowFold=*/false).isInvalid())
9820 Failed = true;
9821
9822 if (!Failed && !Cond) {
9823 llvm::SmallString<256> MsgBuffer;
9824 llvm::raw_svector_ostream Msg(MsgBuffer);
9825 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
9826 Diag(StaticAssertLoc, diag::err_static_assert_failed)
9827 << Msg.str() << AssertExpr->getSourceRange();
9828 Failed = true;
9829 }
9830 }
9831
9832 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9833 AssertExpr, AssertMessage, RParenLoc,
9834 Failed);
9835
9836 CurContext->addDecl(Decl);
9837 return Decl;
9838 }
9839
9840 /// \brief Perform semantic analysis of the given friend type declaration.
9841 ///
9842 /// \returns A friend declaration that.
CheckFriendTypeDecl(SourceLocation Loc,SourceLocation FriendLoc,TypeSourceInfo * TSInfo)9843 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9844 SourceLocation FriendLoc,
9845 TypeSourceInfo *TSInfo) {
9846 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9847
9848 QualType T = TSInfo->getType();
9849 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9850
9851 // C++03 [class.friend]p2:
9852 // An elaborated-type-specifier shall be used in a friend declaration
9853 // for a class.*
9854 //
9855 // * The class-key of the elaborated-type-specifier is required.
9856 if (!ActiveTemplateInstantiations.empty()) {
9857 // Do not complain about the form of friend template types during
9858 // template instantiation; we will already have complained when the
9859 // template was declared.
9860 } else if (!T->isElaboratedTypeSpecifier()) {
9861 // If we evaluated the type to a record type, suggest putting
9862 // a tag in front.
9863 if (const RecordType *RT = T->getAs<RecordType>()) {
9864 RecordDecl *RD = RT->getDecl();
9865
9866 std::string InsertionText = std::string(" ") + RD->getKindName();
9867
9868 Diag(TypeRange.getBegin(),
9869 getLangOpts().CPlusPlus0x ?
9870 diag::warn_cxx98_compat_unelaborated_friend_type :
9871 diag::ext_unelaborated_friend_type)
9872 << (unsigned) RD->getTagKind()
9873 << T
9874 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9875 InsertionText);
9876 } else {
9877 Diag(FriendLoc,
9878 getLangOpts().CPlusPlus0x ?
9879 diag::warn_cxx98_compat_nonclass_type_friend :
9880 diag::ext_nonclass_type_friend)
9881 << T
9882 << SourceRange(FriendLoc, TypeRange.getEnd());
9883 }
9884 } else if (T->getAs<EnumType>()) {
9885 Diag(FriendLoc,
9886 getLangOpts().CPlusPlus0x ?
9887 diag::warn_cxx98_compat_enum_friend :
9888 diag::ext_enum_friend)
9889 << T
9890 << SourceRange(FriendLoc, TypeRange.getEnd());
9891 }
9892
9893 // C++0x [class.friend]p3:
9894 // If the type specifier in a friend declaration designates a (possibly
9895 // cv-qualified) class type, that class is declared as a friend; otherwise,
9896 // the friend declaration is ignored.
9897
9898 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9899 // in [class.friend]p3 that we do not implement.
9900
9901 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
9902 }
9903
9904 /// Handle a friend tag declaration where the scope specifier was
9905 /// templated.
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,MultiTemplateParamsArg TempParamLists)9906 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9907 unsigned TagSpec, SourceLocation TagLoc,
9908 CXXScopeSpec &SS,
9909 IdentifierInfo *Name, SourceLocation NameLoc,
9910 AttributeList *Attr,
9911 MultiTemplateParamsArg TempParamLists) {
9912 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9913
9914 bool isExplicitSpecialization = false;
9915 bool Invalid = false;
9916
9917 if (TemplateParameterList *TemplateParams
9918 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9919 TempParamLists.data(),
9920 TempParamLists.size(),
9921 /*friend*/ true,
9922 isExplicitSpecialization,
9923 Invalid)) {
9924 if (TemplateParams->size() > 0) {
9925 // This is a declaration of a class template.
9926 if (Invalid)
9927 return 0;
9928
9929 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9930 SS, Name, NameLoc, Attr,
9931 TemplateParams, AS_public,
9932 /*ModulePrivateLoc=*/SourceLocation(),
9933 TempParamLists.size() - 1,
9934 TempParamLists.data()).take();
9935 } else {
9936 // The "template<>" header is extraneous.
9937 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9938 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9939 isExplicitSpecialization = true;
9940 }
9941 }
9942
9943 if (Invalid) return 0;
9944
9945 bool isAllExplicitSpecializations = true;
9946 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9947 if (TempParamLists[I]->size()) {
9948 isAllExplicitSpecializations = false;
9949 break;
9950 }
9951 }
9952
9953 // FIXME: don't ignore attributes.
9954
9955 // If it's explicit specializations all the way down, just forget
9956 // about the template header and build an appropriate non-templated
9957 // friend. TODO: for source fidelity, remember the headers.
9958 if (isAllExplicitSpecializations) {
9959 if (SS.isEmpty()) {
9960 bool Owned = false;
9961 bool IsDependent = false;
9962 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9963 Attr, AS_public,
9964 /*ModulePrivateLoc=*/SourceLocation(),
9965 MultiTemplateParamsArg(), Owned, IsDependent,
9966 /*ScopedEnumKWLoc=*/SourceLocation(),
9967 /*ScopedEnumUsesClassTag=*/false,
9968 /*UnderlyingType=*/TypeResult());
9969 }
9970
9971 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9972 ElaboratedTypeKeyword Keyword
9973 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9974 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9975 *Name, NameLoc);
9976 if (T.isNull())
9977 return 0;
9978
9979 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9980 if (isa<DependentNameType>(T)) {
9981 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9982 TL.setElaboratedKeywordLoc(TagLoc);
9983 TL.setQualifierLoc(QualifierLoc);
9984 TL.setNameLoc(NameLoc);
9985 } else {
9986 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9987 TL.setElaboratedKeywordLoc(TagLoc);
9988 TL.setQualifierLoc(QualifierLoc);
9989 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9990 }
9991
9992 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9993 TSI, FriendLoc);
9994 Friend->setAccess(AS_public);
9995 CurContext->addDecl(Friend);
9996 return Friend;
9997 }
9998
9999 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10000
10001
10002
10003 // Handle the case of a templated-scope friend class. e.g.
10004 // template <class T> class A<T>::B;
10005 // FIXME: we don't support these right now.
10006 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10007 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10008 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10009 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10010 TL.setElaboratedKeywordLoc(TagLoc);
10011 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10012 TL.setNameLoc(NameLoc);
10013
10014 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10015 TSI, FriendLoc);
10016 Friend->setAccess(AS_public);
10017 Friend->setUnsupportedFriend(true);
10018 CurContext->addDecl(Friend);
10019 return Friend;
10020 }
10021
10022
10023 /// Handle a friend type declaration. This works in tandem with
10024 /// ActOnTag.
10025 ///
10026 /// Notes on friend class templates:
10027 ///
10028 /// We generally treat friend class declarations as if they were
10029 /// declaring a class. So, for example, the elaborated type specifier
10030 /// in a friend declaration is required to obey the restrictions of a
10031 /// class-head (i.e. no typedefs in the scope chain), template
10032 /// parameters are required to match up with simple template-ids, &c.
10033 /// However, unlike when declaring a template specialization, it's
10034 /// okay to refer to a template specialization without an empty
10035 /// template parameter declaration, e.g.
10036 /// friend class A<T>::B<unsigned>;
10037 /// We permit this as a special case; if there are any template
10038 /// parameters present at all, require proper matching, i.e.
10039 /// template <> template \<class T> friend class A<int>::B;
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams)10040 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10041 MultiTemplateParamsArg TempParams) {
10042 SourceLocation Loc = DS.getLocStart();
10043
10044 assert(DS.isFriendSpecified());
10045 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10046
10047 // Try to convert the decl specifier to a type. This works for
10048 // friend templates because ActOnTag never produces a ClassTemplateDecl
10049 // for a TUK_Friend.
10050 Declarator TheDeclarator(DS, Declarator::MemberContext);
10051 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10052 QualType T = TSI->getType();
10053 if (TheDeclarator.isInvalidType())
10054 return 0;
10055
10056 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10057 return 0;
10058
10059 // This is definitely an error in C++98. It's probably meant to
10060 // be forbidden in C++0x, too, but the specification is just
10061 // poorly written.
10062 //
10063 // The problem is with declarations like the following:
10064 // template <T> friend A<T>::foo;
10065 // where deciding whether a class C is a friend or not now hinges
10066 // on whether there exists an instantiation of A that causes
10067 // 'foo' to equal C. There are restrictions on class-heads
10068 // (which we declare (by fiat) elaborated friend declarations to
10069 // be) that makes this tractable.
10070 //
10071 // FIXME: handle "template <> friend class A<T>;", which
10072 // is possibly well-formed? Who even knows?
10073 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10074 Diag(Loc, diag::err_tagless_friend_type_template)
10075 << DS.getSourceRange();
10076 return 0;
10077 }
10078
10079 // C++98 [class.friend]p1: A friend of a class is a function
10080 // or class that is not a member of the class . . .
10081 // This is fixed in DR77, which just barely didn't make the C++03
10082 // deadline. It's also a very silly restriction that seriously
10083 // affects inner classes and which nobody else seems to implement;
10084 // thus we never diagnose it, not even in -pedantic.
10085 //
10086 // But note that we could warn about it: it's always useless to
10087 // friend one of your own members (it's not, however, worthless to
10088 // friend a member of an arbitrary specialization of your template).
10089
10090 Decl *D;
10091 if (unsigned NumTempParamLists = TempParams.size())
10092 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10093 NumTempParamLists,
10094 TempParams.data(),
10095 TSI,
10096 DS.getFriendSpecLoc());
10097 else
10098 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10099
10100 if (!D)
10101 return 0;
10102
10103 D->setAccess(AS_public);
10104 CurContext->addDecl(D);
10105
10106 return D;
10107 }
10108
ActOnFriendFunctionDecl(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParams)10109 Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10110 MultiTemplateParamsArg TemplateParams) {
10111 const DeclSpec &DS = D.getDeclSpec();
10112
10113 assert(DS.isFriendSpecified());
10114 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10115
10116 SourceLocation Loc = D.getIdentifierLoc();
10117 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10118
10119 // C++ [class.friend]p1
10120 // A friend of a class is a function or class....
10121 // Note that this sees through typedefs, which is intended.
10122 // It *doesn't* see through dependent types, which is correct
10123 // according to [temp.arg.type]p3:
10124 // If a declaration acquires a function type through a
10125 // type dependent on a template-parameter and this causes
10126 // a declaration that does not use the syntactic form of a
10127 // function declarator to have a function type, the program
10128 // is ill-formed.
10129 if (!TInfo->getType()->isFunctionType()) {
10130 Diag(Loc, diag::err_unexpected_friend);
10131
10132 // It might be worthwhile to try to recover by creating an
10133 // appropriate declaration.
10134 return 0;
10135 }
10136
10137 // C++ [namespace.memdef]p3
10138 // - If a friend declaration in a non-local class first declares a
10139 // class or function, the friend class or function is a member
10140 // of the innermost enclosing namespace.
10141 // - The name of the friend is not found by simple name lookup
10142 // until a matching declaration is provided in that namespace
10143 // scope (either before or after the class declaration granting
10144 // friendship).
10145 // - If a friend function is called, its name may be found by the
10146 // name lookup that considers functions from namespaces and
10147 // classes associated with the types of the function arguments.
10148 // - When looking for a prior declaration of a class or a function
10149 // declared as a friend, scopes outside the innermost enclosing
10150 // namespace scope are not considered.
10151
10152 CXXScopeSpec &SS = D.getCXXScopeSpec();
10153 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10154 DeclarationName Name = NameInfo.getName();
10155 assert(Name);
10156
10157 // Check for unexpanded parameter packs.
10158 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10159 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10160 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10161 return 0;
10162
10163 // The context we found the declaration in, or in which we should
10164 // create the declaration.
10165 DeclContext *DC;
10166 Scope *DCScope = S;
10167 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10168 ForRedeclaration);
10169
10170 // FIXME: there are different rules in local classes
10171
10172 // There are four cases here.
10173 // - There's no scope specifier, in which case we just go to the
10174 // appropriate scope and look for a function or function template
10175 // there as appropriate.
10176 // Recover from invalid scope qualifiers as if they just weren't there.
10177 if (SS.isInvalid() || !SS.isSet()) {
10178 // C++0x [namespace.memdef]p3:
10179 // If the name in a friend declaration is neither qualified nor
10180 // a template-id and the declaration is a function or an
10181 // elaborated-type-specifier, the lookup to determine whether
10182 // the entity has been previously declared shall not consider
10183 // any scopes outside the innermost enclosing namespace.
10184 // C++0x [class.friend]p11:
10185 // If a friend declaration appears in a local class and the name
10186 // specified is an unqualified name, a prior declaration is
10187 // looked up without considering scopes that are outside the
10188 // innermost enclosing non-class scope. For a friend function
10189 // declaration, if there is no prior declaration, the program is
10190 // ill-formed.
10191 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10192 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10193
10194 // Find the appropriate context according to the above.
10195 DC = CurContext;
10196 while (true) {
10197 // Skip class contexts. If someone can cite chapter and verse
10198 // for this behavior, that would be nice --- it's what GCC and
10199 // EDG do, and it seems like a reasonable intent, but the spec
10200 // really only says that checks for unqualified existing
10201 // declarations should stop at the nearest enclosing namespace,
10202 // not that they should only consider the nearest enclosing
10203 // namespace.
10204 while (DC->isRecord() || DC->isTransparentContext())
10205 DC = DC->getParent();
10206
10207 LookupQualifiedName(Previous, DC);
10208
10209 // TODO: decide what we think about using declarations.
10210 if (isLocal || !Previous.empty())
10211 break;
10212
10213 if (isTemplateId) {
10214 if (isa<TranslationUnitDecl>(DC)) break;
10215 } else {
10216 if (DC->isFileContext()) break;
10217 }
10218 DC = DC->getParent();
10219 }
10220
10221 // C++ [class.friend]p1: A friend of a class is a function or
10222 // class that is not a member of the class . . .
10223 // C++11 changes this for both friend types and functions.
10224 // Most C++ 98 compilers do seem to give an error here, so
10225 // we do, too.
10226 if (!Previous.empty() && DC->Equals(CurContext))
10227 Diag(DS.getFriendSpecLoc(),
10228 getLangOpts().CPlusPlus0x ?
10229 diag::warn_cxx98_compat_friend_is_member :
10230 diag::err_friend_is_member);
10231
10232 DCScope = getScopeForDeclContext(S, DC);
10233
10234 // C++ [class.friend]p6:
10235 // A function can be defined in a friend declaration of a class if and
10236 // only if the class is a non-local class (9.8), the function name is
10237 // unqualified, and the function has namespace scope.
10238 if (isLocal && D.isFunctionDefinition()) {
10239 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10240 }
10241
10242 // - There's a non-dependent scope specifier, in which case we
10243 // compute it and do a previous lookup there for a function
10244 // or function template.
10245 } else if (!SS.getScopeRep()->isDependent()) {
10246 DC = computeDeclContext(SS);
10247 if (!DC) return 0;
10248
10249 if (RequireCompleteDeclContext(SS, DC)) return 0;
10250
10251 LookupQualifiedName(Previous, DC);
10252
10253 // Ignore things found implicitly in the wrong scope.
10254 // TODO: better diagnostics for this case. Suggesting the right
10255 // qualified scope would be nice...
10256 LookupResult::Filter F = Previous.makeFilter();
10257 while (F.hasNext()) {
10258 NamedDecl *D = F.next();
10259 if (!DC->InEnclosingNamespaceSetOf(
10260 D->getDeclContext()->getRedeclContext()))
10261 F.erase();
10262 }
10263 F.done();
10264
10265 if (Previous.empty()) {
10266 D.setInvalidType();
10267 Diag(Loc, diag::err_qualified_friend_not_found)
10268 << Name << TInfo->getType();
10269 return 0;
10270 }
10271
10272 // C++ [class.friend]p1: A friend of a class is a function or
10273 // class that is not a member of the class . . .
10274 if (DC->Equals(CurContext))
10275 Diag(DS.getFriendSpecLoc(),
10276 getLangOpts().CPlusPlus0x ?
10277 diag::warn_cxx98_compat_friend_is_member :
10278 diag::err_friend_is_member);
10279
10280 if (D.isFunctionDefinition()) {
10281 // C++ [class.friend]p6:
10282 // A function can be defined in a friend declaration of a class if and
10283 // only if the class is a non-local class (9.8), the function name is
10284 // unqualified, and the function has namespace scope.
10285 SemaDiagnosticBuilder DB
10286 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10287
10288 DB << SS.getScopeRep();
10289 if (DC->isFileContext())
10290 DB << FixItHint::CreateRemoval(SS.getRange());
10291 SS.clear();
10292 }
10293
10294 // - There's a scope specifier that does not match any template
10295 // parameter lists, in which case we use some arbitrary context,
10296 // create a method or method template, and wait for instantiation.
10297 // - There's a scope specifier that does match some template
10298 // parameter lists, which we don't handle right now.
10299 } else {
10300 if (D.isFunctionDefinition()) {
10301 // C++ [class.friend]p6:
10302 // A function can be defined in a friend declaration of a class if and
10303 // only if the class is a non-local class (9.8), the function name is
10304 // unqualified, and the function has namespace scope.
10305 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10306 << SS.getScopeRep();
10307 }
10308
10309 DC = CurContext;
10310 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10311 }
10312
10313 if (!DC->isRecord()) {
10314 // This implies that it has to be an operator or function.
10315 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10316 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10317 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10318 Diag(Loc, diag::err_introducing_special_friend) <<
10319 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10320 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10321 return 0;
10322 }
10323 }
10324
10325 // FIXME: This is an egregious hack to cope with cases where the scope stack
10326 // does not contain the declaration context, i.e., in an out-of-line
10327 // definition of a class.
10328 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10329 if (!DCScope) {
10330 FakeDCScope.setEntity(DC);
10331 DCScope = &FakeDCScope;
10332 }
10333
10334 bool AddToScope = true;
10335 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10336 TemplateParams, AddToScope);
10337 if (!ND) return 0;
10338
10339 assert(ND->getDeclContext() == DC);
10340 assert(ND->getLexicalDeclContext() == CurContext);
10341
10342 // Add the function declaration to the appropriate lookup tables,
10343 // adjusting the redeclarations list as necessary. We don't
10344 // want to do this yet if the friending class is dependent.
10345 //
10346 // Also update the scope-based lookup if the target context's
10347 // lookup context is in lexical scope.
10348 if (!CurContext->isDependentContext()) {
10349 DC = DC->getRedeclContext();
10350 DC->makeDeclVisibleInContext(ND);
10351 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10352 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10353 }
10354
10355 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10356 D.getIdentifierLoc(), ND,
10357 DS.getFriendSpecLoc());
10358 FrD->setAccess(AS_public);
10359 CurContext->addDecl(FrD);
10360
10361 if (ND->isInvalidDecl()) {
10362 FrD->setInvalidDecl();
10363 } else {
10364 if (DC->isRecord()) CheckFriendAccess(ND);
10365
10366 FunctionDecl *FD;
10367 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10368 FD = FTD->getTemplatedDecl();
10369 else
10370 FD = cast<FunctionDecl>(ND);
10371
10372 // Mark templated-scope function declarations as unsupported.
10373 if (FD->getNumTemplateParameterLists())
10374 FrD->setUnsupportedFriend(true);
10375 }
10376
10377 return ND;
10378 }
10379
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc)10380 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10381 AdjustDeclIfTemplate(Dcl);
10382
10383 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10384 if (!Fn) {
10385 Diag(DelLoc, diag::err_deleted_non_function);
10386 return;
10387 }
10388 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10389 // Don't consider the implicit declaration we generate for explicit
10390 // specializations. FIXME: Do not generate these implicit declarations.
10391 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10392 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10393 Diag(DelLoc, diag::err_deleted_decl_not_first);
10394 Diag(Prev->getLocation(), diag::note_previous_declaration);
10395 }
10396 // If the declaration wasn't the first, we delete the function anyway for
10397 // recovery.
10398 }
10399 Fn->setDeletedAsWritten();
10400
10401 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10402 if (!MD)
10403 return;
10404
10405 // A deleted special member function is trivial if the corresponding
10406 // implicitly-declared function would have been.
10407 switch (getSpecialMember(MD)) {
10408 case CXXInvalid:
10409 break;
10410 case CXXDefaultConstructor:
10411 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10412 break;
10413 case CXXCopyConstructor:
10414 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10415 break;
10416 case CXXMoveConstructor:
10417 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10418 break;
10419 case CXXCopyAssignment:
10420 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10421 break;
10422 case CXXMoveAssignment:
10423 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10424 break;
10425 case CXXDestructor:
10426 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10427 break;
10428 }
10429 }
10430
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)10431 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10432 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10433
10434 if (MD) {
10435 if (MD->getParent()->isDependentType()) {
10436 MD->setDefaulted();
10437 MD->setExplicitlyDefaulted();
10438 return;
10439 }
10440
10441 CXXSpecialMember Member = getSpecialMember(MD);
10442 if (Member == CXXInvalid) {
10443 Diag(DefaultLoc, diag::err_default_special_members);
10444 return;
10445 }
10446
10447 MD->setDefaulted();
10448 MD->setExplicitlyDefaulted();
10449
10450 // If this definition appears within the record, do the checking when
10451 // the record is complete.
10452 const FunctionDecl *Primary = MD;
10453 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
10454 // Find the uninstantiated declaration that actually had the '= default'
10455 // on it.
10456 Pattern->isDefined(Primary);
10457
10458 if (Primary == Primary->getCanonicalDecl())
10459 return;
10460
10461 CheckExplicitlyDefaultedSpecialMember(MD);
10462
10463 switch (Member) {
10464 case CXXDefaultConstructor: {
10465 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10466 if (!CD->isInvalidDecl())
10467 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10468 break;
10469 }
10470
10471 case CXXCopyConstructor: {
10472 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10473 if (!CD->isInvalidDecl())
10474 DefineImplicitCopyConstructor(DefaultLoc, CD);
10475 break;
10476 }
10477
10478 case CXXCopyAssignment: {
10479 if (!MD->isInvalidDecl())
10480 DefineImplicitCopyAssignment(DefaultLoc, MD);
10481 break;
10482 }
10483
10484 case CXXDestructor: {
10485 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10486 if (!DD->isInvalidDecl())
10487 DefineImplicitDestructor(DefaultLoc, DD);
10488 break;
10489 }
10490
10491 case CXXMoveConstructor: {
10492 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10493 if (!CD->isInvalidDecl())
10494 DefineImplicitMoveConstructor(DefaultLoc, CD);
10495 break;
10496 }
10497
10498 case CXXMoveAssignment: {
10499 if (!MD->isInvalidDecl())
10500 DefineImplicitMoveAssignment(DefaultLoc, MD);
10501 break;
10502 }
10503
10504 case CXXInvalid:
10505 llvm_unreachable("Invalid special member.");
10506 }
10507 } else {
10508 Diag(DefaultLoc, diag::err_default_special_members);
10509 }
10510 }
10511
SearchForReturnInStmt(Sema & Self,Stmt * S)10512 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10513 for (Stmt::child_range CI = S->children(); CI; ++CI) {
10514 Stmt *SubStmt = *CI;
10515 if (!SubStmt)
10516 continue;
10517 if (isa<ReturnStmt>(SubStmt))
10518 Self.Diag(SubStmt->getLocStart(),
10519 diag::err_return_in_constructor_handler);
10520 if (!isa<Expr>(SubStmt))
10521 SearchForReturnInStmt(Self, SubStmt);
10522 }
10523 }
10524
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)10525 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10526 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10527 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10528 SearchForReturnInStmt(*this, Handler);
10529 }
10530 }
10531
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)10532 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10533 const CXXMethodDecl *Old) {
10534 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10535 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10536
10537 if (Context.hasSameType(NewTy, OldTy) ||
10538 NewTy->isDependentType() || OldTy->isDependentType())
10539 return false;
10540
10541 // Check if the return types are covariant
10542 QualType NewClassTy, OldClassTy;
10543
10544 /// Both types must be pointers or references to classes.
10545 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10546 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10547 NewClassTy = NewPT->getPointeeType();
10548 OldClassTy = OldPT->getPointeeType();
10549 }
10550 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10551 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10552 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10553 NewClassTy = NewRT->getPointeeType();
10554 OldClassTy = OldRT->getPointeeType();
10555 }
10556 }
10557 }
10558
10559 // The return types aren't either both pointers or references to a class type.
10560 if (NewClassTy.isNull()) {
10561 Diag(New->getLocation(),
10562 diag::err_different_return_type_for_overriding_virtual_function)
10563 << New->getDeclName() << NewTy << OldTy;
10564 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10565
10566 return true;
10567 }
10568
10569 // C++ [class.virtual]p6:
10570 // If the return type of D::f differs from the return type of B::f, the
10571 // class type in the return type of D::f shall be complete at the point of
10572 // declaration of D::f or shall be the class type D.
10573 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10574 if (!RT->isBeingDefined() &&
10575 RequireCompleteType(New->getLocation(), NewClassTy,
10576 diag::err_covariant_return_incomplete,
10577 New->getDeclName()))
10578 return true;
10579 }
10580
10581 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10582 // Check if the new class derives from the old class.
10583 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10584 Diag(New->getLocation(),
10585 diag::err_covariant_return_not_derived)
10586 << New->getDeclName() << NewTy << OldTy;
10587 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10588 return true;
10589 }
10590
10591 // Check if we the conversion from derived to base is valid.
10592 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10593 diag::err_covariant_return_inaccessible_base,
10594 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10595 // FIXME: Should this point to the return type?
10596 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10597 // FIXME: this note won't trigger for delayed access control
10598 // diagnostics, and it's impossible to get an undelayed error
10599 // here from access control during the original parse because
10600 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10601 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10602 return true;
10603 }
10604 }
10605
10606 // The qualifiers of the return types must be the same.
10607 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10608 Diag(New->getLocation(),
10609 diag::err_covariant_return_type_different_qualifications)
10610 << New->getDeclName() << NewTy << OldTy;
10611 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10612 return true;
10613 };
10614
10615
10616 // The new class type must have the same or less qualifiers as the old type.
10617 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10618 Diag(New->getLocation(),
10619 diag::err_covariant_return_type_class_type_more_qualified)
10620 << New->getDeclName() << NewTy << OldTy;
10621 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10622 return true;
10623 };
10624
10625 return false;
10626 }
10627
10628 /// \brief Mark the given method pure.
10629 ///
10630 /// \param Method the method to be marked pure.
10631 ///
10632 /// \param InitRange the source range that covers the "0" initializer.
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)10633 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10634 SourceLocation EndLoc = InitRange.getEnd();
10635 if (EndLoc.isValid())
10636 Method->setRangeEnd(EndLoc);
10637
10638 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10639 Method->setPure();
10640 return false;
10641 }
10642
10643 if (!Method->isInvalidDecl())
10644 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10645 << Method->getDeclName() << InitRange;
10646 return true;
10647 }
10648
10649 /// \brief Determine whether the given declaration is a static data member.
isStaticDataMember(Decl * D)10650 static bool isStaticDataMember(Decl *D) {
10651 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10652 if (!Var)
10653 return false;
10654
10655 return Var->isStaticDataMember();
10656 }
10657 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10658 /// an initializer for the out-of-line declaration 'Dcl'. The scope
10659 /// is a fresh scope pushed for just this purpose.
10660 ///
10661 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10662 /// static data member of class X, names should be looked up in the scope of
10663 /// class X.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)10664 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10665 // If there is no declaration, there was an error parsing it.
10666 if (D == 0 || D->isInvalidDecl()) return;
10667
10668 // We should only get called for declarations with scope specifiers, like:
10669 // int foo::bar;
10670 assert(D->isOutOfLine());
10671 EnterDeclaratorContext(S, D->getDeclContext());
10672
10673 // If we are parsing the initializer for a static data member, push a
10674 // new expression evaluation context that is associated with this static
10675 // data member.
10676 if (isStaticDataMember(D))
10677 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10678 }
10679
10680 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10681 /// initializer for the out-of-line declaration 'D'.
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)10682 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10683 // If there is no declaration, there was an error parsing it.
10684 if (D == 0 || D->isInvalidDecl()) return;
10685
10686 if (isStaticDataMember(D))
10687 PopExpressionEvaluationContext();
10688
10689 assert(D->isOutOfLine());
10690 ExitDeclaratorContext(S);
10691 }
10692
10693 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10694 /// C++ if/switch/while/for statement.
10695 /// e.g: "if (int x = f()) {...}"
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)10696 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10697 // C++ 6.4p2:
10698 // The declarator shall not specify a function or an array.
10699 // The type-specifier-seq shall not contain typedef and shall not declare a
10700 // new class or enumeration.
10701 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10702 "Parser allowed 'typedef' as storage class of condition decl.");
10703
10704 Decl *Dcl = ActOnDeclarator(S, D);
10705 if (!Dcl)
10706 return true;
10707
10708 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10709 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10710 << D.getSourceRange();
10711 return true;
10712 }
10713
10714 return Dcl;
10715 }
10716
LoadExternalVTableUses()10717 void Sema::LoadExternalVTableUses() {
10718 if (!ExternalSource)
10719 return;
10720
10721 SmallVector<ExternalVTableUse, 4> VTables;
10722 ExternalSource->ReadUsedVTables(VTables);
10723 SmallVector<VTableUse, 4> NewUses;
10724 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10725 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10726 = VTablesUsed.find(VTables[I].Record);
10727 // Even if a definition wasn't required before, it may be required now.
10728 if (Pos != VTablesUsed.end()) {
10729 if (!Pos->second && VTables[I].DefinitionRequired)
10730 Pos->second = true;
10731 continue;
10732 }
10733
10734 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10735 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10736 }
10737
10738 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10739 }
10740
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)10741 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10742 bool DefinitionRequired) {
10743 // Ignore any vtable uses in unevaluated operands or for classes that do
10744 // not have a vtable.
10745 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10746 CurContext->isDependentContext() ||
10747 ExprEvalContexts.back().Context == Unevaluated)
10748 return;
10749
10750 // Try to insert this class into the map.
10751 LoadExternalVTableUses();
10752 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10753 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10754 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10755 if (!Pos.second) {
10756 // If we already had an entry, check to see if we are promoting this vtable
10757 // to required a definition. If so, we need to reappend to the VTableUses
10758 // list, since we may have already processed the first entry.
10759 if (DefinitionRequired && !Pos.first->second) {
10760 Pos.first->second = true;
10761 } else {
10762 // Otherwise, we can early exit.
10763 return;
10764 }
10765 }
10766
10767 // Local classes need to have their virtual members marked
10768 // immediately. For all other classes, we mark their virtual members
10769 // at the end of the translation unit.
10770 if (Class->isLocalClass())
10771 MarkVirtualMembersReferenced(Loc, Class);
10772 else
10773 VTableUses.push_back(std::make_pair(Class, Loc));
10774 }
10775
DefineUsedVTables()10776 bool Sema::DefineUsedVTables() {
10777 LoadExternalVTableUses();
10778 if (VTableUses.empty())
10779 return false;
10780
10781 // Note: The VTableUses vector could grow as a result of marking
10782 // the members of a class as "used", so we check the size each
10783 // time through the loop and prefer indices (which are stable) to
10784 // iterators (which are not).
10785 bool DefinedAnything = false;
10786 for (unsigned I = 0; I != VTableUses.size(); ++I) {
10787 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10788 if (!Class)
10789 continue;
10790
10791 SourceLocation Loc = VTableUses[I].second;
10792
10793 bool DefineVTable = true;
10794
10795 // If this class has a key function, but that key function is
10796 // defined in another translation unit, we don't need to emit the
10797 // vtable even though we're using it.
10798 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10799 if (KeyFunction && !KeyFunction->hasBody()) {
10800 switch (KeyFunction->getTemplateSpecializationKind()) {
10801 case TSK_Undeclared:
10802 case TSK_ExplicitSpecialization:
10803 case TSK_ExplicitInstantiationDeclaration:
10804 // The key function is in another translation unit.
10805 DefineVTable = false;
10806 break;
10807
10808 case TSK_ExplicitInstantiationDefinition:
10809 case TSK_ImplicitInstantiation:
10810 // We will be instantiating the key function.
10811 break;
10812 }
10813 } else if (!KeyFunction) {
10814 // If we have a class with no key function that is the subject
10815 // of an explicit instantiation declaration, suppress the
10816 // vtable; it will live with the explicit instantiation
10817 // definition.
10818 bool IsExplicitInstantiationDeclaration
10819 = Class->getTemplateSpecializationKind()
10820 == TSK_ExplicitInstantiationDeclaration;
10821 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10822 REnd = Class->redecls_end();
10823 R != REnd; ++R) {
10824 TemplateSpecializationKind TSK
10825 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10826 if (TSK == TSK_ExplicitInstantiationDeclaration)
10827 IsExplicitInstantiationDeclaration = true;
10828 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10829 IsExplicitInstantiationDeclaration = false;
10830 break;
10831 }
10832 }
10833
10834 if (IsExplicitInstantiationDeclaration)
10835 DefineVTable = false;
10836 }
10837
10838 // The exception specifications for all virtual members may be needed even
10839 // if we are not providing an authoritative form of the vtable in this TU.
10840 // We may choose to emit it available_externally anyway.
10841 if (!DefineVTable) {
10842 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10843 continue;
10844 }
10845
10846 // Mark all of the virtual members of this class as referenced, so
10847 // that we can build a vtable. Then, tell the AST consumer that a
10848 // vtable for this class is required.
10849 DefinedAnything = true;
10850 MarkVirtualMembersReferenced(Loc, Class);
10851 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10852 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10853
10854 // Optionally warn if we're emitting a weak vtable.
10855 if (Class->getLinkage() == ExternalLinkage &&
10856 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10857 const FunctionDecl *KeyFunctionDef = 0;
10858 if (!KeyFunction ||
10859 (KeyFunction->hasBody(KeyFunctionDef) &&
10860 KeyFunctionDef->isInlined()))
10861 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10862 TSK_ExplicitInstantiationDefinition
10863 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10864 << Class;
10865 }
10866 }
10867 VTableUses.clear();
10868
10869 return DefinedAnything;
10870 }
10871
MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,const CXXRecordDecl * RD)10872 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10873 const CXXRecordDecl *RD) {
10874 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10875 E = RD->method_end(); I != E; ++I)
10876 if ((*I)->isVirtual() && !(*I)->isPure())
10877 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10878 }
10879
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD)10880 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10881 const CXXRecordDecl *RD) {
10882 // Mark all functions which will appear in RD's vtable as used.
10883 CXXFinalOverriderMap FinalOverriders;
10884 RD->getFinalOverriders(FinalOverriders);
10885 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10886 E = FinalOverriders.end();
10887 I != E; ++I) {
10888 for (OverridingMethods::const_iterator OI = I->second.begin(),
10889 OE = I->second.end();
10890 OI != OE; ++OI) {
10891 assert(OI->second.size() > 0 && "no final overrider");
10892 CXXMethodDecl *Overrider = OI->second.front().Method;
10893
10894 // C++ [basic.def.odr]p2:
10895 // [...] A virtual member function is used if it is not pure. [...]
10896 if (!Overrider->isPure())
10897 MarkFunctionReferenced(Loc, Overrider);
10898 }
10899 }
10900
10901 // Only classes that have virtual bases need a VTT.
10902 if (RD->getNumVBases() == 0)
10903 return;
10904
10905 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10906 e = RD->bases_end(); i != e; ++i) {
10907 const CXXRecordDecl *Base =
10908 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10909 if (Base->getNumVBases() == 0)
10910 continue;
10911 MarkVirtualMembersReferenced(Loc, Base);
10912 }
10913 }
10914
10915 /// SetIvarInitializers - This routine builds initialization ASTs for the
10916 /// Objective-C implementation whose ivars need be initialized.
SetIvarInitializers(ObjCImplementationDecl * ObjCImplementation)10917 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10918 if (!getLangOpts().CPlusPlus)
10919 return;
10920 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10921 SmallVector<ObjCIvarDecl*, 8> ivars;
10922 CollectIvarsToConstructOrDestruct(OID, ivars);
10923 if (ivars.empty())
10924 return;
10925 SmallVector<CXXCtorInitializer*, 32> AllToInit;
10926 for (unsigned i = 0; i < ivars.size(); i++) {
10927 FieldDecl *Field = ivars[i];
10928 if (Field->isInvalidDecl())
10929 continue;
10930
10931 CXXCtorInitializer *Member;
10932 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10933 InitializationKind InitKind =
10934 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10935
10936 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10937 ExprResult MemberInit =
10938 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10939 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10940 // Note, MemberInit could actually come back empty if no initialization
10941 // is required (e.g., because it would call a trivial default constructor)
10942 if (!MemberInit.get() || MemberInit.isInvalid())
10943 continue;
10944
10945 Member =
10946 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10947 SourceLocation(),
10948 MemberInit.takeAs<Expr>(),
10949 SourceLocation());
10950 AllToInit.push_back(Member);
10951
10952 // Be sure that the destructor is accessible and is marked as referenced.
10953 if (const RecordType *RecordTy
10954 = Context.getBaseElementType(Field->getType())
10955 ->getAs<RecordType>()) {
10956 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10957 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10958 MarkFunctionReferenced(Field->getLocation(), Destructor);
10959 CheckDestructorAccess(Field->getLocation(), Destructor,
10960 PDiag(diag::err_access_dtor_ivar)
10961 << Context.getBaseElementType(Field->getType()));
10962 }
10963 }
10964 }
10965 ObjCImplementation->setIvarInitializers(Context,
10966 AllToInit.data(), AllToInit.size());
10967 }
10968 }
10969
10970 static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallSet<CXXConstructorDecl *,4> & Valid,llvm::SmallSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallSet<CXXConstructorDecl *,4> & Current,Sema & S)10971 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10972 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10973 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10974 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10975 Sema &S) {
10976 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10977 CE = Current.end();
10978 if (Ctor->isInvalidDecl())
10979 return;
10980
10981 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
10982
10983 // Target may not be determinable yet, for instance if this is a dependent
10984 // call in an uninstantiated template.
10985 if (Target) {
10986 const FunctionDecl *FNTarget = 0;
10987 (void)Target->hasBody(FNTarget);
10988 Target = const_cast<CXXConstructorDecl*>(
10989 cast_or_null<CXXConstructorDecl>(FNTarget));
10990 }
10991
10992 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10993 // Avoid dereferencing a null pointer here.
10994 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10995
10996 if (!Current.insert(Canonical))
10997 return;
10998
10999 // We know that beyond here, we aren't chaining into a cycle.
11000 if (!Target || !Target->isDelegatingConstructor() ||
11001 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11002 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11003 Valid.insert(*CI);
11004 Current.clear();
11005 // We've hit a cycle.
11006 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11007 Current.count(TCanonical)) {
11008 // If we haven't diagnosed this cycle yet, do so now.
11009 if (!Invalid.count(TCanonical)) {
11010 S.Diag((*Ctor->init_begin())->getSourceLocation(),
11011 diag::warn_delegating_ctor_cycle)
11012 << Ctor;
11013
11014 // Don't add a note for a function delegating directly to itself.
11015 if (TCanonical != Canonical)
11016 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11017
11018 CXXConstructorDecl *C = Target;
11019 while (C->getCanonicalDecl() != Canonical) {
11020 const FunctionDecl *FNTarget = 0;
11021 (void)C->getTargetConstructor()->hasBody(FNTarget);
11022 assert(FNTarget && "Ctor cycle through bodiless function");
11023
11024 C = const_cast<CXXConstructorDecl*>(
11025 cast<CXXConstructorDecl>(FNTarget));
11026 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11027 }
11028 }
11029
11030 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11031 Invalid.insert(*CI);
11032 Current.clear();
11033 } else {
11034 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11035 }
11036 }
11037
11038
CheckDelegatingCtorCycles()11039 void Sema::CheckDelegatingCtorCycles() {
11040 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11041
11042 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11043 CE = Current.end();
11044
11045 for (DelegatingCtorDeclsType::iterator
11046 I = DelegatingCtorDecls.begin(ExternalSource),
11047 E = DelegatingCtorDecls.end();
11048 I != E; ++I)
11049 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11050
11051 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11052 (*CI)->setInvalidDecl();
11053 }
11054
11055 namespace {
11056 /// \brief AST visitor that finds references to the 'this' expression.
11057 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11058 Sema &S;
11059
11060 public:
FindCXXThisExpr(Sema & S)11061 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11062
VisitCXXThisExpr(CXXThisExpr * E)11063 bool VisitCXXThisExpr(CXXThisExpr *E) {
11064 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11065 << E->isImplicit();
11066 return false;
11067 }
11068 };
11069 }
11070
checkThisInStaticMemberFunctionType(CXXMethodDecl * Method)11071 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11072 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11073 if (!TSInfo)
11074 return false;
11075
11076 TypeLoc TL = TSInfo->getTypeLoc();
11077 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11078 if (!ProtoTL)
11079 return false;
11080
11081 // C++11 [expr.prim.general]p3:
11082 // [The expression this] shall not appear before the optional
11083 // cv-qualifier-seq and it shall not appear within the declaration of a
11084 // static member function (although its type and value category are defined
11085 // within a static member function as they are within a non-static member
11086 // function). [ Note: this is because declaration matching does not occur
11087 // until the complete declarator is known. - end note ]
11088 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11089 FindCXXThisExpr Finder(*this);
11090
11091 // If the return type came after the cv-qualifier-seq, check it now.
11092 if (Proto->hasTrailingReturn() &&
11093 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11094 return true;
11095
11096 // Check the exception specification.
11097 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11098 return true;
11099
11100 return checkThisInStaticMemberFunctionAttributes(Method);
11101 }
11102
checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl * Method)11103 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11104 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11105 if (!TSInfo)
11106 return false;
11107
11108 TypeLoc TL = TSInfo->getTypeLoc();
11109 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11110 if (!ProtoTL)
11111 return false;
11112
11113 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11114 FindCXXThisExpr Finder(*this);
11115
11116 switch (Proto->getExceptionSpecType()) {
11117 case EST_Uninstantiated:
11118 case EST_Unevaluated:
11119 case EST_BasicNoexcept:
11120 case EST_DynamicNone:
11121 case EST_MSAny:
11122 case EST_None:
11123 break;
11124
11125 case EST_ComputedNoexcept:
11126 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11127 return true;
11128
11129 case EST_Dynamic:
11130 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11131 EEnd = Proto->exception_end();
11132 E != EEnd; ++E) {
11133 if (!Finder.TraverseType(*E))
11134 return true;
11135 }
11136 break;
11137 }
11138
11139 return false;
11140 }
11141
checkThisInStaticMemberFunctionAttributes(CXXMethodDecl * Method)11142 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11143 FindCXXThisExpr Finder(*this);
11144
11145 // Check attributes.
11146 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11147 A != AEnd; ++A) {
11148 // FIXME: This should be emitted by tblgen.
11149 Expr *Arg = 0;
11150 ArrayRef<Expr *> Args;
11151 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11152 Arg = G->getArg();
11153 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11154 Arg = G->getArg();
11155 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11156 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11157 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11158 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11159 else if (ExclusiveLockFunctionAttr *ELF
11160 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11161 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11162 else if (SharedLockFunctionAttr *SLF
11163 = dyn_cast<SharedLockFunctionAttr>(*A))
11164 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11165 else if (ExclusiveTrylockFunctionAttr *ETLF
11166 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11167 Arg = ETLF->getSuccessValue();
11168 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11169 } else if (SharedTrylockFunctionAttr *STLF
11170 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11171 Arg = STLF->getSuccessValue();
11172 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11173 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11174 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11175 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11176 Arg = LR->getArg();
11177 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11178 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11179 else if (ExclusiveLocksRequiredAttr *ELR
11180 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11181 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11182 else if (SharedLocksRequiredAttr *SLR
11183 = dyn_cast<SharedLocksRequiredAttr>(*A))
11184 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11185
11186 if (Arg && !Finder.TraverseStmt(Arg))
11187 return true;
11188
11189 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11190 if (!Finder.TraverseStmt(Args[I]))
11191 return true;
11192 }
11193 }
11194
11195 return false;
11196 }
11197
11198 void
checkExceptionSpecification(ExceptionSpecificationType EST,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr,llvm::SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExtProtoInfo & EPI)11199 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11200 ArrayRef<ParsedType> DynamicExceptions,
11201 ArrayRef<SourceRange> DynamicExceptionRanges,
11202 Expr *NoexceptExpr,
11203 llvm::SmallVectorImpl<QualType> &Exceptions,
11204 FunctionProtoType::ExtProtoInfo &EPI) {
11205 Exceptions.clear();
11206 EPI.ExceptionSpecType = EST;
11207 if (EST == EST_Dynamic) {
11208 Exceptions.reserve(DynamicExceptions.size());
11209 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11210 // FIXME: Preserve type source info.
11211 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11212
11213 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11214 collectUnexpandedParameterPacks(ET, Unexpanded);
11215 if (!Unexpanded.empty()) {
11216 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11217 UPPC_ExceptionType,
11218 Unexpanded);
11219 continue;
11220 }
11221
11222 // Check that the type is valid for an exception spec, and
11223 // drop it if not.
11224 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11225 Exceptions.push_back(ET);
11226 }
11227 EPI.NumExceptions = Exceptions.size();
11228 EPI.Exceptions = Exceptions.data();
11229 return;
11230 }
11231
11232 if (EST == EST_ComputedNoexcept) {
11233 // If an error occurred, there's no expression here.
11234 if (NoexceptExpr) {
11235 assert((NoexceptExpr->isTypeDependent() ||
11236 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11237 Context.BoolTy) &&
11238 "Parser should have made sure that the expression is boolean");
11239 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11240 EPI.ExceptionSpecType = EST_BasicNoexcept;
11241 return;
11242 }
11243
11244 if (!NoexceptExpr->isValueDependent())
11245 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11246 diag::err_noexcept_needs_constant_expression,
11247 /*AllowFold*/ false).take();
11248 EPI.NoexceptExpr = NoexceptExpr;
11249 }
11250 return;
11251 }
11252 }
11253
11254 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
IdentifyCUDATarget(const FunctionDecl * D)11255 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11256 // Implicitly declared functions (e.g. copy constructors) are
11257 // __host__ __device__
11258 if (D->isImplicit())
11259 return CFT_HostDevice;
11260
11261 if (D->hasAttr<CUDAGlobalAttr>())
11262 return CFT_Global;
11263
11264 if (D->hasAttr<CUDADeviceAttr>()) {
11265 if (D->hasAttr<CUDAHostAttr>())
11266 return CFT_HostDevice;
11267 else
11268 return CFT_Device;
11269 }
11270
11271 return CFT_Host;
11272 }
11273
CheckCUDATarget(CUDAFunctionTarget CallerTarget,CUDAFunctionTarget CalleeTarget)11274 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11275 CUDAFunctionTarget CalleeTarget) {
11276 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11277 // Callable from the device only."
11278 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11279 return true;
11280
11281 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11282 // Callable from the host only."
11283 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11284 // Callable from the host only."
11285 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11286 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11287 return true;
11288
11289 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11290 return true;
11291
11292 return false;
11293 }
11294